问:
Why my observable variable can not update the "main.dart" in Flutter using GetX?
The following code is my auth_controller.dart code. I see the response comes from the backend works and it is what was expected and I have token and the isAuth value changes to true after I submit the form:

```<code>enum AuthMode { Signup, Login }

class AuthController extends GetxController
    with GetSingleTickerProviderStateMixin {
  static AuthController instance = Get.find();
  Rx<dynamic>? authMode = AuthMode.Login.obs;
  RxBool? isLoading = false.obs;
  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;
  final _isAuth = false.obs;

  AnimationController? controller;
  Animation<Offset>? slideAnimation;
  Animation<double>? opacityAnimation;
  // late TextEditingController passwordController;
  // final key = GlobalKey<FormState>();

  @override
  void onInit() {
    super.onInit();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 300,
      ),
    );
    slideAnimation = Tween<Offset>(
      begin: const Offset(0, -1.5),
      end: const Offset(0, 0),
    ).animate(
      CurvedAnimation(
        parent: controller as Animation<double>,
        curve: Curves.fastOutSlowIn,
      ),
    );
    opacityAnimation = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: controller as Animation<double>,
        curve: Curves.easeIn,
      ),
    );
    // _heightAnimation.addListener(() => setState(() {}));

    // passwordController = TextEditingController();
  }

  @override
  void onClose() {
    super.onClose();
    // passwordController.dispose();
  }

  bool get isAuth {
    _isAuth.value = token != null;
    return _isAuth.value;
  }

  String? get token {
    if (_expiryDate != null &&
        _expiryDate!.isAfter(DateTime.now()) &&
        _token != null) {
      return _token;
    }
    return null;
  }

  String? get userId {
    return _userId;
  }

  Future<void> _authenticate(
      String email, String password, String urlSegment) async {
    // print('app is here!!!5555');

    final host = UniversalPlatform.isAndroid ? '10.0.2.2' : '127.0.0.1';
    final url = Uri.parse('http://$host:8000/api/$urlSegment');
    //final url = Uri.parse('http://10.0.2.2:8000/api/$urlSegment');
    //final url = Uri.parse('http://127.0.0.1:8000/api/$urlSegment');

    try {
      final http.Response response = await http.post(
        url,
        headers: {"Content-Type": "application/json"},
        body: json.encode(
          {
            'email': email,
            'password': password,

            //'returnSecureToken': true,
          },
        ),
      );
      print('this is responsde ');
      print(json.decode(response.body));

      final responseData = json.decode(response.body);

      if (responseData['error'] != null) {
        throw HttpException(responseData['error']['message']);
      } else {
        _token = responseData['idToken'];
        _userId = responseData['id'];
        _expiryDate = DateTime.now().add(
          Duration(
            seconds: responseData['expiresIn'],
          ),
        );
      }
      _autoLogout();
      // update();
      final prefs = await SharedPreferences.getInstance();
      final userData = json.encode(
        {
          'token': _token,
          'userId': _userId,
          'expiryDate': _expiryDate!.toIso8601String(),
        },
      );
      prefs.setString('userData', userData);

      // print(prefs.getString('userData'));

    } catch (error) {
      throw error;
    }
  }

  Future<void> signup(String email, String password) async {
    return _authenticate(email, password, 'signup');
  }

  Future<void> login(String email, String password) async {
    return _authenticate(email, password, 'login');
  }

  Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('userData')) {
      return false;
    }
    final Map<String, Object> extractedUserData = Map<String, Object>.from(
        json.decode(prefs.getString('userData') as String));
    final expiryDate =
        DateTime.parse(extractedUserData['expiryDate'] as String);

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token'] as String;
    _userId = extractedUserData['userId'] as String;
    _expiryDate = expiryDate;
    // update();
    _autoLogout();
    return true;
  }

  Future<void> logout() async {
    _token = null;
    _userId = null;
    _expiryDate = null;
    if (_authTimer != null) {
      _authTimer!.cancel();
      _authTimer = null;
    }
    // update();
    final prefs = await SharedPreferences.getInstance();
    // prefs.remove('userData');
    prefs.clear();
  }

  void _autoLogout() {
    if (_authTimer != null) {
      _authTimer!.cancel();
    }
    final timeToExpiry = _expiryDate!.difference(DateTime.now()).inSeconds;
    _authTimer = Timer(Duration(seconds: timeToExpiry), logout);
  }
}
</code>```

But it will still sticks to the Authentication page and won't go to the Home page as I defined in my main.dart file:

```<code>void main() {
  Get.put(MenuController());
  Get.put(NavigationController());
  Get.put(AuthController());
  Get.put(AuthCard);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Obx(() => GetMaterialApp(
          initialRoute: AuthController.instance.isAuth
              ? homeScreenRoute
              : authenticationScreenRoute,
          unknownRoute: GetPage(
              name: '/not-found',
              page: () => PageNotFound(),
              transition: Transition.fadeIn),
          getPages: [
            GetPage(
                name: rootRoute,
                page: () {
                  return SiteLayout();
                }),
            GetPage(
                name: authenticationScreenRoute,
                page: () => const AuthenticationScreen()),
            GetPage(name: homeScreenRoute, page: () => const HomeScreen()),
          ],
          debugShowCheckedModeBanner: false,
          title: 'BasicCode',
          theme: ThemeData(
            scaffoldBackgroundColor: light,
            textTheme: GoogleFonts.mulishTextTheme(Theme.of(context).textTheme)
                .apply(bodyColor: Colors.black),
            pageTransitionsTheme: const PageTransitionsTheme(builders: {
              TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
              TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
            }),
            primarySwatch: Colors.blue,
          ),
        ));
  }
}
</code>```

What is the problem and how can I fix that?

答:
I could simply resolve the problem by adding following lines to my main.dart file:

```<code>  home: Obx(() => AuthController.instance.isAuth
      ? const HomeScreen()
      : const AuthenticationScreen()),
</code>```

And removing the followings:

```<code>   initialRoute
   : AuthController.instance.isAuth
       ? homeScreenRoute
       : authenticationScreenRoute,
</code>```

I also deleted the Obx before the GetMaterialApp().

The new main.dart looks like this:

```<code>void main() {
  Get.put(MenuController());
  Get.put(NavigationController());
  Get.put(AuthController());
  Get.put(AuthCard);
  AuthController.instance.isAuth ? runApp(MyApp()) : runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      unknownRoute: GetPage(
          name: '/not-found',
          page: () => PageNotFound(),
          transition: Transition.fadeIn),
      getPages: [
        GetPage(
            name: rootRoute,
            page: () {
              return SiteLayout();
            }),
        GetPage(
            name: authenticationScreenRoute,
            page: () => const AuthenticationScreen()),
        GetPage(name: homeScreenRoute, page: () => const HomeScreen()),
      ],
      debugShowCheckedModeBanner: false,
      title: 'BasicCode',
      theme: ThemeData(
        scaffoldBackgroundColor: light,
        textTheme: GoogleFonts.mulishTextTheme(Theme.of(context).textTheme)
            .apply(bodyColor: Colors.black),
        pageTransitionsTheme: const PageTransitionsTheme(builders: {
          TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
          TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
        }),
        primarySwatch: Colors.blue,
      ),
      home: Obx(() => AuthController.instance.isAuth
          ? const HomeScreen()
          : const AuthenticationScreen()),
    );
  }
}
</code>```

Body:
The following code is my auth_controller.dart code. I see the response comes from the backend works and it is what was expected and I have token and the isAuth value changes to true after I submit the form:

enum AuthMode { Signup, Login }

class AuthController extends GetxController
    with GetSingleTickerProviderStateMixin {
  static AuthController instance = Get.find();
  Rx<dynamic>? authMode = AuthMode.Login.obs;
  RxBool? isLoading = false.obs;
  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;
  final _isAuth = false.obs;

  AnimationController? controller;
  Animation<Offset>? slideAnimation;
  Animation<double>? opacityAnimation;
  // late TextEditingController passwordController;
  // final key = GlobalKey<FormState>();

  @override
  void onInit() {
    super.onInit();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 300,
      ),
    );
    slideAnimation = Tween<Offset>(
      begin: const Offset(0, -1.5),
      end: const Offset(0, 0),
    ).animate(
      CurvedAnimation(
        parent: controller as Animation<double>,
        curve: Curves.fastOutSlowIn,
      ),
    );
    opacityAnimation = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: controller as Animation<double>,
        curve: Curves.easeIn,
      ),
    );
    // _heightAnimation.addListener(() => setState(() {}));

    // passwordController = TextEditingController();
  }

  @override
  void onClose() {
    super.onClose();
    // passwordController.dispose();
  }

  bool get isAuth {
    _isAuth.value = token != null;
    return _isAuth.value;
  }

  String? get token {
    if (_expiryDate != null &&
        _expiryDate!.isAfter(DateTime.now()) &&
        _token != null) {
      return _token;
    }
    return null;
  }

  String? get userId {
    return _userId;
  }

  Future<void> _authenticate(
      String email, String password, String urlSegment) async {
    // print('app is here!!!5555');

    final host = UniversalPlatform.isAndroid ? '10.0.2.2' : '127.0.0.1';
    final url = Uri.parse('http://$host:8000/api/$urlSegment');
    //final url = Uri.parse('http://10.0.2.2:8000/api/$urlSegment');
    //final url = Uri.parse('http://127.0.0.1:8000/api/$urlSegment');

    try {
      final http.Response response = await http.post(
        url,
        headers: {"Content-Type": "application/json"},
        body: json.encode(
          {
            'email': email,
            'password': password,

            //'returnSecureToken': true,
          },
        ),
      );
      print('this is responsde ');
      print(json.decode(response.body));

      final responseData = json.decode(response.body);

      if (responseData['error'] != null) {
        throw HttpException(responseData['error']['message']);
      } else {
        _token = responseData['idToken'];
        _userId = responseData['id'];
        _expiryDate = DateTime.now().add(
          Duration(
            seconds: responseData['expiresIn'],
          ),
        );
      }
      _autoLogout();
      // update();
      final prefs = await SharedPreferences.getInstance();
      final userData = json.encode(
        {
          'token': _token,
          'userId': _userId,
          'expiryDate': _expiryDate!.toIso8601String(),
        },
      );
      prefs.setString('userData', userData);

      // print(prefs.getString('userData'));

    } catch (error) {
      throw error;
    }
  }

  Future<void> signup(String email, String password) async {
    return _authenticate(email, password, 'signup');
  }

  Future<void> login(String email, String password) async {
    return _authenticate(email, password, 'login');
  }

  Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('userData')) {
      return false;
    }
    final Map<String, Object> extractedUserData = Map<String, Object>.from(
        json.decode(prefs.getString('userData') as String));
    final expiryDate =
        DateTime.parse(extractedUserData['expiryDate'] as String);

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token'] as String;
    _userId = extractedUserData['userId'] as String;
    _expiryDate = expiryDate;
    // update();
    _autoLogout();
    return true;
  }

  Future<void> logout() async {
    _token = null;
    _userId = null;
    _expiryDate = null;
    if (_authTimer != null) {
      _authTimer!.cancel();
      _authTimer = null;
    }
    // update();
    final prefs = await SharedPreferences.getInstance();
    // prefs.remove('userData');
    prefs.clear();
  }

  void _autoLogout() {
    if (_authTimer != null) {
      _authTimer!.cancel();
    }
    final timeToExpiry = _expiryDate!.difference(DateTime.now()).inSeconds;
    _authTimer = Timer(Duration(seconds: timeToExpiry), logout);
  }
}

But it will still sticks to the Authentication page and won't go to the Home page as I defined in my main.dart file:

void main() {
  Get.put(MenuController());
  Get.put(NavigationController());
  Get.put(AuthController());
  Get.put(AuthCard);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Obx(() => GetMaterialApp(
          initialRoute: AuthController.instance.isAuth
              ? homeScreenRoute
              : authenticationScreenRoute,
          unknownRoute: GetPage(
              name: '/not-found',
              page: () => PageNotFound(),
              transition: Transition.fadeIn),
          getPages: [
            GetPage(
                name: rootRoute,
                page: () {
                  return SiteLayout();
                }),
            GetPage(
                name: authenticationScreenRoute,
                page: () => const AuthenticationScreen()),
            GetPage(name: homeScreenRoute, page: () => const HomeScreen()),
          ],
          debugShowCheckedModeBanner: false,
          title: 'BasicCode',
          theme: ThemeData(
            scaffoldBackgroundColor: light,
            textTheme: GoogleFonts.mulishTextTheme(Theme.of(context).textTheme)
                .apply(bodyColor: Colors.black),
            pageTransitionsTheme: const PageTransitionsTheme(builders: {
              TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
              TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
            }),
            primarySwatch: Colors.blue,
          ),
        ));
  }
}

What is the problem and how can I fix that?

Body:
I could simply resolve the problem by adding following lines to my main.dart file:

  home: Obx(() => AuthController.instance.isAuth
      ? const HomeScreen()
      : const AuthenticationScreen()),

And removing the followings:

   initialRoute
   : AuthController.instance.isAuth
       ? homeScreenRoute
       : authenticationScreenRoute,

I also deleted the Obx before the GetMaterialApp().

The new main.dart looks like this:

void main() {
  Get.put(MenuController());
  Get.put(NavigationController());
  Get.put(AuthController());
  Get.put(AuthCard);
  AuthController.instance.isAuth ? runApp(MyApp()) : runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      unknownRoute: GetPage(
          name: '/not-found',
          page: () => PageNotFound(),
          transition: Transition.fadeIn),
      getPages: [
        GetPage(
            name: rootRoute,
            page: () {
              return SiteLayout();
            }),
        GetPage(
            name: authenticationScreenRoute,
            page: () => const AuthenticationScreen()),
        GetPage(name: homeScreenRoute, page: () => const HomeScreen()),
      ],
      debugShowCheckedModeBanner: false,
      title: 'BasicCode',
      theme: ThemeData(
        scaffoldBackgroundColor: light,
        textTheme: GoogleFonts.mulishTextTheme(Theme.of(context).textTheme)
            .apply(bodyColor: Colors.black),
        pageTransitionsTheme: const PageTransitionsTheme(builders: {
          TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
          TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
        }),
        primarySwatch: Colors.blue,
      ),
      home: Obx(() => AuthController.instance.isAuth
          ? const HomeScreen()
          : const AuthenticationScreen()),
    );
  }
}


来源: stackexchange

问:
Flutter background service in custome time fireing function
I should implement feature which should fires function in every 10 seconds in the the background and I had tried out work manager but it minimal time is 15 min but I want 10 seconds and I cant find any packages or good example for it ,</p>

答:
```<code>dependencies:
  flutter_background_service: ^0.2.4
</code>```

Example:

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  initializeService();
  runApp(MyApp());
}

Future<void> initializeService() async {
  final service = FlutterBackgroundService();
  await service.configure(
    androidConfiguration: AndroidConfiguration(
      // this will executed when app is in foreground or background in separated isolate
      onStart: onStart,

      // auto start service
      autoStart: true,
      isForegroundMode: true,
    ),
    iosConfiguration: IosConfiguration(
      // auto start service
      autoStart: true,

      // this will executed when app is in foreground in separated isolate
      onForeground: onStart,

      // you have to enable background fetch capability on xcode project
      onBackground: onIosBackground,
    ),
  );
}

// to ensure this executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
void onIosBackground() {
  WidgetsFlutterBinding.ensureInitialized();
  print('FLUTTER BACKGROUND FETCH');
}

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();
  final service = FlutterBackgroundService();
  service.onDataReceived.listen((event) {
    if (event!["action"] == "setAsForeground") {
      service.setForegroundMode(true);
      return;
    }

    if (event["action"] == "setAsBackground") {
      service.setForegroundMode(false);
    }

    if (event["action"] == "stopService") {
      service.stopBackgroundService();
    }
  });

  // bring to foreground
  service.setForegroundMode(true);
  Timer.periodic(Duration(seconds: 1), (timer) async {
    if (!(await service.isServiceRunning())) timer.cancel();
    service.setNotificationInfo(
      title: "My App Service",
      content: "Updated at ${DateTime.now()}",
    );

    service.sendData(
      {"current_date": DateTime.now().toIso8601String()},
    );
  });
}

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

class _MyAppState extends State<MyApp> {
  String text = "Stop Service";
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Service App'),
        ),
        body: Column(
          children: [
            StreamBuilder<Map<String, dynamic>?>(
              stream: FlutterBackgroundService().onDataReceived,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }

                final data = snapshot.data!;
                DateTime? date = DateTime.tryParse(data["current_date"]);
                return Text(date.toString());
              },
            ),
            ElevatedButton(
              child: Text("Foreground Mode"),
              onPressed: () {
                FlutterBackgroundService()
                    .sendData({"action": "setAsForeground"});
              },
            ),
            ElevatedButton(
              child: Text("Background Mode"),
              onPressed: () {
                FlutterBackgroundService()
                    .sendData({"action": "setAsBackground"});
              },
            ),
            ElevatedButton(
              child: Text(text),
              onPressed: () async {
                final service = FlutterBackgroundService();
                var isRunning = await service.isServiceRunning();
                if (isRunning) {
                  service.sendData(
                    {"action": "stopService"},
                  );
                } else {
                  service.start();
                }

                if (!isRunning) {
                  text = 'Stop Service';
                } else {
                  text = 'Start Service';
                }
                setState(() {});
              },
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            FlutterBackgroundService().sendData({
              "hello": "world",
            });
          },
          child: Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
dependencies:
  flutter_background_service: ^0.2.4

Example:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  initializeService();
  runApp(MyApp());
}

Future<void> initializeService() async {
  final service = FlutterBackgroundService();
  await service.configure(
    androidConfiguration: AndroidConfiguration(
      // this will executed when app is in foreground or background in separated isolate
      onStart: onStart,

      // auto start service
      autoStart: true,
      isForegroundMode: true,
    ),
    iosConfiguration: IosConfiguration(
      // auto start service
      autoStart: true,

      // this will executed when app is in foreground in separated isolate
      onForeground: onStart,

      // you have to enable background fetch capability on xcode project
      onBackground: onIosBackground,
    ),
  );
}

// to ensure this executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
void onIosBackground() {
  WidgetsFlutterBinding.ensureInitialized();
  print('FLUTTER BACKGROUND FETCH');
}

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();
  final service = FlutterBackgroundService();
  service.onDataReceived.listen((event) {
    if (event!["action"] == "setAsForeground") {
      service.setForegroundMode(true);
      return;
    }

    if (event["action"] == "setAsBackground") {
      service.setForegroundMode(false);
    }

    if (event["action"] == "stopService") {
      service.stopBackgroundService();
    }
  });

  // bring to foreground
  service.setForegroundMode(true);
  Timer.periodic(Duration(seconds: 1), (timer) async {
    if (!(await service.isServiceRunning())) timer.cancel();
    service.setNotificationInfo(
      title: "My App Service",
      content: "Updated at ${DateTime.now()}",
    );

    service.sendData(
      {"current_date": DateTime.now().toIso8601String()},
    );
  });
}

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

class _MyAppState extends State<MyApp> {
  String text = "Stop Service";
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Service App'),
        ),
        body: Column(
          children: [
            StreamBuilder<Map<String, dynamic>?>(
              stream: FlutterBackgroundService().onDataReceived,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }

                final data = snapshot.data!;
                DateTime? date = DateTime.tryParse(data["current_date"]);
                return Text(date.toString());
              },
            ),
            ElevatedButton(
              child: Text("Foreground Mode"),
              onPressed: () {
                FlutterBackgroundService()
                    .sendData({"action": "setAsForeground"});
              },
            ),
            ElevatedButton(
              child: Text("Background Mode"),
              onPressed: () {
                FlutterBackgroundService()
                    .sendData({"action": "setAsBackground"});
              },
            ),
            ElevatedButton(
              child: Text(text),
              onPressed: () async {
                final service = FlutterBackgroundService();
                var isRunning = await service.isServiceRunning();
                if (isRunning) {
                  service.sendData(
                    {"action": "stopService"},
                  );
                } else {
                  service.start();
                }

                if (!isRunning) {
                  text = 'Stop Service';
                } else {
                  text = 'Start Service';
                }
                setState(() {});
              },
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            FlutterBackgroundService().sendData({
              "hello": "world",
            });
          },
          child: Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}


问:
Using @react-pdf/renderer on an express js server
I have a react webapp that I'd like have to render a pdf and email it when a button is pushed. For testing sake, when the button is pushed in the react frontend, it sends a request to my expressjs backend and attempts to generate a static pdf through @react-pdf/renderer.

I don't have a clear understanding of ES Modules vs CommonJS, but my server was using CommonJS, so I added "type": "module" to the server's package.json and updated the imports in server.js. However, the compiler complains about SyntaxError: Unexpected token '<' in server.js and materials.js (depending on setup). What am I doing wrong?

(code below has been cleaned to anonymize)

Edit
Here is an example of react-pdf/renderer being used on Node

server.js:

```<code>// const express = require('express');
// const cors = require('cors');
// const fs = require('fs')
// const react = require('react')
// const reactpdf = require('@react-pdf/renderer');
// const materials = require('./pdf/src/materials');
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import react from 'react';
import ReactPDF from '@react-pdf/renderer';
import MaterialsList from './materials.js';

const app = express();
const port = 5000;

app.use(cors())

app.use(express.urlencoded());
app.use(express.json());

app.listen(port, function () {
    console.log(`server running on http://localhost:${port}`);
})

app.post('/sendmaterials', cors(), function (req, res) {
    // const pdf = req.body;
    // console.log(pdf);

    // reactpdf.render(pdf, `${__dirname}/trial.pdf`);
    reactpdf.render(<MaterialsList />, `${__dirname}/trial.pdf`);
    // fs.writeFile('trial.pdf', pdf, (err) => {
    //     // throws an error, you could also catch it here
    //     if (err) throw err;

    //     // success case, the file was saved
    //     console.log('PDF saved!');
    // });
})
</code>```

package.json:

```<code>{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "dependencies": {
    "@react-pdf/renderer": "^1.6.13",
    "concurrently": "^5.3.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "firebase": "^9.0.0-beta.1",
    "nodemon": "^2.0.6",
    "react": "^17.0.2"
  },
  "devDependencies": {
    "husky": "^5.1.3",
    "lint-staged": "^10.5.4",
    "prettier": "^2.2.1",
    "pretty-quick": "^3.1.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "concurrently \"nodemon server.js\" \"cd frontend && yarn start\"",
    "init": "concurrently \"yarn\" \"cd frontend && yarn\"",
    "install-initial": "concurrently \"yarn install\" \"cd frontend && yarn install\"",
    "start-frontend": "cd frontend && yarn start",
    "start-server": "nodemon server.js",
    "pretty-quick": "pretty-quick",
    "prepare": "husky install"
  },
  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged"
    }
  },
  "lint-staged": {
    "linters": {
      "src/**/*.{js,css}": [
        "prettier --write",
        "git add"
      ]
    }
  }
}
</code>```

materials.js:

```<code>import React from 'react';
import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  Image,
  // Font,
} from '@react-pdf/renderer';
import Logo from './images/img.png'
// import Trebuchet from './fonts/Trebuchet/trebuchet-ms.ttf'

// Font.register({
//   family: 'Trebuchet MS',
//   src: Trebuchet,
// })

// Create styles
const styles = StyleSheet.create({
  page: {
    padding: 30,
  },
  container: {
    marginTop: 20,
    marginBottom: 20,
    flex: 0,
    flexDirection: 'row',
    '@media max-width: 400': {
      flexDirection: 'column',
    },
  },
  image: {
    marginTop: 20,
  },
  mainTitle: {
    // fontFamily: 'Trebuchet MS',
    paddingLeft: 15,
    fontWeight: 'bold',
    color: "#000000",
    fontSize: 19,
  },
  title: {
    // fontFamily: 'Trebuchet MS',
    fontWeight: 'bold',
    color: "#000000",
    fontSize: 16,
    textDecoration: 'underline',
  },
  regGrey: {
    // fontFamily: 'Trebuchet MS',
    color: "#8d8d8d",
    fontSize: 12,
  },
  regBlack: {
    // fontFamily: 'Trebuchet MS',
    color: "#101010",
    fontSize: 12,
    marginBottom: 15,
  },
  column: {
    flexDirection: 'column',
    width: 180,
    paddingLeft: 15,
    paddingRight: 15,
    '@media max-width: 400': {
      width: '100%',
      paddingRight: 0,
    },
    '@media orientation: landscape': {
      width: 200,
    },
  },
  table: {
      width: '100%',
      alignContent: 'center',
      borderWidth: 0,
      display: 'flex',
      flexDirection: 'column',
      paddingTop: 10,
  },
  header: {
    backgroundColor: "#4c4c4c",
    fontWeight: 'bold',
    color: "#fdfdfd",
    flexWrap: 'wrap'
  },
  tableRow:{
    display: 'flex',
    flexDirection: 'row',
  },
  lightRow:{
    display: 'flex',
    flexDirection: 'row',
    backgroundColor: "#cfcfcf",
  },
  darkRow:{
    display: 'flex',
    flexDirection: 'row',
    backgroundColor: "#aeaeae",
  },
  cell: {
    fontColor: "#101010",
    // fontFamily: 'Trebuchet MS',
    fontSize: 12,
    borderWidth: 0,
    display: 'flex',
    justifyContent: 'center',
    alignContent: 'center',
    textAlign: 'center',
    flexWrap: 'wrap'
  },
});

// Create table object
const Table = ({header, alternate, children, col}) => (
    <View style={styles.table}>
        {children.map((row, ind) =>
            <View key={ind} style={[styles.tableRow,
              header && ind === 0 ? styles.header: {},
              alternate && ind % 2 === 0 && ind !== 0 ? styles.lightRow: {},
              alternate && ind % 2 !== 0 && ind !== 0 ? styles.darkRow: {},
            ]}>
                {row.map((cell, j) =>
                    <View key={j} style={[styles.cell, {width:col[j], height: 40}]}>
                        {
                            typeof(cell) === 'string' || typeof(cell) === 'number' ?
                            <Text>{cell}</Text> : cell
                        }
                    </View>
                )}
            </View>
        )}
    </View>
)

// Create Document Component
const MaterialsList = () => (
  <Document>
    <Page style={styles.page}>
      <View style={styles.container}>
        <View style={styles.column}>
          <Text style={styles.title}>
            Steels
          </Text>
          <Table
            col={['60%', '40%']}
            header
            alternate
            children={[
              ['Item', 'Quantity'],
              ['Steel', '10'],
              ['U Channel', '10'],
              ['Gate Insert', '10'],
            ]} />
        </View>
      </View>
    </Page>
  </Document>
);

export default MaterialsList
</code>```

答: The problem was in the package.json file, I was missing the babel libraries and config file. I have a example repo showing the correct setup and a link to the discussion on the react-pdf/renderer github discussion.

Body:
I have a react webapp that I'd like have to render a pdf and email it when a button is pushed. For testing sake, when the button is pushed in the react frontend, it sends a request to my expressjs backend and attempts to generate a static pdf through @react-pdf/renderer.

I don't have a clear understanding of ES Modules vs CommonJS, but my server was using CommonJS, so I added "type": "module" to the server's package.json and updated the imports in server.js. However, the compiler complains about SyntaxError: Unexpected token '<' in server.js and materials.js (depending on setup). What am I doing wrong?

(code below has been cleaned to anonymize)

Edit
Here is an example of react-pdf/renderer being used on Node

server.js:

// const express = require('express');
// const cors = require('cors');
// const fs = require('fs')
// const react = require('react')
// const reactpdf = require('@react-pdf/renderer');
// const materials = require('./pdf/src/materials');
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import react from 'react';
import ReactPDF from '@react-pdf/renderer';
import MaterialsList from './materials.js';

const app = express();
const port = 5000;

app.use(cors())

app.use(express.urlencoded());
app.use(express.json());

app.listen(port, function () {
    console.log(`server running on http://localhost:${port}`);
})

app.post('/sendmaterials', cors(), function (req, res) {
    // const pdf = req.body;
    // console.log(pdf);

    // reactpdf.render(pdf, `${__dirname}/trial.pdf`);
    reactpdf.render(<MaterialsList />, `${__dirname}/trial.pdf`);
    // fs.writeFile('trial.pdf', pdf, (err) => {
    //     // throws an error, you could also catch it here
    //     if (err) throw err;

    //     // success case, the file was saved
    //     console.log('PDF saved!');
    // });
})

package.json:

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "dependencies": {
    "@react-pdf/renderer": "^1.6.13",
    "concurrently": "^5.3.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "firebase": "^9.0.0-beta.1",
    "nodemon": "^2.0.6",
    "react": "^17.0.2"
  },
  "devDependencies": {
    "husky": "^5.1.3",
    "lint-staged": "^10.5.4",
    "prettier": "^2.2.1",
    "pretty-quick": "^3.1.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "concurrently \"nodemon server.js\" \"cd frontend && yarn start\"",
    "init": "concurrently \"yarn\" \"cd frontend && yarn\"",
    "install-initial": "concurrently \"yarn install\" \"cd frontend && yarn install\"",
    "start-frontend": "cd frontend && yarn start",
    "start-server": "nodemon server.js",
    "pretty-quick": "pretty-quick",
    "prepare": "husky install"
  },
  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged"
    }
  },
  "lint-staged": {
    "linters": {
      "src/**/*.{js,css}": [
        "prettier --write",
        "git add"
      ]
    }
  }
}

materials.js:

import React from 'react';
import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  Image,
  // Font,
} from '@react-pdf/renderer';
import Logo from './images/img.png'
// import Trebuchet from './fonts/Trebuchet/trebuchet-ms.ttf'

// Font.register({
//   family: 'Trebuchet MS',
//   src: Trebuchet,
// })

// Create styles
const styles = StyleSheet.create({
  page: {
    padding: 30,
  },
  container: {
    marginTop: 20,
    marginBottom: 20,
    flex: 0,
    flexDirection: 'row',
    '@media max-width: 400': {
      flexDirection: 'column',
    },
  },
  image: {
    marginTop: 20,
  },
  mainTitle: {
    // fontFamily: 'Trebuchet MS',
    paddingLeft: 15,
    fontWeight: 'bold',
    color: "#000000",
    fontSize: 19,
  },
  title: {
    // fontFamily: 'Trebuchet MS',
    fontWeight: 'bold',
    color: "#000000",
    fontSize: 16,
    textDecoration: 'underline',
  },
  regGrey: {
    // fontFamily: 'Trebuchet MS',
    color: "#8d8d8d",
    fontSize: 12,
  },
  regBlack: {
    // fontFamily: 'Trebuchet MS',
    color: "#101010",
    fontSize: 12,
    marginBottom: 15,
  },
  column: {
    flexDirection: 'column',
    width: 180,
    paddingLeft: 15,
    paddingRight: 15,
    '@media max-width: 400': {
      width: '100%',
      paddingRight: 0,
    },
    '@media orientation: landscape': {
      width: 200,
    },
  },
  table: {
      width: '100%',
      alignContent: 'center',
      borderWidth: 0,
      display: 'flex',
      flexDirection: 'column',
      paddingTop: 10,
  },
  header: {
    backgroundColor: "#4c4c4c",
    fontWeight: 'bold',
    color: "#fdfdfd",
    flexWrap: 'wrap'
  },
  tableRow:{
    display: 'flex',
    flexDirection: 'row',
  },
  lightRow:{
    display: 'flex',
    flexDirection: 'row',
    backgroundColor: "#cfcfcf",
  },
  darkRow:{
    display: 'flex',
    flexDirection: 'row',
    backgroundColor: "#aeaeae",
  },
  cell: {
    fontColor: "#101010",
    // fontFamily: 'Trebuchet MS',
    fontSize: 12,
    borderWidth: 0,
    display: 'flex',
    justifyContent: 'center',
    alignContent: 'center',
    textAlign: 'center',
    flexWrap: 'wrap'
  },
});

// Create table object
const Table = ({header, alternate, children, col}) => (
    <View style={styles.table}>
        {children.map((row, ind) =>
            <View key={ind} style={[styles.tableRow,
              header && ind === 0 ? styles.header: {},
              alternate && ind % 2 === 0 && ind !== 0 ? styles.lightRow: {},
              alternate && ind % 2 !== 0 && ind !== 0 ? styles.darkRow: {},
            ]}>
                {row.map((cell, j) =>
                    <View key={j} style={[styles.cell, {width:col[j], height: 40}]}>
                        {
                            typeof(cell) === 'string' || typeof(cell) === 'number' ?
                            <Text>{cell}</Text> : cell
                        }
                    </View>
                )}
            </View>
        )}
    </View>
)

// Create Document Component
const MaterialsList = () => (
  <Document>
    <Page style={styles.page}>
      <View style={styles.container}>
        <View style={styles.column}>
          <Text style={styles.title}>
            Steels
          </Text>

        </View>
      </View>
    </Page>
  </Document>
);

export default MaterialsList


问:
Stop Notification sound when Notification clicked android
I am building an android application which show notification with custom sound, when user click this notification I start an activity.
all of that working well for me but when user clicked notification sound still playing I want to stop the sound when user clicked on notification How can I do that.
this is my code</p>
```<code>public void ShowNotification(String title,String message) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("com.mkandeel.test","Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"com.mkandeel.test");
        builder.setSmallIcon(R.drawable.notif)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        Intent intent = new Intent(context,MainActivity2.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        PendingIntent pi = PendingIntent.getActivity(context,99,
                intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);

        NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);

        Uri sound = Uri.parse("android.resource://"
                + context.getPackageName() + "/" + R.raw.sound);

        MediaPlayer mp = MediaPlayer.create(context, sound);
        mp.start();

        builder.setAutoCancel(true);

        mcompact.notify(99,builder.build());
    }
</code>```

答:
I finally found solution to create MediaPlayer object global variable and send boolean extra in intent as true
and in MainActivity2 I got this boolean variable and if it is true I accessed MediaPlayer object and stop it and this is modified code

```<code>public class MainActivity extends AppCompatActivity {

    public MediaPlayer mp;
    private Button btn;

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

        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowNotification("Test notification","Hello World!");
            }
        });

    }

public void ShowNotification(String title,String message) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("com.mkandeel.test","Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"com.mkandeel.test");
        builder.setSmallIcon(R.drawable.notif)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        Intent intent = new Intent(context,MainActivity2.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.putExtra("clicked",true);
        PendingIntent pi = PendingIntent.getActivity(context,99,
                intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);

        NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);

        Uri sound = Uri.parse("android.resource://"
                + context.getPackageName() + "/" + R.raw.sound);

        mp = MediaPlayer.create(context, sound);
        mp.start();

        builder.setAutoCancel(true);

        mcompact.notify(99,builder.build());
    }
}
</code>```

and in MainActivity2.java

```<code>public class MainActivity2 extends AppCompatActivity {

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

        MainActivity activity = new MainActivity();

        boolean clicked = getIntent().getBooleanExtra("clicked",false);
        if (clicked) {
            activity.mp.stop();
            activity.mp.release();
        }
    }
}
</code>```

Body:
I am building an android application which show notification with custom sound, when user click this notification I start an activity.
all of that working well for me but when user clicked notification sound still playing I want to stop the sound when user clicked on notification How can I do that.
this is my code

public void ShowNotification(String title,String message) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("com.mkandeel.test","Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"com.mkandeel.test");
        builder.setSmallIcon(R.drawable.notif)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        Intent intent = new Intent(context,MainActivity2.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        PendingIntent pi = PendingIntent.getActivity(context,99,
                intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);

        NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);

        Uri sound = Uri.parse("android.resource://"
                + context.getPackageName() + "/" + R.raw.sound);

        MediaPlayer mp = MediaPlayer.create(context, sound);
        mp.start();

        builder.setAutoCancel(true);

        mcompact.notify(99,builder.build());
    }

Body:
I finally found solution to create MediaPlayer object global variable and send boolean extra in intent as true
and in MainActivity2 I got this boolean variable and if it is true I accessed MediaPlayer object and stop it and this is modified code

public class MainActivity extends AppCompatActivity {

    public MediaPlayer mp;
    private Button btn;

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

        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowNotification("Test notification","Hello World!");
            }
        });

    }

public void ShowNotification(String title,String message) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("com.mkandeel.test","Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"com.mkandeel.test");
        builder.setSmallIcon(R.drawable.notif)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        Intent intent = new Intent(context,MainActivity2.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.putExtra("clicked",true);
        PendingIntent pi = PendingIntent.getActivity(context,99,
                intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);

        NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);

        Uri sound = Uri.parse("android.resource://"
                + context.getPackageName() + "/" + R.raw.sound);

        mp = MediaPlayer.create(context, sound);
        mp.start();

        builder.setAutoCancel(true);

        mcompact.notify(99,builder.build());
    }
}

and in MainActivity2.java

public class MainActivity2 extends AppCompatActivity {

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

        MainActivity activity = new MainActivity();

        boolean clicked = getIntent().getBooleanExtra("clicked",false);
        if (clicked) {
            activity.mp.stop();
            activity.mp.release();
        }
    }
}


问:
Ranking in python dataframe
I have data of cooking oil and its boiling temp and try to rank it by higher boiling temp. I'm using these code below:

```<code>df['ranking']=df['boil_temp'].rank(ascending=False)
df = df.set_index('ranking')

df_ranked = df.sort_values(by=['ranking'],ascending=True)
print(df_ranked)

                      oil  boil_temp
Ranking
1.0               avocado        270
2.0             sunflower        252
4.0           beef_tallow        250
4.0      butter_clarified        250
4.0               mustard        250
6.0                  palm        235
7.0                  corn        230
8.0             grapeseed        216
9.0                canola        204
10.0              coconut        200
11.0             olive_ev        160
12.0               butter        150
</code>```

But I want the rank to be like this:

```<code>                      oil  boil_temp
Ranking
1.0               avocado        270
2.0             sunflower        252
3.0           beef_tallow        250
3.0      butter_clarified        250
3.0               mustard        250
4.0                  palm        235
5.0                  corn        230
6.0             grapeseed        216
7.0                canola        204
8.0               coconut        200
9.0              olive_ev        160
10.0               butter        150
</code>```

What should I do?

答:
An interesting thing about the rank function is that if there is a tie between N previous records for the value in the column, the rank function skips the next N-1 positions before incrementing the counter.

However the dense rank function does not skip any ranks if there is a tie between the ranks of the preceding records

Addition to what @bb1 has suggested -

```<code>>>> df['Ranking'] = df['boil_temp'].rank(ascending=False, method='dense')

>>> df = df.sort_values(by='Ranking', ascending=True)

>>> df.reset_index(drop=True, inplace=True)

>>> print(df)

Ranking               Oil  boil_temp
0       1.0           avocado        270
1       2.0            canola        260
2       3.0         sunflower        252
3       4.0       beef_tallow        250
4       4.0  butter_clarified        250
5       4.0           mustard        250
6       5.0              palm        235
7       6.0              corn        230
8       7.0         grapeseed        216
9       8.0           coconut        200
10      9.0          olive_ev        160
11     10.0            butter        150

</code>```

Title: Ranking in python dataframe

Body:
I have data of cooking oil and its boiling temp and try to rank it by higher boiling temp. I'm using these code below:

df['ranking']=df['boil_temp'].rank(ascending=False)
df = df.set_index('ranking')

df_ranked = df.sort_values(by=['ranking'],ascending=True)
print(df_ranked)

                      oil  boil_temp
Ranking
1.0               avocado        270
2.0             sunflower        252
4.0           beef_tallow        250
4.0      butter_clarified        250
4.0               mustard        250
6.0                  palm        235
7.0                  corn        230
8.0             grapeseed        216
9.0                canola        204
10.0              coconut        200
11.0             olive_ev        160
12.0               butter        150

But I want the rank to be like this:

                      oil  boil_temp
Ranking
1.0               avocado        270
2.0             sunflower        252
3.0           beef_tallow        250
3.0      butter_clarified        250
3.0               mustard        250
4.0                  palm        235
5.0                  corn        230
6.0             grapeseed        216
7.0                canola        204
8.0               coconut        200
9.0              olive_ev        160
10.0               butter        150

What should I do?

Body:
An interesting thing about the rank function is that if there is a tie between N previous records for the value in the column, the rank function skips the next N-1 positions before incrementing the counter.

However the dense rank function does not skip any ranks if there is a tie between the ranks of the preceding records

Addition to what @bb1 has suggested -

>>> df['Ranking'] = df['boil_temp'].rank(ascending=False, method='dense')

>>> df = df.sort_values(by='Ranking', ascending=True)

>>> df.reset_index(drop=True, inplace=True)

>>> print(df)

Ranking               Oil  boil_temp
0       1.0           avocado        270
1       2.0            canola        260
2       3.0         sunflower        252
3       4.0       beef_tallow        250
4       4.0  butter_clarified        250
5       4.0           mustard        250
6       5.0              palm        235
7       6.0              corn        230
8       7.0         grapeseed        216
9       8.0           coconut        200
10      9.0          olive_ev        160
11     10.0            butter        150


问:
The command 'pip freeze' on the linux bash shell is not showing any of the installed packages in the output
I'm using the Linux Bash shell on Windows to activate django virtual environment and I want to see if the packages I'm using in this certain project are showing up using pip freeze (just like in the tutorial I am watching, since I'm very new to Linux in general) but once I put in the command, it doesn't give me any errors it's just that it won't output any packages at all. This might be a very simple question to some of you guys but I was doing some research and I can't find anyone in the exact same circumstances I'm in, so I decided to come to SO for help.

```<code>(djangoenv) winston1420@DESKTOP-PS608FU:/mnt/c/Users/admin/desktop/first_djangoproject_venv$ pip freeze +pip freeze
</code>```

As you can see in the image, or code, it only shows the + pip freeze. Please, any help would be appreciated.

答:
This is what fixed it for me:

After I used the commnad python -m pip install --upgrade pip, the packages are showing up when using the pip freeze command.

Body:
I'm using the Linux Bash shell on Windows to activate django virtual environment and I want to see if the packages I'm using in this certain project are showing up using pip freeze (just like in the tutorial I am watching, since I'm very new to Linux in general) but once I put in the command, it doesn't give me any errors it's just that it won't output any packages at all. This might be a very simple question to some of you guys but I was doing some research and I can't find anyone in the exact same circumstances I'm in, so I decided to come to SO for help.

(djangoenv) winston1420@DESKTOP-PS608FU:/mnt/c/Users/admin/desktop/first_djangoproject_venv$ pip freeze +pip freeze

As you can see in the image, or code, it only shows the + pip freeze. Please, any help would be appreciated.


问:
How to alter address bar URL while I'm in a different website?
Let's say I'm on a https://www.example.com. Can I alter address bar URL to display https://www.google.com while I'm in https://www.example.com website using JavaScript?

ex:

I'm on https://www.example.com website, But what if I wanna display different URL like http://www.google.com in the address bar? Is it possible?

Just asking based on learning purpose about the information security.

答:
No, that would be a security risk, if any website could make it appear to the user to actually be on any other website. Phishing would be a whole lot easier if that was permitted.

The best you can do is history.pushState (or .replaceState), which has the reasonable restriction that:

The new URL can be any URL in the same origin as the current URL.

Or, of course, you could actually redirect to the other website by assigning to location.href.

It might be possible to write a browser extension that fiddles with the internals of the browser so that it displays your arbitrary desired text instead of the actual current page, but such a thing would have to be deliberately installed by the user.


问:
Writing and Reading JSON files locally in Flutter Doesn't include Quotes
I am writing an object to a JSON file locally. When I try and read it, I receive this error:

```<code>E/flutter ( 7621): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter ( 7621): {players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
E/flutter ( 7621):  ^
</code>```

I understand that the reason I'm getting this error is because that player is not between quotes. i.e. "player". I do not know how to write the object as a JSON with the quotes included.

This code was generated by the JsonSerializableGenerator

PlayerList.toJson:

```<code>PlayerList _$PlayerListFromJson(Map<String, dynamic> json) {
  return PlayerList(
    (json['players'] as List)
        ?.map((e) =>
            e == null ? null : Player.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$PlayerListToJson(PlayerList instance) =>
    <String, dynamic>{
      'players': instance.players?.map((e) => e?.toJson())?.toList(),
    };
</code>```

This is how I read and write the file:

```<code>Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/playerData.json');
}

Future<File> writePlayerData(PlayerList playerList) async {
  final file = await _localFile;
  return file.writeAsString(playerList.toJson().toString());
}

Future<PlayerList> readPlayerData () async {
  try {
    final file = await _localFile;
    String contents = await file.readAsString();
    final jsonResponse = jsonDecode(contents);
    PlayerList playerList = PlayerList.fromJson(jsonResponse);
    return playerList;
  } catch (e) {
    print(e);
    return getPlayerList(); //just loads a placeholder json in the assets folder;
  }
}
</code>```

What I want the JSON to be formatted as:

```<code>{
  "players": [
    {
      "id": "Filler Character",
      "setCount": "0 - 0",
      "characters": {
        "char1": "",
        "char2": ""
      },
      "notes": "Filler Character"
    }
  ]
}
</code>```

What the program saves:

```<code>{players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
</code>```

Do I need to manually add the quotes back into the JSON, or is there a different way of saving them?

答:
Let, test.json is a locally stored json file in your desktop. test.json -

```<code>[
  {"name":"Ash","age":"22","hobby":"golf"},
  {"name":"philip","age":"17","hobby":"fishing"},
  {"name":"charles","age":"32","hobby":"drawing"},
]
</code>```

Now we want to read from it and write to it. The code below does the task. test.dart -

```<code>import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/.../test.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}

class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}
</code>```

Body:
I am writing an object to a JSON file locally. When I try and read it, I receive this error:

E/flutter ( 7621): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter ( 7621): {players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
E/flutter ( 7621):  ^

I understand that the reason I'm getting this error is because that player is not between quotes. i.e. "player". I do not know how to write the object as a JSON with the quotes included.

This code was generated by the JsonSerializableGenerator

PlayerList.toJson:

PlayerList _$PlayerListFromJson(Map<String, dynamic> json) {
  return PlayerList(
    (json['players'] as List)
        ?.map((e) =>
            e == null ? null : Player.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$PlayerListToJson(PlayerList instance) =>
    <String, dynamic>{
      'players': instance.players?.map((e) => e?.toJson())?.toList(),
    };

This is how I read and write the file:

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/playerData.json');
}

Future<File> writePlayerData(PlayerList playerList) async {
  final file = await _localFile;
  return file.writeAsString(playerList.toJson().toString());
}

Future<PlayerList> readPlayerData () async {
  try {
    final file = await _localFile;
    String contents = await file.readAsString();
    final jsonResponse = jsonDecode(contents);
    PlayerList playerList = PlayerList.fromJson(jsonResponse);
    return playerList;
  } catch (e) {
    print(e);
    return getPlayerList(); //just loads a placeholder json in the assets folder;
  }
}

What I want the JSON to be formatted as:

{
  "players": [
    {
      "id": "Filler Character",
      "setCount": "0 - 0",
      "characters": {
        "char1": "",
        "char2": ""
      },
      "notes": "Filler Character"
    }
  ]
}

What the program saves:

{players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}

Do I need to manually add the quotes back into the JSON, or is there a different way of saving them?

Body:
Let, test.json is a locally stored json file in your desktop. test.json -

[
  {"name":"Ash","age":"22","hobby":"golf"},
  {"name":"philip","age":"17","hobby":"fishing"},
  {"name":"charles","age":"32","hobby":"drawing"},
]

Now we want to read from it and write to it. The code below does the task. test.dart -

import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/.../test.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}

class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}


问:
How get the card type from reading a range of bins
I am trying to get a range of card type from a list bins that are associated with that card type, but whenever I ran the code the card-type is printed as null am not sure what I am doing wrong

This are the bins in a text

```<code>400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
</code>```

Whenever I Pass 4111111111111111 instead of getting visa i end getting null,

this is what I have done so far

```<code>package cardsystem;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class Solution {

    /**
     * An entity to hold bin range details. A bin range is a pair of 12 digit numbers that
     * mark the boundaries of the range which is maped to other bin range properties such
     * as a card type. The range boundaries are inclusive.
     */
    static final class BinRange {
        final String start;
        final String end;
        final String cardType;

        BinRange(String start, String end, String cardType) {
            this.start = start;
            this.end = end;
            this.cardType = cardType;
        }
    }

    //  I need a hashmap which hold index and CardType. Each index corresponding an interval (start-end).
    private static HashMap<Integer, String> cache = new HashMap<>();
    private static List<Long> startEndList = new ArrayList<>();

    interface CardTypeCache {
        /**
         * @param cardNumber 12 to 23 digit card number.
         * @return the card type for this cardNumber or null if the card number does not
         * fall into any valid bin ranges.
         */
        String get(String cardNumber);
    }

    /**
     * @param binRanges the list of card bin ranges to build a cache from.
     * @return an implementation of CardTypeCache.
     */
    public static CardTypeCache buildCache(List<BinRange> binRanges) {

        cache = new HashMap<>();

        for (int i = 0; i < binRanges.size(); i++) {
            cache.put(i, binRanges.get(i).cardType);
        }

        for (BinRange binRange : binRanges) {
            startEndList.add(Long.valueOf(binRange.start)); // Previously, Integer type used, I converted it to 'Long' type
            startEndList.add(Long.valueOf(binRange.end));
        }

        return new CardTypeCacheImpl();
    }

    static class CardTypeCacheImpl implements CardTypeCache {

        public String get(String cardNumber) {

            //Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
            Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
            return (index != -1) ? cache.get(index) : "null";
        }

        /**
         * Linear Search O(n)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexLinear(Long cardNumber) {

            for (int i = 1; i < startEndList.size(); i += 2) {
                if (startEndList.get(i - 1) <= cardNumber && cardNumber <= startEndList.get(i)) {
                    return i / 2;
                }
            }
            return -1;
        }

        /**
         * Binary Search O(logn)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexBinary(Long cardNumber) {

            int left = 0;
            int right = startEndList.size();

            while (left < right) {

                int mid = left + (right - left) / 2;

                if (mid % 2 == 0 && startEndList.get(mid) <= cardNumber && cardNumber <= startEndList.get(mid + 1)) { // right pair (start-end) of mid
                    return mid / 2;
                } else if (mid % 2 == 1 && startEndList.get(mid - 1) <= cardNumber && cardNumber <= startEndList.get(mid)) {  // left pair
                    return mid / 2;
                }

                if (cardNumber < startEndList.get(mid)) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            return -1;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        File text = new File("D:/dev/CardSystem/src/cardsystem/input.txt");

        try (final Scanner scanner = new Scanner(text)) {
            List<Solution.BinRange> binRanges = new ArrayList<>();

            /*
            4111111111111111
            400000000000,499999999999,visa
            500000000000,599999999999,mc
            */

            String cardNumber = scanner.next();
            scanner.nextLine();

            scanner.useDelimiter("[,\n]");

            while (scanner.hasNext()) {
                String start = scanner.next();
                String end = scanner.next();
                String cardType = scanner.next();
                binRanges.add(new Solution.BinRange(start, end, cardType));
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                }
            }

            Solution.CardTypeCache cache = Solution.buildCache(binRanges);
            if (cache != null) {
                bufferedWriter.write(String.valueOf(cache.get(cardNumber)));
            }
        }

        bufferedWriter.newLine();
        bufferedWriter.close();
    }
}
</code>```

What am I doing wrong, been scratching my head for hours

答:
FROM

```<code>400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
</code>```

TO

```<code>400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc
</code>```

you can try and trim the numbers to the left and omit everything that exceeds 12 digits and then you will get  a print of the card type to the console

here is a line to add

```<code> cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
</code>```

so the whole function will look like

```<code>public String get(String cardNumber) {

        cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
        Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
        //Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
        return (index != -1) ? cache.get(index) : "null";
    }
</code>```

Body:
I am trying to get a range of card type from a list bins that are associated with that card type, but whenever I ran the code the card-type is printed as null am not sure what I am doing wrong

This are the bins in a text

400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

Whenever I Pass 4111111111111111 instead of getting visa i end getting null,

this is what I have done so far

package cardsystem;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class Solution {

    /**
     * An entity to hold bin range details. A bin range is a pair of 12 digit numbers that
     * mark the boundaries of the range which is maped to other bin range properties such
     * as a card type. The range boundaries are inclusive.
     */
    static final class BinRange {
        final String start;
        final String end;
        final String cardType;

        BinRange(String start, String end, String cardType) {
            this.start = start;
            this.end = end;
            this.cardType = cardType;
        }
    }

    //  I need a hashmap which hold index and CardType. Each index corresponding an interval (start-end).
    private static HashMap<Integer, String> cache = new HashMap<>();
    private static List<Long> startEndList = new ArrayList<>();

    interface CardTypeCache {
        /**
         * @param cardNumber 12 to 23 digit card number.
         * @return the card type for this cardNumber or null if the card number does not
         * fall into any valid bin ranges.
         */
        String get(String cardNumber);
    }

    /**
     * @param binRanges the list of card bin ranges to build a cache from.
     * @return an implementation of CardTypeCache.
     */
    public static CardTypeCache buildCache(List<BinRange> binRanges) {

        cache = new HashMap<>();

        for (int i = 0; i < binRanges.size(); i++) {
            cache.put(i, binRanges.get(i).cardType);
        }

        for (BinRange binRange : binRanges) {
            startEndList.add(Long.valueOf(binRange.start)); // Previously, Integer type used, I converted it to 'Long' type
            startEndList.add(Long.valueOf(binRange.end));
        }

        return new CardTypeCacheImpl();
    }

    static class CardTypeCacheImpl implements CardTypeCache {

        public String get(String cardNumber) {

            //Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
            Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
            return (index != -1) ? cache.get(index) : "null";
        }

        /**
         * Linear Search O(n)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexLinear(Long cardNumber) {

            for (int i = 1; i < startEndList.size(); i += 2) {
                if (startEndList.get(i - 1) <= cardNumber && cardNumber <= startEndList.get(i)) {
                    return i / 2;
                }
            }
            return -1;
        }

        /**
         * Binary Search O(logn)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexBinary(Long cardNumber) {

            int left = 0;
            int right = startEndList.size();

            while (left < right) {

                int mid = left + (right - left) / 2;

                if (mid % 2 == 0 && startEndList.get(mid) <= cardNumber && cardNumber <= startEndList.get(mid + 1)) { // right pair (start-end) of mid
                    return mid / 2;
                } else if (mid % 2 == 1 && startEndList.get(mid - 1) <= cardNumber && cardNumber <= startEndList.get(mid)) {  // left pair
                    return mid / 2;
                }

                if (cardNumber < startEndList.get(mid)) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            return -1;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        File text = new File("D:/dev/CardSystem/src/cardsystem/input.txt");

        try (final Scanner scanner = new Scanner(text)) {
            List<Solution.BinRange> binRanges = new ArrayList<>();

            /*
            4111111111111111
            400000000000,499999999999,visa
            500000000000,599999999999,mc
            */

            String cardNumber = scanner.next();
            scanner.nextLine();

            scanner.useDelimiter("[,\n]");

            while (scanner.hasNext()) {
                String start = scanner.next();
                String end = scanner.next();
                String cardType = scanner.next();
                binRanges.add(new Solution.BinRange(start, end, cardType));
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                }
            }

            Solution.CardTypeCache cache = Solution.buildCache(binRanges);
            if (cache != null) {
                bufferedWriter.write(String.valueOf(cache.get(cardNumber)));
            }
        }

        bufferedWriter.newLine();
        bufferedWriter.close();
    }
}

What am I doing wrong, been scratching my head for hours

Body:
FROM

400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

TO

400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

you can try and trim the numbers to the left and omit everything that exceeds 12 digits and then you will get  a print of the card type to the console

here is a line to add

 cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;

so the whole function will look like

public String get(String cardNumber) {

        cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
        Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
        //Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
        return (index != -1) ? cache.get(index) : "null";
    }


问:
How to pass struct array arguments to a function the right way?
Source Code:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}
</code>```

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

答:
You are reading data 3 times into the first element in your array:

Employee employee[3];

for(int i = 0; i < sizeOfEmployee; i++) {
    cout << "Enter name for employee " << i + 1 << ": ";
    cin >> employee->name; // employee points to the first element in the array
}
```
<p>One more comment: your are passing the <code>Employee</code> class by value just to display it. It would be mych better, efficient and robust to pass it by const reference:</p>
<pre class="lang-cpp prettyprint-override"><code>void displayData(const Employee&);
</code>```

Body:
Source Code:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

Body:
You are reading data 3 times into the first element in your array:

Employee employee[3];

for(int i = 0; i < sizeOfEmployee; i++) {
    cout << "Enter name for employee " << i + 1 << ": ";
    cin >> employee->name; // employee points to the first element in the array
}

One more comment: your are passing the Employee class by value just to display it. It would be mych better, efficient and robust to pass it by const reference:

void displayData(const Employee&);


问:
What is an optimal setting for AAC voice recording with AVAudioSession?
I'm looking to record voice on the iPhone and produce a file that is optimized for small size and recording quality for voice.  With the settings below for AAC I'm getting a small file size, but I'm not sure I'm getting optimal quality.   Other than trial and error, is there anything I can turn to, or any recommendations?</p>

```<code>[recordSetting setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setObject:[NSNumber numberWithInt:AVAudioQualityLow] forKey: AVEncoderAudioQualityKey];
[recordSetting setValue:[NSNumber numberWithInt: 8000] forKey:AVEncoderBitRateKey];
</code>```

答: There are several codecs which are optimized for voice, including iLBC. Using iLBC at the 8kHz sample rate that you have will result in a file that is approximately 7MB per hour of recording. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to record voice on the iPhone and produce a file that is optimized for small size and recording quality for voice.  With the settings below for AAC I'm getting a small file size, but I'm not sure I'm getting optimal quality.   Other than trial and error, is there anything I can turn to, or any recommendations?

[recordSetting setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setObject:[NSNumber numberWithInt:AVAudioQualityLow] forKey: AVEncoderAudioQualityKey];
[recordSetting setValue:[NSNumber numberWithInt: 8000] forKey:AVEncoderBitRateKey];


问:
What is the type of function that I'm biding and passing down as props in React with TypeScript?
I have created a custom Checkbox component.

TypeScript in the project does not accept any types, so I need to indicate the exact type of handleCheckbox() function (located in FilterBox component) that I am passing down as props to child component Checkbox.

```<code>const handleCheckbox = (state: Record<string, unknown>) => {
    const _preProcessNewState = { ...globalStatus, ...state };
    //Change the States
    setGlobalStatus(_preProcessNewState);
  };
</code>```

Below we pass this function to Checkbox:

```<code><Checkbox
                text={t(TranslationConstants.Map.asapOrderInFilter)}
                property={t(TranslationConstants.Map.checkboxAsapProperty)}
                checked={globalStatus['asap']}
                fn={handleCheckbox.bind(this)}
              />
</code>```

Now, in Checkbox component I need to declare the correct type for fn():

```<code>import { useState, useEffect } from 'react';

type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (e: any) => void;
  property: string;
};

const CheckBox = (props: checkboxProps) => {
  const { text, checked, fn, property } = props;
  const [statusCheck, setStatusCheck] = useState(checked);

  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn({ [property]: _newState });
  };

  useEffect(() => {
    setStatusCheck(checked);
  }, [checked]);

  return (
    <div>
      {' '}
      <label>
        {' '}
        <input
          type="checkbox"
          checked={statusCheck}
          onChange={handleChange}
        />{' '}
        {text}
      </label>{' '}
    </div>
  );
};

export default CheckBox;

</code>```

I've tried HTMLInputElement, React.HTMLInputElement. Didn't work.

Here is a full code if you need more context: https://codesandbox.io/s/quizzical-gould-d4bry?file=/src/App.tsx

Along with it I also need to fix any types in OrderList.
All builds break if there is type any so it is crucial to declare correct types.

答:
I need to indicate the exact type of handleCheckbox() function (located in FilterBox component) that I'm passing down as props to child component Checkbox

I guess you rather mean that you need to improve the checkboxProps["fn"] definition (which is the prop that you pass handleCheckbox to), in order to avoid the usage of any:

```<code>type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (e: any) => void;
  // It throws warning here. Here is where I need to indicate type for e: and returning value (not sure if it's void)

  property: string;
};
</code>```

I've tried HTMLInputElement, React.HTMLInputElement

That could have been in the right track, should that fn prop function be called directly as an event listener of your <input>.

But you have a handleChange function in between, which calls your fn in a different way than a simple event listener:

```<code>        <input
          type="checkbox"
          checked={statusCheck}
          onChange={handleChange}
        />
</code>```
```<code>  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn({ [property]: _newState });
  };
</code>```

That handleChange function does not use your event argument, so there is really no need to look for such event type.

It calls your fn prop function with 1 argument { [property]: _newState }, which is of type Record<string, boolean>.

So you can define your fn prop as: fn: (newState: Record<string, boolean>) => void;

It might also be possible to further define the type, to indicate that it has a single member, defined by the property prop string, but that would involve generics in several places.

On the other hand, it seems to me that your checkboxProps type is more complex than it could be: you are passing down a property name, which is solely used to build an ad hoc object to be passed to your fn prop callback. In that case, it would be simpler to pass it directly the bare new checked value, and let the callback handle its object and property name, which is known by the parent component (FilterBox in your case). That way, you avoid having to pass down the property string, and break this strong coupling between FilterBox and Checkbox: now your Checkbox component can be used with other parent components, which may not use any object state.

```<code>type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (newIsChecked: boolean) => void;
};

// In Checkbox component
  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn(_newState);
  };

// In FilterBox component (or any other parent component)
<Checkbox
  text={t(TranslationConstants.Map.asapOrderInFilter)}
  checked={globalStatus['asap']}
  fn={(newIsChecked) => {
    handleCheckbox({
      asap: newIsChecked
    });
  }}
/>
</code>```

Then if you want to avoid having to manually build the callback when you use the <Checkbox> component many times with different property names, you could make a generating function, for example in the lines of:

```<code>function makeHandleCheckboxFnForProperty(propertyName: string) {
  return (newIsChecked: boolean) => {
    handleCheckbox({
      [propertyName]: newIsChecked
    });
  }
}
</code>```

and then in your template:

```<code><Checkbox
  text={t(TranslationConstants.Map.asapOrderInFilter)}
  checked={globalStatus['asap']}
  fn={makeHandleCheckboxFnForProperty('asap')}
/>
</code>```

Body:
I have created a custom Checkbox component.

TypeScript in the project does not accept any types, so I need to indicate the exact type of handleCheckbox() function (located in FilterBox component) that I am passing down as props to child component Checkbox.

const handleCheckbox = (state: Record<string, unknown>) => {
    const _preProcessNewState = { ...globalStatus, ...state };
    //Change the States
    setGlobalStatus(_preProcessNewState);
  };

Below we pass this function to Checkbox:

<Checkbox
                text={t(TranslationConstants.Map.asapOrderInFilter)}
                property={t(TranslationConstants.Map.checkboxAsapProperty)}
                checked={globalStatus['asap']}
                fn={handleCheckbox.bind(this)}
              />

Now, in Checkbox component I need to declare the correct type for fn():

import { useState, useEffect } from 'react';

type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (e: any) => void;
  property: string;
};

const CheckBox = (props: checkboxProps) => {
  const { text, checked, fn, property } = props;
  const [statusCheck, setStatusCheck] = useState(checked);

  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn({ [property]: _newState });
  };

  useEffect(() => {
    setStatusCheck(checked);
  }, [checked]);

  return (

      {' '}

        {' '}
        <input
          type="checkbox"
          checked={statusCheck}
          onChange={handleChange}
        />{' '}
        {text}
      {' '}

  );
};

export default CheckBox;

I've tried HTMLInputElement, React.HTMLInputElement. Didn't work.

Here is a full code if you need more context: https://codesandbox.io/s/quizzical-gould-d4bry?file=/src/App.tsx

Along with it I also need to fix any types in OrderList.
All builds break if there is type any so it is crucial to declare correct types.

Body:
I need to indicate the exact type of handleCheckbox() function (located in FilterBox component) that I'm passing down as props to child component Checkbox

I guess you rather mean that you need to improve the checkboxProps["fn"] definition (which is the prop that you pass handleCheckbox to), in order to avoid the usage of any:

type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (e: any) => void;
  // It throws warning here. Here is where I need to indicate type for e: and returning value (not sure if it's void)

  property: string;
};

I've tried HTMLInputElement, React.HTMLInputElement

That could have been in the right track, should that fn prop function be called directly as an event listener of your <input>.

But you have a handleChange function in between, which calls your fn in a different way than a simple event listener:

        <input
          type="checkbox"
          checked={statusCheck}
          onChange={handleChange}
        />

  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn({ [property]: _newState });
  };

That handleChange function does not use your event argument, so there is really no need to look for such event type.

It calls your fn prop function with 1 argument { [property]: _newState }, which is of type Record<string, boolean>.

So you can define your fn prop as: fn: (newState: Record<string, boolean>) => void;

It might also be possible to further define the type, to indicate that it has a single member, defined by the property prop string, but that would involve generics in several places.

On the other hand, it seems to me that your checkboxProps type is more complex than it could be: you are passing down a property name, which is solely used to build an ad hoc object to be passed to your fn prop callback. In that case, it would be simpler to pass it directly the bare new checked value, and let the callback handle its object and property name, which is known by the parent component (FilterBox in your case). That way, you avoid having to pass down the property string, and break this strong coupling between FilterBox and Checkbox: now your Checkbox component can be used with other parent components, which may not use any object state.

type checkboxProps = {
  text: string;
  checked: boolean;
  fn: (newIsChecked: boolean) => void;
};

// In Checkbox component
  const handleChange = () => {
    const _newState = !statusCheck;
    setStatusCheck(_newState);
    fn(_newState);
  };

// In FilterBox component (or any other parent component)
<Checkbox
  text={t(TranslationConstants.Map.asapOrderInFilter)}
  checked={globalStatus['asap']}
  fn={(newIsChecked) => {
    handleCheckbox({
      asap: newIsChecked
    });
  }}
/>

Then if you want to avoid having to manually build the callback when you use the <Checkbox> component many times with different property names, you could make a generating function, for example in the lines of:

function makeHandleCheckboxFnForProperty(propertyName: string) {
  return (newIsChecked: boolean) => {
    handleCheckbox({
      [propertyName]: newIsChecked
    });
  }
}

and then in your template:

<Checkbox
  text={t(TranslationConstants.Map.asapOrderInFilter)}
  checked={globalStatus['asap']}
  fn={makeHandleCheckboxFnForProperty('asap')}
/>


问:
RSelenium or Javascript: Expand all java expandable element on a website
I am working on a project right now that requires me to scrape information from this website:

https://www.domstol.no/enkelt-domstol/hoyesterett/saksliste/berammingsliste/

I have already managed to scrape the table with RSelenium and Rvest. But there are some details I would like to add to the dataframe, which can be found in an expandable java (?) object. I have illustrated the object here:

Tables

Essentially, I need to expand ALL of them before scraping in order to include them. Is there an easy way to do this with a code? Yesterday I had a script that clicked them all manually, which took hours to complete.

Is it possible to inject a code on the website that expands them all, or have RSelenium execute a code?

答:
The below script will allow you to scrape the web page and select the relevant dates and the court. Modify "Query" with the date range and the court you need.  I picked the first court in the list.  You can find the court codes by inspecting the page and searching for FormData.Court.</p>
```<code>    library(tidyverse)
    library(httr)
    library(rvest)

    #################################
    ## FUNCTION TO PROCESS DATA    ##
    #################################

    parseDetails <- function(pg_dtls){

      dt <- pg_dtls %>%
        html_elements('dt') %>%
        html_text()

      dd <- pg_dtls %>%
        html_elements('dd') %>%
        html_text()

      tbl <- pg_dtls %>%
        html_element('table') %>%
        html_table()

      df <- as.data.frame(dd, row.names = dt) %>% set_names("Details")

      rtnList <- list(mainData = df, otherData = tbl)
    }

    ###############################
    ##  SCRAPE WEB PAGE          ##
    ###############################

    url <- "https://www.domstol.no/enkelt-domstol/hoyesterett/saksliste/berammingsliste/"

    query <- list('FormData.From'="25.02.2022",
                  'FormData.To'="07.03.2022",
'FormData.Court'="AAAA2104220835148622091WAFLAU#EJBOrgUnit")
    response <- POST(url, body = query)
    dtls <- content(response, "parsed") %>%
      html_elements("button") %>%
      html_attr("data-action") %>%
      na.omit() %>%
      paste0("https://www.domstol.no/", .) %>%
      map(read_html)

    scrapedData <- map(dtls, parseDetails)
</code>```

Body:
The below script will allow you to scrape the web page and select the relevant dates and the court. Modify "Query" with the date range and the court you need.  I picked the first court in the list.  You can find the court codes by inspecting the page and searching for FormData.Court.

    library(tidyverse)
    library(httr)
    library(rvest)

    #################################
    ## FUNCTION TO PROCESS DATA    ##
    #################################

    parseDetails <- function(pg_dtls){

      dt <- pg_dtls %>%
        html_elements('dt') %>%
        html_text()

      dd <- pg_dtls %>%
        html_elements('dd') %>%
        html_text()

      tbl <- pg_dtls %>%
        html_element('table') %>%
        html_table()

      df <- as.data.frame(dd, row.names = dt) %>% set_names("Details")

      rtnList <- list(mainData = df, otherData = tbl)
    }

    ###############################
    ##  SCRAPE WEB PAGE          ##
    ###############################

    url <- "https://www.domstol.no/enkelt-domstol/hoyesterett/saksliste/berammingsliste/"

    query <- list('FormData.From'="25.02.2022",
                  'FormData.To'="07.03.2022",
'FormData.Court'="AAAA2104220835148622091WAFLAU#EJBOrgUnit")
    response <- POST(url, body = query)
    dtls <- content(response, "parsed") %>%
      html_elements("button") %>%
      html_attr("data-action") %>%
      na.omit() %>%
      paste0("https://www.domstol.no/", .) %>%
      map(read_html)

    scrapedData <- map(dtls, parseDetails)