问:
How to click button in my login form in my Android Studio project
I am a beginner to Android. I tried a lot to find this error but I haven't got a satisfactory answer. In my program I created a login and register page and connected to Firebase. But since I am not able to click the button I am not able to register the user.

When I click the button it does nothing. And even I linked another button to a login page that is also not working.

```<code> private EditText inputEmail, inputPassword;
    private Button btnSignIn, btnSignUp;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginreg);
        auth = FirebaseAuth.getInstance();

        btnSignIn = (Button) findViewById(R.id.lo);//This is sign in button
        btnSignUp = (Button) findViewById(R.id.register_btn);//This is the sign up button
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                //create user
                auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(loginreg.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(loginreg.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Toast.makeText(loginreg.this, "Authentication failed." + task.getException(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    startActivity(new Intent(loginreg.this, activity_second.class));
                                             finish()
                                }
                            }
                        });

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }
</code>```

This is my XML code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary"
    tools:context=".loginreg">

    <EditText
        android:id="@+id/name"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="62dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/username"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="11dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Password"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/password"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="256dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Conform Password"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionDone"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/username"
        tools:ignore="RtlCompat" />

    <Button
        android:id="@+id/register_btn"
        android:layout_width="112dp"
        android:layout_height="63dp"
        android:layout_alignTop="@+id/name"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="236dp"
        android:layout_marginBottom="107dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Register"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <Button
        android:id="@+id/lo"
        android:layout_width="363dp"
        android:layout_height="51dp"
        android:layout_alignTop="@+id/username"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="290dp"
        android:layout_marginBottom="14dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="164dp"
        android:layout_height="476dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="129dp"
        android:layout_marginLeft="129dp"
        android:layout_marginTop="-170dp"
        app:srcCompat="@drawable/film_1" />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="162dp"
        android:layout_height="64dp"
        android:layout_above="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="171dp"
        android:layout_marginBottom="90dp"
        android:text="Register"
        android:textColor="@android:color/white"
        android:textSize="40dp" />
</RelativeLayout>
</code>```

答:
Your missing the android:onClick="yourmethod" in the xml file <Button> tag. And also set the android:enabled="false" to true or remove it.

Update

In the activity you can have the onClick as:

```<code>btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yourMethod(v);
            }
});
</code>```

Body:
I am a beginner to Android. I tried a lot to find this error but I haven't got a satisfactory answer. In my program I created a login and register page and connected to Firebase. But since I am not able to click the button I am not able to register the user.

When I click the button it does nothing. And even I linked another button to a login page that is also not working.

 private EditText inputEmail, inputPassword;
    private Button btnSignIn, btnSignUp;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginreg);
        auth = FirebaseAuth.getInstance();

        btnSignIn = (Button) findViewById(R.id.lo);//This is sign in button
        btnSignUp = (Button) findViewById(R.id.register_btn);//This is the sign up button
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                //create user
                auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(loginreg.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(loginreg.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Toast.makeText(loginreg.this, "Authentication failed." + task.getException(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    startActivity(new Intent(loginreg.this, activity_second.class));
                                             finish()
                                }
                            }
                        });

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }

This is my XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary"
    tools:context=".loginreg">

    <EditText
        android:id="@+id/name"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="62dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/username"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="11dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Password"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/password"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="256dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Conform Password"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionDone"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/username"
        tools:ignore="RtlCompat" />

    <Button
        android:id="@+id/register_btn"
        android:layout_width="112dp"
        android:layout_height="63dp"
        android:layout_alignTop="@+id/name"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="236dp"
        android:layout_marginBottom="107dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Register"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <Button
        android:id="@+id/lo"
        android:layout_width="363dp"
        android:layout_height="51dp"
        android:layout_alignTop="@+id/username"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="290dp"
        android:layout_marginBottom="14dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="164dp"
        android:layout_height="476dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="129dp"
        android:layout_marginLeft="129dp"
        android:layout_marginTop="-170dp"
        app:srcCompat="@drawable/film_1" />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="162dp"
        android:layout_height="64dp"
        android:layout_above="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="171dp"
        android:layout_marginBottom="90dp"
        android:text="Register"
        android:textColor="@android:color/white"
        android:textSize="40dp" />
</RelativeLayout>

Body:
Your missing the android:onClick="yourmethod" in the xml file <Button> tag. And also set the android:enabled="false" to true or remove it.

Update

In the activity you can have the onClick as:

btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yourMethod(v);
            }
});


来源: stackexchange

问:
Typescript - classes which share method but are not derived from a shared base class
Basically my setup is
I have a library, which contains a bunch of classes A, B, ... , Z
All of these classes share a common method call foo, but none of them derive from a base class.

These methods accept an argument, data, which is of type AT, BT, ... , ZT

e.g.

```<code>class B {
   foo(data: BT)
}

class Q {
   foo(data: QT);
}
</code>```

In my code, I have to do something very repetitive which boils down do creating a method which takes a class (e.g. A) and a data object (e.g. of type AT) and then calling foo on that class object with the data object.

In typescript, is there a nice way i can just have one helper function rather than having to write a bunch of boiler plate code

i.e. today I do

```<code>createA(data: AT): A {
   let a: A;
   a.foo(data);
   return a;
}

createB(data: BT): B {
   let b: B;
   b.foo(data);
   return b;
}

...

createZ(data: ZT): Z {
   let z: Z;
   z.foo(data);
   return z;
}
</code>```

I want to be able to do

```<code>createObject<ClassType, ArgumentType>(data: ArgumentType): ClassType {
   let myObj: ClassType;
   myObj.foo(data);
   return myObj;
}
</code>```

Thanks

答:
Side note: code like let b: B; doesn't actually create an object of type B; at runtime, b will be undefined and you will have immediate problems trying to call its foo() method.  I am supposing/hoping that in your actual code you are actually constructing instances of B etc.  But that implies that you should be passing a class constructor to your createObject() function.  I'm ignoring that for the rest of the answer and will use your signature and implementation more or less as-is.  Be warned.

You can write your generic function like this:

```<code>function createObject<C extends { foo(a: A): void }, A>(data: A): C {
  let myObj: C = null!; // <-- this isn't initialized?
  myObj.foo(data);
  return myObj;
}
</code>```

where we've used a generic constraint to tell the compiler that C will have a foo() method that takes an argument of type A.  You should then be able to call it:

```<code>declare const qt: QT;
const obj = createObject<Q, QT>(qt); // okay, type Q
</code>```

Note that you are required here to manually specify the C and A type parameters when you call the function if you expect to see a strongly-typed output:

```<code>const oops = createObject(qt); //
// const oops: { foo(a: QT): void; }
</code>```

If you want the compiler to infer the output type from the input type, then you need to give createObject() a call signature that tells the compiler every input-output mapping you care about:

```<code>type IOMap = [QT, Q] | [BT, B] // | ... | [ZT, Z];
type ClassType<A extends IOMap[0]> = Extract<IOMap, [A, any]>[1];

function createObject<A extends IOMap[0]>(data: A): ClassType<A>;
function createObject<C extends { foo(a: A): void }, A>(data: A): C {
  let myObj: C = null!; // <-- this isn't initialized?
  myObj.foo(data);
  return myObj;
}
</code>```

That's a bit annoying to declare, but is easier to use:

```<code>const obj = createObject(qt); // okay
// const obj: Q
</code>```

Okay, hope that helps; good luck!

Playground link to code

ContentLicense: CC BY-SA 4.0

Body:
Basically my setup is
I have a library, which contains a bunch of classes A, B, ... , Z
All of these classes share a common method call foo, but none of them derive from a base class.

These methods accept an argument, data, which is of type AT, BT, ... , ZT

e.g.

class B {
   foo(data: BT)
}

class Q {
   foo(data: QT);
}

In my code, I have to do something very repetitive which boils down do creating a method which takes a class (e.g. A) and a data object (e.g. of type AT) and then calling foo on that class object with the data object.

In typescript, is there a nice way i can just have one helper function rather than having to write a bunch of boiler plate code

i.e. today I do

createA(data: AT): A {
   let a: A;
   a.foo(data);
   return a;
}

createB(data: BT): B {
   let b: B;
   b.foo(data);
   return b;
}

...

createZ(data: ZT): Z {
   let z: Z;
   z.foo(data);
   return z;
}

I want to be able to do

createObject<ClassType, ArgumentType>(data: ArgumentType): ClassType {
   let myObj: ClassType;
   myObj.foo(data);
   return myObj;
}

Thanks

Body:
Side note: code like let b: B; doesn't actually create an object of type B; at runtime, b will be undefined and you will have immediate problems trying to call its foo() method.  I am supposing/hoping that in your actual code you are actually constructing instances of B etc.  But that implies that you should be passing a class constructor to your createObject() function.  I'm ignoring that for the rest of the answer and will use your signature and implementation more or less as-is.  Be warned.

You can write your generic function like this:

function createObject<C extends { foo(a: A): void }, A>(data: A): C {
  let myObj: C = null!; // <-- this isn't initialized?
  myObj.foo(data);
  return myObj;
}

where we've used a generic constraint to tell the compiler that C will have a foo() method that takes an argument of type A.  You should then be able to call it:

declare const qt: QT;
const obj = createObject<Q, QT>(qt); // okay, type Q

Note that you are required here to manually specify the C and A type parameters when you call the function if you expect to see a strongly-typed output:

const oops = createObject(qt); //
// const oops: { foo(a: QT): void; }

If you want the compiler to infer the output type from the input type, then you need to give createObject() a call signature that tells the compiler every input-output mapping you care about:

type IOMap = [QT, Q] | [BT, B] // | ... | [ZT, Z];
type ClassType<A extends IOMap[0]> = Extract<IOMap, [A, any]>[1];

function createObject<A extends IOMap[0]>(data: A): ClassType<A>;
function createObject<C extends { foo(a: A): void }, A>(data: A): C {
  let myObj: C = null!; // <-- this isn't initialized?
  myObj.foo(data);
  return myObj;
}

That's a bit annoying to declare, but is easier to use:

const obj = createObject(qt); // okay
// const obj: Q

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAQgKlAvFA3lARgLigRigXwG4AoAYwBsBDAZ2tlWKigDMB7VgCgBNLhLt4ASlQFi+YhIo06ARQZM2nHn2wy4wtOPGhIUNUhEBHbHiJQJzAK4A7UsACWra1FIAnCLwgB5dACsIdgA8AMJQEAAewBDWXHRoihz8UACCgtgAbqz2XAQANCkAfNy8SanYoSiMUOQQwFAAtiA+vuUG1pbk5ACEhFAA9H1QgQC0w1DAABb2dNPWAOR19tb2DpTk9gBeEFwA-FWNzQB0CcqUgiRM7sCWrs4HfiTixFwBVO4uTtR1hsCqcCSkT51Vh+AxuDxRZoBYCBGT5NRFH7nfqDVgAa0oIGIAw+1i+UBBLT0kiBBNYYDoyHBnihdg4SJIOMBeOB5Oo2Hi7ESfzSUEy2V6T2slHqEGoYEopGgADEOuQALKUMBgJYAcwYVR00AAkl5FWADABtNTwgC6UAAPlBDfB8jBzTirYdnZbrQAtOD5N2mi7jcDQYJUWhwf2BZJhSLRWJQXX6w0ABlNBQMAFFIq5JTDY0r8obkvlKNYQEnDTgfRIFDY7I5nNTIX5oWGI1EYnRs2AE0niioUrzA9IQ5AwwVfVZbA4nC53DSG0FQhEW9HOZxSrz+Tl8PlkkVTtgylAKlUmDU6vciaFkO1Oj0UUNRuMpjNqPNFstVustrsjw0mn5jlzTnOb8rhuO5f18X0niYF4pHeZl8R+P5fXg4FQSpad638OkGVvdFMSqJlSUJVQJDEIA" rel="nofollow noreferrer">Playground link to code


问:
Separate dataframe lat/lon pairs and plot multiple figures based on column value
I have a dataframe of lat/lon pairs that form a polygon. The rows with 'GAP' and NaN's in the lat/lon columns are separators. So in this case I have 4 polygons with multiple lat/lon locations. My goal is to separate these polygons from each other and then plot using cartopy.

```<code>    0      1           2
0   POINT  87.6298     9.397332
1   POINT  87.8435     9.842206
2   POINT  87.2354     9.472004
4     GAP         NaN       NaN
5   POINT  87.8354     9.397332
6   POINT  87.9544     9.472004
7   POINT  87.9632     9.191509
8   POINT  87.6244     9.221509
9   POINT  87.4554     9.397332
10    GAP         NaN       NaN
11  POINT  87.6249     9.397332
12  POINT  87.7556     9.221509
13  POINT  87.5567     9.086767
14  POINT  87.3222     9.397332
15    GAP         NaN       NaN
16  POINT  87.6554     9.221509
17  POINT  87.9667     9.191509
18  POINT  87.8854     9.056767
19  POINT  87.4452     9.086767
</code>```

Assume that with any time this is run, the amount of polygons and amount of lat/lon pairs in each polygon can change.

Sample code below of the set up:

```<code>df = pd.read_excel(xl, sheet_name=0, header=None)
#change column names
df.rename(columns={1:'lon', 2:'lat'},inplace=True)
#replace GAP with nan so i can separate by group numbers with each line of nans (didnt work with 'GAP')
df.replace('GAP',np.nan, inplace=True)
df['group_no'] = df.isnull().all(axis=1).cumsum()
#define amount of unique numbers and put into list for looping
numbers = df['group_no'].unique()

aa = list(numbers)
</code>```

Here is where I get lost (area after set up and before plotting code) shown below.

```<code>a_lon, a_lat = 87.8544, 8.721576
b_lon, b_lat = 87.6554, 8.585951

fig,ax = plt.subplots()
plt.figure(figsize=(10.6,6))
proj = ccrs.PlateCarree()

ax = plt.axes(projection=proj)
ax.stock_img()
ax.set_extent([90, 85, 7, 11], crs=ccrs.PlateCarree())

proj = ccrs.Geodetic()
plt.plot([a_lon, b_lon], [a_lat, b_lat], linewidth=1, color='blue', transform=proj)
#plt.show()
</code>```

So as you can see, I replaced the 'GAP' with a NaN, then separated the rows by 'group_no', which is a new column. Then removed the Nan's. Resulting dataframe:

```<code>        0         lon       lat  group_no
0   POINT  87.6298     9.397332         0
1   POINT  87.8435     9.842206         0
2   POINT  87.2354     9.472004         0
4   POINT  87.8354     9.397332         1
5   POINT  87.9544     9.472004         1
6   POINT  87.9632     9.191509         1
7   POINT  87.6244     9.221509         1
8   POINT  87.4554     9.397332         1
10  POINT  87.6249     9.397332         2
11  POINT  87.7556     9.221509         2
12  POINT  87.5567     9.086767         2
13  POINT  87.3222     9.397332         2
15  POINT  87.6554     9.221509         3
16  POINT  87.9667     9.191509         3
17  POINT  87.8854     9.056767         3
18  POINT  87.4452     9.086767         3
</code>```

I've attempted a few things but can't seem to close the deal. I've tried separated them in a dictionary using group_by, key being the group_no, values being lat/lon pair, but I don't know dictionaries well enough to manipulate them and plot for each 'key'.

I also attempted to separate each into a new dataframe. Thinking I could loop through and create a df0, df1, etc. and then use a for loop to plot, but couldn't figure that out either.

Any help would be appreciated and please ask if further details are needed.

答:
You're almost there, if you call groupby on the group number you can just pull out each group and get the lat/lon pairs.  Make sure you have proper projections set up as well.</p>

```<code>from shapely.geometry import Polygon

for group_no,group_data in df.groupby('group_no'):
    poly_coords = group_data[['lon','lat']].values

    # Whatever function you are using to create shape with the 'poly_coords e.g.'
    polygon = Polygon(poly_coords)

    #add to map ...

</code>```

Body:
I have a dataframe of lat/lon pairs that form a polygon. The rows with 'GAP' and NaN's in the lat/lon columns are separators. So in this case I have 4 polygons with multiple lat/lon locations. My goal is to separate these polygons from each other and then plot using cartopy.

    0      1           2
0   POINT  87.6298     9.397332
1   POINT  87.8435     9.842206
2   POINT  87.2354     9.472004
4     GAP         NaN       NaN
5   POINT  87.8354     9.397332
6   POINT  87.9544     9.472004
7   POINT  87.9632     9.191509
8   POINT  87.6244     9.221509
9   POINT  87.4554     9.397332
10    GAP         NaN       NaN
11  POINT  87.6249     9.397332
12  POINT  87.7556     9.221509
13  POINT  87.5567     9.086767
14  POINT  87.3222     9.397332
15    GAP         NaN       NaN
16  POINT  87.6554     9.221509
17  POINT  87.9667     9.191509
18  POINT  87.8854     9.056767
19  POINT  87.4452     9.086767

Assume that with any time this is run, the amount of polygons and amount of lat/lon pairs in each polygon can change.

Sample code below of the set up:

df = pd.read_excel(xl, sheet_name=0, header=None)
#change column names
df.rename(columns={1:'lon', 2:'lat'},inplace=True)
#replace GAP with nan so i can separate by group numbers with each line of nans (didnt work with 'GAP')
df.replace('GAP',np.nan, inplace=True)
df['group_no'] = df.isnull().all(axis=1).cumsum()
#define amount of unique numbers and put into list for looping
numbers = df['group_no'].unique()

aa = list(numbers)

Here is where I get lost (area after set up and before plotting code) shown below.

a_lon, a_lat = 87.8544, 8.721576
b_lon, b_lat = 87.6554, 8.585951

fig,ax = plt.subplots()
plt.figure(figsize=(10.6,6))
proj = ccrs.PlateCarree()

ax = plt.axes(projection=proj)
ax.stock_img()
ax.set_extent([90, 85, 7, 11], crs=ccrs.PlateCarree())

proj = ccrs.Geodetic()
plt.plot([a_lon, b_lon], [a_lat, b_lat], linewidth=1, color='blue', transform=proj)
#plt.show()

So as you can see, I replaced the 'GAP' with a NaN, then separated the rows by 'group_no', which is a new column. Then removed the Nan's. Resulting dataframe:

        0         lon       lat  group_no
0   POINT  87.6298     9.397332         0
1   POINT  87.8435     9.842206         0
2   POINT  87.2354     9.472004         0
4   POINT  87.8354     9.397332         1
5   POINT  87.9544     9.472004         1
6   POINT  87.9632     9.191509         1
7   POINT  87.6244     9.221509         1
8   POINT  87.4554     9.397332         1
10  POINT  87.6249     9.397332         2
11  POINT  87.7556     9.221509         2
12  POINT  87.5567     9.086767         2
13  POINT  87.3222     9.397332         2
15  POINT  87.6554     9.221509         3
16  POINT  87.9667     9.191509         3
17  POINT  87.8854     9.056767         3
18  POINT  87.4452     9.086767         3

I've attempted a few things but can't seem to close the deal. I've tried separated them in a dictionary using group_by, key being the group_no, values being lat/lon pair, but I don't know dictionaries well enough to manipulate them and plot for each 'key'.

I also attempted to separate each into a new dataframe. Thinking I could loop through and create a df0, df1, etc. and then use a for loop to plot, but couldn't figure that out either.

Any help would be appreciated and please ask if further details are needed.

Body:
You're almost there, if you call groupby on the group number you can just pull out each group and get the lat/lon pairs.  Make sure you have proper projections set up as well.

from shapely.geometry import Polygon

for group_no,group_data in df.groupby('group_no'):
    poly_coords = group_data[['lon','lat']].values

    # Whatever function you are using to create shape with the 'poly_coords e.g.'
    polygon = Polygon(poly_coords)

    #add to map ...


问:
How to grab text values from getAllByTestId?
I have a component that lists a bunch of items. In this, they're cryptocurrency assets. When I click the header labelled Name, it sorts the items in alphabetical order. I would like to test this functionality by clicking the Name button in order to fire the event, and then asserting that the values in the name column are sorted alphabetically:

```<code>  it("Sorts by name on click", () => {
    const sortedByName = spotData
      .sort((a, b) => {
        return a.name < b.name ? -1 : a.name === b.name ? 0 : 1;
      })
      .map((ticker) => ticker.name);

    const { getByText, getAllByTestId } = renderWithProviders(
      <MarketSelectorPanel marketsList={spotData} />
    );

    fireEvent.click(getByText("Name"));
    expect(getAllByTestId("market-selector-row-name")).toEqual(
      sortedByName
    );
  });
</code>```

The above doesn't work because expect(getAllByTestId("market-selector-row-name")) grabs the entire HTML element:

● MarketSelectorPanel tables › Sorts by name on click

```<code>expect(received).toEqual(expected) // deep equality

- Expected
+ Received

  Array [
-   "BCH/USD",
-   "BTC/USD",
-   "ETH/USD",
+   <span
+     class="market-selector-row-val"
+     data-testid="market-selector-row-name"
+   >
+     BCH/USD
+   </span>,
+   <span
+     class="market-selector-row-val"
+     data-testid="market-selector-row-name"
+   >
+     BTC/USD
+   </span>,
+   <span
+     class="market-selector-row-val"
+     data-testid="market-selector-row-name"
+   >
+     ETH/USD
+   </span>
]
</code>```

答:
Solved using getNodeText:

```<code>const columnAfterClick = getAllByTestId("market-selector-row-name").map(getNodeText); // Contains array of text strings only now

expect(columnAfterClick).toEqual(sortedByName);
</code>```

Body:
I have a component that lists a bunch of items. In this, they're cryptocurrency assets. When I click the header labelled Name, it sorts the items in alphabetical order. I would like to test this functionality by clicking the Name button in order to fire the event, and then asserting that the values in the name column are sorted alphabetically:

  it("Sorts by name on click", () => {
    const sortedByName = spotData
      .sort((a, b) => {
        return a.name  ticker.name);

    const { getByText, getAllByTestId } = renderWithProviders(
      <MarketSelectorPanel marketsList={spotData} />
    );

    fireEvent.click(getByText("Name"));
    expect(getAllByTestId("market-selector-row-name")).toEqual(
      sortedByName
    );
  });

The above doesn't work because expect(getAllByTestId("market-selector-row-name")) grabs the entire HTML element:

● MarketSelectorPanel tables › Sorts by name on click

expect(received).toEqual(expected) // deep equality

- Expected
+ Received

  Array [
-   "BCH/USD",
-   "BTC/USD",
-   "ETH/USD",
+
+     BCH/USD
+   ,
+
+     BTC/USD
+   ,
+
+     ETH/USD
+
]

Body:
Solved using getNodeText:

const columnAfterClick = getAllByTestId("market-selector-row-name").map(getNodeText); // Contains array of text strings only now

expect(columnAfterClick).toEqual(sortedByName);


问:
where is data stored?
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
</code>```

model class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}
</code>```

view.cshtml

```<code>@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            name
        </th>
        <th>
            fname
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fname)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>
</code>```

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.

答: That logindata DBContext looks like it was created by Entity Framework. That's pointing to a database somewhere, and that database is where you'd go to find your data. You could look in web.config for a connection string that has the database info, or if your project has a .edmx file in it open that and see what its pointing at.</p>

ContentLicense: CC BY-SA 3.0

Title: where is data stored?

Body:
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

model class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}

view.cshtml

@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            name

            fname

@foreach (var item in Model) {

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

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

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

}

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.


答:
There are (probably) two BTrees involved in the queries you show.  One BTree for the data, sorted by the PRIMARY KEY, which I assume is id.  The other for the INDEX on user_id (again, I am guessing).  When InnoDB (which I assume you are using) builds a "secondary index", such as INDEX(user_id), it silently tacks on the PK of the table.  So, effectively it becomes a BTree containing two columns: (user_id, id) and sorted by that pair.

When the Optimizer looks at SELECT * FROM t WHERE user_id=?, it probed the table and discovered that "a lot" of rows had user_id = 1 and not many rows had the other values you tried.

The Optimizer has two (or more) ways to evaluate the queries like that --

Plan A (use the index):  Here's what it does:

Drill down the Index's BTree to find the first occurrence of user_id=2.

There it will find an id.

Use that id to drill down the data's BTree to find * (as in SELECT *).

Move on to the next entry in the Index BTree.  (This is actually rather efficient since it is really a "B+Tree"; see Wikipedia.)

If found, loop back to step 2.  If not found (no more index entries with user_id=2), exit.

Plan B (don't use the index -- useful for your user_id=1):

Simply walk through the data BTree in whatever order.

Skip any row that does not have user_id=1.

The bouncing back and forth between the two BTrees costs something.  The Optimizer decided your =1 case would need to look at more than about 20% of the table and decided that plan B would be faster.  That is, it deliberately ignored the INDEX.

There are a lot of factors that the Optimizer can't or doesn't estimate correctly, but generally picking between these two Plans leads to faster execution.  (Your table is too small to reliably measure a difference.)

Other "Plans" -- If the index is "covering", there is no need to use the data BTree.  If there is an ORDER BY that can be used, then the Optimizer will probably use Plan A to avoid the "filesort".  (See EXPLAIN SELECT ...)  Etc.

Title: Why does MySQL not always use index for select query?

Body:
I have two tables in my database users and articles.

Records in my users and articles table are given below:

+----+--------+
| id | name   |
+----+--------+
|  1 | user1  |
|  2 | user2  |
|  3 | user3  |
+----+--------+

+----+---------+----------+
| id | user_id | article  |
+----+---------+----------+
|  1 |       1 | article1 |
|  2 |       1 | article2 |
|  3 |       1 | article3 |
|  4 |       2 | article4 |
|  5 |       2 | article5 |
|  6 |       3 | article6 |
+----+---------+----------+

Given below the queries and the respected EXPLAIN output.

EXPLAIN SELECT * FROM articles WHERE user_id = 1;

+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | articles | NULL       | ALL  | user_id       | NULL | NULL    | NULL |    6 |    50.00 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+

EXPLAIN SELECT * FROM articles WHERE user_id = 2;
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table    | partitions | type | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | articles | NULL       | ref  | user_id       | user_id | 5       | const |    2 |   100.00 | NULL  |
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+

EXPLAIN SELECT * FROM articles WHERE user_id = 3;
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table    | partitions | type | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | articles | NULL       | ref  | user_id       | user_id | 5       | const |    1 |   100.00 | NULL  |
+----+-------------+----------+------------+------+---------------+---------+---------+-------+------+----------+-------+

Looking at the EXPLAIN plans for my select queries, it seems that queries are not always using the indexes.

In case,

when user_id is 1, it doesn't use the key and scans the complete table.

otherwise, it uses the user_id key and scans only few rows.

Could you please explain why queries don't always use the index here?


问:
How can I clone an Object (deep copy) in Dart?
Is there a Language supported way to make a full (deep) copy of an Object in Dart?

If multiple options exist, what are their differences?

答:
To copy an object without reference, the solution I found was similar to the one posted here, however if the object contains MAP or LIST you have to do it this way:

```<code>class Item {
  int id;
  String nome;
  String email;
  bool logado;
  Map mapa;
  List lista;
  Item({this.id, this.nome, this.email, this.logado, this.mapa, this.lista});

  Item copyWith({ int id, String nome, String email, bool logado, Map mapa, List lista }) {
    return Item(
      id: id ?? this.id,
      nome: nome ?? this.nome,
      email: email ?? this.email,
      logado: logado ?? this.logado,
      mapa: mapa ?? Map.from(this.mapa ?? {}),
      lista: lista ?? List.from(this.lista ?? []),
    );
  }
}
</code>```

```<code>Item item1 = Item(
    id: 1,
    nome: 'João Silva',
    email: 'joaosilva@gmail.com',
    logado: true,
    mapa: {
      'chave1': 'valor1',
      'chave2': 'valor2',
    },
    lista: ['1', '2'],
  );

// -----------------
// copy and change data
Item item2 = item1.copyWith(
    id: 2,
    nome: 'Pedro de Nobrega',
    lista: ['4', '5', '6', '7', '8']
  );

// -----------------
// copy and not change data
Item item3 = item1.copyWith();

// -----------------
// copy and change a specific key of Map or List
Item item4 = item1.copyWith();
item4.mapa['chave2'] = 'valor2New';

</code>```

See an example on dartpad

https://dartpad.dev/f114ef18700a41a3aa04a4837c13c70e

Body:
To copy an object without reference, the solution I found was similar to the one posted here, however if the object contains MAP or LIST you have to do it this way:

class Item {
  int id;
  String nome;
  String email;
  bool logado;
  Map mapa;
  List lista;
  Item({this.id, this.nome, this.email, this.logado, this.mapa, this.lista});

  Item copyWith({ int id, String nome, String email, bool logado, Map mapa, List lista }) {
    return Item(
      id: id ?? this.id,
      nome: nome ?? this.nome,
      email: email ?? this.email,
      logado: logado ?? this.logado,
      mapa: mapa ?? Map.from(this.mapa ?? {}),
      lista: lista ?? List.from(this.lista ?? []),
    );
  }
}

Item item1 = Item(
    id: 1,
    nome: 'João Silva',
    email: 'joaosilva@gmail.com',
    logado: true,
    mapa: {
      'chave1': 'valor1',
      'chave2': 'valor2',
    },
    lista: ['1', '2'],
  );

// -----------------
// copy and change data
Item item2 = item1.copyWith(
    id: 2,
    nome: 'Pedro de Nobrega',
    lista: ['4', '5', '6', '7', '8']
  );

// -----------------
// copy and not change data
Item item3 = item1.copyWith();

// -----------------
// copy and change a specific key of Map or List
Item item4 = item1.copyWith();
item4.mapa['chave2'] = 'valor2New';

See an example on dartpad

https://dartpad.dev/f114ef18700a41a3aa04a4837c13c70e


问:
issues with CNN to make predictions in video frames
```<code>import cv2
import numpy as np
import tensorflow as tf

model = tf.keras.models.load_model("oneptwoside.model")
CATEGORIES = ["front", "back"]
cap = cv2.VideoCapture(0)

if cap.isOpened():
    ret, frame = cap.read()
else:
        ret = False

while ret:
       ret, frame = cap.read()
       gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
       cv2.imshow('frame',gray)
       IMG_SIZE = 200
       img_array = cv2.imread(frame, cv2.IMREAD_GRAYSCALE)
       new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
       prediction = model.predict([img_array])
       print(prediction)
       print(CATEGORIES[int(prediction[0][0])])
       if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
</code>```

<p>I cant make predictions with my webcam. I try the same code in image it's working fine with a little bit of tweak. However in video is always not reading the frame or some resizing issue </p>

答:
```<code>if cap.isOpened():
    ret, frame = cap.read()
else:
        ret = False

while ret:
       curr_time = time.time()
       ret, frame = cap.read()
       gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

       curTime = time.time()
       sec = curTime - prevTime
       prevTime = curTime

       fps = 1/(sec)

       str = "FPS : %0.1f" % fps

       cv2.putText(frame, str, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 150, 0))
       cv2.imshow('frame',gray)
       cv2.imshow('color', frame)
       if curr_time - last_recorded_time >= 0.0001:

          last_recorded_time = curr_time

          IMG_SIZE = 200
          #img_array = cv2.imread('frame', cv2.IMREAD_GRAYSCALE)
          frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
          frame = cv2.resize(frame, (IMG_SIZE, IMG_SIZE))
          #frame = frame[np.newaxis, ...]
          frame = frame.reshape((-1, 200, 200, 1))
          cv2.rectangle(frame,(200,0),(150,128),(0,255,0),3)
          prediction = model.predict([frame])
          #prediction = model.predict([frame])
          print(prediction)
          print(CATEGORIES[int(prediction[0][0])])

          if cv2.waitKey(1) & 0xFF == ord('q'):
           break
</code>```

here is a solution not ideal but it's working

Body:
import cv2
import numpy as np
import tensorflow as tf

model = tf.keras.models.load_model("oneptwoside.model")
CATEGORIES = ["front", "back"]
cap = cv2.VideoCapture(0)

if cap.isOpened():
    ret, frame = cap.read()
else:
        ret = False

while ret:
       ret, frame = cap.read()
       gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
       cv2.imshow('frame',gray)
       IMG_SIZE = 200
       img_array = cv2.imread(frame, cv2.IMREAD_GRAYSCALE)
       new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
       prediction = model.predict([img_array])
       print(prediction)
       print(CATEGORIES[int(prediction[0][0])])
       if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

I cant make predictions with my webcam. I try the same code in image it's working fine with a little bit of tweak. However in video is always not reading the frame or some resizing issue

Body:
if cap.isOpened():
    ret, frame = cap.read()
else:
        ret = False

while ret:
       curr_time = time.time()
       ret, frame = cap.read()
       gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

       curTime = time.time()
       sec = curTime - prevTime
       prevTime = curTime

       fps = 1/(sec)

       str = "FPS : %0.1f" % fps

       cv2.putText(frame, str, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 150, 0))
       cv2.imshow('frame',gray)
       cv2.imshow('color', frame)
       if curr_time - last_recorded_time >= 0.0001:

          last_recorded_time = curr_time

          IMG_SIZE = 200
          #img_array = cv2.imread('frame', cv2.IMREAD_GRAYSCALE)
          frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
          frame = cv2.resize(frame, (IMG_SIZE, IMG_SIZE))
          #frame = frame[np.newaxis, ...]
          frame = frame.reshape((-1, 200, 200, 1))
          cv2.rectangle(frame,(200,0),(150,128),(0,255,0),3)
          prediction = model.predict([frame])
          #prediction = model.predict([frame])
          print(prediction)
          print(CATEGORIES[int(prediction[0][0])])

          if cv2.waitKey(1) & 0xFF == ord('q'):
           break

here is a solution not ideal but it's working


问:
Issue with add method in tensorflow : AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'
```<code>import keras as K
from keras.models import Sequential
from keras.layers import Dense
from tensorflow import set_random_seed

for hidden_neuron in hidden_neurons:
  model = Sequential()
</code>```

model.add(Dense(hidden_neuron, input_dim=61, activation='relu'))

-> i am getting error at this line. I am not really sure what am i missing here.

Traceback (most recent call last):

File "PycharmProjects/HW2/venv/bin/hw3q4.py", line 46, in
      model.add(Dense(hidden_neuron, input_dim=61, activation='relu'))   File
  "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/sequential.py",
  line 165, in add
      layer(x)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/base_layer.py",
  line 414, in call
      self.assert_input_compatibility(inputs)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/base_layer.py",
  line 279, in assert_input_compatibility
      K.is_keras_tensor(x)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py",
  line 472, in is_keras_tensor
      if not is_tensor(x):   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py",
  line 480, in is_tensor
      return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)
  AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'

答:
For me, the fix was importing

```<code>from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense
</code>```

instead of

```<code>from keras import Sequential
from keras.layers import Conv2D, Flatten, Dense
</code>```

There seems to be some weird compatibility issues between keras and tensorflow.keras

Body:
import keras as K
from keras.models import Sequential
from keras.layers import Dense
from tensorflow import set_random_seed

for hidden_neuron in hidden_neurons:
  model = Sequential()

model.add(Dense(hidden_neuron, input_dim=61, activation='relu'))

-> i am getting error at this line. I am not really sure what am i missing here.

Traceback (most recent call last):

File "PycharmProjects/HW2/venv/bin/hw3q4.py", line 46, in
      model.add(Dense(hidden_neuron, input_dim=61, activation='relu'))   File
  "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/sequential.py",
  line 165, in add
      layer(x)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/base_layer.py",
  line 414, in call
      self.assert_input_compatibility(inputs)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/base_layer.py",
  line 279, in assert_input_compatibility
      K.is_keras_tensor(x)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py",
  line 472, in is_keras_tensor
      if not is_tensor(x):   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py",
  line 480, in is_tensor
      return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)
  AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'

Body:
For me, the fix was importing

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense

instead of

from keras import Sequential
from keras.layers import Conv2D, Flatten, Dense

There seems to be some weird compatibility issues between keras and tensorflow.keras


问:
Setting up session using CAS
I'm working on integrating CAS in a legacy Java application. It's looking promising at the moment but I'm a bit confused as to where to handle the 'on-login' logic. The app relies on certain session variables being set when the user logs in. How can I handle this in my application?

i.e. User A has logs into client app A and decides he wants to do something in client B.

Since he's authenticated in client A, he is automatically authenticated and logged into client B. Since he wasn't logged into client B before (i.e. this is a new session) some house-keeping tasks need to take place. I'm a bit confused as to how and where I can take care of these tasks?

答: The way to do this (or at the least the way I approached it) would be within a filter that is run after the CAS has completed.</p>

Title: Setting up session using CAS


问:
'Schema class name does not revalidate' error when trying to add a class to parse
I'm trying to save a class to parse. However, when I do that it gives me the error 'schema class name does not revalidate'. How do I handle this?

I've already tried to change the name of the class, but even then it does not work. I'm a beginner when it comes to parse.

```<code>let myPost = PFObject(className: textField.text!)
            myPost["Name"] = textField.text!
            myPost["Notes"] = Note.text
            myPost["memberNumber"] = Int(stepper.value)
            myPost["members"] = "\((Auth.auth().currentUser?.uid)!):\((Auth.auth().currentUser?.email)!)'"
            myPost.saveInBackground { (successful, error) in
                if successful {
                   NSLog("Event Saved")
                }
                else {
                    NSLog("Save failed")
                    print(error)
                }
</code>```

It should save, but it doesn't for some reason.

答:
i think the issue has to do with your class name i had the same error the class name should  be in a string without space  or any other symbols i.e "Username" not "User name" or "user name ?"

i hope this helps.

Body:
I'm trying to save a class to parse. However, when I do that it gives me the error 'schema class name does not revalidate'. How do I handle this?

I've already tried to change the name of the class, but even then it does not work. I'm a beginner when it comes to parse.

let myPost = PFObject(className: textField.text!)
            myPost["Name"] = textField.text!
            myPost["Notes"] = Note.text
            myPost["memberNumber"] = Int(stepper.value)
            myPost["members"] = "\((Auth.auth().currentUser?.uid)!):\((Auth.auth().currentUser?.email)!)'"
            myPost.saveInBackground { (successful, error) in
                if successful {
                   NSLog("Event Saved")
                }
                else {
                    NSLog("Save failed")
                    print(error)
                }

It should save, but it doesn't for some reason.


问:
How to define a generic type that is a string field of another type?
Is it possible to define a type that is a name of another's type field but only if the field is a string?</p>

```<code>interface Person {
    name: string;
    age: number;
}

type StringField<T> = keyof T & T[keyof T]: string; // This doesn't work. What should I put here?

function f<T>(obj: T, field: StringField<T>) {
    return obj[field].length;
}

f<Person>({name: "Bill", age: 42}, "name"); // This should work
f<Person>({name: "Bill", age: 42}, "age"); // This should return an error at compile time
</code>```

答:
I would write your code like this:

```<code>type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

interface Person {
  name: string;
  age: number;
}

function f<T>(obj: T, field: KeysMatching<T, string>): number;
function f<K extends PropertyKey>(obj: Record<K, string>, field: K) {
  return obj[field].length;
}

f<Person>({ name: "Bill", age: 42 }, "name"); // This should work
f<Person>({ name: "Bill", age: 42 }, "age"); // This should return an error at compile time
</code>```

This question is almost certainly a duplicate though; I'm looking for an existing question/answer pair to point you to for an explanation.

Ah, here it is: TypeScript: Accept all Object keys that map to a specific type

Body:
Is it possible to define a type that is a name of another's type field but only if the field is a string?

interface Person {
    name: string;
    age: number;
}

type StringField<T> = keyof T & T[keyof T]: string; // This doesn't work. What should I put here?

function f<T>(obj: T, field: StringField<T>) {
    return obj[field].length;
}

f<Person>({name: "Bill", age: 42}, "name"); // This should work
f<Person>({name: "Bill", age: 42}, "age"); // This should return an error at compile time

Body:
I would write your code like this:

type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

interface Person {
  name: string;
  age: number;
}

function f<T>(obj: T, field: KeysMatching<T, string>): number;
function f<K extends PropertyKey>(obj: Record<K, string>, field: K) {
  return obj[field].length;
}

f<Person>({ name: "Bill", age: 42 }, "name"); // This should work
f<Person>({ name: "Bill", age: 42 }, "age"); // This should return an error at compile time

This question is almost certainly a duplicate though; I'm looking for an existing question/answer pair to point you to for an explanation.

Ah, here it is: TypeScript: Accept all Object keys that map to a specific type


问:
Object property called with dot notation showing console.log 'undefined'
fairly new to Javascript.

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as ‘undefined’ but when put in a function it works fine. Why does it show undefined with just the console log? Why doesn't it get displayed and why does it need a function to do so.

Here’s the code.

```<code>var toDoList = {
// Holding the List
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}
</code>```

This will display it as ‘undefined’ when I try to access the object property displayMyList with dot notation. However when a method is used it displays the list fine. I am wondering why is that?

```<code> var toDoList = {
    // Holding the List
    myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
    // Displaying the List
    displayMyList: function(){
  console.log(this.myList)
}
    }
</code>```

答:
You'll want to use an object method to log your list

var toDoList = {
  // Holding the List
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList() { console.log(this.myList) },
}

toDoList.displayMyList()```

Body:
fairly new to Javascript.

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as ‘undefined’ but when put in a function it works fine. Why does it show undefined with just the console log? Why doesn't it get displayed and why does it need a function to do so.

Here’s the code.

var toDoList = {
// Holding the List
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}

This will display it as ‘undefined’ when I try to access the object property displayMyList with dot notation. However when a method is used it displays the list fine. I am wondering why is that?

 var toDoList = {
    // Holding the List
    myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
    // Displaying the List
    displayMyList: function(){
  console.log(this.myList)
}
    }


答:
You could use defaultdict to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).

Possible implementation:

# Test Data
from collections import defaultdict

sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89),
              ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85),
              ('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2), ('2020/04/19', 6), ('2020/04/26', 5),
              ('2020/05/03', 14),
              ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28)]

results = defaultdict(int)
for date, count in sum_weekly: # used unpacking to make it clearer
    month = date.split('/')[1]
    # because we use a defaultdict if the key does not exist it
    # the entry for the key will be created and initialize at zero
    results[month] += count

print(results)
```

Title: Group items in a list and calculate sums

Body:
I have a list with weekly figures and need to obtain the grouped totals by month.

The following code does the job, but there should be a more pythonic way of doing it with using the  standard libraries.
The drawback of the code below is that the list needs to be in sorted order.

#Test data (not sorted)
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89),
 ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85),
  ('2020/04/19', 6), ('2020/04/26', 5), ('2020/05/03', 14),
 ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28),('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2),]

month = sum_weekly[0][0].split('/')[1]
count=0
out=[]
for item in sum_weekly:
    m_sel = item[0].split('/')[1]
    if m_sel!=month:
        out.append((month, count))
        count=item[1]
    else:
        count+=item[1]
    month = m_sel
out.append((month, count))

# monthly sums output as ('01', 242), ('02', 360), ('03', 220), ('04', 13), ('05', 67)
print (out)


答:
Repurposed from How can I extract the names of all fields of a specific type from an interface in Typescript?

```<code>export interface Person {
  name: string;
  age: number;
}

type ExtractFieldsOfType<O, T> = {
    [K in keyof O]: O[K] extends T ? K : never
}[keyof O];

type StringField<T> = ExtractFieldsOfType<T, string>

function f<T>(obj: T, field: StringField<T>) {
    // Your logic here
}

let person: Person = {
    name: "Bill",
    age: 42,
};

f<Person>({name: "Bill", age: 42}, "name"); // This works
f<Person>({name: "Bill", age: 42}, "age"); // This errors out
</code>```

Used types from this question

Title: How to define a generic type that is a string field of another type?

Body:
Repurposed from How can I extract the names of all fields of a specific type from an interface in Typescript?

export interface Person {
  name: string;
  age: number;
}

type ExtractFieldsOfType<O, T> = {
    [K in keyof O]: O[K] extends T ? K : never
}[keyof O];

type StringField<T> = ExtractFieldsOfType<T, string>

function f<T>(obj: T, field: StringField<T>) {
    // Your logic here
}

let person: Person = {
    name: "Bill",
    age: 42,
};

f<Person>({name: "Bill", age: 42}, "name"); // This works
f<Person>({name: "Bill", age: 42}, "age"); // This errors out

Used types from this question


问:
Possible to call stateful function in a class in Python?
Is it possible to directly set a certain value and get it in a class by any mean(inheritance, metaclass, class decorator) in Python? class B must not be polluted by set('a') in A.

import sys

class A:
    set('a')
    get()
    # -> 'a'

    print(sys.modules[__name__])
    # => <module '__main__'>

class B:
    get()
    # -> None
```

答:
Assuming you know what you are doing, yes, it is possible to set values with programmatic names in a class body, and retrieve then, and have these values restricted to that class body.

All you have to do is to use thelocals() call to get the namespace dictionary, and use that dictionary to hold your values:

class A:
    locals()["key"] = "a"
    print(locals()["key"] )
```

<p>This will print "a",
and obviously, this value won't be part of a class B namespace.</p>

<p>If you want just to store values without associating then
with a name, the <code>stackfull</code> project provide a
<code>push</code> and <code>pop</code> calls that will behave just like
you proposed in your example -
but if you try  a <code>pop()</code> withour a previous <code>push</code>
in the same scope, you will get an error due to
a stack underflow:</p>

<pre class="lang-py prettyprint-override"><code>
In [4]: !pip install stackfull
Collecting stackfull
...
Successfully installed stackfull-1.0.0

In [5]: from stackfull import push, pop

In [6]: class A:
   ...:     push("a")
   ...:     push("b")
   ...:     print(pop())
   ...:     print(pop())
   ...:
b
a
In [7]: class B:
   ...:     pop()
   ...:
...
StackUnderflowError:
</code>```

(Disclaimer -  I am the author of the stackfull package. I never really needed
anything beyond what is already there, so it  has not been updated in a long time - and with the "walrus" operator in Python 3.8, it is no longer that useful)

Ok - so I listed this because it resembles the code in your question, but chances are you need something more mainstream, like writing your code in methods, and set instance attributes.

Body:
Assuming you know what you are doing, yes, it is possible to set values with programmatic names in a class body, and retrieve then, and have these values restricted to that class body.

All you have to do is to use thelocals() call to get the namespace dictionary, and use that dictionary to hold your values:

class A:
    locals()["key"] = "a"
    print(locals()["key"] )

This will print "a",
and obviously, this value won't be part of a class B namespace.

If you want just to store values without associating then
with a name, the stackfull project provide a
push and pop calls that will behave just like
you proposed in your example -
but if you try  a pop() withour a previous push
in the same scope, you will get an error due to
a stack underflow:

In [4]: !pip install stackfull
Collecting stackfull
...
Successfully installed stackfull-1.0.0

In [5]: from stackfull import push, pop

In [6]: class A:
   ...:     push("a")
   ...:     push("b")
   ...:     print(pop())
   ...:     print(pop())
   ...:
b
a
In [7]: class B:
   ...:     pop()
   ...:
...
StackUnderflowError:

(Disclaimer -  I am the author of the stackfull package. I never really needed
anything beyond what is already there, so it  has not been updated in a long time - and with the "walrus" operator in Python 3.8, it is no longer that useful)

Ok - so I listed this because it resembles the code in your question, but chances are you need something more mainstream, like writing your code in methods, and set instance attributes.


问:
unrecognized data type error in phpmyadmin
when i do this :

```<code>CREATE TABLE new_table AS SELECT id, name FROM users;
</code>```

it works but when i try to change the columns names while doing so by typing this line

```<code>CREATE TABLE new_table (user_id, user_name) AS SELECT id, name FROM users;
</code>```

this error shows

```<code>Static analysis:

2 errors were found during analysis.

Unrecognized data type. (near "," at position 36)
A comma or a closing bracket was expected. (near "user_name" at position 38)
</code>```

i tried it with different tables but the same error occurs, looked it up and found that my code is correct so what could be the problem ?

答:
The create table statement requires column types.  Something like:

```<code>CREATE TABLE new_table (user_id int, user_name varchar(255)) AS
    SELECT id, name FROM users;
</code>```

Here is a db<>fiddle.

Or, alternatively, change the names in the SELECT:

```<code>CREATE TABLE new_table AS
    SELECT id as user_id, name as user_name
    FROM users;
</code>```

Body:
when i do this :

CREATE TABLE new_table AS SELECT id, name FROM users;

it works but when i try to change the columns names while doing so by typing this line

CREATE TABLE new_table (user_id, user_name) AS SELECT id, name FROM users;

this error shows

Static analysis:

2 errors were found during analysis.

Unrecognized data type. (near "," at position 36)
A comma or a closing bracket was expected. (near "user_name" at position 38)

i tried it with different tables but the same error occurs, looked it up and found that my code is correct so what could be the problem ?

Body:
The create table statement requires column types.  Something like:

CREATE TABLE new_table (user_id int, user_name varchar(255)) AS
    SELECT id, name FROM users;

Here is a db<>fiddle.

Or, alternatively, change the names in the SELECT:

CREATE TABLE new_table AS
    SELECT id as user_id, name as user_name
    FROM users;


问:
creating a chart.js scatter graph with variables for data
I am writing a program that will eventually generate a graph based on user input. so I've created a proof of concept that should click a button and make a chart.js scatter graph my issue is that the data is not included for some reason not sure why.

```<code><html>

<head>
<title>Test1</title>

<script src="Chart.min.js"></script>
</head>
<body>

<button onmousedown="addData()"></button>

<script>
function addData(){
    ABC=[[1,2,1],[2,2,2],[3,3,3]];
    chart(ABC);
}

function chart(array)
{
    for (counter = 0; counter < array.length; counter++)
    {
        var entery = {x: array[counter][0], y: array[counter][3]};
        storage.push(entery);
    }

    document.write('<canvas id="lineChart" height="200" width="450"></canvas>');

    const chart=document.getElementById("lineChart");
    console.log(chart)
    var myChart = new Chart(chart, {
        type: 'scatter',
        data: {
            datasets: [{
                "fill":false,
                pointRadius: 10,
                label: 'Scatter Dataset',
                data: storage
                }]

        },
        options: {
            scales: {
                xAxes: [{
                    type: 'linear',
                }]
            }
        }
    });

}
</script>

</body>
</html>
</code>```

I cannot work out why the data is not included any help would be appreciated

答:
You have some issues with setting up your code:

You have not defined storage array

console.log(chart) throws an error, you have to comment that line out or remove it

The elements in your ABC array does not have 4 elements(arrays are 0 indexed and
your last index will be 2 not 3)
So this line var entery = {x: array[counter][0], y: array[counter][3]}; should be changed to var entery = {x: array[counter][0], y: array[counter][2]};

So, your code should look like this:

```<code><html>

<head>
    <title>Test1</title>
    <script src="Chart.min.js"></script>
</head>
<body>
    <button onclick="addData();">Test</button>

    <script type="text/javascript">
        function addData(){
            ABC=[[1,2,1],[2,2,2],[3,3,3]];
            chart(ABC);
        }

        function chart(array)
        {
            var storage = [];
            for (counter = 0; counter < array.length; counter++)
            {
                var entery = {x: array[counter][0], y: array[counter][2]};
                storage.push(entery);
            }

            document.write('<canvas id="lineChart" height="200" width="450"></canvas>');

            const chart = document.getElementById("lineChart");
            //console.log(chart)
            var myChart = new Chart(chart, {
                type: 'scatter',
                data: {
                    datasets: [{
                        "fill":false,
                        pointRadius: 10,
                        label: 'Scatter Dataset',
                        data: storage
                        }]
                },
                options: {
                    scales: {
                        xAxes: [{
                            type: 'linear',
                        }]
                    }
                }
            });
        }
    </script>
</body>
</html>
</code>```

Also here you can find a working copy of the chart.

Body:
I am writing a program that will eventually generate a graph based on user input. so I've created a proof of concept that should click a button and make a chart.js scatter graph my issue is that the data is not included for some reason not sure why.

<title>Test1</title>

<button onmousedown="addData()"></button>

I cannot work out why the data is not included any help would be appreciated

Body:
You have some issues with setting up your code:

You have not defined storage array

console.log(chart) throws an error, you have to comment that line out or remove it

The elements in your ABC array does not have 4 elements(arrays are 0 indexed and
your last index will be 2 not 3)
So this line var entery = {x: array[counter][0], y: array[counter][3]}; should be changed to var entery = {x: array[counter][0], y: array[counter][2]};

So, your code should look like this:

<html>

<head>
    <title>Test1</title>
    <script src="Chart.min.js"></script>
</head>
<body>
    <button onclick="addData();">Test</button>

    <script type="text/javascript">
        function addData(){
            ABC=[[1,2,1],[2,2,2],[3,3,3]];
            chart(ABC);
        }

        function chart(array)
        {
            var storage = [];
            for (counter = 0; counter < array.length; counter++)
            {
                var entery = {x: array[counter][0], y: array[counter][2]};
                storage.push(entery);
            }

            document.write('<canvas id="lineChart" height="200" width="450"></canvas>');

            const chart = document.getElementById("lineChart");
            //console.log(chart)
            var myChart = new Chart(chart, {
                type: 'scatter',
                data: {
                    datasets: [{
                        "fill":false,
                        pointRadius: 10,
                        label: 'Scatter Dataset',
                        data: storage
                        }]
                },
                options: {
                    scales: {
                        xAxes: [{
                            type: 'linear',
                        }]
                    }
                }
            });
        }
    </script>
</body>
</html>

Also here you can find a working copy of the chart.


问:
c++ error: "array must be initialized with a brace-enclosed initializer"
i need your help with this.
my function is: (the way it works is true)

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

#define V 4
#define INF 999
int floydWarshall(int graph[][V]){

        int dist[V][V], i, j, k;

        for (i = 0; i < V; i++)
            for (j = 0; j < V; j++)
                dist[i][j] = graph[i][j];

        for (k = 0; k < V; k++)
        {

            for (i = 0; i < V; i++)
            {

                for (j = 0; j < V; j++)
                {

                    if (dist[i][k] + dist[k][j] < dist[i][j])
                        dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }

        return dist[V][V];
    }
</code>```

and this line has the error array must be initialized with a brace-enclosed initializer:

```<code>int dist[V][V] = floydWarshall(graph[][V]);
</code>```

答:
You can't use C arrays like other variables or objects in many cases. You can't pass a C array by value to a function or return a C array from a function. It will decay to a pointer to the first element. Therefore std::array was introduced in C++. It does exactly what you expected from C arrays in your code:

```<code>#include <array>

constexpr int V = 4;

auto floydWarshall(std::array<std::array<int, V>, V> graph){
    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (graph[i][k] + graph[k][j] < graph[i][j])
                    graph[i][j] = graph[i][k] + graph[k][j];
            }
        }
    }
    return graph;
}
</code>```

With std::array you can pass a copy of the array to the function and don't need to copy it manually. You can return a copy of the array instead of using dynamic memory allocation and pointers.

You use the function with

```<code>auto dist = floydWarshall(graph);
</code>```

where graph has type std::array<std::array<int, V>, V>.

Body:
i need your help with this.
my function is: (the way it works is true)

#include <iostream>
using namespace std;

#define V 4
#define INF 999
int floydWarshall(int graph[][V]){

        int dist[V][V], i, j, k;

        for (i = 0; i < V; i++)
            for (j = 0; j < V; j++)
                dist[i][j] = graph[i][j];

        for (k = 0; k < V; k++)
        {

            for (i = 0; i < V; i++)
            {

                for (j = 0; j < V; j++)
                {

                    if (dist[i][k] + dist[k][j] < dist[i][j])
                        dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }

        return dist[V][V];
    }

and this line has the error array must be initialized with a brace-enclosed initializer:

int dist[V][V] = floydWarshall(graph[][V]);

Body:
You can't use C arrays like other variables or objects in many cases. You can't pass a C array by value to a function or return a C array from a function. It will decay to a pointer to the first element. Therefore std::array was introduced in C++. It does exactly what you expected from C arrays in your code:

#include <array>

constexpr int V = 4;

auto floydWarshall(std::array<std::array<int, V>, V> graph){
    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (graph[i][k] + graph[k][j] < graph[i][j])
                    graph[i][j] = graph[i][k] + graph[k][j];
            }
        }
    }
    return graph;
}

With std::array you can pass a copy of the array to the function and don't need to copy it manually. You can return a copy of the array instead of using dynamic memory allocation and pointers.

You use the function with

auto dist = floydWarshall(graph);

where graph has type std::array<std::array<int, V>, V>.


问:
how to combine two selectors?
in my example http://jsfiddle.net/radek/HnXC4/2/ I defined jQuery handler for click

on button

that have a class run

via $(":button, .run").click(function(){

how come the this button should NOT work button's clicked is fired too? It doesn't have class "run".

答:
You don't need the comma in between:</p>

```<code>$(":button.run").click(function(){};
</code>```

Title: how to combine two selectors?

Body:
You don't need the comma in between:

$(":button.run").click(function(){};


问:
I want to open a file for reading in the constructor. The file should be readable in any method without creating another reader object
The constructor opens a file for reading. I have a method called getNext() which returns the next line of the file in a String array. However it says that the BufferedReader object in already created in the constructor cannot be found
import java.io.;
import java.util.;

```<code>public class SNIDDb
{
  private char delimiter;
  private String name;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      BufferedReader br= new BufferReader(fr);
    }
    catch(Exception e)
    {
      System.out.print(e.getMessage());
    }
  }

  public Boolean hasNext() throws Exception
  {
    return !(br.readLine()==null);
  }

  public String[] getNext() throws Exception
  {
    String c_line="";
    c_line=br.readLine();
    String[] n_line=c_line.split(delimiter);
    return n_line;
  }

  public void rewrite() throws Exception
  {
    br.close();
    BufferedWriter writer = new BufferedWriter(new FileWriter(name));
  }
</code>```

答: br is a local variable only available for use inside the constructor. You should make it an instance member variable like delimiter and name.

Body:
The constructor opens a file for reading. I have a method called getNext() which returns the next line of the file in a String array. However it says that the BufferedReader object in already created in the constructor cannot be found
import java.io.;
import java.util.;

public class SNIDDb
{
  private char delimiter;
  private String name;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      BufferedReader br= new BufferReader(fr);
    }
    catch(Exception e)
    {
      System.out.print(e.getMessage());
    }
  }

  public Boolean hasNext() throws Exception
  {
    return !(br.readLine()==null);
  }

  public String[] getNext() throws Exception
  {
    String c_line="";
    c_line=br.readLine();
    String[] n_line=c_line.split(delimiter);
    return n_line;
  }

  public void rewrite() throws Exception
  {
    br.close();
    BufferedWriter writer = new BufferedWriter(new FileWriter(name));
  }


问:
Notepad++ - Find duplicate lines by first word
I've been searching on the internet to solve my problem and read through several Stack Overflow topics but I can't get it working.

So I have multiple files with translations. Each line contains one translation with a translation key in front of it.
The key is split from the translated phrase with a :. There can be multiple underscores in the key but no space. Each key has to be unique even if the translation phrase is different.

This is a small example how these files look:

```<code>CONFIRM: Conferma
FOR: per
YOU_WILL_RECEIVE: Riceverai
ENCHANTED: Incantato
ITEMS_AVAILABLE: Prodotti disponibili
CONTINUE: Continua
MONEY_PAID: Money Paid
GUI_OVERVIEW_OPENSHOPS_ACTION: Clicca per aprire i negozi
GUI_OVERVIEW_OPENSETTINGS_ACTION: Clicca per aprire le impostazioni
GUI_SHOPSETTINGS_BUY_LEFTACTION: **Tasto Sinistro** per **cambiare** il prezzo d'acquisto
GUI_SHOPSETTINGS_BUY_QACTION: **Premi Q** per disabilitare l'acquisto
ENCHANTED: Incantato premituro
GUI_SHOPSETTINGS_BUY_OTHERACTION: **Clicca** per abilitare l'**acquisto**
</code>```

In this example the ENCHANTED key is duplicate even these keys have different translation phrases. I just want to see that this key is duplicated.

My plan is to match all these lines with a regex pattern with the help of notepad++ but if it's easier for you, it would also be okay if I have to use a script. Something like Batch or even a little NodeJS application.

答:
In notepad++ you can use this regex to find the first occurrence of any key which is duplicated:

```<code>^(\w+):(?=.*\R\1:)
</code>```

It looks for a sequence of word characters between the start of a line and a :, captured in group 1 and then asserts a positive lookahead for the same string starting a line again (\R matches a newline/crlf character). Note you need to have the . matches newline checkbox selected.

Body:
I've been searching on the internet to solve my problem and read through several Stack Overflow topics but I can't get it working.

So I have multiple files with translations. Each line contains one translation with a translation key in front of it.
The key is split from the translated phrase with a :. There can be multiple underscores in the key but no space. Each key has to be unique even if the translation phrase is different.

This is a small example how these files look:

CONFIRM: Conferma
FOR: per
YOU_WILL_RECEIVE: Riceverai
ENCHANTED: Incantato
ITEMS_AVAILABLE: Prodotti disponibili
CONTINUE: Continua
MONEY_PAID: Money Paid
GUI_OVERVIEW_OPENSHOPS_ACTION: Clicca per aprire i negozi
GUI_OVERVIEW_OPENSETTINGS_ACTION: Clicca per aprire le impostazioni
GUI_SHOPSETTINGS_BUY_LEFTACTION: **Tasto Sinistro** per **cambiare** il prezzo d'acquisto
GUI_SHOPSETTINGS_BUY_QACTION: **Premi Q** per disabilitare l'acquisto
ENCHANTED: Incantato premituro
GUI_SHOPSETTINGS_BUY_OTHERACTION: **Clicca** per abilitare l'**acquisto**

In this example the ENCHANTED key is duplicate even these keys have different translation phrases. I just want to see that this key is duplicated.

My plan is to match all these lines with a regex pattern with the help of notepad++ but if it's easier for you, it would also be okay if I have to use a script. Something like Batch or even a little NodeJS application.

Body:
In notepad++ you can use this regex to find the first occurrence of any key which is duplicated:

^(\w+):(?=.*\R\1:)

It looks for a sequence of word characters between the start of a line and a :, captured in group 1 and then asserts a positive lookahead for the same string starting a line again (\R matches a newline/crlf character). Note you need to have the . matches newline checkbox selected.


问:
Docker compose volume mount ignores the data
I have a docker compose file as:

```<code>    ...
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tablestruct:/docker-entrypoint-initdb.d/folder1
      - ./tablestruct1:/docker-entrypoint-initdb.d/folder2

volumes:
  folder1:
  folder2:

</code>```

When i run compose up, i get:

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder2

答:
From dockerhub postgres image documentation:

If you would like to do additional initialization in an image derived
  from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under
  /docker-entrypoint-initdb.d (creating the directory if necessary).
  After the entrypoint calls initdb to create the default postgres user
  and database, it will run any *.sql files, run any executable *.sh
  scripts, and source any non-executable *.sh scripts found in that
  directory to do further initialization before starting the service.

Warning: scripts in /docker-entrypoint-initdb.d are only run if you
  start the container with a data directory that is empty; any
  pre-existing database will be left untouched on container startup. One
  common problem is that if one of your /docker-entrypoint-initdb.d
  scripts fails (which will cause the entrypoint script to exit) and
  your orchestrator restarts the container with the already initialized
  data directory, it will not continue on with your scripts.

You should move everything to the same directory and mount it as /docker-entrypoint-initdb.d/ and not a folder inside it.

So:

```<code>volumes:
  - ./tablestruct:/docker-entrypoint-initdb.d
</code>```

Body:
I have a docker compose file as:

    ...
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tablestruct:/docker-entrypoint-initdb.d/folder1
      - ./tablestruct1:/docker-entrypoint-initdb.d/folder2

volumes:
  folder1:
  folder2:

When i run compose up, i get:

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder2

Body:
From dockerhub postgres image documentation:

If you would like to do additional initialization in an image derived
  from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under
  /docker-entrypoint-initdb.d (creating the directory if necessary).
  After the entrypoint calls initdb to create the default postgres user
  and database, it will run any *.sql files, run any executable *.sh
  scripts, and source any non-executable *.sh scripts found in that
  directory to do further initialization before starting the service.

Warning: scripts in /docker-entrypoint-initdb.d are only run if you
  start the container with a data directory that is empty; any
  pre-existing database will be left untouched on container startup. One
  common problem is that if one of your /docker-entrypoint-initdb.d
  scripts fails (which will cause the entrypoint script to exit) and
  your orchestrator restarts the container with the already initialized
  data directory, it will not continue on with your scripts.

You should move everything to the same directory and mount it as /docker-entrypoint-initdb.d/ and not a folder inside it.

So:

volumes:
  - ./tablestruct:/docker-entrypoint-initdb.d


问:
Database design for multiple game variations
Hopefully the purpose of these tables will be apparent, but just in case here's a simple explanation: I basically wish to store the results of matches (8 ball pool etc.) but also log the results on a frame by frame basis. Where I am getting a problem is that I intend to allow for different game types as my application grows, and as such, the scoring system used within each frame would vary. I think the solution below could work, but it doesn't quite seem right to me, all advice is appreciated.

Is there a more sensible approach than using the following tables:

# Players

id

name

nickname

# NormalMatches

id

playerA

playerB

# NormalFrames

id

match_id

playerAWon (BOOL)

# ScoringPoolMatches

id

playerA

playerB

# ScoringPoolFrames

id

match_id

playerA_cue_ball_potted

playerB_cue_ball_potted

playerA_balls_potted

playerB_balls_potted

playerA_balls_remaining

playerB_balls_remaining

(edit: altered ScoringPoolFrame table to give better idea of what the problem is.)

Many thanks.

答:
i'm not sure what the different is between your normal matches table and your scoring pool matches....
i would have things set up a little differently, with one table to score final win/loss results for a match, and one table to score all games/frames.  (* indicates a primary key field)

Players

id *

name

nickname

Matches

id *

playerA

playerB

winning_player_id

Games

match_id *

game_id *

player_id

score

the game_id would be a frame number in bowling, or a set number in tennis, or an inning in baseball

you might even want to flatten the matches table into something like this:

Matches

match_id *

player_id *

winner (bool)

so that you can select all matches for a certain player without searching on two columns.  you could also have more than two players in a game that way.


问:
Is it possible to create complex images (like cross functional flowchart) with Graphviz?
I need to create a complex image with lanes (like a cross functional flowchart). Is it possible to use Graphviz to automatically (based on a csv file) generate something like the picture below? If not, how can I achieve that?

答:
You could probably render some of it in Graphviz, such as in the cluster example, but Graphviz isn't really suited to this type of diagram. Its strength is directed graphs and hierarchical info.

Have a look at some of the declarative graphics libraries such as Altair or Matplotlib or Plotly. There is various levels of support for plotting axes in the style of lanes, then the rest is mostly textual annotations.