问:
my provider is not found, when I use selector
I run the below code using consumer and provider and it worked smoothly but when I add selector it geive me an error,
the error:
Error: Could not find the correct Provider above this Selector<SignInUpProvider, int> Widget

This happens because you used a BuildContext that does not include the provider

```<code>import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'providers/sign_in_up_provider.dart';
import 'utilities/myColors.dart' ;
 class SigInUpPage extends StatefulWidget {
  const SigInUpPage({Key? key}) : super(key: key);

  @override
  _SigInUpPageState createState() => _SigInUpPageState();
}

class _SigInUpPageState extends State<SigInUpPage> {

   @override
  Widget build(BuildContext context) {
     return ChangeNotifierProvider(create: (context)=> SignInUpProvider(),
     child: const SignInUpScreen(),);

  }

}
class SignInUpScreen extends StatefulWidget {
  const SignInUpScreen({Key? key}) : super(key: key);

  @override
  _SignInUpScreenState createState() => _SignInUpScreenState();
}

class _SignInUpScreenState extends State<SignInUpScreen> {

  // determine the sign in or sign up screen!!
  // 0 = sign up , 1 = sign in
   // sign up contents
  // final  GlobalKey<FormState> _keySignUp = GlobalKey<FormState>();
  final   TextEditingController _nameSignUp = TextEditingController();
  final   TextEditingController _passSignup = TextEditingController();
  final TextEditingController _emailSignUp = TextEditingController();
  // sign in contents
  final GlobalKey<FormState> _keySignIn = GlobalKey<FormState>();
  final TextEditingController  _emailSignIn = TextEditingController();
  final      TextEditingController _passSifnIn = TextEditingController();

  @override
  void dispose() {
    _nameSignUp.dispose();
    _passSifnIn.dispose();
    _passSignup.dispose();
    _emailSignIn.dispose();
    _emailSignUp.dispose();

    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: Colors.white,
        child: Stack(
          children: [
            // dummy design
            firstScreen(context),
            // dummy design
            secondScreen(context),
            // sign in screen
            thirdScreen(context),
          ],
        ),
      ),
    );

  }
  // first background in stack
  Widget firstScreen(BuildContext context){
    return
      Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color:MyColors.blueColor(),
      );

  }
  // second background in stack
  Widget secondScreen(BuildContext context){
    return Align(
      alignment: Alignment.bottomRight,
      child: Container(
        decoration:   BoxDecoration(
            color: MyColors.purple(),

            borderRadius: const BorderRadius.only(bottomLeft:Radius.circular(1000),
                topLeft: Radius.circular(1000)
            )
        ),
        width: MediaQuery.of(context).size.width * 0.5,
        height: MediaQuery.of(context).size.height,
      ),
    );
  }
  // sign in up screen // the white box
  Widget thirdScreen(BuildContext context){
    return Align(alignment: Alignment.bottomCenter,
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Container(
          margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
          width: MediaQuery.of(context).size.width*0.7,
          height: MediaQuery.of(context).size.height*0.7,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(50))),
          child: Selector<SignInUpProvider, int>(
            selector: (context, userState) => userState.getUserState,
            builder: (context, state, widget){
            return Form(
              key: _keySignIn,
              child: (state == 0 )?
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:

                [
                  logo(context),
                  nameBox(context),
                  emailBox(context),
                  passText(context),
                  signButton(context),
                  // this to change between sign in and sign up
                  changeState(context),

                ],
              ):
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:

                [
                  logo(context),
                  emailBox(context),
                  passText(context),
                  signButton(context),
                  // this to change between sign in and sign up
                  changeState(context),

                ],
              ),
            );
            }
          ),
        ),
      ),
    );
  }
// the logo inside the white box
  Widget logo(context) {
    return Container(
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(50))
      ),
      width: MediaQuery.of(context).size.width*0.7,
      height: MediaQuery.of(context).size.height*0.1,
      child: const Align(
          alignment: Alignment.center,
          child: Text("mekyajat",style: TextStyle(
            fontStyle: FontStyle.italic,
            fontSize: 16,
            color: Color.fromRGBO(249, 229, 230, 1),
          ),)),
    );
  }
  // name box
  Widget nameBox(context){
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:_nameSignUp ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.person),
          hintText: "name",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 8 ){
            Fluttertoast.showToast(msg: "please insert your name \n more than 8 charecters",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }   return null ;
        },

      ),
    );
  }

  Widget  emailBox(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:(context.read<SignInUpProvider>().getUserState
            == 0) ? _emailSignUp : _emailSignIn ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.email_outlined),
          hintText: "E-mail @",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 10 ){
            Fluttertoast.showToast(msg: "please insert your email \n ",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }
          else if (!containSymbol(value.toString(), "@")){
            return "please insert @ symbol";
          }
          return null ;
        },

      ),

    );

  }

  Widget passText(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:(context.read<SignInUpProvider>().getUserState ==0)? _passSignup :_passSifnIn ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.password_sharp),
          hintText: "password",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 8 ){
            Fluttertoast.showToast(msg: "please insert your password \n more than 8 charecters",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }   return null ;
        },

      ),

    );

  }

  Widget signButton(BuildContext context) {
    return Selector<SignInUpProvider, int>(
      selector: (context,userState)=> userState.getUserState,
    builder: (context, currentState, widget){
    return  InkWell(
        child: Container(
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width*0.40,
          height: MediaQuery.of(context).size.height*0.06,
          child: (currentState == 0 )?
          const Text("SIGN UP", textAlign: TextAlign.center,style: TextStyle(color: Colors.white),):
          const Text("SIGN IN",textAlign: TextAlign.center, style: TextStyle(color: Colors.white),),
          decoration:  BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(25)),
            gradient: LinearGradient(colors: [
               MyColors.blueColor(),
              MyColors.purple(),

                 ]),

          ),
        ),
        onTap: (){},
      );
    },
    );
  }

  Widget changeState(BuildContext context) {
    return Consumer<SignInUpProvider>(

     builder: (context, userSt , widget){
       return InkWell(
         child: SizedBox(
             width: MediaQuery.of(context).size.width*0.55,
             height: MediaQuery.of(context).size.height*0.05,
             child:(userSt.userState == 0)?
             const Text("sign in",
               textAlign: TextAlign.right,
               style: TextStyle(color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
               ),) :
             const Text("sign up",
               textAlign: TextAlign.right,
               style: TextStyle(
                 color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
               ),)

         ),
         onTap: (){
           userSt.changeUserState(userSt.userState);
           // SignInUpProvider().changeUserState(userState);
           // signProvider.changeUserState(signProvider.userState);

         },
       );
     },
     );
  }
}

// provide this function with one char and one string
// this run to see if the string contains char or not
bool containSymbol(String fullString ,  String char){
   bool _result = false ;
   List<String> _chars = [];
   int _stringLingth = fullString.length;
   int _keyLoop = 0 ;
   while (_keyLoop < _stringLingth){
     _chars.add(fullString[_keyLoop]);
     _keyLoop++;
   }
   for(int x = 0 ; x < _chars.length; x++){
     if(_chars[x] == char){
       _result = true;
       break;
     }
   }

   return _result;
}
</code>```

答:
1 - move up your ChangeNotifierProvider step above in the widget tree for example in the routes you can wrap the SigInUpPage like this :

```<code>ChangeNotifierProvider<SignInUpProvider>(
        create: (_) => SignInUpProvider(),
        child: SigInUpPage(),
        ),
</code>```

2 - don't pass the context as a parameter to the other screens,use a builder in each screen like this for the second screen:

```<code>class secondScreen extends StatelessWidget {
    const secondScreen({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {

      return Align(
        alignment: Alignment.bottomCenter,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Container(
            margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
            width: MediaQuery.of(context).size.width*0.7,
            height: MediaQuery.of(context).size.height*0.7,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(50))),
                  child: Selector<SignInUpProvider, int>(
                selector: (context, userState) =>       userState.getUserState,
                builder: (context, state, widget){
                  return Form(
                    key: _keySignIn,
                    child: (state == 0 )?
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children:

                      [
                        logo(context),
                        nameBox(context),
                        emailBox(context),
                        passText(context),
                        signButton(context),
                        // this to change between sign in and sign up
                        changeState(context),

                      ],
                    ):
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children:

                      [
                        logo(context),
                        emailBox(context),
                        passText(context),
                        signButton(context),
                        // this to change between sign in and sign up
                        changeState(context),

                      ],
                    ),
                  );
                }
            ),
          ),
        ),
      );
    }

  }
</code>```

this should work

Body:
I run the below code using consumer and provider and it worked smoothly but when I add selector it geive me an error,
the error:
Error: Could not find the correct Provider above this Selector<SignInUpProvider, int> Widget

This happens because you used a BuildContext that does not include the provider

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'providers/sign_in_up_provider.dart';
import 'utilities/myColors.dart' ;
 class SigInUpPage extends StatefulWidget {
  const SigInUpPage({Key? key}) : super(key: key);

  @override
  _SigInUpPageState createState() => _SigInUpPageState();
}

class _SigInUpPageState extends State<SigInUpPage> {

   @override
  Widget build(BuildContext context) {
     return ChangeNotifierProvider(create: (context)=> SignInUpProvider(),
     child: const SignInUpScreen(),);

  }

}
class SignInUpScreen extends StatefulWidget {
  const SignInUpScreen({Key? key}) : super(key: key);

  @override
  _SignInUpScreenState createState() => _SignInUpScreenState();
}

class _SignInUpScreenState extends State<SignInUpScreen> {

  // determine the sign in or sign up screen!!
  // 0 = sign up , 1 = sign in
   // sign up contents
  // final  GlobalKey<FormState> _keySignUp = GlobalKey<FormState>();
  final   TextEditingController _nameSignUp = TextEditingController();
  final   TextEditingController _passSignup = TextEditingController();
  final TextEditingController _emailSignUp = TextEditingController();
  // sign in contents
  final GlobalKey<FormState> _keySignIn = GlobalKey<FormState>();
  final TextEditingController  _emailSignIn = TextEditingController();
  final      TextEditingController _passSifnIn = TextEditingController();

  @override
  void dispose() {
    _nameSignUp.dispose();
    _passSifnIn.dispose();
    _passSignup.dispose();
    _emailSignIn.dispose();
    _emailSignUp.dispose();

    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: Colors.white,
        child: Stack(
          children: [
            // dummy design
            firstScreen(context),
            // dummy design
            secondScreen(context),
            // sign in screen
            thirdScreen(context),
          ],
        ),
      ),
    );

  }
  // first background in stack
  Widget firstScreen(BuildContext context){
    return
      Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color:MyColors.blueColor(),
      );

  }
  // second background in stack
  Widget secondScreen(BuildContext context){
    return Align(
      alignment: Alignment.bottomRight,
      child: Container(
        decoration:   BoxDecoration(
            color: MyColors.purple(),

            borderRadius: const BorderRadius.only(bottomLeft:Radius.circular(1000),
                topLeft: Radius.circular(1000)
            )
        ),
        width: MediaQuery.of(context).size.width * 0.5,
        height: MediaQuery.of(context).size.height,
      ),
    );
  }
  // sign in up screen // the white box
  Widget thirdScreen(BuildContext context){
    return Align(alignment: Alignment.bottomCenter,
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Container(
          margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
          width: MediaQuery.of(context).size.width*0.7,
          height: MediaQuery.of(context).size.height*0.7,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(50))),
          child: Selector<SignInUpProvider, int>(
            selector: (context, userState) => userState.getUserState,
            builder: (context, state, widget){
            return Form(
              key: _keySignIn,
              child: (state == 0 )?
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:

                [
                  logo(context),
                  nameBox(context),
                  emailBox(context),
                  passText(context),
                  signButton(context),
                  // this to change between sign in and sign up
                  changeState(context),

                ],
              ):
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:

                [
                  logo(context),
                  emailBox(context),
                  passText(context),
                  signButton(context),
                  // this to change between sign in and sign up
                  changeState(context),

                ],
              ),
            );
            }
          ),
        ),
      ),
    );
  }
// the logo inside the white box
  Widget logo(context) {
    return Container(
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(50))
      ),
      width: MediaQuery.of(context).size.width*0.7,
      height: MediaQuery.of(context).size.height*0.1,
      child: const Align(
          alignment: Alignment.center,
          child: Text("mekyajat",style: TextStyle(
            fontStyle: FontStyle.italic,
            fontSize: 16,
            color: Color.fromRGBO(249, 229, 230, 1),
          ),)),
    );
  }
  // name box
  Widget nameBox(context){
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:_nameSignUp ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.person),
          hintText: "name",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 8 ){
            Fluttertoast.showToast(msg: "please insert your name \n more than 8 charecters",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }   return null ;
        },

      ),
    );
  }

  Widget  emailBox(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:(context.read<SignInUpProvider>().getUserState
            == 0) ? _emailSignUp : _emailSignIn ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.email_outlined),
          hintText: "E-mail @",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 10 ){
            Fluttertoast.showToast(msg: "please insert your email \n ",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }
          else if (!containSymbol(value.toString(), "@")){
            return "please insert @ symbol";
          }
          return null ;
        },

      ),

    );

  }

  Widget passText(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width*0.55,
      height: MediaQuery.of(context).size.height*0.1,
      decoration: const BoxDecoration(
        color: Colors.white70,
      ),
      child: TextFormField(
        controller:(context.read<SignInUpProvider>().getUserState ==0)? _passSignup :_passSifnIn ,
        decoration:   const InputDecoration(
          icon: Icon(Icons.password_sharp),
          hintText: "password",
          hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 14
          ),

        ),
        textAlign: TextAlign.center,
        validator: (value){
          if(  value.toString().length < 8 ){
            Fluttertoast.showToast(msg: "please insert your password \n more than 8 charecters",
                gravity: ToastGravity.CENTER,
                toastLength: Toast.LENGTH_SHORT,
                backgroundColor: Colors.redAccent,
                textColor: Colors.white,
                fontSize: 16
            );
          }   return null ;
        },

      ),

    );

  }

  Widget signButton(BuildContext context) {
    return Selector<SignInUpProvider, int>(
      selector: (context,userState)=> userState.getUserState,
    builder: (context, currentState, widget){
    return  InkWell(
        child: Container(
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width*0.40,
          height: MediaQuery.of(context).size.height*0.06,
          child: (currentState == 0 )?
          const Text("SIGN UP", textAlign: TextAlign.center,style: TextStyle(color: Colors.white),):
          const Text("SIGN IN",textAlign: TextAlign.center, style: TextStyle(color: Colors.white),),
          decoration:  BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(25)),
            gradient: LinearGradient(colors: [
               MyColors.blueColor(),
              MyColors.purple(),

                 ]),

          ),
        ),
        onTap: (){},
      );
    },
    );
  }

  Widget changeState(BuildContext context) {
    return Consumer<SignInUpProvider>(

     builder: (context, userSt , widget){
       return InkWell(
         child: SizedBox(
             width: MediaQuery.of(context).size.width*0.55,
             height: MediaQuery.of(context).size.height*0.05,
             child:(userSt.userState == 0)?
             const Text("sign in",
               textAlign: TextAlign.right,
               style: TextStyle(color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
               ),) :
             const Text("sign up",
               textAlign: TextAlign.right,
               style: TextStyle(
                 color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
               ),)

         ),
         onTap: (){
           userSt.changeUserState(userSt.userState);
           // SignInUpProvider().changeUserState(userState);
           // signProvider.changeUserState(signProvider.userState);

         },
       );
     },
     );
  }
}

// provide this function with one char and one string
// this run to see if the string contains char or not
bool containSymbol(String fullString ,  String char){
   bool _result = false ;
   List<String> _chars = [];
   int _stringLingth = fullString.length;
   int _keyLoop = 0 ;
   while (_keyLoop < _stringLingth){
     _chars.add(fullString[_keyLoop]);
     _keyLoop++;
   }
   for(int x = 0 ; x < _chars.length; x++){
     if(_chars[x] == char){
       _result = true;
       break;
     }
   }

   return _result;
}

Body:
1 - move up your ChangeNotifierProvider step above in the widget tree for example in the routes you can wrap the SigInUpPage like this :

ChangeNotifierProvider<SignInUpProvider>(
        create: (_) => SignInUpProvider(),
        child: SigInUpPage(),
        ),

2 - don't pass the context as a parameter to the other screens,use a builder in each screen like this for the second screen:

class secondScreen extends StatelessWidget {
    const secondScreen({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {

      return Align(
        alignment: Alignment.bottomCenter,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Container(
            margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
            width: MediaQuery.of(context).size.width*0.7,
            height: MediaQuery.of(context).size.height*0.7,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(50))),
                  child: Selector<SignInUpProvider, int>(
                selector: (context, userState) =>       userState.getUserState,
                builder: (context, state, widget){
                  return Form(
                    key: _keySignIn,
                    child: (state == 0 )?
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children:

                      [
                        logo(context),
                        nameBox(context),
                        emailBox(context),
                        passText(context),
                        signButton(context),
                        // this to change between sign in and sign up
                        changeState(context),

                      ],
                    ):
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children:

                      [
                        logo(context),
                        emailBox(context),
                        passText(context),
                        signButton(context),
                        // this to change between sign in and sign up
                        changeState(context),

                      ],
                    ),
                  );
                }
            ),
          ),
        ),
      );
    }

  }

this should work


来源: stackexchange

问:
compiler says member function not defined however it is included in the header file c++
Compiler says member function not defined however it is included in the header file c++. I have about 10 functions and one function find_similar the compiler says undeclared variable on the tester implementation file. The purpose of the program is to check the validity of two entries from the main.cpp/test file. I made a program which checks the entries from the test file.

CarInventory.cpp

```<code>#include <iostream>
#include <cstring>
#include <iomanip>
#include <string.h>
#include "CarInventory.h"
using namespace std;
using namespace sdds;

void CarInventory::resetInfo()

{

    m_type = nullptr;

    m_brand = nullptr;

    m_model = nullptr;

    m_year = 0;

    m_code = 0;

    m_price = 0;

}

CarInventory::CarInventory()

{

    resetInfo();

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    resetInfo();

    setInfo(type, brand, model, year, code, price);

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model)

{

    resetInfo();

    setInfo(type, brand, model, 2022, 100, 1);

}

CarInventory::~CarInventory()

{

    delete[] m_type;

    delete[] m_brand;

    delete[] m_model;

}

CarInventory& CarInventory::setInfo(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    if (type == nullptr || brand == nullptr || model == nullptr || year < 1990 || code < 100 || price < 0)

    {

        resetInfo();

    }

    else

    {

        delete[] m_type;

        delete[] m_brand;

        delete[] m_model;

        m_type = new char[strlen(type) + 1];

        strcpy_s(m_type, sizeof(type), type);

        m_brand = new char[strlen(brand) + 1];

        strcpy_s(m_brand, sizeof(brand),  brand);

        m_model = new char[strlen(model) + 1];

        strcpy_s(m_model, sizeof(m_model),  model);

        m_year = year;

        m_code = code;

        m_price = price;

    }

    return *this;

}

bool CarInventory::isValid() const

{

    return m_type != nullptr && m_brand != nullptr && m_model != nullptr && m_year >= 1990 && m_code >= 100 && m_price >= 0;

}

bool sdds::CarInventory::find_similar(CarInventory car[], const int num_cars)
{
    return false;
}

void CarInventory::printInfo() const

{

    std::cout << "|" << std::setw(12) << m_type << "|" << std::setw(18) << m_brand << "|" << std::setw(18) << m_model << "|" << std::setw(6) << m_year << "|" << std::setw(6) << m_code << "|" << std::setw(11) << m_price << "|" << std::endl;

}

bool CarInventory::isSimilarTo(const CarInventory& car) const

{

    return m_type == car.m_type && m_brand == car.m_brand && m_model == car.m_model && m_year == car.m_year;

}

namespace sdds {

    bool find_similar(CarInventory car[], const int num_cars)

    {

        for (int i = 0; i < num_cars; i++)

        {

            for (int j = i + 1; j < num_cars; j++)

            {

                if (car[i].isSimilarTo(car[j]))

                {

                    return true;

                }

            }

        }

        return false;

    }
}
</code>```

Header File

```<code>#ifndef CARINVENTORY_H
#define CARINVENTORY_H
#define _CRT_SECURE_NO_WARNINGS

namespace sdds {
class CarInventory {
    char* m_type;
    char* m_brand;
    char* m_model;
    int m_year;
    int m_code;
    double m_price;
    void resetInfo();
public:
    CarInventory();
    CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price);
    CarInventory(const char* type, const char* brand, const char* model);
    bool isSimilarTo(const CarInventory& car) const;
    ~CarInventory();
    CarInventory& setInfo(const char* type, const char* brand, const char* model, int year, int code, double price);
    void printInfo() const;
    bool isValid() const;
    bool find_similar(CarInventory car[], const int num_cars);

   };
 }
 #endif
</code>```

main/tester file

```<code>        #include<iostream>
        #include<iomanip>
        #include "CarInventory.h"
        using namespace std;
        using namespace sdds;

        int main()
         {
         const int num_cars = 6;
          bool invalid_data = false;
          CarInventory cars[num_cars] = {
       {},
    {"suv", "volvo", "xc90"},
    {"Truck", "Ford", "F 150", 2021, 105, 55000},
    {"Sedan", "BMW", "M550i", 2022, 101, 91000},
    {"Truck", "Tesla", "Cybertruck", 2021, 102, 65000},
    {"Sedan", "BMW", "M550i"}
};

if (cars[2].setInfo("SUV", "Volvo", "XC90", 2019, 109, 80000).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}
if (cars[1].setInfo("SUV", "Volvo", "XC90", 1234, 1, 1).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}

cout << setw(60) << "----- Car Inventory Information -----" << endl << endl;;
cout << "| Type       | Brand            | Model            | Year | Code |     Price |" << endl;
cout << "+------------+------------------+------------------+------+------+-----------+" << endl;
for (int i = 0; i < num_cars; i++) {
    if (cars[i].isValid())
        cars[i].printInfo();
    else
        invalid_data = true;
}

if (invalid_data) {
    cout << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
    cout << "*  WARNING: There are invalid data in the inventory!      *" << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
}
if (find_similar)(cars, num_cars)) {
    cout << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
    cout << "+  WARNING: There are similar entries in the inventory!   +" << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
}
return 0;
  }
</code>```

Error message:

答:
This is not a valid call:

```<code>if (find_similar)(cars, num_cars)) {
</code>```

The syntax is wrong.

You need a CarInventory instance since the function is not static.

```<code>CarInventory foo;
if( foo.find_similar(cars, num_cars) ) {
</code>```

I think you should make find_similar a non-member function instead. Just move the declaration outside of the class:

```<code>class CarInventory {
    // remove this:
    // bool find_similar(CarInventory car[], const int num_cars);
};

// declare this:
bool find_similar(CarInventory car[], const int num_cars);
</code>```

The free function sdds::find_similar (that you've already defined in CarInventory.cpp) will then be found via ADL (argument-dependent lookup) - even if you don't do using namespace sdds; first. You also need to remove the definition of CarInventory::find_similar in CarInventory.cpp.

Finally, correct the call in main. You will not get this program to work without changing main:

```<code>if(find_similar(cars, num_cars)) {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Compiler says member function not defined however it is included in the header file c++. I have about 10 functions and one function find_similar the compiler says undeclared variable on the tester implementation file. The purpose of the program is to check the validity of two entries from the main.cpp/test file. I made a program which checks the entries from the test file.

CarInventory.cpp

#include <iostream>
#include <cstring>
#include <iomanip>
#include <string.h>
#include "CarInventory.h"
using namespace std;
using namespace sdds;

void CarInventory::resetInfo()

{

    m_type = nullptr;

    m_brand = nullptr;

    m_model = nullptr;

    m_year = 0;

    m_code = 0;

    m_price = 0;

}

CarInventory::CarInventory()

{

    resetInfo();

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    resetInfo();

    setInfo(type, brand, model, year, code, price);

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model)

{

    resetInfo();

    setInfo(type, brand, model, 2022, 100, 1);

}

CarInventory::~CarInventory()

{

    delete[] m_type;

    delete[] m_brand;

    delete[] m_model;

}

CarInventory& CarInventory::setInfo(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    if (type == nullptr || brand == nullptr || model == nullptr || year < 1990 || code < 100 || price < 0)

    {

        resetInfo();

    }

    else

    {

        delete[] m_type;

        delete[] m_brand;

        delete[] m_model;

        m_type = new char[strlen(type) + 1];

        strcpy_s(m_type, sizeof(type), type);

        m_brand = new char[strlen(brand) + 1];

        strcpy_s(m_brand, sizeof(brand),  brand);

        m_model = new char[strlen(model) + 1];

        strcpy_s(m_model, sizeof(m_model),  model);

        m_year = year;

        m_code = code;

        m_price = price;

    }

    return *this;

}

bool CarInventory::isValid() const

{

    return m_type != nullptr && m_brand != nullptr && m_model != nullptr && m_year >= 1990 && m_code >= 100 && m_price >= 0;

}

bool sdds::CarInventory::find_similar(CarInventory car[], const int num_cars)
{
    return false;
}

void CarInventory::printInfo() const

{

    std::cout << "|" << std::setw(12) << m_type << "|" << std::setw(18) << m_brand << "|" << std::setw(18) << m_model << "|" << std::setw(6) << m_year << "|" << std::setw(6) << m_code << "|" << std::setw(11) << m_price << "|" << std::endl;

}

bool CarInventory::isSimilarTo(const CarInventory& car) const

{

    return m_type == car.m_type && m_brand == car.m_brand && m_model == car.m_model && m_year == car.m_year;

}

namespace sdds {

    bool find_similar(CarInventory car[], const int num_cars)

    {

        for (int i = 0; i < num_cars; i++)

        {

            for (int j = i + 1; j < num_cars; j++)

            {

                if (car[i].isSimilarTo(car[j]))

                {

                    return true;

                }

            }

        }

        return false;

    }
}

Header File

#ifndef CARINVENTORY_H
#define CARINVENTORY_H
#define _CRT_SECURE_NO_WARNINGS

namespace sdds {
class CarInventory {
    char* m_type;
    char* m_brand;
    char* m_model;
    int m_year;
    int m_code;
    double m_price;
    void resetInfo();
public:
    CarInventory();
    CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price);
    CarInventory(const char* type, const char* brand, const char* model);
    bool isSimilarTo(const CarInventory& car) const;
    ~CarInventory();
    CarInventory& setInfo(const char* type, const char* brand, const char* model, int year, int code, double price);
    void printInfo() const;
    bool isValid() const;
    bool find_similar(CarInventory car[], const int num_cars);

   };
 }
 #endif

main/tester file

        #include<iostream>
        #include<iomanip>
        #include "CarInventory.h"
        using namespace std;
        using namespace sdds;

        int main()
         {
         const int num_cars = 6;
          bool invalid_data = false;
          CarInventory cars[num_cars] = {
       {},
    {"suv", "volvo", "xc90"},
    {"Truck", "Ford", "F 150", 2021, 105, 55000},
    {"Sedan", "BMW", "M550i", 2022, 101, 91000},
    {"Truck", "Tesla", "Cybertruck", 2021, 102, 65000},
    {"Sedan", "BMW", "M550i"}
};

if (cars[2].setInfo("SUV", "Volvo", "XC90", 2019, 109, 80000).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}
if (cars[1].setInfo("SUV", "Volvo", "XC90", 1234, 1, 1).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}

cout << setw(60) << "----- Car Inventory Information -----" << endl << endl;;
cout << "| Type       | Brand            | Model            | Year | Code |     Price |" << endl;
cout << "+------------+------------------+------------------+------+------+-----------+" << endl;
for (int i = 0; i < num_cars; i++) {
    if (cars[i].isValid())
        cars[i].printInfo();
    else
        invalid_data = true;
}

if (invalid_data) {
    cout << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
    cout << "*  WARNING: There are invalid data in the inventory!      *" << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
}
if (find_similar)(cars, num_cars)) {
    cout << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
    cout << "+  WARNING: There are similar entries in the inventory!   +" << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
}
return 0;
  }

Error message:

Body:
This is not a valid call:

if (find_similar)(cars, num_cars)) {

The syntax is wrong.

You need a CarInventory instance since the function is not static.

CarInventory foo;
if( foo.find_similar(cars, num_cars) ) {

I think you should make find_similar a non-member function instead. Just move the declaration outside of the class:

class CarInventory {
    // remove this:
    // bool find_similar(CarInventory car[], const int num_cars);
};

// declare this:
bool find_similar(CarInventory car[], const int num_cars);

The free function sdds::find_similar (that you've already defined in CarInventory.cpp) will then be found via ADL (argument-dependent lookup) - even if you don't do using namespace sdds; first. You also need to remove the definition of CarInventory::find_similar in CarInventory.cpp.

Finally, correct the call in main. You will not get this program to work without changing main:

if(find_similar(cars, num_cars)) {


问:
Discord.js return message reply embed
```<code>if(message.content.startsWith(config.prefix + "övgü")) {

        var c1 = message.content.split(" ")

        if(c1.length < 3) {
            return message.reply({content:"**Lütfen bir steam64ID ve miktar giriniz.**"})
        }

        var steam64ID = c1[1];
        var steamidResolver = require("steamid-resolver");

        steamidResolver.steamID64ToFullInfo(String(steam64ID), (err, info) => {
            if(err) return message.reply({content: "**Lütfen geçerli bir steam64ID giriniz.**"});

    client.channels.cache.get(config.channel).send({content: `~commend ${steam64ID} ${count}`})
    return message.reply({ content: "nice"})
</code>```

Here, when command is sent as a message, it tags the user who wrote it and gives a "nice" reply as a message, how can I embed it?

答:
```<code>client.channels.cache.get(config.channel).send({content: `~commend ${steam64ID} ${count}`})

const embed = new MessageEmbed()
.setTitle('nice')
.setDescription('nice')
.setColor('<your color>')

 return message.reply({embeds: [embed]})
</code>```

Is this what you wanted to do?

Title: Discord.js return message reply embed

Body:
if(message.content.startsWith(config.prefix + "övgü")) {

        var c1 = message.content.split(" ")

        if(c1.length < 3) {
            return message.reply({content:"**Lütfen bir steam64ID ve miktar giriniz.**"})
        }

        var steam64ID = c1[1];
        var steamidResolver = require("steamid-resolver");

        steamidResolver.steamID64ToFullInfo(String(steam64ID), (err, info) => {
            if(err) return message.reply({content: "**Lütfen geçerli bir steam64ID giriniz.**"});

    client.channels.cache.get(config.channel).send({content: `~commend ${steam64ID} ${count}`})
    return message.reply({ content: "nice"})

Here, when command is sent as a message, it tags the user who wrote it and gives a "nice" reply as a message, how can I embed it?

Body:
client.channels.cache.get(config.channel).send({content: `~commend ${steam64ID} ${count}`})

const embed = new MessageEmbed()
.setTitle('nice')
.setDescription('nice')
.setColor('<your color>')

 return message.reply({embeds: [embed]})

Is this what you wanted to do?


问:
dart - a generic method getter or what is this
I have come across this in moctail, what is "get when" in the function signature - a generic method getter, and why can you use it as a function in test?</p>
```<code>When<T> Function<T>(T Function() x) get when {
  if (_whenCall != null) {
    throw StateError('Cannot call `when` within a stub response');
  }
  _whenInProgress = true;
  return <T>(T Function() _) {
    try {
      _();
    } catch (_) {
      if (_ is! TypeError) rethrow;
    }
    _whenInProgress = false;
    return When<T>();
  };
}
</code>```

答:
when is a getter that returns a generic function.  That generic function takes another function as an argument and returns a When<T>.

When<T> Function<T>(T Function() x) get when { ... }
\_________________________________/  ^   ^
                |                    |   |
                |                    |   +-- Name of the member
                |                    |
                |                    +------ Member is a getter
                |
                +--------------------------- Return type of the getter
```

Body:
I have come across this in moctail, what is "get when" in the function signature - a generic method getter, and why can you use it as a function in test?

When<T> Function<T>(T Function() x) get when {
  if (_whenCall != null) {
    throw StateError('Cannot call `when` within a stub response');
  }
  _whenInProgress = true;
  return <T>(T Function() _) {
    try {
      _();
    } catch (_) {
      if (_ is! TypeError) rethrow;
    }
    _whenInProgress = false;
    return When<T>();
  };
}


问:
C code runs but nothing happens when i read from file
What I'm trying to do here is to read lines 3 to 32 and 35 to 44 from a CSV file.
When I read the lines, I use strtok to separate the values and fill a struct with each token.
The thing is when I run the code nothing happens. I was able to trace the error to this part of the code because when I commented this part of the code the program ran perfectly.
Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "carregar_files.h"
#include <string.h>
#include "mylib.h"

void necessidades_de_producao()
{
    FILE *fp = fopen("OP_2022_02_01.csv", "r");
    int i = 1, cont = 0;
    char buff[1000];
    ordens_compra *necessidades;
    ordens *op;
    necessidades = (ordens_compra*)malloc(1 * sizeof(ordens_compra));
    op = (ordens*)malloc(1 * sizeof(ordens));

    if(!fp)
    {
        printf("Erro ao abrir o ficheiro!!!!!!\n");
    }
    else
    {

        while(fgets(buff, 1000, fp) != NULL)
        {
            char *token;
            int count;

            if(i>=3 && i<=32)//linhas de operacao
            {
                op = (ordens*)realloc(op, sizeof(ordens) * (cont + 1));// atualiza o tamanho da struct para o numero de ordens

                token = strtok(buff,";"); // seprara a string buff em vários tokens

                count = 0;

                while(token != NULL){// percorrer os tokens, e verificar qual a posição do token para preencher corretamente

                    if(count == 0){op[cont].id = atoi(token);}//atoi recebe string e converte em int
                    if(count == 1){strcpy(op[cont].tipo,token);}
                    if(count == 2){op[cont].tamanho = atoi(token);}
                    if(count == 3){op[cont].quantidade = atoi(token);}
                    count ++;
                }

                cont++;
            }

            if(i>=35 && i<=44)//linhas de necessidade
            {
                necessidades = (ordens_compra*)realloc(necessidades, sizeof(ordens_compra) * (cont + 1));

                token = strtok(buff,";");

                count = 0;

                while(token != NULL){

                    if(count == 0){necessidades[cont].OP = atoi(token);}//atoi recebe string e converte em int
                    if(count == 1){necessidades[cont].materia_prima = atoi(token);}
                    if(count == 2){necessidades[cont].quantidade = atoi(token);}
                    count ++;
                }
                cont++;
            }

            i++;
        }

    }
}
</code>```

And here is the structs header file:

```<code>#ifndef CARREGAR_FILES_H
#define CARREGAR_FILES_H

#ifdef __cplusplus
extern "C" {
#endif

#define SUCESS "\nOs dados foram carregados com sucesso!\n"

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_couro;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_tecido;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_borracha;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_cordoes;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_palmilhas;

//------------------------------------------------------//

typedef struct
{
    MP_couro *couro;
    MP_tecido *tecido;
    MP_borracha *borracha;
    MP_cordoes *cordoes;
    MP_palmilhas *palmilhas;
} tabela_stock;//estrutura para interligar as estruturas das matérias-Primas

typedef struct key_value
{
    char col0[50];//coluna 1 da tabela de stocks
    char col1[50];//coluna 2 da tabela de stocks
    char col2[50];//coluna 3 da tabela de stocks
    char col3[50];//coluna 4 da tabela de stocks
} row_structure;

typedef struct
{
    int id;
    char tipo[50];
    int tamanho;
    int quantidade;
} ordens;//estrutura para as ordens de produção

typedef struct
{
    int OP;
    int materia_prima;
    int quantidade;
}ordens_compra;//estrutura para as necessidades de compra

void carregar_stocks(MP_couro *c,MP_tecido *t,MP_borracha *b, MP_cordoes *cs, MP_palmilhas *p);
void editar_stock_min(MP_couro *c,MP_tecido *t,MP_borracha *b, MP_cordoes *cs, MP_palmilhas *p);
void necessidades_de_producao();//!!!!
void free_memoria (tabela_stock *stock);

#ifdef __cplusplus
}
#endif

#endif
</code>```

File that I'm trying to read from:

答:
you have to call strtok again in the loop

```<code>           while(token != NULL){// percorrer os tokens, e verificar qual a posição do token para preencher corretamente

                if(count == 0){op[cont].id = atoi(token);}//atoi recebe string e converte em int
                if(count == 1){strcpy(op[cont].tipo,token);}
                if(count == 2){op[cont].tamanho = atoi(token);}
                if(count == 3){op[cont].quantidade = atoi(token);}
                count ++;
                token = strtok(NULL, ";"); <<<=====
            }
</code>```

otherwise you loop forever

see https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/

Body:
What I'm trying to do here is to read lines 3 to 32 and 35 to 44 from a CSV file.
When I read the lines, I use strtok to separate the values and fill a struct with each token.
The thing is when I run the code nothing happens. I was able to trace the error to this part of the code because when I commented this part of the code the program ran perfectly.
Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include "carregar_files.h"
#include <string.h>
#include "mylib.h"

void necessidades_de_producao()
{
    FILE *fp = fopen("OP_2022_02_01.csv", "r");
    int i = 1, cont = 0;
    char buff[1000];
    ordens_compra *necessidades;
    ordens *op;
    necessidades = (ordens_compra*)malloc(1 * sizeof(ordens_compra));
    op = (ordens*)malloc(1 * sizeof(ordens));

    if(!fp)
    {
        printf("Erro ao abrir o ficheiro!!!!!!\n");
    }
    else
    {

        while(fgets(buff, 1000, fp) != NULL)
        {
            char *token;
            int count;

            if(i>=3 && i<=32)//linhas de operacao
            {
                op = (ordens*)realloc(op, sizeof(ordens) * (cont + 1));// atualiza o tamanho da struct para o numero de ordens

                token = strtok(buff,";"); // seprara a string buff em vários tokens

                count = 0;

                while(token != NULL){// percorrer os tokens, e verificar qual a posição do token para preencher corretamente

                    if(count == 0){op[cont].id = atoi(token);}//atoi recebe string e converte em int
                    if(count == 1){strcpy(op[cont].tipo,token);}
                    if(count == 2){op[cont].tamanho = atoi(token);}
                    if(count == 3){op[cont].quantidade = atoi(token);}
                    count ++;
                }

                cont++;
            }

            if(i>=35 && i<=44)//linhas de necessidade
            {
                necessidades = (ordens_compra*)realloc(necessidades, sizeof(ordens_compra) * (cont + 1));

                token = strtok(buff,";");

                count = 0;

                while(token != NULL){

                    if(count == 0){necessidades[cont].OP = atoi(token);}//atoi recebe string e converte em int
                    if(count == 1){necessidades[cont].materia_prima = atoi(token);}
                    if(count == 2){necessidades[cont].quantidade = atoi(token);}
                    count ++;
                }
                cont++;
            }

            i++;
        }

    }
}

And here is the structs header file:

#ifndef CARREGAR_FILES_H
#define CARREGAR_FILES_H

#ifdef __cplusplus
extern "C" {
#endif

#define SUCESS "\nOs dados foram carregados com sucesso!\n"

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_couro;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_tecido;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_borracha;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_cordoes;

typedef struct
{
    int code;
    char produto[10];
    int min_stock;
    int atual_stock;
} MP_palmilhas;

//------------------------------------------------------//

typedef struct
{
    MP_couro *couro;
    MP_tecido *tecido;
    MP_borracha *borracha;
    MP_cordoes *cordoes;
    MP_palmilhas *palmilhas;
} tabela_stock;//estrutura para interligar as estruturas das matérias-Primas

typedef struct key_value
{
    char col0[50];//coluna 1 da tabela de stocks
    char col1[50];//coluna 2 da tabela de stocks
    char col2[50];//coluna 3 da tabela de stocks
    char col3[50];//coluna 4 da tabela de stocks
} row_structure;

typedef struct
{
    int id;
    char tipo[50];
    int tamanho;
    int quantidade;
} ordens;//estrutura para as ordens de produção

typedef struct
{
    int OP;
    int materia_prima;
    int quantidade;
}ordens_compra;//estrutura para as necessidades de compra

void carregar_stocks(MP_couro *c,MP_tecido *t,MP_borracha *b, MP_cordoes *cs, MP_palmilhas *p);
void editar_stock_min(MP_couro *c,MP_tecido *t,MP_borracha *b, MP_cordoes *cs, MP_palmilhas *p);
void necessidades_de_producao();//!!!!
void free_memoria (tabela_stock *stock);

#ifdef __cplusplus
}
#endif

#endif

File that I'm trying to read from:

Body:
you have to call strtok again in the loop

           while(token != NULL){// percorrer os tokens, e verificar qual a posição do token para preencher corretamente

                if(count == 0){op[cont].id = atoi(token);}//atoi recebe string e converte em int
                if(count == 1){strcpy(op[cont].tipo,token);}
                if(count == 2){op[cont].tamanho = atoi(token);}
                if(count == 3){op[cont].quantidade = atoi(token);}
                count ++;
                token = strtok(NULL, ";"); <<<=====
            }

otherwise you loop forever

see https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/


问:
Printing date from Year, Month and Day columns in Pandas
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

```<code>df['Year'] = pd.to_datetime(df[['Year','Month','Day']])
</code>```

But, I keep getting the error as below:

```<code>ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)
</code>```

It would be great if I can get any help for the same.

答:
Following up on my comment, I was able to reproduce the error and solve it by adding 1900 to the year

df = pd.DataFrame({"year": [61,99], "month": [1, 2], "day": [3, 12]})
df["year"] = df["year"] + 1900
df['full_date'] = pd.to_datetime(df[['year','month','day']])
```
<p>Output:</p>
```    year    month   day full_date
0   1961    1   3   1961-01-03
1   1999    2   12  1999-02-12
```
<p>There is a <code>format</code> parameter to the <code>to_datetime</code> method but for some reason I wasn't able to make it work. doc</p>
<pre class="lang-py prettyprint-override"><code>df['full_date'] = pd.to_datetime(df[['year','month','day']], format="%y%m%d", infer_datetime_format=False)
</code>```

this still throw the same error although I am using %y which should be 2 digit year but the error message still says it does not match this format '%Y%m%d'

Body:
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

df['Year'] = pd.to_datetime(df[['Year','Month','Day']])

But, I keep getting the error as below:

ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)

It would be great if I can get any help for the same.

Body:
Following up on my comment, I was able to reproduce the error and solve it by adding 1900 to the year

df = pd.DataFrame({"year": [61,99], "month": [1, 2], "day": [3, 12]})
df["year"] = df["year"] + 1900
df['full_date'] = pd.to_datetime(df[['year','month','day']])

Output:

    year    month   day full_date
0   1961    1   3   1961-01-03
1   1999    2   12  1999-02-12

There is a format parameter to the to_datetime method but for some reason I wasn't able to make it work. doc

df['full_date'] = pd.to_datetime(df[['year','month','day']], format="%y%m%d", infer_datetime_format=False)

this still throw the same error although I am using %y which should be 2 digit year but the error message still says it does not match this format '%Y%m%d'


问:
android editText
I'm looking for the easiest way (ie without rewritting a keyboard, if possible - maybe using an existing one out there?) to create an editText to input a digit password.

It's not that uncommon, yet I found no flag combination to do that.

Since it's digit only characters, I either want a digit only keyboard (ideally like on the iphone, 4*3=12 keys, 0-10+del+ok), or at least a phone-like keyboard, with ()+* and characters like that, but so that they can't be written in the textEdit.

I don't mind using deprecated flags.

In particular, number|textPassword for inputType doesn't work (characters not hidden), android:password="true" android:inputType="phone" and android:numeric="integer" android:password="true" produce the same result, but the hint text disappears and special characters are still allowed.

Thanks.

答:
```<code>//declarations
AlertDialog keyboardBuilder;
String number;
float myValue;

//building the keyboard
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.keyboard, (ViewGroup) findViewById(R.id.keyboardLayout));
keyboardBuilder = new AlertDialog.Builder(this).create();
keyboardBuilder.setView(layout);

//When you your keyboard to appear
keyboardBuilder.show();

//actions of keys
public void kb1(View v) {number += "1"; keyboardBuilder.setTitle(number);}
    public void kb2(View v) {number += "2"; keyboardBuilder.setTitle(number);}
    public void kb3(View v) {number += "3"; keyboardBuilder.setTitle(number);}
    public void kb4(View v) {number += "4"; keyboardBuilder.setTitle(number);}
    public void kb5(View v) {number += "5"; keyboardBuilder.setTitle(number);}
    public void kb6(View v) {number += "6"; keyboardBuilder.setTitle(number);}
    public void kb7(View v) {number += "7"; keyboardBuilder.setTitle(number);}
    public void kb8(View v) {number += "8"; keyboardBuilder.setTitle(number);}
    public void kb9(View v) {number += "9"; keyboardBuilder.setTitle(number);}
    public void kbPoint(View v) {number += "."; keyboardBuilder.setTitle(number);}
    public void kbE(View v) {number += "e"; keyboardBuilder.setTitle(number);}
    public void kbMoins(View v) {number += "-"; keyboardBuilder.setTitle(number);}

    public void kbDelete(View v)
    {
        if (number.length() > 0)
        {
            number = number.substring(0, number.length()-1);
        }
        keyboardBuilder.setTitle(number);
    }

    public void kbSave(View v)
    {
        try
        {
            myValue = Float.parseFloat(String.valueOf(number)));
            keyboardBuilder.dismiss();
        }
        catch(Exception e)
        {
            Toast.makeText(this,"Forbidden value.", Toast.LENGTH_SHORT).show();
        }
    }

              android:id="@+id/keyboardLayout"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="-" android:onClick="kbMoins" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="1" android:onClick="kb1" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="2" android:onClick="kb2" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="." android:onClick="kbPoint" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="3" android:onClick="kb3" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="4" android:onClick="kb4" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="e" android:onClick="kbE" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="5" android:onClick="kb5" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="6" android:onClick="kb6" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>`
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="delete" android:onClick="kbDelete" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="20px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="7" android:onClick="kb7" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="8" android:onClick="kb8" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="save" android:onClick="kbSave" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="20px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="9" android:onClick="kb9" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="0" android:onClick="kb0" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>`
        </LinearLayout>

</LinearLayout>
</code>```

If you want to hide the password you can delete the keyboardBuilder.setTitle.

The xml was poorly made for a 800*480 landscape, feel free to write it better.

You can also delete the "e", "-" and "." since you just want it for password use.

Note that the checking for not a value with the toast can be deleted, but you can replace it by checking password size for example.

ContentLicense: CC BY-SA 3.0

Title: android editText

Body:
//declarations
AlertDialog keyboardBuilder;
String number;
float myValue;

//building the keyboard
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.keyboard, (ViewGroup) findViewById(R.id.keyboardLayout));
keyboardBuilder = new AlertDialog.Builder(this).create();
keyboardBuilder.setView(layout);

//When you your keyboard to appear
keyboardBuilder.show();

//actions of keys
public void kb1(View v) {number += "1"; keyboardBuilder.setTitle(number);}
    public void kb2(View v) {number += "2"; keyboardBuilder.setTitle(number);}
    public void kb3(View v) {number += "3"; keyboardBuilder.setTitle(number);}
    public void kb4(View v) {number += "4"; keyboardBuilder.setTitle(number);}
    public void kb5(View v) {number += "5"; keyboardBuilder.setTitle(number);}
    public void kb6(View v) {number += "6"; keyboardBuilder.setTitle(number);}
    public void kb7(View v) {number += "7"; keyboardBuilder.setTitle(number);}
    public void kb8(View v) {number += "8"; keyboardBuilder.setTitle(number);}
    public void kb9(View v) {number += "9"; keyboardBuilder.setTitle(number);}
    public void kbPoint(View v) {number += "."; keyboardBuilder.setTitle(number);}
    public void kbE(View v) {number += "e"; keyboardBuilder.setTitle(number);}
    public void kbMoins(View v) {number += "-"; keyboardBuilder.setTitle(number);}

    public void kbDelete(View v)
    {
        if (number.length() > 0)
        {
            number = number.substring(0, number.length()-1);
        }
        keyboardBuilder.setTitle(number);
    }

    public void kbSave(View v)
    {
        try
        {
            myValue = Float.parseFloat(String.valueOf(number)));
            keyboardBuilder.dismiss();
        }
        catch(Exception e)
        {
            Toast.makeText(this,"Forbidden value.", Toast.LENGTH_SHORT).show();
        }
    }

              android:id="@+id/keyboardLayout"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="-" android:onClick="kbMoins" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="1" android:onClick="kb1" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="2" android:onClick="kb2" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="." android:onClick="kbPoint" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="3" android:onClick="kb3" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="4" android:onClick="kb4" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="e" android:onClick="kbE" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="5" android:onClick="kb5" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="6" android:onClick="kb6" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>`
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="delete" android:onClick="kbDelete" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="20px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="7" android:onClick="kb7" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="8" android:onClick="kb8" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
        </LinearLayout>

        <LinearLayout android:id="@+id/keyboardLayout"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:gravity="center">
                      <Button android:text="save" android:onClick="kbSave" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="20px"></Button>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <TextView android:id="@+id/espace" android:text="" android:gravity="center" android:textSize="35px" android:layout_height="65px" android:layout_width="85px"> </TextView>
                      <Button android:text="9" android:onClick="kb9" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>
                      <Button android:text="0" android:onClick="kb0" android:id="@+id/hideVerticalDocks" android:layout_height="65px" android:layout_width="85px" android:textSize="35px"></Button>`
        </LinearLayout>

</LinearLayout>

If you want to hide the password you can delete the keyboardBuilder.setTitle.

The xml was poorly made for a 800*480 landscape, feel free to write it better.

You can also delete the "e", "-" and "." since you just want it for password use.

Note that the checking for not a value with the toast can be deleted, but you can replace it by checking password size for example.


问:
Flutter app with AdMob crash after pushing to another page and moving the app to the background
Now I have a two-page app with the first page to show an adMob banner.

When I move the app to the background, everything is good.

If I navigate to the second page, one logging message is shown.

```<code>E/Surface (12399): getSlotFromBufferLocked: unknown buffer: 0xbc288b10
</code>```

Then I move the app to the background again, while in the second page, the app crashes with the following log.

```<code>E/BufferQueueProducer(12399): [ImageReader-1080x1794f1m3-12399-1](id:306f00000001,api:1,p:12399,c:12399) cancelBuffer: BufferQueue has been abandoned
D/AndroidRuntime(12399): Shutting down VM
E/AndroidRuntime(12399): FATAL EXCEPTION: main
E/AndroidRuntime(12399): Process: com.example.testapp, PID: 12399
E/AndroidRuntime(12399): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.dispatchWindowVisibilityChanged(int)' on a null object reference
4
E/AndroidRuntime(12399):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1614)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2433)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
E/AndroidRuntime(12399):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
E/AndroidRuntime(12399):    at android.view.Choreographer.doCallbacks(Choreographer.java:796)
E/AndroidRuntime(12399):    at android.view.Choreographer.doFrame(Choreographer.java:731)
E/AndroidRuntime(12399):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
E/AndroidRuntime(12399):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(12399):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(12399):    at android.os.Looper.loop(Looper.java:223)
E/AndroidRuntime(12399):    at android.app.ActivityThread.main(ActivityThread.java:7656)
E/AndroidRuntime(12399):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12399):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime(12399):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process (12399): Sending signal. PID: 12399 SIG: 9
Lost connection to device.
</code>```

The first page source

```<code>import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'second_page_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Ads"),
          ),
          body: MainBody()),
    );
  }
}

class MainBody extends StatefulWidget {
  MainBody({Key? key}) : super(key: key);

  @override
  State<MainBody> createState() => _MainBodyState();
}

class _MainBodyState extends State<MainBody> {
  late BannerAd myBanner;
  late BannerAdListener listener;
  late AdWidget adWidget;
  late Container adContainer;

  @override
  void initState() {
    super.initState();

    listener = BannerAdListener(
      onAdLoaded: (Ad ad) => print('Ad loaded.'),
      onAdFailedToLoad: (Ad ad, LoadAdError error) {
        ad.dispose();
        print('Ad failed to load: $error');
      },
      onAdOpened: (Ad ad) => print('Ad opened.'),
      onAdClosed: (Ad ad) => print('Ad closed.'),
      onAdImpression: (Ad ad) => print('Ad impression.'),
    );

    myBanner = BannerAd(
      // final BannerAd myBanner = BannerAd(
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      size: AdSize.largeBanner,
      request: const AdRequest(
        keywords: <String>['foo', 'bar'],
        contentUrl: 'http://example.com',
        nonPersonalizedAds: true,
      ),
      listener: listener,
    );

    myBanner.load();
    adWidget = AdWidget(ad: myBanner);

    adContainer = Container(
      alignment: Alignment.center,
      child: adWidget,
      width: myBanner.size.width.toDouble(),
      height: myBanner.size.height.toDouble(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    myBanner.dispose();
  }

  @override
  Widget build(BuildContext context) {
    void _pushPage() {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const SecondPageScreen(),
        ),
      );
    }

    return Column(
      children: [
        Container(
          decoration:
              BoxDecoration(border: Border.all(color: Colors.black, width: 2)),
          child: adContainer,
        ),
        TextButton(onPressed: _pushPage, child: Text('Next Page'))
      ],
    );
  }
}
</code>```

[Here is the screenshot of the first page, just for quick reference][1]
[1]: https://i.stack.imgur.com/Mdi67.png

The second page source

```<code>import 'package:flutter/material.dart';

class SecondPageScreen extends StatelessWidget {
  const SecondPageScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('second page')),
      body: Container(

        child: Text('hi')
      ),
    );
  }
}
</code>```

What I have done:

I tried following the AdMob documentation step by step:
https://developers.google.com/admob/flutter/quick-start

And I used the designated test banner ad as shown on the following page:
https://developers.google.com/admob/android/test-ads

I registered the app id in adMob

Quite sure that I made the changes in gradle/androidmanifest/pubspec files correctly.

but in vain...

答:
My friend searched me a page which produced the same exception

https://github.com/flutter/flutter/issues/96875

the problem is solved by downgrading flutter to 2.8.1

Body:
Now I have a two-page app with the first page to show an adMob banner.

When I move the app to the background, everything is good.

If I navigate to the second page, one logging message is shown.

E/Surface (12399): getSlotFromBufferLocked: unknown buffer: 0xbc288b10

Then I move the app to the background again, while in the second page, the app crashes with the following log.

E/BufferQueueProducer(12399): [ImageReader-1080x1794f1m3-12399-1](id:306f00000001,api:1,p:12399,c:12399) cancelBuffer: BufferQueue has been abandoned
D/AndroidRuntime(12399): Shutting down VM
E/AndroidRuntime(12399): FATAL EXCEPTION: main
E/AndroidRuntime(12399): Process: com.example.testapp, PID: 12399
E/AndroidRuntime(12399): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.dispatchWindowVisibilityChanged(int)' on a null object reference
4
E/AndroidRuntime(12399):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1614)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2433)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
E/AndroidRuntime(12399):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
E/AndroidRuntime(12399):    at android.view.Choreographer.doCallbacks(Choreographer.java:796)
E/AndroidRuntime(12399):    at android.view.Choreographer.doFrame(Choreographer.java:731)
E/AndroidRuntime(12399):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
E/AndroidRuntime(12399):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(12399):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(12399):    at android.os.Looper.loop(Looper.java:223)
E/AndroidRuntime(12399):    at android.app.ActivityThread.main(ActivityThread.java:7656)
E/AndroidRuntime(12399):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12399):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime(12399):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process (12399): Sending signal. PID: 12399 SIG: 9
Lost connection to device.

The first page source

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'second_page_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Ads"),
          ),
          body: MainBody()),
    );
  }
}

class MainBody extends StatefulWidget {
  MainBody({Key? key}) : super(key: key);

  @override
  State<MainBody> createState() => _MainBodyState();
}

class _MainBodyState extends State<MainBody> {
  late BannerAd myBanner;
  late BannerAdListener listener;
  late AdWidget adWidget;
  late Container adContainer;

  @override
  void initState() {
    super.initState();

    listener = BannerAdListener(
      onAdLoaded: (Ad ad) => print('Ad loaded.'),
      onAdFailedToLoad: (Ad ad, LoadAdError error) {
        ad.dispose();
        print('Ad failed to load: $error');
      },
      onAdOpened: (Ad ad) => print('Ad opened.'),
      onAdClosed: (Ad ad) => print('Ad closed.'),
      onAdImpression: (Ad ad) => print('Ad impression.'),
    );

    myBanner = BannerAd(
      // final BannerAd myBanner = BannerAd(
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      size: AdSize.largeBanner,
      request: const AdRequest(
        keywords: <String>['foo', 'bar'],
        contentUrl: 'http://example.com',
        nonPersonalizedAds: true,
      ),
      listener: listener,
    );

    myBanner.load();
    adWidget = AdWidget(ad: myBanner);

    adContainer = Container(
      alignment: Alignment.center,
      child: adWidget,
      width: myBanner.size.width.toDouble(),
      height: myBanner.size.height.toDouble(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    myBanner.dispose();
  }

  @override
  Widget build(BuildContext context) {
    void _pushPage() {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const SecondPageScreen(),
        ),
      );
    }

    return Column(
      children: [
        Container(
          decoration:
              BoxDecoration(border: Border.all(color: Colors.black, width: 2)),
          child: adContainer,
        ),
        TextButton(onPressed: _pushPage, child: Text('Next Page'))
      ],
    );
  }
}

[Here is the screenshot of the first page, just for quick reference][1]
[1]: https://i.stack.imgur.com/Mdi67.png

The second page source

import 'package:flutter/material.dart';

class SecondPageScreen extends StatelessWidget {
  const SecondPageScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('second page')),
      body: Container(

        child: Text('hi')
      ),
    );
  }
}

What I have done:

I tried following the AdMob documentation step by step:
https://developers.google.com/admob/flutter/quick-start

And I used the designated test banner ad as shown on the following page:
https://developers.google.com/admob/android/test-ads

I registered the app id in adMob

Quite sure that I made the changes in gradle/androidmanifest/pubspec files correctly.

but in vain...


问:
Gmail push notifications not triggered when inbox changes
I have a webhook that is receiving messages published from a topic via a subscription.

I also gave "Pub/Sub Publisher" role to gmail-api-push@system.gserviceaccount.com

I expected this to be sufficient to setup notifications for new mails.

Is there something I missed?

答:
Indeed, I had a functional Subscriber (my webhook). So, once the messages where available, I got notified. The issue was that I did not requested a watch.

https://developers.google.com/gmail/api/reference/rest/v1/users/watch

At this moment I had 2 more issues:

Requesting a watch as per example above requires oAuth authentification.

Push notifications only contains the historyId of the email. Not the Email ID required to fetch the content.

The email content can be fetched via https://developers.google.com/gmail/api/reference/rest/v1/users.messages/get

I foud a solution in assigning domain-wide permissions to my service. Now I can read my own emails without using a oAuth popup to authentificate my user.

Client is unauthorized to retrieve access tokens using this method Gmail API C#