text:
Q: How to check if the user is logged in, if so show other screen? My first screen is a login screen and it needs to check if the user is logged in to open the home screen directly but I get an error using this check.
I'm doing the check on initState, the condition is returning true, so looks like the problem is with the Navigator.
What is the correct way to skip the first screen if the user is logged in?
Error:
I/flutter (20803): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (20803): The following assertion was thrown building Navigator-[GlobalObjectKey<NavigatorState>
I/flutter (20803): _WidgetsAppState#8ce27](dirty, state: NavigatorState#db484(tickers: tracking 2 tickers)):
I/flutter (20803): 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2106 pos 12: '!_debugLocked':
I/flutter (20803): is not true.
I/flutter (20803): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (20803): more information in this error message to help you determine and fix the underlying cause.

Code:
class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {

  final _emailController = TextEditingController();
  final _passController = TextEditingController();

  final _formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

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

    if(FirebaseAuth.instance.currentUser() != null){

      Navigator.of(context).pushReplacement(MaterialPageRoute(
        builder: (context) => HomeScreen()
      ));
    }

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      key: _scaffoldKey,
      body: ScopedModelDescendant<UserModel>(
          builder: (context, child, model){

            if(model.isLoading)
              return Center(
                child: CircularProgressIndicator(),
              );

            return Form(
              key: _formKey,
              child: ListView(
                padding: EdgeInsets.all(16),
                children: <Widget>[
                  SizedBox(height: 67),
                  Icon(Icons.chrome_reader_mode, size: 150, color: Colors.blue,),
                  SizedBox(height: 16,),
                  TextFormField(
                    controller: _emailController,
                    decoration: InputDecoration(
                        hintText: "Digite seu e-mail",
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                        ),
                      fillColor: Colors.blueAccent
                    ),
                    keyboardType: TextInputType.emailAddress,
                    validator: (text){
                      if(text.isEmpty || !text.contains("@"))
                        return "E-mail inválido!";
                    },
                  ),
                  SizedBox(height: 16,),
                  TextFormField(
                    controller: _passController,
                    decoration: InputDecoration(
                        hintText: "Digite sua senha",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                        fillColor: Colors.blueAccent
                    ),
                    obscureText: true,
                    validator: (text){
                      if(text.isEmpty || text.length < 6)
                        return "Digite a senha!";
                    },
                  ),
                  SizedBox(height: 16,),
                  FlatButton(
                    padding: EdgeInsets.all(13),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)
                    ),
                    color: Colors.blue,
                      child: Text("Entrar",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20
                        ),
                      ),
                      onPressed: (){

                          if(_formKey.currentState.validate()){

                            model.signIn(

                              email: _emailController.text,
                              pass: _passController.text,
                              onSuccess: _onSuccess,
                              onFail: _onFail,

                            );

                          }

                      },
                  ),
                  SizedBox(height: 10,),
                  InkWell(
                    onTap: (){

                      if(_emailController.text.isEmpty || !_emailController.text.contains("@")){

                        _scaffoldKey.currentState.showSnackBar(
                            SnackBar(content: Text("Insira um e-mail válido para recuperação",
                              style: TextStyle(fontSize: 14),
                            ),
                              backgroundColor: Colors.redAccent,
                              duration: Duration(seconds: 3),
                            )
                        );

                      } else {
                         model.recoverPass(_emailController.text);
                         _scaffoldKey.currentState.showSnackBar(
                           SnackBar(
                             content: Text("O e-mail de recuperação foi enviado!",
                               style: TextStyle(fontSize: 14),
                             ),
                             backgroundColor: Colors.green,
                             duration: Duration(seconds: 3),
                           )
                         );
                      }

                    },
                    child: Text("Esqueci minha senha",
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 16,
                          fontWeight: FontWeight.w400
                      ),
                      textAlign: TextAlign.center,

                    ),
                  ),
                  SizedBox(height: 30,),
                  InkWell(
                    onTap: (){

                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (context)=> SignUpScreen())
                      );

                    },
                    child: Text("Não tem conta? Cadastre-se!",
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                        fontWeight: FontWeight.w600
                      ),
                      textAlign: TextAlign.center,

                    ),
                  ),
                ],
              ),
            );

          },
      ),

    );
  }

}

A: Make use of FirebaseAuth to get the current user. If the user is not logged in the value is null otherwise, the user is logged in.
// Get the firebase user
User firebaseUser = FirebaseAuth.instance.currentUser;
// Define a widget
Widget firstWidget;

// Assign widget based on availability of currentUser
if (firebaseUser != null) {
  firstWidget = Home();
} else {
  firstWidget = LoginScreen();
}

// Run the app with appropriate screen
return MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'UniClass',
  theme: ThemeData(
    primaryColor: kPrimaryColor,
    scaffoldBackgroundColor: Colors.white,
  ),
  home: firstWidget,
);

A: I did it using Shared preferences in main.dart file.
Worked fine for me.
Widget build(BuildContext context) {
return FutureBuilder(
    future: SharedPreferences.getInstance(),
    builder:
        (BuildContext context, AsyncSnapshot<SharedPreferences> prefs) {
      var x = prefs.data;
      if (prefs.hasData) {
        if (x.getBool('isloggedin')) {
          if (x.getString('type') == 'doctor') {
            return MaterialApp(home: DrHome());
          } else
            return MaterialApp(home: PtHome());
        }
      }

      return MaterialApp(home: SignIn());
    });
}

A: Well you can solve this kind of problem using another approach. Instead check if there is user logged inside your loginScreen class you can do this a step before and then decide if you will show the loginScreen if there is no user logged or show another screen, MainScreen I' am supposing, if the user is already logged.
I will put some snipet showing how to accomplish this. I hope it helps. But before I will explain you what is wrong in your source code.
if(FirebaseAuth.instance.currentUser() != null){
      // wrong call in wrong place!
      Navigator.of(context).pushReplacement(MaterialPageRoute(
        builder: (context) => HomeScreen()
      ));
}

Your code is broken because currentUser() is a async function and when you make the call this function is returning a incomplete Future object which is a non null object. So the navigator pushReplacement  is always been called and it's crashing because the state of your widget is not ready yet.
Well as solution you can user FutureBuilder and decide which screen you will open.
int main(){
   runApp(  YourApp() )
}

class YourApp extends StatelessWidget{

    @override
    Widget build(BuildContext context){
        return FutureBuilder<FirebaseUser>(
            future: FirebaseAuth.instance.currentUser(),
            builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot){
                       if (snapshot.hasData){
                           FirebaseUser user = snapshot.data; // this is your user instance
                           /// is because there is user already logged
                           return MainScreen();
                        }
                         /// other way there is no user logged.
                         return LoginScreen();
             }
          );
    }
}

Using this approach you avoid your LoginScreen class to verify if there is a user logged!
As advise you can make use of snapshot.connectionState property with a switch case to implement a more refined control.

A: Achieved without Firebase, but by using SharedPreferences
find code at gist
here is a simple code: Main.dart
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  var isLoggedIn = (prefs.getBool('isLoggedIn') == null) ? false : prefs.getBool('isLoggedIn');
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: isLoggedIn ? anotherPage() : loginPage(),
  ));
}

using flutter package: shared_preferences
DemoApp if you don't want to use SharedPreferences in Main()

A: I don't know if this will be of help for any other person, but my approach was to use Provider and create another class called wrapper, this class will be in charge of switching btw screens without stress... I don't know how you did your auth, But I do all my auth inside another class which I create and name AuthService inside AuthService all auths are done
class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<UserModels>(context);
    if (user == null) {
      return LoginScreen();
    } else {
      return HomeScreen();
    }
  }
}

Now for your auth
class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  //create user object based on firebase user
  UserModels _userFromFirebaseUser(User user) {
    return user != null ? UserModels(uid: user.uid) : null;
  }

  //auth change user stream
  Stream<UserModels> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser);
  }

// sign in with email and password
  Future signInUser(String email, String pwd, {context}) async {
    try {
      await _auth
          .signInWithEmailAndPassword(email: email, password: pwd)
          .then((result) {
        User user = result.user;
        return _userFromFirebaseUser(user);
      }).catchError((err) {
        if (err.code == 'user-not-found') {
          Flushbar(
            message: "No user found for that email.",
            duration: Duration(seconds: 7),
          )..show(context);
        } else if (err.code == 'wrong-password') {
          Flushbar(
            message: "Wrong password provided for that user.",
            duration: Duration(seconds: 7),
          )..show(context);
        } else {
          Flushbar(
            message: "Internal Error: Something went wrong.",
            duration: Duration(seconds: 7),
          )..show(context);
        }
      });
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

Now go to your sign-in button onpress
onPressed: () async {
   var form = formKey.currentState;
    if (form.validate()) {
      setState(() {
        _isChecking = true;
      });
      String email = _email.text;
      String pwd = _pwd.text;

      await _authService
          .signInUser(email, pwd, context: context)
          .then((result) {
        if (result != null) {
          setState(() {
            _isChecking = false;
          });
        } else {
          setState(() {
            _isChecking = false;
          });
        }
      }).catchError((error) {
        setState(() {
          _isChecking = false;
        });
      });
    }
},

This should do all the job for you without you thinking about it too much

A: I used Flutter Secure Storage token. I will delete the token when user logoff explicitly so the null check.
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: UserSecureStorage.getAuthToken(),
      builder: (BuildContext context, AsyncSnapshot<String?> token) {
        return GetMaterialApp(
          title: "app",
          home: (token.hasData && token.data != null) ? HomePage() : LoginPage()
        );
      }
    );
  }
}

A: it's working for me. null safety supported.
import 'package:firebase_auth/firebase_auth.dart';

FirebaseAuth auth = FirebaseAuth.instance;

FirebaseAuth.instance
    .authStateChanges()
    .listen((User? user) {
  if (user == null) {
    print('User is currently signed out!');
  } else {
    print('User is signed in!');
  }
 });

A: This is what I got, after opening several web pages
Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); // waiting for firebase initialization to finish
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  Widget build(BuildContext context){
    bool isLoggedIn = FirebaseAuth.instance.currentUser != null ? true : false; // check user logged in or not
    if (isLoggedIn) { // if user is logged in, open dashboard
      return MaterialApp(
        home: dashboard(), //dashboard
      );
    } else {// if user isn't logged in, open login page
      return MaterialApp(
        home: loginWithGoogle(), //login page
      );
    }
  }

}

A: use this, I had the same error (Navigator error called on null) and I fixed it.
In your code add await before firebase Auth
just check this solution:
 @override
  void initState() {
    super.initState();
    detectUser();
  }

  void detectUser() async {
    setState(() {
      loading = true;
    });
    FirebaseAuth _auth1 = await FirebaseAuth.instance;

    if (_auth1.currentUser != null) {
      print('email: ' + _auth1.currentUser.email);
      Navigator.push(
        context,
        CupertinoPageRoute(
          builder: (context) => Main(),
        ),
      );
      setState(() {
        loading = false;
      });
    } else {
      //print(user1);
      setState(() {
        loading = false;
      });
    }
  }


text:
Q: why there is no running process, but there is an error saying" cuda out of memory"? enter image description here
In the code part, i set device='cuda'

A: The process was killed because it raised a Runtime error because of your GPU device ran out of memory. And by the time you entered nvidia-smi in the console, the GPU memory was already cleared.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate a range of dates using SQL I have a SQL query that takes a date parameter (if I were to throw it into a function) and I need to run it on every day of the last year.
How to generate a list of the last 365 days, so I can use straight-up SQL to do this?
Obviously generating a list 0..364 would work, too, since I could always:
SELECT SYSDATE - val FROM (...);

A: A method quite frequently used in Oracle is something like this:
select trunc(sysdate)-rn
from
(   select rownum rn
    from   dual
    connect by level <= 365)
/

Personally, if an application has a need for a list of dates then I'd just create a table with them, or create a table with a series of integers up to something ridiculous like one million that can be used for this sort of thing.

A: Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.
SELECT c1 from dual
  MODEL DIMENSION BY (1 as rn)  MEASURES (sysdate as c1)
  RULES ITERATE (365)
  (c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1

A: About a year and a half too late, but for posterity here is a version for Teradata:
SELECT calendar_date
FROM SYS_CALENDAR.Calendar
WHERE SYS_CALENDAR.Calendar.calendar_date between '2010-01-01' (date) and '2010-01-03' (date)

A: Date range between 12/31/1996 and 12/31/2020
SELECT dt, to_char(dt, 'MM/DD/YYYY') as date_name,
  EXTRACT(year from dt) as year,
  EXTRACT(year from fiscal_dt) as fiscal_year,
  initcap(to_char(dt, 'MON')) as month,
  to_char(dt, 'YYYY')        || ' ' || initcap(to_char(dt, 'MON')) as year_month,
  to_char(fiscal_dt, 'YYYY') || ' ' || initcap(to_char(dt, 'MON')) as fiscal_year_month,
  EXTRACT(year from dt)*100        + EXTRACT(month from dt) as year_month_id,
  EXTRACT(year from fiscal_dt)*100 + EXTRACT(month from fiscal_dt) as fiscal_year_month_id,
  to_char(dt, 'YYYY')        || ' Q' || to_char(dt, 'Q') as quarter,
  to_char(fiscal_dt, 'YYYY') || ' Q' || to_char(fiscal_dt, 'Q') as fiscal_quarter
  --, EXTRACT(day from dt) as day_of_month, to_char(dt, 'YYYY-WW') as week_of_year, to_char(dt, 'D') as day_of_week
  FROM (
    SELECT dt, add_months(dt, 6) as fiscal_dt --starts July 1st
    FROM (
      SELECT TO_DATE('12/31/1996', 'mm/dd/yyyy') + ROWNUM as dt
      FROM DUAL CONNECT BY ROWNUM < 366 * 30 --30 years
    )
    WHERE dt <= TO_DATE('12/31/2020', 'mm/dd/yyyy')
  )

A: Ahahaha, here's a funny way I just came up with to do this:
select SYSDATE - ROWNUM
from shipment_weights sw
where ROWNUM < 365;

where shipment_weights is any large table;

A: I had the same requirement - I just use this. User enters the number of days by which he/she wants to limit the calendar range to.
  SELECT DAY, offset
    FROM (SELECT to_char(SYSDATE, 'DD-MON-YYYY') AS DAY, 0 AS offset
            FROM DUAL
          UNION ALL
          SELECT to_char(SYSDATE - rownum, 'DD-MON-YYYY'), rownum
            FROM all_objects d)
            where offset <= &No_of_days

I use the above result set as driving view in LEFT OUTER JOIN with other views involving tables which have dates.

A: A week from 6 months back
SELECT (date'2015-08-03' + (LEVEL-1)) AS DATES
 FROM DUAL
 where ROWNUM < 8
 connect by level <= (sysdate-date'2015-08-03');

if you omit ROWNUM you get 50 rows only, independent of the value.

A: Better late than never.  Here's a method that I devised (after reading this post) for returning a list of dates that includes: (a) day 1 of of the current month through today, PLUS (b) all dates for the past two months:
select (sysdate +1 - rownum) dt
from dual
 connect by rownum <= (sysdate - add_months(sysdate - extract(day from sysdate),-2));

The "-2" is the number of prior full months of dates to include.  For example, on July 10th, this SQL returns a list of all dates from May 1 through July 10 - i.e. two full prior months plus the current partial month.

A: Another simple way to get 365 days from today would be:
SELECT (TRUNC(sysdate) + (LEVEL-366)) AS DATE_ID
FROM DUAL connect by level <=( (sysdate)-(sysdate-366));

A: Recently I had a similar problem and solved it with this easy query:
SELECT
  (to_date(:p_to_date,'DD-MM-YYYY') - level + 1) AS day
FROM
  dual
CONNECT BY LEVEL <= (to_date(:p_to_date,'DD-MM-YYYY') - to_date(:p_from_date,'DD-MM-YYYY') + 1);

Example
SELECT
  (to_date('01-05-2015','DD-MM-YYYY') - level + 1) AS day
FROM
  dual
CONNECT BY LEVEL <= (to_date('01-05-2015','DD-MM-YYYY') - to_date('01-04-2015','DD-MM-YYYY') + 1);

Result
01-05-2015 00:00:00
30-04-2015 00:00:00
29-04-2015 00:00:00
28-04-2015 00:00:00
27-04-2015 00:00:00
26-04-2015 00:00:00
25-04-2015 00:00:00
24-04-2015 00:00:00
23-04-2015 00:00:00
22-04-2015 00:00:00
21-04-2015 00:00:00
20-04-2015 00:00:00
19-04-2015 00:00:00
18-04-2015 00:00:00
17-04-2015 00:00:00
16-04-2015 00:00:00
15-04-2015 00:00:00
14-04-2015 00:00:00
13-04-2015 00:00:00
12-04-2015 00:00:00
11-04-2015 00:00:00
10-04-2015 00:00:00
09-04-2015 00:00:00
08-04-2015 00:00:00
07-04-2015 00:00:00
06-04-2015 00:00:00
05-04-2015 00:00:00
04-04-2015 00:00:00
03-04-2015 00:00:00
02-04-2015 00:00:00
01-04-2015 00:00:00

A:  SELECT (sysdate-365 + (LEVEL -1)) AS DATES
 FROM DUAL connect by level <=( sysdate-(sysdate-365))

if a 'from' and a 'to' date is replaced in place of sysdate and sysdate-365, the output will be a range of dates between the from and to date.

A: There's no need to use extra large tables or ALL_OBJECTS table:
SELECT TRUNC (SYSDATE - ROWNUM) dt
  FROM DUAL CONNECT BY ROWNUM < 366

will do the trick.

A: For the fun of it, here's some code that should work in SQL Server, Oracle, or MySQL:
SELECT current_timestamp - CAST(d1.digit + d2.digit + d3.digit as int)
FROM
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d1
CROSS JOIN
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d2
CROSS JOIN
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d3
WHERE CAST(d1.digit + d2.digit + d3.digit as int) < 365
ORDER BY d1.digit, d2.digit, d3.digit -- order not really needed here

Bonus points if you can give me a cross-platform syntax to re-use the digits table.

A: I do this so often for a scheduling app I work on that I created a pipelined table function.  Sometimes I need days, hours or 15 minutes between times.  This is not exactly the same function I use, because my code is in a package.  However, here, I'm getting days between Jan 1 2020 and Jan 10 2020:
SELECT
    days.date_time
FROM
    table(between_times(TO_DATE('2020-01-01'),TO_DATE('2020-01-10'),(60*24), 'Y')) days

The pipelined function:
function between_times(i_start_time TIMESTAMP, i_end_time TIMESTAMP, i_interval_in_minutes NUMBER, include_end_time VARCHAR2 := 'N')
  RETURN DateTableType  PIPELINED
  AS
    time_counter TIMESTAMP := i_start_time;
  BEGIN
    IF i_start_time IS NULL OR i_end_time IS NULL or i_start_time > i_end_time OR i_interval_in_minutes IS NULL OR
      i_interval_in_minutes <= 0 THEN
        RETURN;
      END IF;
      LOOP

        -- by default does not include end time
        if (include_end_time = 'Y') THEN
          exit when time_counter > i_end_time;
        ELSE
          exit when time_counter >= i_end_time;
        END IF;

        pipe row(DateType( time_counter ));
        time_counter := time_counter + i_interval_in_minutes/(60*24);

      END LOOP;

      EXCEPTION  WHEN NO_DATA_NEEDED THEN NULL;
  END;

A: WITH Date_Table (Dates, Heading) AS  -- Using Oracle SQL
(SELECT  TRUNC(SYSDATE) Dates, '  Start' as Heading FROM dual
UNION ALL
SELECT TRUNC(DATES-1) ,  '  Inside recursion' as Heading FROM Date_Table
WHERE Dates > sysdate-365 )  -- Go back one year
SELECT TO_CHAR(Dates,'MM/DD/YYYY')
FROM Date_Table
ORDER BY Dates DESC;

A: I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.
print("code sample");

select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select  1 as A union
select  2 union
select  3 union
select  4 union
select  5 union
select  6 union
select  7 union
select  8 union
select  9 union
select  10 union
select  11 union
select  12 union
select  13 union
select  14 union
select  15 union
select  16 union
select  17 union
select  18 union
select  19 union
select  20 union
select  21
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");

A: This query generates a list of dates 4000 days in the future and 5000 in the past as of today (inspired on http://blogs.x2line.com/al/articles/207.aspx):
SELECT * FROM (SELECT
    (CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) AS Date,
    year(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Year,
    month(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Month,
    day(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Day
           FROM (SELECT 0 AS num union ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n1
               ,(SELECT 0 AS num UNION ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n2
               ,(SELECT 0 AS num union ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n3
               ,(SELECT 0 AS num UNION ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8) n4
        ) GenCalendar  ORDER BY 1


text: Q: Flexagons - where to learn the theory behind them? The subject says it all! A friend of mine introduced me to these cool objects made of paper strips, and I was wondering if anyone could point me to any resources (ideally freely accessible) to learn more about the mathematical theory behind them.


text:
Q: Convert.ToDateTime , any way to depict month and year fields C#? I have the following wonderfully unreliable statement:
  string LastsuccessfuldownloadDateTime = "04.07.2009 19:21:36"
  DateTime myDate = Convert.ToDateTime(LastsuccessfuldownloadDateTime);

Is it possible to depict the day and month fields explicitly in the conversion?
Because my month and day fields are getting swapped....
Thanks

A: You can use DateTime.ParseExact():
// for European format (day followed by month)
DateTime myDate = DateTime.ParseExact(LastsuccessfuldownloadDateTime ,
                                      "dd.MM.yyyy HH:mm:ss", null);


text:
Q: What will be the implementation code of RecyclerView and CardView under dependencies for target SDK Version 29 I am a beginner in android development course,
Can anyone please tell me, what will be the implementation code of RecyclerView and Card view under dependencies for target SDK Version 29.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.myfirstapplication.recyclerview"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

        buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

A: This may help you
implementation 'com.google.android.material:material:1.3.0-alpha03'


text:
Q: Applying event handler on newly added element This is the the code i am trying in jquery.
$(document).ready(function()
{

$("#button1").bind("click", function(){
  $("tr:contains('Clothing')").after("
Special offer!!!
");
  });

$("#removeit").live('click', function(){

  $(".special").remove();

  $("p").text("its remove");

  });

  $("#removeit").trigger("click");

});

Problem : when i click on #removeit button it doesn't remove the row(tr) with special offer I have added earlier, I tried different event method like: live, on but nothing works.

A: Take a look at this (may be it'll give you an idea)
$(document).ready(function()
{
    $("#button1").on("click", function(){
        $("tr:contains('Clothing')")
        .after("
Special offer!!!	<button class='removeit btn btn-mini'>Remove</button>
");
    });

    $('.myTable').on('click', '.removeit', function(){
        $(this).closest('tr').remove();
        $("p#msg").text("it\'s removed");
    });
});

DEMO.
Also this could be helpful .


text:
Q: Flutter Stackoverflow Error when using Firebase I don't know where this Stackoverflow Error comes from
I/flutter (20342): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
    I/flutter (20342): The following StackOverflowError was thrown building Analytics(dirty):
    I/flutter (20342): Stack Overflow
    I/flutter (20342):
    I/flutter (20342): The relevant error-causing widget was:
    I/flutter (20342):   Analytics
    I/flutter (20342):   file:///C:/Users/OneDrive/Dokumente/Development/GitHub/trimlog/src/flutter_app/lib/screens/wrapper.dart:87:11
    I/flutter (20342):
    I/flutter (20342): When the exception was thrown, this was the stack:
    I/flutter (20342): #0      _LinkedHashMapMixin._getValueOrData (dart:collection-patch/compact_hash.dart:331:3)
    I/flutter (20342): #1      _LinkedHashMapMixin.containsKey (dart:collection-patch/compact_hash.dart:355:54)
    I/flutter (20342): #2      FirebaseFirestore.instanceFor (package:cloud_firestore/src/firestore.dart:50:26)
    I/flutter (20342): #3      new Database (package:Trimlog/services/database/database.dart:39:97)
    I/flutter (20342): #4      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #5      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #6      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #7      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #8      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #9      new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #10     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #11     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #12     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #13     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #14     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #15     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #16     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #17     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #18     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #19     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #20     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #21     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #22     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #23     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #24     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #25     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #26     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #27     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #28     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #29     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #30     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #31     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #32     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #33     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #34     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #35     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #36     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #37     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #38     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #39     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #40     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #41     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #42     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): #43     new Database (package:Trimlog/services/database/database.dart)
    I/flutter (20342): ...
    I/flutter (20342): ...
    I/flutter (20342): #15600  ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4606:5)
    I/flutter (20342): #15601  StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4791:11)
    I/flutter (20342): #15602  ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
    I/flutter (20342): ...     Normal element mounting (7 frames)
    I/flutter (20342): #15609  Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
    I/flutter (20342): #15610  Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
    I/flutter (20342): #15611  SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1158:36)
    I/flutter (20342): #15612  SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1143:20)
    I/flutter (20342): #15613  BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2683:19)
    I/flutter (20342): #15614  SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1136:11)
    I/flutter (20342): #15615  RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:350:23)
    I/flutter (20342): #15616  RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1883:59)
    I/flutter (20342): #15617  PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:915:15)
    I/flutter (20342): #15618  RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1883:14)
    I/flutter (20342): #15619  RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:339:5)
    I/flutter (20342): #15620  RenderSliverMultiBoxAdaptor.insertAndLayoutChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:485:5)
    I/flutter (20342): #15621  RenderSliverFixedExtentBoxAdaptor.performLayout (package:flutter/src/rendering/sliver_fixed_extent_list.dart:259:17)
    I/flutter (20342): #15622  RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
    I/flutter (20342): #15623  RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:132:12)
    I/flutter (20342): #15624  _RenderSliverFractionalPadding.performLayout (package:flutter/src/widgets/sliver_fill.dart:170:11)
    I/flutter (20342): #15625  RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
    I/flutter (20342): #15626  RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:507:13)
    I/flutter (20342): #15627  RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1561:12)
    I/flutter (20342): #15628  RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1470:20)
    I/flutter (20342): #15629  RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1634:7)
    I/flutter (20342): #15630  PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:884:18)
    I/flutter (20342): #15631  RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:436:19)
    I/flutter (20342): #15632  WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:914:13)
    I/flutter (20342): #15633  RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5)
    I/flutter (20342): #15634  SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
    I/flutter (20342): #15635  SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9)
    I/flutter (20342): #15636  SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5)
    I/flutter (20342): #15640  _invoke (dart:ui/hooks.dart:251:10)
    I/flutter (20342): #15641  _drawFrame (dart:ui/hooks.dart:209:3)
    I/flutter (20342): (elided 3 frames from dart:async)
    I/flutter (20342):
    I/flutter (20342): ════════════════════════════════════════════════════════════════════════════════════════════════════
    I/flutter (20342): Another exception was thrown: NoSuchMethodError: The getter 'analytic' was called on null.

In my main.dart
class Instances {
  static Database database = new Database();
}

In database.dart
class Database {
  final _databaseReference = FirebaseFirestore.instance; // Instance of Firebase
  final user = new DatabaseUser();
  final boat = new DatabaseBoat();
  final trim = new DatabaseTrim();
  final analytic = new DatabaseAnalytic();

In database_analytic.dart
class DatabaseAnalytic extends Database {

How I access for example DatabaseAnalytic
Instances.database.analytic.deleteAnalyticOfBoat(widget.boat.documentid, widget.analytic.documentid)

wrapper.dart: https://hastebin.com/eholocelug.java
Can someone tell me where the error comes from?
I have seen, that it says "The getter 'analytic' was called on null.", but I cannot figure out why that is.
I am also not sure whether this is the best way to work with the Database, if there is a better way it would be great if you let me know.

A: We can see this in your error output

Another exception was thrown: NoSuchMethodError: The getter 'analytic' was called on null.

With this line
Instances.database.analytic.deleteAnalyticOfBoat(widget.boat.documentid,widget.analytic.documentid)

Your error assumes that Instances.database is null

A: If you look at the rest of the error, Database is constantly being instantiated over and over again.   Database is instantiating DatabaseAnalytic which is instantiating Database again.  It's what is causing an overflow error.


text:
Q: Enviar una variable al controlador desde AJAX en CodeIgniter Tengo el siguiente problema, en una vista obtengo los datos de un usuario a través de un foreach y uno de ellos es el código, el cual mediante un enlace, ejecuto una función que le paso como parámetro el mismo código:
<a  href="" onclick="cargarID(<?=$fila->Id_usuario?>)"><?=$fila->Id_usuario?>

La función envía el id a un método de mi controlador:

Éste es mi controlador, hago esto porque necesito enviarle un parámetro a una consulta que tengo en el modelo.
function index()
{
  $this->load->view('guest/section');
  $datos['arrPerfil'] = $this->model_usuario->consulta();
  $this->load->view('user/usuario_view', $datos);
}
public function getID($id)
{
  if($id) {
    $data = $this->model_usuario->consulta($id);
    echo json_encode($data);
  }
}

A: Suponiendo que la siguiente linea funciona:
<a  href="" onclick="cargarID(<?=$fila->Id_usuario?>)"><?=$fila->Id_usuario?>

Y esta llegando correctamente el Id_usuario.
Tu función
function cargarID(id= null){
      if(id) {
      $.ajax({
        url:"http://localhost/sistema/usuario_consulta/getID/"+id,
      type:"POST",
      dataType: 'json',
      success:function(respuesta){
         window.location.href = "http://localhost/sistema/usuario_consulta/index";
       }
     });
    }
   }

Está mal en la parte de la llamada ajax especificamente en:
type:"POST",

Esta enviando una peticion post y en tu controlador en codeigniter lo que esperas es una peticion get
public function getID($id)
{
  if($id) {
    $data = $this->model_usuario->consulta($id);
    echo json_encode($data);
  }
}

No se que devuelve tu consulta en model_usario pero ahi deberias devolver un arreglo que después puedas recorrer con jquery o javascript.
Lo que podrías hacer es cambiar el tipo de petición en la llamada ajax de POST a GET, o mejor te recomendaría que lo hagas mediante POST y tambien cambies tu controlador en codeigniter, para que tengas mayor control de los datos que envias.
Por ejemplo tu llamada ajax quedaria:
function cargarID(id){
   if(id != null) {
         $.ajax({
            url:"http://localhost/sistema/usuario_consulta/getID",
            type:"POST",
            dataType: 'json',
            data: {'id_persona': id},
            success:function(respuesta){
             window.location.href = "http://localhost/sistema/usuario_consulta/index";
           }
         });
   }
}

Y tu funcion getID en el controlador quedaría:
public function getID()
{
  $id = $this->input->post("id_persona");
  if($id != null) {
    $data = $this->model_usuario->consulta($id);

    header('Content-Type: application/json');
    echo json_encode($data);
  }
}

A: Prueba con async:false, y saca el success fuera:


text:
Q: Calculo IMC retnornando NaN JS Estou tendo problema no cálculo simples de IMC já tentei de tudo mas não consigo resolver.
O retorno do cálculo é sempre NaN.
Código:

let paciente_um = document.querySelector("#primeiroPaciente");

let tdpeso = paciente_um.querySelector(".info-peso");

tdpeso.textContent ="200";

let tdAltura = paciente_um.querySelector(".info-altura");
tdAltura.textContent = "4.00";

let imc = tdpeso/(tdAltura*tdAltura);
let tdImc = paciente_um.querySelector(".info-imc");
tdimc.textContent = imc;

Aparecida Nutrição

Meus pacientes

                            Nome
                            Peso(kg)
                            Altura(m)
                            Gordura Corporal(%)
                            IMC

                            Paulo
                            100
                            2.00
                            10
                            0

                            João
                            80
                            1.72
                            40
                            0

                            Erica
                            54
                            1.64
                            14
                            0

                            Douglas
                            85
                            1.73
                            24
                            0

                            Tatiana
                            46
                            1.55
                            19
                            0

A: Sim lucas resolveu o problema, porem apenas criei uma variavel para receber a propriedade peso.textContent e altura.
let paciente_um = document.querySelector("#primeiroPaciente");

let tdpeso = paciente_um.querySelector(".info-peso");

let peso = tdpeso.textContent = 100;

let tdAltura = paciente_um.querySelector(".info-altura");
let altura = tdAltura.textContent = 1.70;

let imc = peso/(altura*altura);

let tdImc = paciente_um.querySelector(".info-imc");
tdImc.textContent = imc;

A: Como @Danizavtz disse, você não pode realizar cálculos com o tipo string (que são os dados exibidos na tabela).
Você também não está acessando os valores das células da tabela.
Tenta esse código:
let paciente_um = document.querySelector("#primeiroPaciente");

let tdpeso = parseFloat(paciente_um.querySelector(".info-peso").innerHTML);

let tdAltura = parseFloat(paciente_um.querySelector(".info-altura").innerHTML);

let imc = tdpeso/(tdAltura*tdAltura);
let tdImc = paciente_um.querySelector(".info-imc");
tdImc.textContent = imc;


text:
Q: How to get the container ID from docker-py I'm trying to check whether a docker container is up or not using filter of docker-py module. However able to check whether it is up or down.
For reference :
def checkDockerContainerStatus( container):
    client = docker.from_env()
    cli = docker.APIClient()
    if client.containers.list(filters={'name': container}):
        response = client.containers.list(filters={'name': container})
        return 'Up'
    else:
        return 'Down'

checkDockerContainerStatus('app-container')

and I got response as [<Container: eb42d23b6f>]
How to retrieve the container id from this response inorder to check it is log .
I tried response['container'] , but it didn't work out. May I know to get the result as my requirement

A: The a lot of id's is confusing in docker.
You can read about types of id's here.
When you understand what is short form and long form of container id your code can be something like:
import docker

def checkDockerContainerStatus( container):
    client = docker.from_env()
    #cli = docker.APIClient()
    if client.containers.list(filters={'name': container}):
        response = client.containers.list(filters={'name': container})
        return str(response[0].id)[:12]
    else:
        return None

running_id = checkDockerContainerStatus('app-container')

if running_id is not None:
    print(f"Found! {running_id}")
else:
    print("Container app-container is not found")

Also I would recommend to use docker SDK instead docker-py.
Your code wont run on docker-py and run properly on docker SDK.


text:
Q: R - How to create a loop which bases its function on a previous value in a column without specifying exactly what this value is I am trying to predict population numbers for every country in the world. I want to do this by using the previous year population and multiplying it by the predicted growth for the current year. Because I will have multiple countries in the dataframe I want the code to identify the last population for Afghanistan for example, rather than going off the previous row, which could be another country like Bangladesh for example.
The ALL_DATA is my data frame and contains the below columns
Country - AFG
Code - AFG_2016
Population - 200000
Growth - 0.0002

I have tried ordering the data and using the below loop, however, it struggles ordering the data with multiple countries and years with NAs.
ALL_DATA[order(ALL_DATA$Code)

index<-min(which(is.na(ALL_DATA$Population)))
for(i in index:dim(ALL_DATA[1])){ALL_DATA$Population[i]<-(ALL_DATA$Population[i-1]*(1+ALL_DATA$Growth[i]))
}

Thanks for your help, let me know if you require anymore information


text:
Q: Finding the largest value in a python set I am writing a program that asks a user to input 10 integers, then points to the largest odd integer among them. If no odd numbers are entered then a message should be printed to that effect.
What I have already is below:
a = int(input("Enter an integer: "))
b = int(input("Enter an integer: "))
c = int(input("Enter an integer: "))
d = int(input("Enter an integer: "))
e = int(input("Enter an integer: "))
f = int(input("Enter an integer: "))
g = int(input("Enter an integer: "))
h = int(input("Enter an integer: "))
i = int(input("Enter an integer: "))
j = int(input("Enter an integer: "))

numset = [a, b, c, d, e, f, g, h, i, j]
oddset = []
if (a%2, b%2, c%2, d%2, e%2, f%2, g%2, h%2, i%2, j%2) == (0, 0, 0, 0, 0, 0, 0, 0, 0, 0):
    print("No odd number was entered.")
else:
    for x in numset:
        if x%2 == 1:
            oddset.append(int(x))
    print(oddset)

I was able to identify all entered odd integers, but I'm stumped when it comes to picking out the largest from my list of odd numbers I called oddset. It may be an easy addition, but I am new to python so all help is appreciated. Also, if there are alternative ways of writing my code that are more concise, I'd love to see those too.

A: You can simplify this. Create a list of odds, then you can use it for checking if it is empty or not as well as finding its max:
numset = [int(input("Enter an integer: ")) for _ in range(10)]  # list
# or
numset = {int(input("Enter an integer: ")) for _ in range(10)}  # set
# or most space efficient, not storing non-odds at all
numset = (int(input("Enter an integer: ")) for _ in range(10))  # lazy iterator

odds = [n for n in numset if n % 2]
try:
    print(max(odds))
except ValueError:
    print("No odd number was entered.")


text:
Q: Refactor componentWillReceiveProps to Hook I am using Formik Effect library to control my onChange effect. However the Formik Effect Library is broken, so then I need to write my own Effect to trigger the Formik onChange() function. I wrote a class componentWillReceiveProps component for my <Effect />. However, all my components are functions components. I am requested to refactor my class component to function component. I am a still a beginner of React, so I am struggling how to refactor it.
This is my class <Effect /> component
// TODO: refactor with HOOK!

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'formik';

class Effect extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { formik } = this.props;
    const { onChange } = this.props;
    const { values, touched, errors, isSubmitting } = formik;
    const {
      values: nextValues,
      touched: nextTouched,
      errors: nextErrors,
      isSubmitting: nextIsSubmitting
    } = nextProps.formik;
    if (nextProps.formik !== formik) {
      onChange(
        {
          values,
          touched,
          errors,
          isSubmitting
        },
        {
          values: nextValues,
          touched: nextTouched,
          errors: nextErrors,
          isSubmitting: nextIsSubmitting
        }
      );
    }
  }

  // eslint-disable-next-line
  render() {
    return null;
  }
}

Effect.defaultProps = {
  formik: {
    errors: {},
    touched: {},
    values: {},
    isSubmitting: false
  },
  onChange: () => {}
};

Effect.propTypes = {
  formik: PropTypes.shape({
    errors: PropTypes.shape({}),
    touched: PropTypes.shape({}),
    values: PropTypes.shape({}),
    isSubmitting: PropTypes.bool
  }),
  onChange: PropTypes.func
};

export default connect(Effect);

Within my , I return
<Effect
 onChange={(currentFormikState, nextFormikState) => {
                    if (
                      currentFormikState &&
                      nextFormikState &&
                      currentFormikState.values.pdsaType !==
                        nextFormikState.values.pdsaType
                    ) {
                      resetForm(initialValues[nextFormikState.values.type]);
                      setType(nextFormikState.values.type);
                    }
                  }}
                />

The purpose of this Effect is to reset the initialValue when user select a different type of form because initialValue only render once. And the current Formik library doesn't support onChange() function.
The currentFormikState is the initialValue that Formik render, and the nextFormikState is the type value that user select.

A: I don't know formik but I guess from your code you can transform to function component like this

import React, { useEffect, useRef } from "react";

function Effect(props) {
  const { formik, onChange } = props;
  const { values, touched, errors, isSubmitting } = formik;
  const formVariableRef = useRef();
  const formFormikRef = useRef();
  useEffect(() => {
    formFormikRef.current = formik;
    formVariableRef.current = { values, touched, errors, isSubmitting };
    if (formik !== formFormikRef) {
      onChange(
        {
          value: formVariableRef.current.values,
          touched: formVariableRef.current.touched,
          errors: formVariableRef.current.errors,
          isSubmitting: formVariableRef.current.isSubmitting
        },
        { values, touched, errors, isSubmitting }
      );
    }
    return function() {
      formFormikRef.current = formik;
      formVariableRef.current = { values, touched, errors, isSubmitting };
    };
  }, [values, touched, errors, isSubmitting, formik]); //try add this
  return null
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Try this one in replace for your class form. The rest might not need to change.
Updated Try adding the code above. I just add some dependencies to useEffect


text:
Q: mysql alter table won't work in php if column have incorrect values i have a varchar column in my table. sometimes the column data could be empty, and sometimes it may contain some strange characters. so i'm trying to change the data type of the column to decimal 15,4.
so here's my php code
mysql_query("ALTER TABLE income CHANGE total total DECIMAL (15,4)", $db);

i run the code without any problem (no errors) but when i checked the table income, the datatype has not been changed to decimal. but when i run the query directly into mysql, the column would be successfully changed to decimal, but not without mysql displaying some warnings like
  Warning Code : 1292
Truncated incorrect DECIMAL value: ''

but the point is, the datatype conversion is successful when I run the query directly in mysql (i'm using sqlyog), but not when i tried to run the query in php. any idea why? and how can I avoid this?

A: When dealing with larger numbers (i.e. when selecting LENGTH()) the truncation does not happen when length >65 but rather at >81,
and then gives a warning about "Truncated incorrect DECIMAL value: ''" Which would have been incorrect already >65.
in your case you may have dealing with numbers hence length >15
EDIT: following your needs to make all values as decimal.
   UPDATE income SET total = CAST(total AS DECIMAL(15,4))


text:
Q: Javascript array object return empty array I try to filter jsonplaceholder comments to get by id but return empty array
axios.get('https://jsonplaceholder.typicode.com/comments').then((result) => {

 // const arr = _.find(result.data, { postID: 1});
 // console.log(arr);
 console.log(result.data.filter(x => x.postID === 1))

}).catch((err) => {
 console.log(err);
});

A: Change postID by postId:
console.log(result.data.filter(x => x.postId === 1))

A: Log both the result data and the post id property type. So it could either be an absence  of data from the response in the request or it could be a flawed comparison because of the "===" operandi

A: You're comparing postID instead of postId.
Working example at Codesandbox

axios
  .get("https://jsonplaceholder.typicode.com/comments")
  .then((result) => {
    // const arr = _.find(result.data, { postID: 1});
    // console.log(arr);
    console.log(result.data.filter((x) => x.postId === 1));
  })
  .catch((err) => {
    console.log(err);
  });


text:
Q: mysql: compare value from same column with other values I can't get proper title for the ask, but I will try to explain my question very well.
Table sells(This has record for items say beer, pizza, etc sold by each restaurant at particular price)
restaurantID | item_name | price
----------------------------------
1              beer1        4
1              beer2        5
2              beer1        7
2              beer2        6

Constraint:
for any two items say A and B, item A should be sold at value lower than value B or greater than value of B in all restaurant. We can not have a situation where in particular restaurant item A is cheaper than item B compared to all other restaurants.
In above example, beer1 is sold costly than beer 2 in restaurant 2, where as same is sold cheaper in restaurant 1.
My question is, How can we write a query to validate this constraint on a table like above. In this situation we should get 'False' return value as table is violating constraint.

A: Assuming the anti-capitalist criteria is that restaurant 1 is cheapest:
You can validate the contents of the table with:
SELECT A.*, B.*
FROM sells A
JOIN sells B
  ON A.item_name=B.item_name
WHERE
  A.price < B.price AND
  A.restaurant_ID != 1

This select all the items where restaurant 1 is not the cheapest.
You can't easily write a table constraint. However when inserting a new product we can ensure that it only gets inserted if cheapist:
So for inserting a restaurant 1 item:
INSERT INTO sells
SELECT 1,"beer3",8
FROM sells A
LEFT JOIN sells B
  ON A.item_name=B.item_name AND
  B.item_name = "beer3" AND
  B.price < 8 AND
  B.restaurant_ID != 1
WHERE
  B.restaurant_ID IS NULL
LIMIT 1

Inserting a restaurant_ID != 1 item would reverse the criteria.


text:
Q: Unit test class runs old version in eclipse I have a JUnit test class in my project which is updated incrementally - I add tests every few weeks and sometimes modify the tests' code.
Surprisingly, when I run the test class using eclipse JUnit Runner 4, it runs my old code (before the update) and not the new one. I can change the code, add or remove tests but it still runs the old code.
I tried to isolate the problem and run a single test that I've just written and got the infamous "Unrooted tests" error without any stack trace to give me a clue what the problem is.

I did some research and according to a few other threads here, many people encountered this problem with regards to JUnit 3 \ JUnit 4 compatibility, but this is not the case here - I annotate all my tests with @Test and I do NOT extends the TestCase class.
Cleaning / Building all eclipse projects doesn't help.
However, this problem does work itself around when I mvn clean install my project, but this takes too much time.
Also, renaming the class (Alt+Shift+R in eclipse) gets the new code to run immediately, but renaming it back to its original (and valid) name, gets the old code to run again (WTF?)
Help would be appreciated,
10x

A: I managed to solve the problem on my own (inspired by a comment contributed by Harlard).
After examining the target directory of my project, I noticed that the test-classes dir inside it doesn't include the binaries of my test.
I then noticed that I misplaced the classes within src/test/java and put them in a package structure that doesn't conform to the package structure of my project, they were direct sub-directories of src/test/java.
Therefore, eclipse didn't put them in the correct place and the only way to generate binaries for them was by executing a maven build.
After refactoring all my test classes to the correct package structure, everything worked perfectly.

A: I had the same issue. It was due to a defective .classpath. Removing this .classpath and re-importing the project, generates a correct .classpath and  fixed the environment.

A: Another solution would be manually deleting the "target" folder of the project and rebuilding it. This should solve all problems of this kind.


text:
Q: Starting service 'ipsec' tries to run uninstalled OpenSwan instead of StrongSwan I installed OpenSwan to setup VPN server. It was not enough for my requirements so I had to uninstall it. Later, I installed StrongSwan to handle IPsec VPN.
Now all my StrongSwan configuration is complete but I am unable to start the IPsec service through sudo service ipsec start because it tries to start OpenSwan Daemon while my configuration files are set according to StrongSwan, hence everything fails.
How can I tell the ipsec service that I want to run StrongSwan, not OpenSwan daemon?

A: I resolved this by downloading the source code to OpenSwan from its web site and running sudo make uninstall, which fixes that problem. However, it has created the new problem that ipsec is not a recognized service.


text:
Q: How to store values to array when doing recursion? For example, in this method, the method builds an array of sorted from a BST
public E[] inOrderSort(TreeNode tree){
    E[] array1 = new E[tree.size];
    inOrder(tree, array1, 0);
    return array1;
}

public void inOrder(TreeNode node, E[] array, int index){
    if(node == null){
        return;
    }
    inOrder(node.getLeft(), array, index);
    array[index++]= node.getData();
    inOrder(node.getRight(), array, index);
}

Here, how am I getting the correct result when array1 is returned in the inOrderSort method? How did Java pass the array1 declared in the method inOrderSort to the inOrder method can fill up the values for array1 in inorder sort? I thought Java is pass by reference not pass by value?

A: Primitive values are passed-by-value. So anything that is done to the index variable in inOrder won't have an effect in the caller. The array is not a primitive and is passed-by-reference, thus, any modification to it will be visible to the caller.
Now you have two options:

*

*wrap the index position in an object (NOT an Integer because it's immutable, AtomicInteger would do, same as an int[] with one element) - But I wouldn't do it that way because the intention of the method is to apply ordering to the array and not updating the index. The index is nothing more than a hint for the sort function.

*return the new index as result and use it in the following calls (I'd prefer this one)

For Example:
public int inOrder(TreeNode node, E[] array, int start){
  if(node == null){
    return;
  }
  int index = inOrder(node.getLeft(), array, start);
  array[index++]= node.getData();
  return inOrder(node.getRight(), array, index);
}

A: Java uses call-by-reference for all object types, but primitive types are call-by-value.
In your case, index being a primitive type will not keep its value retained across recursions. index will act like a local variable and its scope is limited to function call stack trace, where array1 being an object will be passed as reference and can retain its values across recursion, because its scope is java heap.
Try using return values:
public E[] inOrderSort(TreeNode tree){
    E[] array1 = new E[tree.size];
    int index = 0;
    index = inOrder(tree, array1, index);
    if(index != tree.size){
        //error
    }
    return array1;
}

public int inOrder(TreeNode node, E[] array, int index){
    if(node == null){
        return index;
    }
    index = inOrder(node.getLeft(), array, index);
    array[index]= node.getData();
    index++;
    index = inOrder(node.getRight(), array, index);
    return index;
}

A: Variable array1 is a reference to array object. When you pass array1 to method you pass it by value (value of reference) and then you can modify object by that reference in inOrder() method.


text:
Q: Rails defining methods I would like to define a method where the first argument is required and the rest are optional. Only first argument must be at first pace.
I try to do this:
my_method(:id, :tags, :user)
my_method(:id, :user, :tags)

def(id, *args)
 ... id...
 ... args[:tags]...
 ... args[:user]...
end

Thank you!

A: Found it. I used this code:
def(id, options={})
end


text:
Q: How to localize individual values of domain objects in a REST API build with Spring Boot? I want to implement an API Rest that verifies the internationalized database and replaces it with the one found in the MESSAGES table according to the regional configuration. The product in the database:
Insert into PRODUCTS (ID, NAME, PRICE) VALUES (1, 'products.name.generatedproductcode', 100.00);

Where NAME is an i18n key of the MESSAGE table
In the MESSAGES table
Insert into MESSAGES (LOCALE,KEY_REFERENCE,VALUE) values ('es_ES','products.name.generatedproductcode','teléfono móvil');
Insert into MESSAGES (LOCALE,KEY_REFERENCE,VALUE) values ('en_GB','products.name.generatedproductcode','mobile phone');

I would like to have a situation where I have to duplicate code that I can mark with an annotation like in18n the field or using aspectj to replace the value with the language that exists in the Locale
@Entity
public class Product {
    private Long id;
    @CustomI18nResource
    private String name;
    private Double price;
}

There are some limitations for example the Locale would have it only in HTTP. I am currently replacing manually from the controller and the value (something expensive at the code level since there are several entities). I am thinking what I should do as a solution to send the KEY to the frontend and that the i18n be administered in the front. Has anyone faced this problem and how has it been resolved?
Solution:
Oliver's answer is just what i was trying to do thank you very much
I have written the solution and published it on Github here:
https://github.com/jestevez/springboot-i18n-database

A: The abstraction that's probably useful here is MessageSource. Within Spring Framework it's usually used to resolve messages against a resource bundle (a properties file) but you can easily implement a database backed variant, probably rather using JDBC to avoid overhead and heavily caching the values.
If you have that, you can use a MessageSourceAccessor e.g. in your controller code to prepare a model to be rendered for the domain object at hand that would know which values to i18nize, lookup the translated value and put that into the model. The …Accessor abstraction picks up the locale from whatever LocaleResolver is configured. IIRC, in Spring Boot this is an AcceptHeaderLocaleResolver, i.e. the value given in the Accept-Language HTTP request header defines which language is chosen.
If you want to completely automate this you might want to plug into your serialization mechanism to do the translation transparently for you. Jackson allows the customization of serializers so that those could use the MessageSourceAccessor to automatically translate all fields equipped with a certain annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface JsonInternationalized {}

@RequiredArgsConstructor
class I18nModule extends SimpleModule {

  private final MessageSource messageSource;

  @Override
  public void setupModule(SetupContext context) {

    MessageSourceAccessor accessor = new MessageSourceAccessor(messageSource);
    InternationalizedSerializer serializer = new InternationalizedSerializer(accessor);
    context.addBeanSerializerModifier(new InternationalizingBeanSerializerModifier(serializer));
  }

  @RequiredArgsConstructor
  static class InternationalizingBeanSerializerModifier extends BeanSerializerModifier {

    private final InternationalizedSerializer serializer;

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
        List<BeanPropertyWriter> beanProperties) {

      for (BeanPropertyWriter writer : beanProperties) {
        if (writer.getAnnotation(JsonInternationalized.class) != null) {
          writer.assignSerializer(serializer);
        }
      }

      return beanProperties;
    }
  }

  @RequiredArgsConstructor
  static class InternationalizedSerializer extends ToStringSerializer {

    private static final long serialVersionUID = -2391442803792997283L;

    private final MessageSourceAccessor accessor;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
      gen.writeString(accessor.getMessage(value.toString()));
    }
  }
}

Here are the important aspects:

*

*We define an annotation to trigger i18n on.

*I18nModule registers a BeanSerializerModifier that inspects the writers for bean properties annotated with said annotation and registers a custom serializer for those properties that will resolve the property via the MessageSource handed into the module.

In a Spring Boot application, you can get this module to work by simply regitering it as Spring bean in a configuration class:
@Bean
I18nModule i18nModule(MessageSource messageSource) {
  return new I18nModule(messageSource);
}

As you can see this requires a bit of ceremony. I'm gonna take this back to the team to see whether we can improve the out of the box experience a bit.


text:
Q: how to find which packages are installed system-wide in NixOS? Is there a command that can be used to figure out which packages are installed system-wide in NixOS?
For instance, I can list packages installed for my current user with nix-env -q.  I don't know of any way to list packages installed on the whole system from /etx/nixos/configuration.nix.

There are two separate instances I would want to use this:

*

*Let's say I add a package to /etc/nixos/configuration.nix in environment.systemPackages, but I forget whether I have run nixos-rebuild switch yet.  It would be nice if there was a command I could run to check whether the package is in the system environment.

*I have programs.bash.enableCompletion set to true in /etc/nixos/configuration.nix.  Without looking at the option in nixpkgs, I would guess that this option would set the bash-completion package to be installed.  It would be nice if there was a command that I could run that checked whether the bash-completion package actually was in the system environment.

A: There's no specific tool for this.  You may like the system.copySystemConfiguration option (see the docs for "caveats").
You'll get relatively close with nix-store -q --references /run/current-system/sw – the list of nix store paths directly contained in systemPackages, but note that various NixOS options may add packages in there.

A: Due to the approach NixOS takes on installing software, there's no such thing as a package which is installed system-wide. Not in the same sense of most package managers, that is.
However, if you treat a user environment (aka. profile) as the equivalent of system-wide, then you can use nix-store -q -R /nix/var/nix/profiles/system-${n}-link to list the dependencies of a given user environment; where ${n} is the profile's generation number. By dependencies, I mean direct and in-direct dependencies.
In addition, if you use the --tree instead of -R argument you can get an ASCII dependency tree.

A: For your first use case you can use:
nixos-rebuild dry-build

This command shows what would be built and download. If all you want to know is if there are new packages that should be built you can use the above command.
Please note that this won't tell you about packages that are already built but not currently active. Ex. If you add firefox to your configuration.nix, rebuild, remove firefox, rebuild, add firefox then run the above it won't show anything because there is nothing new to build. Nix keeps old packages until garbage collection.
There is also nixos-rebuild dry-activate which builds the new system but does no changes. It will show other changes, like if you disable/enable some services.


text:
Q: MS Access Link to an Excel Document on Sharepoint Hi I am trying to link an excel document that is on sharepoint an "Http://..."  but every time I try to link any file it gives me a list. I don't want to link the list I want to be able to pull the data from the actual excel document aand not a list of the file that are on sharepoint. Is that possible?

A: I don't know if this is right but everything that I have found indicates that access will see those things on sharepoint as only "blank blocks" and will not pull the data from the actual files I may be wrong as the article and forums that I found are dated from 2013 and 2012 couldn't find anything else with a newer date. Thanks : ). What I did find was that I can use a macro to download the files very quickly and locate them someone in my shared drive and update them every month or so that access is update and link the file to access via excel files.


text:
Q: Force GraphViz force distance between nodes I use GraphViz with the following dot file:
digraph G
{
    rankdir=LR;
    subgraph commits
    {
        "5c071a6b2c" -> "968bda3251" -> "9754d40473" -> "9e59700d33" -> "2a3242efa4";
    }
    subgraph annotations
    {
        "V1.0" [shape=box];
        "br/HEAD" [shape=box];
        "V1.0" -> "9e59700d33" [weight=0];
        "br/HEAD" -> "2a3242efa4" [weight=0];
    }
}

It give me something like that:

But I want something like that:

                                        V1.0         br/HEAD
                                          |             |
                                         \/            \/

5c071a6b2c -> 968bda3251 -> 9754d40473 -> 9e59700d33 -> 2a3242efa4

How can I do that?
For your help,
Thanks by advance.

A: This will align the annotations with the commits:
digraph G
{
    rankdir=LR;
    subgraph commits
    {
        "5c071a6b2c" -> "968bda3251" -> "9754d40473" -> "9e59700d33" -> "2a3242efa4";
    }
    subgraph annotations1
    {
        rank="same";
        "V1.0" [shape=box];
        "V1.0" -> "9e59700d33" [weight=0];
    }
    subgraph annotations2
    {
        rank="same";
        "br/HEAD" [shape=box];
        "br/HEAD" -> "2a3242efa4" [weight=0];
    }
}

Since the rank="same"; effects the whole subgraph I had to split the annotations in two different subgraphs.
Result is:


text:
Q: Hadoop WebHDFS Java Client API enable SSL and Basic Authentication I have a Spring Boot application that uses spring-yarn-boot:2.2.0.RELEASE to get access to a Hadoop filesystem (HDFS). Operations that I do are LISTSTATUS, GETFILESTATUS and OPEN (to read a file). HDFS URI is specified through application.properties:
spring.hadoop.fsUri=webhdfs://127.0.0.1:50070/webhdfs/v1/

I make a bean to which I provide Hadoop Configuration (that Spring somehow automagically prepares for me on startup):
SimplerFileSystem fs = new SimplerFileSystem(FileSystem.get(configuration));
FsShell shell = new FsShell(configuration);

And everything works well as expected, but the problems came when I got two new requirements.
First thing is that HDFS will be protected with SSL from now on. I can't seem to find any way to tell my application that the fsURI that starts with webhdfs:// is actually a https connection. And if I will give the https URL directly, I'll get an exception:
java.io.IOException: No FileSystem for scheme: https
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2584)

... which is caused by that code: FileSystem.get(configuration).
This thing is driving me crazy, I don't seem to find a way to get pass this.
Second requirement is, that I need to authenticate myself against the WebHDFS with basic authentication. For this I also can't find any means in the client API.
Has anyone done it before and have any instructions to share? Or maybe anyone knows a different client API that I can use to accomplish this?
One option is to implement the REST calls myself with RestTemplate or any other REST service consumer API, but this looks like not-so-special use case so I'm really hoping that there is something that has been done already.
EDIT:
Found a solution to the HTTPS problem. One should use swebhdfs:// as url prefix and everything will work. Still havent found a solution to the Basic Auth problem.


text:
Q: How to change DataTables PageLenght select to bootstrap dropdown? Is there any easy or hard but proper solution to change in DataTables:

    Show
    <select class="form-control input-sm" aria-controls="instruments" name="instruments_length">
        <option value="10">10</option>
        option value="25">25</option>
        <option value="50">50</option>
        <option value="100">100</option>
    </select>
    entries

to something more like this:

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
  </button>

10

25

50

100

Thanks for help! :)


text:
Q: Can you display events in a monthly calendar using sql? I have a table with events (dates and descriptions).
I want to display the coming events in a calendar format of the current month.
What is the best way to display current events in calendar format using SQL?
I'm targeting Oracle, but maybe there are solutions that are more universal than others.
The output should look similar to this one:
     WEEK | MON               | TUE       ! WED       | THU             | FRI       | SAT       | SUN
--------- ------------------- ----------- ----------- ----------------- ----------- ----------- -----------
       36 |                   | 01        | 02        | 03 stay at home | 04        | 05        | 06
       37 | 07                | 08        | 09        | 10              | 11        | 12        | 13
       38 | 14 work from home | 15        | 16        | 17              | 18        | 19        | 20
       39 | 21                | 22        | 23        | 24              | 25        | 26        | 27
       40 | 28                | 29        | 30        |                 |           |           |

A: Sample data (including a day with two events):
create table calendar
( cal_date   date
, cal_event  varchar2(50) );

insert all
    into calendar values (date '2020-09-03', 'stay at home')
    into calendar values (date '2020-09-03', 'play Fallout')
    into calendar values (date '2020-09-14', 'work from home')
select * from dual;

Report:
select cal_week as week
     , mon_events as mon
     , tue_events as tue
     , wed_events as wed
     , thu_events as thu
     , fri_events as fri
from   ( select to_char(d.dt,'Dy') as cal_day
               , to_number(to_char(d.dt,'iw')) as cal_week
               , to_char(d.dt,'DD')||' '||listagg(cal_event,', ') within group (order by c.cal_date) as cal_event
         from    ( select date '2020-09-01' -1 + rownum as dt
                   from   xmltable('1 to 30' ) ) d
                 left join calendar c on c.cal_date = d.dt
         group by d.dt
       )
pivot  (max(cal_event) as events
        for (cal_day) in ('Mon' as mon, 'Tue' as tue, 'Wed' as wed, 'Thu' as thu, 'Fri' as fri))
order by cal_week;

Results:
+------+-------------------+-----+-----+-------------------------------+-----+
| WEEK | MON               | TUE | WED | THU                           | FRI |
+------+-------------------+-----+-----+-------------------------------+-----+
|   36 |                   | 01  | 02  | 03 play Fallout, stay at home | 04  |
|   37 | 07                | 08  | 09  | 10                            | 11  |
|   38 | 14 work from home | 15  | 16  | 17                            | 18  |
|   39 | 21                | 22  | 23  | 24                            | 25  |
|   40 | 28                | 29  | 30  |                               |     |
+------+-------------------+-----+-----+-------------------------------+-----+

I had to concatenate the day number with the event list before the pivot, which meant the aggregation had to be in the subquery and the max(cal_event) is just to satisfy the pivot syntax which requires an aggregate function.

A: I've come up with this solution. Maybe someone will be helped by it, but I'm also curious for other solutions.
Edited to include multiple events on the same day.
with events as (
  select date'2020-09-03' as dy
  ,      'stay at home' as event
  from dual
  union all
  select date'2020-09-03' as dy
  ,      'stay at home 2' as event
  from dual
  union all
  select date'2020-09-14' as dy
  ,      'work from home' as event
  from dual
    union all
  select date'2020-10-14' as dy
  ,      'work from home' as event
  from dual
) ,
day_events as (
  select dy, listagg(event,', ') within group  (order by event) as event
  from events
  group by dy
)
, month(dy) as (
select trunc(sysdate, 'month') as dy from dual
union all
select dy + 1 from month
where dy < last_day(sysdate)-1
)
, days as (
  select to_char(dy, 'iw') as week,
  case to_char(dy, 'dy') when 'mon' then dy end as mon,
  case to_char(dy, 'dy') when 'tue' then dy end as tue,
  case to_char(dy, 'dy') when 'wed' then dy end as wed,
  case to_char(dy, 'dy') when 'thu' then dy end as thu,
  case to_char(dy, 'dy') when 'fri' then dy end as fri,
  case to_char(dy, 'dy') when 'sat' then dy end as sat,
  case to_char(dy, 'dy') when 'sun' then dy end as sun
  from month
), calendar as (
select week
,      max(mon) as mon
,      max(tue) as tue
,      max(wed) as wed
,      max(thu) as thu
,      max(fri) as fri
,      max(sat) as sat
,      max(sun) as sun
from days
group by week
order by week)
select week
, '| '||decode(mon, e.dy, to_char(mon,'dd')||' '||e.event, to_char(mon, 'dd')) as "| MON"
, '| '||decode(tue, e.dy, to_char(tue,'dd')||' '||e.event, to_char(tue, 'dd')) as "| TUE"
, '| '||decode(wed, e.dy, to_char(wed,'dd')||' '||e.event, to_char(wed, 'dd')) as "! WED"
, '| '||decode(thu, e.dy, to_char(thu,'dd')||' '||e.event, to_char(thu, 'dd')) as "| THU"
, '| '||decode(fri, e.dy, to_char(fri,'dd')||' '||e.event, to_char(fri, 'dd')) as "| FRI"
, '| '||decode(sat, e.dy, to_char(sat,'dd')||' '||e.event, to_char(sat, 'dd')) as "| SAT"
, '| '||decode(sun, e.dy, to_char(sun,'dd')||' '||e.event, to_char(sun, 'dd')) as "| SUN"
from calendar c left join day_events e
on c.week = to_char(e.dy, 'iw')
order by c.week;

A: You can use Conditional Aggregation with GROUPing BY week number :
WITH events AS
(
  SELECT date'2020-09-03' AS dy, 'stay at home' AS event
    FROM dual
  UNION ALL
  SELECT date'2020-09-14' AS dy
  ,      'work FROM home' AS event
    FROM dual
    UNION ALL
  SELECT date'2020-10-14' AS dy
  ,      'work FROM home' AS event
    FROM dual
) ,  month(dy) AS (
SELECT trunc(sysdate, 'month') + level - 1 AS dy
  FROM dual
CONNECT BY level <=  last_day(sysdate)-trunc(sysdate, 'month') + 1
)
SELECT TO_CHAR( m.dy, 'iw' ) AS week,
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'MON' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "MON",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'TUE' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "TUE",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'WED' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "WED",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'THU' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "THU",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'FRI' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "FRI",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'SAT' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "SAT",
       MAX(CASE WHEN TO_CHAR( m.dy, 'DY' ) = 'SUN' THEN TO_CHAR( m.dy, 'DD ' )||e.event END) AS "SUN"
  FROM month m
  LEFT JOIN events e
    ON e.dy = m.dy
 GROUP BY TO_CHAR( m.dy, 'iw' )

Demo


text:
Q: Definition of smooth point and its practical application My book defines a smooth point of the boundary of a subset of a manifold as follows. Let $X\subset M\subset\mathbb{R}^n$ where $M$ is a $k$-dimensional manifold. Consider a point $\vec{x}\in\partial_MX$, the boundary between $X$ and $M$. This point is a smooth point if there exists a neighborhood $V\subset\mathbb{R}^n$ of $\vec{x}$ and a single $C^1$ function $g\colon V\cap M\to\mathbb{R}$ such that
$$g(\vec{x})=0,\quad X\cap V=\{g\geq0\},\quad \text{and }[Dg(\vec{x})]\colon T_{\vec{x}}M\to\mathbb{R}\, \text{is surjective.}$$
$[Dg(\vec{x})]$ is the derivative (the Jacobian) of $g$ at $\vec{x}$ and $T_{\vec{x}}M$ is the tangent space of $M$ at $\vec{x}$.
My first question is, why must the derivative be surjective? Furthermore, why does the derivative of $g$ map from the tangent space of $M$ at $\vec{x}$ instead of $V\cap M$ (which is the domain of $g$)?
My second question is best phrased with an example: consider the region bounded by the graphs of $y=x^2$ and $x=y^2$. Apparently, the origin and $(1,1)$ are not smooth points of the boundary. How so? This is stated without proof, but the nonexistence of a function $g$ for those points is not clear to me.

A: This definition is given in order to apply the Implicit Function Theorem:
If $M,N$ are smooth manifolds and $g\colon M \to N$ with $g(x)=0$ is a smooth ($C^1$ is enough) function and if $dg_x \colon T_xM \to T_{g(x)}N$ is surjective, then there exists a neighborhood $U$ of $x$ such that $U \cap \{g=0\}$ is an embedded smooth (or $C^1$, depending on the smoothness of $g$) submanifold of $M$ of dimension $\dim M - \dim N$. In your case, since $N=\mathbb{R}$, the dimension of the submanifold is $\dim M - 1$, so it is a hypersurface
The meaning of your definition of smooth point of the boundary of $X$ is that locally at $x$, your set $X$ is written as a sub-graph of a smooth function ($\{g \geq 0\}$) and $\partial X = \partial \{g \geq 0\} = \{g=0\}$ is a smooth hypersuface.
The surjectivity is important to obtain that $\partial X$ is of dimension $\dim M - 1$: if $M= \mathbb{R}$ and $g \colon \mathbb{R} \to \mathbb{R}$ is such that $g(x)=0$, the hypothesis that $dg_x$ is surjective means that $g'(x) \neq 0$. This implies that in a neighborhood of $x$ you have $\{g=0\}= \{x\}$ which is a submanifold of dimension $0$. If $g'(x)=0$ you may have the set $\{g=0\}$ to be even an interval.
Intuitively, the differential is an application between tangent spaces because it maps tangent vectors to $M$ into tangent vectors to $N$: take a tangent vector $v$ to $M$ at $x$ and pick a curve on $M$ $\gamma \colon (-\varepsilon, \varepsilon) \to M$ which passes through $x$ in direction $v$, that is such that $\gamma(0)=x$ and $\gamma'(0)=v$. Then $g \circ \gamma$ is a curve on $N$, whose tangent at $0$ is $dg_x(v)$.
Thus the differential maps tangent vectors to the domain into tangent vectors to the image.
In higher dimension, the surjectivity of the differential means that for every direction $w$ on $N$ you have a curve on $M$ which is mapped by $g$ into a curve whose tangent is $w$; since the differential is linear, this means that you have exactly $\dim M - \dim N$ independent directions on $M$ which are mapped into $0$; thus exactly in the linear span of these directions, "moving from $x$, $g$ does not change at the first order" and you expect that the set of zeros of $g$ is ($\dim M - \dim N$)-dimensional.
The answer to your second question is contained into the Implict Function Theorem: at the origin and $(1,1)$ the boundary of your set is not a smooth curve (you have different tangents on the left and on the right), thus such a $g$ cannot exist.


text:
Q: Can this animation in jquery be done in JS without jquery and still retain simplicity? I found this "div follows mouse" animation:
JSFiddle that belongs to the answer posted in: How to animate following the mouse in jquery.
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
   mouseX = e.pageX;
   mouseY = e.pageY;
});

// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});

}, 30);

I got quite intrigued by the inner workings and I tried to understand what the code is doing. I am currently learning javascript and I tried to replicate the "point to point" animation. I found this: Point to point animation algorithm, but it feels that the code of the original poster is pretty long and repetitive.
My current basic level of javascript is being an obstacle to fully understand the jQuery version (i still didn't enter into the jQuery realm). Yet, I think that do this kind of animation in javascript might be possible, but the only way I can think about is with a code similar to the "point to point" link.
Can something like this be done with a code as short as the jQuery version? Or to do just javascript requires much longer routine?
Thanks for any suggestion or comment that you might have!

A:
Can something like this be done with a code as short as the jQuery version?

In this case, nearly, yes, because what's being done is fairly simple and only a small amount of jQuery's functionality is used. Specifically:

*

*It's hooking the mousemove event on document, which can easily be done with addEventListener (or attachEvent on older versions of IE).

*It's locating an element by id ($("#follower")), which can easily be done with getElementById.

*It's setting the left and top of an element via jQuery's css function. This can easily be done by setting the left and top properties on the element's style property.
Putting that all together: Fiddle
var mouseX = 0, mouseY = 0;
if (document.addEventListener) {
    document.addEventListener('mousemove', mouseMoveHandler, false);
}
else if (document.attachEvent) {
    document.attachEvent('onmousemove', mouseMoveHandler);
}
else {
    document.onmousemove = function(event) {
        mouseMoveHandler(event || window.event);
    };
}

function mouseMoveHandler(e) {
   mouseX = e.pageX;
   mouseY = e.pageY;
}

// cache the element
var follower = document.getElementById("follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.style.left = xp + "px";
follower.style.top  = yp + "px";

}, 30);

As you can see, the biggest issue is hooking the event in a way that plays nicely with others. Although you could just use the document.onmousemove version, that would clobber any other mousemove handlers on document, which is why we first look for addEventListener or attachEvent.
Some handy references, in roughly chronological order (latter ones update/supercede/add to earlier ones):

*

*DOM2 Core

*DOM2 HTML

*DOM2 Events

*DOM3 Core

*DOM3 Events

*Other DOM specs

*HTML5 Web Application APIs
None of which should be taken to say that you can't use a good library like jQuery, there are several good reasons to (the events thing above is just one example). But it's always best to understand the basics as well, even if you use a library to avoid having to deal with them all that much.


text:
Q: Redirect calls made to apache through a php (apache here I refer to apache2 webserver)
I have a setup where in my jsp calls to tomcat are routed by apache using mod_jk. Both servers reside on the same machine. I want to do away with the mod_jk connector, instead the calls coming to apache is served by making a curl call to the localhost tomcat server.
The problem is the queries comming are of the type 'something/something.jsp' or 'anything/anything.jsp'. I want all this requests coming to apache be serviced by a common php code, which will do the corresponding curl call and return the response. The reason I am using the php connector is for some specific logging purposes.
Completely new to the apache world so any help would be really appreciated !

A: You could try using Mod_rewrite so that apache accepts all requests types as just another call to Logger.php instead of /something/something.jsp. And pass the original request to the php page which from their can make the curl request.
Here is an example of someone trying to route all requests to a particular php page. A bit similar to your scenario but he wants the requests to be changed to query string parameters ->
Redirect all traffic to index.php
Note: URL processing is child's play in Tomcat. I think it would be a lot easier to have your requests come directly to a tomcat filter which can call your PHP page and then send the request onto the designated JSP page. If you are allowed to reverse your architecture.


text:
Q: Linux Arch on ARM - Random USB drive "freeze" I'm running a Linux Box on a Seagate Free Agent Dockstar, very limited machine but more than able to do what I need, which is true most of the times...
I have the operating system on a flash drive and use an external USB 2 "classic magnetic" Western Digital 1,5TB hard disk for massive storage.
Not seldom it happens that the wait for IO % suddenly goes up to almost 100% and the system is on its knees, to the point that is very difficult to even ssh in it; a typical 'iostat -x' in those situations gives output like:
Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util
sdb 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
sda 0.00 0.00 0.00 0.50 0.00 2.00 8.00 14.80 91400.00 0.00 91400.00 2000.00 100.00

where sdb is the flash drive and sda is the usb disk. This tells me that the USB drive is 100% busy but almost no one is writing or reading from it.
I also used a 'lsof +D ' during "normal" use and nothing suspicious is found: a fair amount of file is used, but nothing strange.
How can I debug deeper? Keep in mind that the machine uses an ARM processor,only has 128MB of RAM and has no screen or local console, but, given this limits, I can install almost everything if needed.
Edit: I also tried to run smartctl which says the drive is fit:

SMART overall-health self-assessment test result: PASSED

... there is a lot of output but none of that seems useful
Edit2:
I really think that the drive has hardware issues; I noticed that when it is busy 100% without load it makes a repetitive noise which reminds me of the old day Amiga floppy disks - they made a similar noise like they were going around without a goal...
For this reasons the suggestion to move /var and /tmp to the magnetic disk only worsened the situation.
I guess the only way to solve this is to buy a new hard drive and backup valuable data ASAP. :-(

A: Double-check that the WD drive is OK. I have just detected that one of mine has read errors. It was taking enourmus amounts of time (minutes) to read some bad sectors.
Unfortunately SMART may not work over USB, which makes checking the drives condition hard.
One way to check that is reading the whole disk using dd:
dd if=/dev/sdX of=/dev/null bs=1M
That will take quite some time over USB, but if the dd command errors then you know the disk is broken. You can read the disk while it is mounted, but be careful with if= and of=!

A: Flash drives typically have poor write performance.  So you need to minimize OS writes to the flash drive.

*

*Use "noatime" options in fstab for your / and /usr partition.

*Disable swap.

*Put /var on something else if possible (that "massive storage" if you can), if not, disable all the logging you don't absolutely need.

*Same thing with /tmp.


text:
Q: Binding IСommand к произвольному событию произвольного компонента Все найденные мною примеры демонстрируют привязку IСommand к компонентам, содержащим свойство Command:
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="GO!"/>

Как привязать ICommand к произвольному событию компонента WPF, не содержащего свойство Command, и передать этой команде параметр? Например - повесить команду MyFunnyCommand на событие RowEditEnding компонента DataGrid и передать ей DataGridRow.Item?

A: Здесь у вас несколько путей.
Во-первых, есть примочки Blend. Подключив библиотеку System.Windows.Interactivity, вы сможете писать такой код:
<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDown">
            <i:InvokeCommandAction
                    Command="{Binding ButtonMouseDownCommand}"
                    CommandParameter="{Binding Foo}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Во-вторых, вы можете воспользоваться нормальной MVVM-библиотекой. Например, подключив библиотеку Caliburn.Micro, вы сможете писать такой код:
<Button cal:Message.Attach="ButtonClick"/>

<Button cal:Message.Attach="[Event MouseDown] = [Action ButtonMouseDown($dataContext, 'Foo')]"/>

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDown">
            <cal:ActionMessage MethodName="ButtonMouseDown">
                <cal:Parameter Value="$dataContext"/>
                <cal:Parameter Value="{Binding Foo}"/>
            </cal:ActionMessage>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Причём будут использоваться не команды, а методы.