问:
Flutter pusher works in Android but not in IOS
I use a package pusher_client: ^2.0.0 in Flutter it works without any problem with Android but when run my project on ios simulator I get error in the console.

when I run flutter run I get the following errors, I removed some repeated parts of the error due to content length.

```<code>
Xcode's output:
↳
    2 warnings generated.
    error: the following command failed with exit code 0 but produced no further output
    CompileC
    /Users/zia/Library/Developer/Xcode/DerivedData/Runner-hdzpmljlvwqzschdvjjsljzxqxtc/Build/Intermediates.noindex/
    Pods.build/Debug-iphonesimulator/location.build/Objects-normal/arm64/LocationPlugin.o
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/location-4.3.0/ios/Classes/LocationPlugin.m
    normal arm64 objective-c com.apple.compilers.llvm.clang.1_0.compiler (in target 'location' from project 'Pods')
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:24:22: warning: 'stringByAddingPercentEscapesUsingEncoding:' is deprecated:
    first deprecated in iOS 9.0 - Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always
    uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each
    URL component or subcomponent has different rules for what characters are valid. [-Wdeprecated-declarations]
        number = [number stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                         ^
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    In module 'Foundation' imported from
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSURL.h:599:1: note:
    'stringByAddingPercentEscapesUsingEncoding:' has been explicitly marked deprecated here
    - (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use
    -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding,
    and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has
    different rules for what characters are valid.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0),
    tvos(9.0,9.0));
    ^
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:30:51: warning: 'openURL:' is deprecated: first deprecated in iOS 10.0
    [-Wdeprecated-declarations]
        } else if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]]) {
                                                      ^~~~~~~
                                                      openURL:options:completionHandler:
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h:124:1: note: 'openURL:' has been
    explicitly marked deprecated here
    - (BOOL)openURL:(NSURL*)url API_DEPRECATED_WITH_REPLACEMENT("openURL:options:completionHandler:", ios(2.0,
    10.0)) NS_EXTENSION_UNAVAILABLE_IOS("");
    ^
    2 warnings generated.
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:24:22: warning: 'stringByAddingPercentEscapesUsingEncoding:' is deprecated:
    first deprecated in iOS 9.0 - Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always
    uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each
    URL component or subcomponent has different rules for what characters are valid. [-Wdeprecated-declarations]
        number = [number stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                         ^
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    In module 'Foundation' imported from
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSURL.h:599:1: note:
    'stringByAddingPercentEscapesUsingEncoding:' has been explicitly marked deprecated here
    - (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use
    -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding,
    and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has
    different rules for what characters are valid.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0),
    tvos(9.0,9.0));
    ^
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:30:51: warning: 'openURL:' is deprecated: first deprecated in iOS 10.0
    [-Wdeprecated-declarations]
        } else if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]]) {
                                                      ^~~~~~~
                                                      openURL:options:completionHandler:
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h:124:1: note: 'openURL:' has been
    explicitly marked deprecated here
    - (BOOL)openURL:(NSURL*)url API_DEPRECATED_WITH_REPLACEMENT("openURL:options:completionHandler:", ios(2.0,
    10.0)) NS_EXTENSION_UNAVAILABLE_IOS("");
    ^
    2 warnings generated.
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                               AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:282:30:
    warning: 'withUnsafeMutableBytes' is deprecated: use `withUnsafeMutableBytes<R>(_:
    (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead
                let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
                                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:59:25:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
                            ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:29:
    warning: initialization of 'UnsafeMutablePointer<UInt8>' results in a dangling pointer
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:140:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                     AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:119:35:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WSStreamDelegate: class {
                                      ^~~~~
                         ...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:282:30:
    warning: 'withUnsafeMutableBytes' is deprecated: use `withUnsafeMutableBytes<R>(_:
    (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead
                let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
                                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:59:25:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
                            ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:29:
    warning: initialization of 'UnsafeMutablePointer<UInt8>' results in a dangling pointer
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:57:
    note: implicit argument conversion from '[UInt8]' to 'UnsafeMutablePointer<UInt8>' produces a pointer valid
    only for the duration of the call to 'init(_:)'
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                                            ^~~~~~~
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:57:
    note: use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to
    buffer pointer valid for a defined scope
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                                            ^
...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:140:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                     AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:119:35:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WSStreamDelegate: class {
                                      ^~~~~
     ...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    ld: in
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Sodium/Sodium/libsodium/libsodium-ios.a(libsodium_la-ae
    ad_xchacha20poly1305.o), building for iOS Simulator, but linking in object file built for iOS, for architecture
    arm64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Using new build system
    note: Planning
    note: Build preparation complete
    note: Building targets in dependency order
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a
    placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from
    project 'Runner')
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment
    target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0
    to 15.2.99. (in target 'leveldb-library' from project 'Pods')

Could not build the application for the simulator.
Error launching application on iPhone 13.
</code>```

I could not find any related message in the above error
This is flutter --version

```<code>% flutter --version
Flutter 2.8.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 77d935af4d (7 weeks ago) • 2021-12-16 08:37:33 -0800
Engine • revision 890a5fca2e
Tools • Dart 2.15.1
</code>```

This is how I connect to pusher

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

class Messages extends StatefulWidget {
  final Room room;
  final int user;
  const Messages({Key? key, required this.room, required this.user})
      : super(key: key);

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

class _MessagesState extends State<Messages> {
  TextEditingController _messageController = TextEditingController();
  PusherClient? pusher;
  Channel? channel;
  List<Message> messages = [];

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

  @override
  void dispose() {
    channel?.unbind('chat-event');
    pusher?.unsubscribe('chat.' + widget.room.id.toString());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Message")),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FutureBuilder(
              future: _get(),
              builder: (context, snapshot) {
                if (snapshot.hasData ||
                    snapshot.connectionState == ConnectionState.done) {
                  return Expanded(
                    child: ListView.builder(
                      reverse: true,
                      padding: EdgeInsets.only(top: 12, left: 12, right: 12),
                      shrinkWrap: true,
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        return Column(
                          children: [
                            _buildMyMessage(messages[index]) != null
                                ? MyMessageCard(
                                    message: _buildMyMessage(messages[index]))
                                : Container(),
                            _buildFriendMessage(messages[index]) != null
                                ? FriendMessageCard(
                                    message:
                                        _buildFriendMessage(messages[index]))
                                : Container(),
                          ],
                        );
                      },
                    ),
                  );
                } else if (snapshot.hasError) {
                  return Padding(
                    child: Text("Error: ${snapshot.error}"),
                    padding: EdgeInsets.only(top: 8),
                  );
                } else {
                  return Center(
                      child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: circularProgress(context)));
                }
              },
            ),
            Container(
              padding: EdgeInsets.all(5),
              margin: EdgeInsets.all(5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: SizedBox(
                      height: 55,
                      child: Card(
                        elevation: 2,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.only(
                              left: 18.0, right: 18.0, top: 3),
                          child: TextFormField(
                            controller: _messageController,
                            decoration: InputDecoration(
                                border: InputBorder.none,
                                isDense: true,
                                hintText: 'Message'),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 55,
                    height: 55,
                    child: Card(
                      color: Tingsapp.primary,
                      elevation: 2,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: InkWell(
                          onTap: () => _send(context),
                          child: Icon(
                            Icons.send,
                            color: Colors.white,
                          )),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _send(context) async {
    Api api = new Api();
    try {
      var response = await api.post(
        jsonEncode(
          <String, dynamic>{
            'message': _messageController.text,
          },
        ),
        "chat/room/" + "${widget.room.id}" + "/message",
      );
      if (response.statusCode == 200) {
        _messageController.text = "";
        _get();
      }
    } catch (err) {
      showSnackbar(context, '${err.toString()}');
    }
  }

  Future _get() async {
    Api api = new Api();
    try {
      var response =
          await api.get("chat/room/" + "${widget.room.id}" + "/messages");
      if (response.statusCode == 200) {
        var jsonData = jsonDecode(response.body);
        var messageList =
            (jsonData as List).map((e) => Message.fromJson(e)).toList();
        messages = messageList;
        return messages;
      }
      return [];
    } catch (err) {
      showSnackbar(context, '${err.toString()}');
    }
  }
  Future<void> _initPusher() async {
    Store store = new Store();
    String token = await store.read('token');
    try {
      pusher = PusherClient(
        pusherKey,
        PusherOptions(
          host: broadcastPath,
          encrypted: false,
          auth: PusherAuth(
            broadcastPath + "/broadcasting/auth",
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer $token'
            },
          ),
          cluster: 'eu',
        ),
        enableLogging: true,
      );
      channel = pusher?.subscribe("private-chat." + widget.room.id.toString());

      pusher?.onConnectionStateChange((state) {
        print(
            "previousState: ${state?.previousState}, currentState: ${state?.currentState}");
      });

      pusher?.onConnectionError((error) {
        print("error: ${error?.message}");
      });

      channel?.bind('chat-event', (event) {
        setState(() {});
      });
    } catch (e) {
      print(e.toString());
    }
  }
}
</code>```

But the moment I comment out the above file and pusher_client: ^2.0.0 in pubspec.yaml and then run flutter run my application gets run on ios simulator.

Can anyone help please

this is a link to github with more details
https://github.com/chinloyal/pusher_client/issues/46

答:
First of all, update your ios/Podfile to contain the following line:

platform :ios, '13.0'

Add the following code to your post_install command within the Podfile:

```<code>target.build_configurations.each do |config|
         config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
     end
</code>```

For example, my post_install looks like this:

post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end

Go to your pubspec.yaml. And replace the pusher_client dependency with my fork:

pusher_client:
git:
url: git://github.com/thijskuilman/pusher_client.git

Go to your project root folder. Run flutter clean && flutter pub get && cd ios && pod install

Try to run the app on your iOS device or simulator

Body:
I use a package pusher_client: ^2.0.0 in Flutter it works without any problem with Android but when run my project on ios simulator I get error in the console.

when I run flutter run I get the following errors, I removed some repeated parts of the error due to content length.

Xcode's output:
↳
    2 warnings generated.
    error: the following command failed with exit code 0 but produced no further output
    CompileC
    /Users/zia/Library/Developer/Xcode/DerivedData/Runner-hdzpmljlvwqzschdvjjsljzxqxtc/Build/Intermediates.noindex/
    Pods.build/Debug-iphonesimulator/location.build/Objects-normal/arm64/LocationPlugin.o
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/location-4.3.0/ios/Classes/LocationPlugin.m
    normal arm64 objective-c com.apple.compilers.llvm.clang.1_0.compiler (in target 'location' from project 'Pods')
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:24:22: warning: 'stringByAddingPercentEscapesUsingEncoding:' is deprecated:
    first deprecated in iOS 9.0 - Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always
    uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each
    URL component or subcomponent has different rules for what characters are valid. [-Wdeprecated-declarations]
        number = [number stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                         ^
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    In module 'Foundation' imported from
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSURL.h:599:1: note:
    'stringByAddingPercentEscapesUsingEncoding:' has been explicitly marked deprecated here
    - (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use
    -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding,
    and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has
    different rules for what characters are valid.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0),
    tvos(9.0,9.0));
    ^
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:30:51: warning: 'openURL:' is deprecated: first deprecated in iOS 10.0
    [-Wdeprecated-declarations]
        } else if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]]) {
                                                      ^~~~~~~
                                                      openURL:options:completionHandler:
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h:124:1: note: 'openURL:' has been
    explicitly marked deprecated here
    - (BOOL)openURL:(NSURL*)url API_DEPRECATED_WITH_REPLACEMENT("openURL:options:completionHandler:", ios(2.0,
    10.0)) NS_EXTENSION_UNAVAILABLE_IOS("");
    ^
    2 warnings generated.
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:24:22: warning: 'stringByAddingPercentEscapesUsingEncoding:' is deprecated:
    first deprecated in iOS 9.0 - Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always
    uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each
    URL component or subcomponent has different rules for what characters are valid. [-Wdeprecated-declarations]
        number = [number stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                         ^
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    In module 'Foundation' imported from
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSURL.h:599:1: note:
    'stringByAddingPercentEscapesUsingEncoding:' has been explicitly marked deprecated here
    - (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use
    -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding,
    and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has
    different rules for what characters are valid.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0),
    tvos(9.0,9.0));
    ^
    /Users/zia/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_phone_direct_caller-2.1.0/ios/Classes/F
    lutterPhoneDirectCallerPlugin.m:30:51: warning: 'openURL:' is deprecated: first deprecated in iOS 10.0
    [-Wdeprecated-declarations]
        } else if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]]) {
                                                      ^~~~~~~
                                                      openURL:options:completionHandler:
    In module 'UIKit' imported from /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Target Support
    Files/flutter_phone_direct_caller/flutter_phone_direct_caller-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.
    2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h:124:1: note: 'openURL:' has been
    explicitly marked deprecated here
    - (BOOL)openURL:(NSURL*)url API_DEPRECATED_WITH_REPLACEMENT("openURL:options:completionHandler:", ios(2.0,
    10.0)) NS_EXTENSION_UNAVAILABLE_IOS("");
    ^
    2 warnings generated.
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                               AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:282:30:
    warning: 'withUnsafeMutableBytes' is deprecated: use `withUnsafeMutableBytes<R>(_:
    (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead
                let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
                                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:59:25:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
                            ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:29:
    warning: initialization of 'UnsafeMutablePointer<UInt8>' results in a dangling pointer
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:140:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                     AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:119:35:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WSStreamDelegate: class {
                                      ^~~~~
                         ...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:282:30:
    warning: 'withUnsafeMutableBytes' is deprecated: use `withUnsafeMutableBytes<R>(_:
    (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead
                let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
                                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:59:25:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
                            ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:29:
    warning: initialization of 'UnsafeMutablePointer<UInt8>' results in a dangling pointer
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:57:
    note: implicit argument conversion from '[UInt8]' to 'UnsafeMutablePointer<UInt8>' produces a pointer valid
    only for the duration of the call to 'init(_:)'
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                                            ^~~~~~~
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:83:57:
    note: use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to
    buffer pointer valid for a defined scope
                strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
                                                            ^
...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/Compression.swift:140:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:61:34:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WebSocketClient: class {
                                     ^~~~~
                                     AnyObject
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:119:35:
    warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    public protocol WSStreamDelegate: class {
                                      ^~~~~
     ...
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1326:14:
    warning: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R)
    rethrows -> R` instead
            data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
                 ^
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Starscream/Sources/Starscream/WebSocket.swift:1327:16:
    warning: 'init(bytes:)' is deprecated: use `init(_:)` instead
            return Data(bytes: digest).base64EncodedString()
                   ^
    ld: in
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Sodium/Sodium/libsodium/libsodium-ios.a(libsodium_la-ae
    ad_xchacha20poly1305.o), building for iOS Simulator, but linking in object file built for iOS, for architecture
    arm64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Using new build system
    note: Planning
    note: Build preparation complete
    note: Building targets in dependency order
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a
    placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from
    project 'Runner')
    /Users/zia/Desktop/projects/com_tingsapp_mover/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment
    target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0
    to 15.2.99. (in target 'leveldb-library' from project 'Pods')

Could not build the application for the simulator.
Error launching application on iPhone 13.

I could not find any related message in the above error
This is flutter --version

% flutter --version
Flutter 2.8.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 77d935af4d (7 weeks ago) • 2021-12-16 08:37:33 -0800
Engine • revision 890a5fca2e
Tools • Dart 2.15.1

This is how I connect to pusher

import 'package:pusher_client/pusher_client.dart';
...
...

class Messages extends StatefulWidget {
  final Room room;
  final int user;
  const Messages({Key? key, required this.room, required this.user})
      : super(key: key);

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

class _MessagesState extends State<Messages> {
  TextEditingController _messageController = TextEditingController();
  PusherClient? pusher;
  Channel? channel;
  List<Message> messages = [];

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

  @override
  void dispose() {
    channel?.unbind('chat-event');
    pusher?.unsubscribe('chat.' + widget.room.id.toString());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Message")),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FutureBuilder(
              future: _get(),
              builder: (context, snapshot) {
                if (snapshot.hasData ||
                    snapshot.connectionState == ConnectionState.done) {
                  return Expanded(
                    child: ListView.builder(
                      reverse: true,
                      padding: EdgeInsets.only(top: 12, left: 12, right: 12),
                      shrinkWrap: true,
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        return Column(
                          children: [
                            _buildMyMessage(messages[index]) != null
                                ? MyMessageCard(
                                    message: _buildMyMessage(messages[index]))
                                : Container(),
                            _buildFriendMessage(messages[index]) != null
                                ? FriendMessageCard(
                                    message:
                                        _buildFriendMessage(messages[index]))
                                : Container(),
                          ],
                        );
                      },
                    ),
                  );
                } else if (snapshot.hasError) {
                  return Padding(
                    child: Text("Error: ${snapshot.error}"),
                    padding: EdgeInsets.only(top: 8),
                  );
                } else {
                  return Center(
                      child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: circularProgress(context)));
                }
              },
            ),
            Container(
              padding: EdgeInsets.all(5),
              margin: EdgeInsets.all(5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: SizedBox(
                      height: 55,
                      child: Card(
                        elevation: 2,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.only(
                              left: 18.0, right: 18.0, top: 3),
                          child: TextFormField(
                            controller: _messageController,
                            decoration: InputDecoration(
                                border: InputBorder.none,
                                isDense: true,
                                hintText: 'Message'),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 55,
                    height: 55,
                    child: Card(
                      color: Tingsapp.primary,
                      elevation: 2,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: InkWell(
                          onTap: () => _send(context),
                          child: Icon(
                            Icons.send,
                            color: Colors.white,
                          )),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _send(context) async {
    Api api = new Api();
    try {
      var response = await api.post(
        jsonEncode(
          <String, dynamic>{
            'message': _messageController.text,
          },
        ),
        "chat/room/" + "${widget.room.id}" + "/message",
      );
      if (response.statusCode == 200) {
        _messageController.text = "";
        _get();
      }
    } catch (err) {
      showSnackbar(context, '${err.toString()}');
    }
  }

  Future _get() async {
    Api api = new Api();
    try {
      var response =
          await api.get("chat/room/" + "${widget.room.id}" + "/messages");
      if (response.statusCode == 200) {
        var jsonData = jsonDecode(response.body);
        var messageList =
            (jsonData as List).map((e) => Message.fromJson(e)).toList();
        messages = messageList;
        return messages;
      }
      return [];
    } catch (err) {
      showSnackbar(context, '${err.toString()}');
    }
  }
  Future<void> _initPusher() async {
    Store store = new Store();
    String token = await store.read('token');
    try {
      pusher = PusherClient(
        pusherKey,
        PusherOptions(
          host: broadcastPath,
          encrypted: false,
          auth: PusherAuth(
            broadcastPath + "/broadcasting/auth",
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer $token'
            },
          ),
          cluster: 'eu',
        ),
        enableLogging: true,
      );
      channel = pusher?.subscribe("private-chat." + widget.room.id.toString());

      pusher?.onConnectionStateChange((state) {
        print(
            "previousState: ${state?.previousState}, currentState: ${state?.currentState}");
      });

      pusher?.onConnectionError((error) {
        print("error: ${error?.message}");
      });

      channel?.bind('chat-event', (event) {
        setState(() {});
      });
    } catch (e) {
      print(e.toString());
    }
  }
}

But the moment I comment out the above file and pusher_client: ^2.0.0 in pubspec.yaml and then run flutter run my application gets run on ios simulator.

Can anyone help please

this is a link to github with more details
https://github.com/chinloyal/pusher_client/issues/46

Body:
First of all, update your ios/Podfile to contain the following line:

platform :ios, '13.0'

Add the following code to your post_install command within the Podfile:

target.build_configurations.each do |config|
         config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
     end

For example, my post_install looks like this:

post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end

Go to your pubspec.yaml. And replace the pusher_client dependency with my fork:

pusher_client:
git:
url: git://github.com/thijskuilman/pusher_client.git

Go to your project root folder. Run flutter clean && flutter pub get && cd ios && pod install

Try to run the app on your iOS device or simulator


来源: stackexchange

答:
You could define every column you want to keep on your aggregation function:

df.groupby(["Count"]).agg({k: ['sum', 'mean'] for k in df.columns}).reset_index()
```
<p>This here code calculates the sum and average for every column per group, hence this will work only with a dataframe that has only numeric columns.<br />
Here is a version that will work for streches of groups:</p>
<pre class="lang-py prettyprint-override"><code># firstly, create a helper column called "groups" (this col will signify
# when a value is changed in the Count column):
df['groups'] = None
group = 0
for i, j in df.iterrows():
    if i == 0:
        df.loc[i, 'groups'] = group
        valueBefore = df.loc[i, 'Count']
        continue
    if j.loc['Count'] != valueBefore:
        group += 1
    df.loc[i, 'groups'] = group
    valueBefore = df.loc[i, 'Count']
# then you can use it to groupby all other columns, i.e.:
df.groupby(["groups"]).agg({k: ['sum', 'mean'] for k in df.columns}).reset_index()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Group by based on repeating column values of panda df to sum/average other columns

Body:
I have a df looking like this:

    Activity    Count   angle_1frame_abs
87  11.2454 4   1.9863239600400613
88  14.3124 4   1.633204419481332
89  7.15621 4   1.7235925045363631
90  1.02232 4   1.4205234792290875
172 6.13389 1   1.9096280055821166
187 1.02232 3   1.7052938965382456
188 7.15621 3   1.708833899378485
189 2.04463 3   1.2728507985832682
233 4.08926 1   1.554572584797844
265 4.08926 2   1.512615236089327
266 5.11157 2   1.4850900583919704
281 6.13389 1   1.162132169753371
305 3.06694 2   2.3605660470439824
306 3.06694 2   1.5685525010916657
385 5.11157 2   1.6579646804948973
386 2.04463 2   2.121520877298791
407 5.11157 4   1.1528498264361269
408 12.2678 4   1.7986876725933032
409 9.20082 4   1.5502484587771188
410 2.04463 4   1.6302871732665316

The column "Count" has stretches of repeating values that I would like to use to group the df.

In the above example I would have 8 groups.

I struggle keeping repeating values as separate groups.

My final aim would be to either average (Activity) or sum (angle_1frame_abs) the other columns based on these groups.

My desired output would be something like this (note: the activity and angle_1frames_abs values are made up):

Activity Count angle_1_frames_abs
9   4   1.7
6   1   1.9
4   3   1.7
4   1   1.5
4   2   1.4
6   1   1.1
4   2   1.5
8   4   1.5

I have been trying something like this but this only gave me groups based on unique values in the "count" column.

df.groupby(["Count"]).angle_1frame_abs.sum().reset_index()

Body:
You could define every column you want to keep on your aggregation function:

df.groupby(["Count"]).agg({k: ['sum', 'mean'] for k in df.columns}).reset_index()

This here code calculates the sum and average for every column per group, hence this will work only with a dataframe that has only numeric columns.

Here is a version that will work for streches of groups:

# firstly, create a helper column called "groups" (this col will signify
# when a value is changed in the Count column):
df['groups'] = None
group = 0
for i, j in df.iterrows():
    if i == 0:
        df.loc[i, 'groups'] = group
        valueBefore = df.loc[i, 'Count']
        continue
    if j.loc['Count'] != valueBefore:
        group += 1
    df.loc[i, 'groups'] = group
    valueBefore = df.loc[i, 'Count']
# then you can use it to groupby all other columns, i.e.:
df.groupby(["groups"]).agg({k: ['sum', 'mean'] for k in df.columns}).reset_index()


问:
Next.js 12 breaks when used with theme-ui giving "code: 'ERR_REQUIRE_ESM'"
I'm using Next.js 12 and this error pops up after I created a theme using theme-ui

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\index.js
require() of ES modules is not supported.
require() of E:\fm-nextjs\node_modules\@mdx-js\react\index.js from E:\fm-nextjs\node_modules\@theme-ui\mdx\dist\theme-ui-mdx.cjs.dev.js
is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\fm-nextjs\node_modules\@mdx-js\react\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (E:\fm-nextjs\node_modules\@theme-ui\mdx\dist\theme-ui-mdx.cjs.dev.js:9:15)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
  code: 'ERR_REQUIRE_ESM'
}
```
<p>my package.json has following dependencies</p>
<pre class="lang-json prettyprint-override"><code>  "dependencies": {
    "@emotion/react": "^11.7.1",
    "@emotion/styled": "^11.6.0",
    "@mdx-js/react": "^2.0.0",
    "@theme-ui/presets": "^0.13.1",
    "next": "^12.0.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "theme-ui": "^0.13.1"
  }
</code>```

I tried removing "type": "module" from E:\fm-nextjs\node_modules\@mdx-js\react\package.json but it still gave errors.

How do I actually fix this. Seems like I have to manually change a bunch of files. Would be great if there is a workaround.

答:
Downgrade @mdx-js/react to 1.6.22

Usually in these kind of scenarios, it's good to start downgrading the latest installed packages (especially since @mdx-js seems to have had a major version increase)

Body:
I'm using Next.js 12 and this error pops up after I created a theme using theme-ui

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\index.js
require() of ES modules is not supported.
require() of E:\fm-nextjs\node_modules\@mdx-js\react\index.js from E:\fm-nextjs\node_modules\@theme-ui\mdx\dist\theme-ui-mdx.cjs.dev.js
is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\fm-nextjs\node_modules\@mdx-js\react\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (E:\fm-nextjs\node_modules\@theme-ui\mdx\dist\theme-ui-mdx.cjs.dev.js:9:15)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
  code: 'ERR_REQUIRE_ESM'
}

my package.json has following dependencies

  "dependencies": {
    "@emotion/react": "^11.7.1",
    "@emotion/styled": "^11.6.0",
    "@mdx-js/react": "^2.0.0",
    "@theme-ui/presets": "^0.13.1",
    "next": "^12.0.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "theme-ui": "^0.13.1"
  }

I tried removing "type": "module" from E:\fm-nextjs\node_modules\@mdx-js\react\package.json but it still gave errors.

How do I actually fix this. Seems like I have to manually change a bunch of files. Would be great if there is a workaround.


问:
Why would tee fail to write to stdout?
I typically use tee to receive a piped output data, echo it to standard output, and forward it to the actual intended recipient of the piped data. But sometimes this fails, and I cannot exactly understand why.

I'll try to demonstrate with a series of examples:

$ echo testing with this string | tee
testing with this string
```
<p>So, just echoing some data to <code>tee</code> without arguments, is replicated/printed on the terminal/stdout. Note that this should be <code>tee</code> printing the output, as the output from echo is now "piped"/redirected, and therefore not present in stdout anymore (the same that happens here:</p>
<pre class="lang-none prettyprint-override"><code>$ echo aa | echo bb
bb
</code>```

... i.e. echo aa output got redirected to the next command, - which, being echo b, does not care about the input, and outputs just its own output.)

$ echo testing with this string | tee | python3 -c 'a=1'
$
```
<p>Now here, piping data into <code>tee</code> without arguments, - and then piping, from <code>tee</code>, to a program that does not provide any output to terminal/stdout - prints <em>nothing</em>. I would have expected <code>tee</code> here to duplicate to stdout, and then forward to the next command in the pipeline, but apparently that does not happen.</p>
<hr />
<pre class="lang-none prettyprint-override"><code>$ echo testing with this string | tee /dev/stdout
testing with this string
testing with this string
</code>```

Right, so if we pipe to tee with command line argument /dev/stdout, we get the printout twice - and as concluded earlier, it must be tee that produces both printed lines. That means, that when used without an argument, |tee basically does not open any file for duplicating, and simply forwards what it receives on its input, to its output; but as it is the last in the pipeline, its output is stdout in that case, so we get a single printout.

Here we get double printout, because

tee duplicated its input stream to /dev/stdout due to the argument (which ends up as the first printout); and then

forwarded the same input to its output, which here being stdout (as tee is again last in the pipeline), results with the second printout.

This also would explain why the previous ...| tee | python3 -c 'a=1' did not print anything: tee without arguments did not open any file for duplication, and merely forwarded to next command in the toolchain - and as the next one does not print any output either, no output is generated whatsoever.

Well, if the above understanding is correct, then this:

$ echo testing with this string | tee /dev/stdout | python3 -c 'a=1'
$
```

... should print at least one line (from tee copying to /dev/stdout; the "forwarded" part will end up being "gulped" by the final command as it prints nothing), but it does not.

So, why does this happen - where am I going wrong in my understanding of what tee does?

And how can I use tee, to print to stdout, also when its output is forwarded to a command that doesn't print anything to stdout on its own?

答:
I think I got it, but am not sure if it is correct: I saw this: 19.8. Forgetting That Pipelines Make Subshells - bash Cookbook [Book].

So, if pipelines make subshells, then

```<code>echo testing with this string | tee /dev/stdout | python3 -c 'a=1'
</code>```

... is conceptually equal to:

```<code>echo testing with this string | (tee /dev/stdout | (python3 -c 'a=1'))
</code>```

Note that the second pipe | redirects stdout of the subshell tee runs in, and as /dev/stdout is just an interface to stdout, it is redirected too, so we get nothing printed.

So, while stdout (and /dev/stdout) is local to the (sub)shell, /dev/tty is local to the terminal - and therefore the following:

```<code>$ echo testing with this string | tee /dev/tty | python3 -c 'a=1'
testing with this string
</code>```

... in fact prints a line, as expected.

Title: Why would tee fail to write to stdout?

Body:
I typically use tee to receive a piped output data, echo it to standard output, and forward it to the actual intended recipient of the piped data. But sometimes this fails, and I cannot exactly understand why.

I'll try to demonstrate with a series of examples:

$ echo testing with this string | tee
testing with this string

So, just echoing some data to tee without arguments, is replicated/printed on the terminal/stdout. Note that this should be tee printing the output, as the output from echo is now "piped"/redirected, and therefore not present in stdout anymore (the same that happens here:

$ echo aa | echo bb
bb

... i.e. echo aa output got redirected to the next command, - which, being echo b, does not care about the input, and outputs just its own output.)

$ echo testing with this string | tee | python3 -c 'a=1'
$

Now here, piping data into tee without arguments, - and then piping, from tee, to a program that does not provide any output to terminal/stdout - prints nothing. I would have expected tee here to duplicate to stdout, and then forward to the next command in the pipeline, but apparently that does not happen.

$ echo testing with this string | tee /dev/stdout
testing with this string
testing with this string

Right, so if we pipe to tee with command line argument /dev/stdout, we get the printout twice - and as concluded earlier, it must be tee that produces both printed lines. That means, that when used without an argument, |tee basically does not open any file for duplicating, and simply forwards what it receives on its input, to its output; but as it is the last in the pipeline, its output is stdout in that case, so we get a single printout.

Here we get double printout, because

tee duplicated its input stream to /dev/stdout due to the argument (which ends up as the first printout); and then

forwarded the same input to its output, which here being stdout (as tee is again last in the pipeline), results with the second printout.

This also would explain why the previous ...| tee | python3 -c 'a=1' did not print anything: tee without arguments did not open any file for duplication, and merely forwarded to next command in the toolchain - and as the next one does not print any output either, no output is generated whatsoever.

Well, if the above understanding is correct, then this:

$ echo testing with this string | tee /dev/stdout | python3 -c 'a=1'
$

... should print at least one line (from tee copying to /dev/stdout; the "forwarded" part will end up being "gulped" by the final command as it prints nothing), but it does not.

So, why does this happen - where am I going wrong in my understanding of what tee does?

And how can I use tee, to print to stdout, also when its output is forwarded to a command that doesn't print anything to stdout on its own?

Body:
I think I got it, but am not sure if it is correct: I saw this: 19.8. Forgetting That Pipelines Make Subshells - bash Cookbook [Book].

So, if pipelines make subshells, then

echo testing with this string | tee /dev/stdout | python3 -c 'a=1'

... is conceptually equal to:

echo testing with this string | (tee /dev/stdout | (python3 -c 'a=1'))

Note that the second pipe | redirects stdout of the subshell tee runs in, and as /dev/stdout is just an interface to stdout, it is redirected too, so we get nothing printed.

So, while stdout (and /dev/stdout) is local to the (sub)shell, /dev/tty is local to the terminal - and therefore the following:

$ echo testing with this string | tee /dev/tty | python3 -c 'a=1'
testing with this string

... in fact prints a line, as expected.


问:
Impossible to rename a machine and join it to the active directory : No mapping between account names and security IDs was done
I'm trying to rename a machine and join it to the Active Directory. Each time,, I'm facing the same error : No mapping between account names and security IDs was done

I've tried many scripts without success:

```<code>Rename-Computer -NewName $ComputerName -Force -PassThru -Verbose
Start-Sleep -s 5
Add-Computer -NewName $ComputerName -DomainName $DomainName -Option JoinWithNewName -Credential $credential -OUPath $OUPath -Force  -Passthru -Verbose

Rename-Computer -NewName $ComputerName -Force -PassThru -Verbose
Start-Sleep -s 5
Add-Computer -DomainName $DomainName -Option JoinWithNewName -Credential $credential -OUPath $OUPath -Force  -Passthru -Verbose
</code>```

Any insight?

Thanks.

答:
I am not sure if this is will work for you but this is also possible.

```<code>Add-Computer -ComputerName (Get-Content Servers.txt) -DomainName Domain02 -Credential Domain02\Admin02 -Options Win9xUpgrade  -Restart
</code>```

This command moves the Server01 computer to the Domain02 and changes the machine name to Server044.

The command uses the credential of the current user to connect to the Server01 computer and unjoin it from its current domain. It uses the Credential parameter to specify a user account that has permission to join the computer to the Domain02 domain.

You can refer this documentation from Microsoft

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-computer?view=powershell-5.1

Body:
I'm trying to rename a machine and join it to the Active Directory. Each time,, I'm facing the same error : No mapping between account names and security IDs was done

I've tried many scripts without success:

Rename-Computer -NewName $ComputerName -Force -PassThru -Verbose
Start-Sleep -s 5
Add-Computer -NewName $ComputerName -DomainName $DomainName -Option JoinWithNewName -Credential $credential -OUPath $OUPath -Force  -Passthru -Verbose

Rename-Computer -NewName $ComputerName -Force -PassThru -Verbose
Start-Sleep -s 5
Add-Computer -DomainName $DomainName -Option JoinWithNewName -Credential $credential -OUPath $OUPath -Force  -Passthru -Verbose

Any insight?

Thanks.

Body:
I am not sure if this is will work for you but this is also possible.

Add-Computer -ComputerName (Get-Content Servers.txt) -DomainName Domain02 -Credential Domain02\Admin02 -Options Win9xUpgrade  -Restart

This command moves the Server01 computer to the Domain02 and changes the machine name to Server044.

The command uses the credential of the current user to connect to the Server01 computer and unjoin it from its current domain. It uses the Credential parameter to specify a user account that has permission to join the computer to the Domain02 domain.

You can refer this documentation from Microsoft

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-computer?view=powershell-5.1


问:
unit testing legacy code: limits of "extract and override" vs JustMock/TypeMock/moles?
Given the following conditions:

a very old, big, C# legacy code base with no testcoverage whatsoever

(almost) every class derives from some interface

nothing is sealed

What are the practical benefits of using profiler-API-driven solutions like JustMock and TypeMock, compared to using extract&override + e.g. RhinoMocks? Are there cases I'm not aware of, besides circumventing private/protected, where using TypeMock/JustMock etc. is really needed? I'd especially welcome some experience from people having switched to one of the products.

Using extract&override seems to solve all problems when handling old legacy code, the refactoring seems dead simple, and the possibility for introducing bugs seems very minor. Is the benefit writing less test code? More beautifull classes with less virtual protected stuff? Right now, I don't 'get it', although I understand it's very helpfull to first test private methods in isolation, as public methods may be too large under the hood in such old legacy codebases.

If you don't know what extract&override is: see here.

答:
There are many differences between the frameworks which do not regard the technology on which the frameworks built on.

For example:

API - every framework has different notations and defaults (e.g.
strict defaults vs. relaxed defaults)

Support - the propriety frameworks usually offer support with the licenses

Price - this is not a matter of usage but requires budget

The main advantage of Extract&Override is that it requires some refactoring, if the code you're working on is neglected, it's gives a good chance to go over it and refactor it toward better code and not just for testability.

The main advantage of using an Isolation framework is that you do not need to change the code under test (if it's a large codebase it could take long time just to refactor it for testability). In addition, the Isolation frameworks do not force you into specific design, this could be helpful if the legacy code matches better its existing design. Another feature which is useful in legacy code is swapping instances created in the code under test, usually refactoring instantiations takes more effort and this can be saved. Last thing is faking 3rd party code - using isolation frameworks you can isolate code which is not yours without using wrapper classes.

Disclaimer - I work at Typemock

ContentLicense: CC BY-SA 3.0


问:
Jupyter doesn't load environment kernel
I'm trying to load kernel from conda environment and get following error when trying to do this:

```<code>`[I 22:10:35.989 NotebookApp] KernelRestarter: restarting kernel (5/5), new random ports
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\connect.py", line 18, in <module>
    import jupyter_client
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\__init__.py", line 4, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\connect.py", line 21, in <module>
    import zmq
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\__init__.py", line 50, in <module>
    from zmq import backend
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 40, in <module>
    reraise(*exc_info)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 27, in <module>
    _ns = select_backend(first)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\select.py", line 28, in select_backend
    mod = __import__(name, fromlist=public_api)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\cython\__init__.py", line 6, in <module>
    from . import (constants, error, message, context,
ImportError: DLL load failed: Не найден указанный модуль.
[W 22:10:39.032 NotebookApp] KernelRestarter: restart failed
[W 22:10:39.032 NotebookApp] Kernel 7695680a-c4cf-4408-a228-a36587c6acee died, removing from map.
[W 22:11:20.915 NotebookApp] Timeout waiting for kernel_info reply from 7695680a-c4cf-4408-a228-a36587c6acee
[E 22:11:20.917 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee)
[W 22:11:21.949 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1): Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee
[W 22:11:21.963 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1) 16.000000ms referer=None
[W 22:11:23.987 NotebookApp] Replacing stale connection: 7695680a-c4cf-4408-a228-a36587c6acee:a461c65a632c4842918b17939d5595f1`
</code>```

The error is ImportError: DLL load failed: The specific module was not found.
I've tried to reinstall environment and jupyter and also tried to reinstall pyzmq with pip uninstall pyzmq and pip install pyzmq. I get no problem with running my default kernel.

答: Solution was to run jupyter-notebook whithin activated conda environment, after that kernel selected and loaded correctly.</p>

Title: Jupyter doesn't load environment kernel

Body:
I'm trying to load kernel from conda environment and get following error when trying to do this:

`[I 22:10:35.989 NotebookApp] KernelRestarter: restarting kernel (5/5), new random ports
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\connect.py", line 18, in <module>
    import jupyter_client
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\__init__.py", line 4, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\connect.py", line 21, in <module>
    import zmq
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\__init__.py", line 50, in <module>
    from zmq import backend
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 40, in <module>
    reraise(*exc_info)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 27, in <module>
    _ns = select_backend(first)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\select.py", line 28, in select_backend
    mod = __import__(name, fromlist=public_api)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\cython\__init__.py", line 6, in <module>
    from . import (constants, error, message, context,
ImportError: DLL load failed: Не найден указанный модуль.
[W 22:10:39.032 NotebookApp] KernelRestarter: restart failed
[W 22:10:39.032 NotebookApp] Kernel 7695680a-c4cf-4408-a228-a36587c6acee died, removing from map.
[W 22:11:20.915 NotebookApp] Timeout waiting for kernel_info reply from 7695680a-c4cf-4408-a228-a36587c6acee
[E 22:11:20.917 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee)
[W 22:11:21.949 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1): Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee
[W 22:11:21.963 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1) 16.000000ms referer=None
[W 22:11:23.987 NotebookApp] Replacing stale connection: 7695680a-c4cf-4408-a228-a36587c6acee:a461c65a632c4842918b17939d5595f1`

The error is ImportError: DLL load failed: The specific module was not found.
I've tried to reinstall environment and jupyter and also tried to reinstall pyzmq with pip uninstall pyzmq and pip install pyzmq. I get no problem with running my default kernel.


问:
ImportError: No module named 'Tkinter'
For some reason, I can't use the Tkinter (or tkinter, on Python 3) module.
After running the following command in the python shell:

```<code>import Tkinter
</code>```

or this, in Python 3:

```<code>import tkinter
</code>```

I got this error

ModuleNotFoundError: No module named 'Tkinter'

or this:

ModuleNotFoundError: No module named 'tkinter'

What could be the reason for these errors and how can I solve it?

答:
If you have pip on your path, you could (in your command prompt) just type
pip install tkinter
Most versions of python already come with tkinter.

Title: ImportError: No module named 'Tkinter'

Body:
For some reason, I can't use the Tkinter (or tkinter, on Python 3) module.
After running the following command in the python shell:

import Tkinter

or this, in Python 3:

import tkinter

I got this error

ModuleNotFoundError: No module named 'Tkinter'

or this:

ModuleNotFoundError: No module named 'tkinter'

What could be the reason for these errors and how can I solve it?


问:
Warning: you are leaving 1 commit behind, not connected to any of your branches
EGit strikes again. I made the mistake of trying to switch to a different branch in EGit and it somehow messed up and checked out no branch. I then made a commit to this non-branch, and then when I realized I wasn't tracking the right branch, I ran the following:

```<code>$ git checkout issue2
Warning: you are leaving 1 commit behind, not connected to any of your branches:

    bada553d My commit message

If you want to keep them by creating a new branch, this may be a good time to do so with:

    git branch new_branch_name ....

Branch issue2 set up to track remote branch issue2 from origin.
Switched to a new branch issue2.
</code>```

Now that I've botched things, how do I associate that commit with my current branch? I'm not interested in creating a brand new branch, I just want to pull that commit into my branch, issue2.

答:
If you just want to associate that commit with your current branch, you can simply do this

Run this command to create a new branch with that commit

git branch temp {commit's SHA}

Then simply merge this commit with your current branch

git merge temp

Now just delete the temporary new branch we created

git branch -d temp

Body:
EGit strikes again. I made the mistake of trying to switch to a different branch in EGit and it somehow messed up and checked out no branch. I then made a commit to this non-branch, and then when I realized I wasn't tracking the right branch, I ran the following:

$ git checkout issue2
Warning: you are leaving 1 commit behind, not connected to any of your branches:

    bada553d My commit message

If you want to keep them by creating a new branch, this may be a good time to do so with:

    git branch new_branch_name ....

Branch issue2 set up to track remote branch issue2 from origin.
Switched to a new branch issue2.

Now that I've botched things, how do I associate that commit with my current branch? I'm not interested in creating a brand new branch, I just want to pull that commit into my branch, issue2.


问:
Should a internal C# app be compiled with business logic?
[background]

So, I've got a C# application that was written before I got here.  I'm not in the dev org, at this time, but I am the tech lead in my sub-group within the internet marketing org.  My responsibility is process automation, minimal desktop support, and custom apps that make our lives easier.

[/background]

[app details]

We've got an app that creates a custom database file from a list of URLs.  It was designed to have one input file, and two output files for the two applications that use these sort of db files.  The rule for the difference between the two output files is compiled into the code.

[/app details]

Should an internal C# app be compiled with business logic that can't be changed without it being re-built?

答:
How long does it take to alter business logic and then recompile?

How long will it take to alter business logic without recompiling in new version?

How long will it take to recode it?

How will this affect maintainence in terms of extra hours spent in the future?

Are any of the people who need the app unable to alter the business logic because it is in code form?

Answering those 5 questions will yield an answer.

OwnerDisplayName: Sean Ochoa

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brian


问:
How to find longest words in all files using ForkJoin
Using the resources of the Fork-Join framework, create an asynchronous multithreaded system to form a collection of words of maximum length from three text files.

How to find the longest words in all files?

In my case, I'm looking for each file separately, but I don't understand how to do it together, and I need to use ForkJoin framework.

```<code>import java.io.File;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class loop {
    public static void main(String[] args) {

        File[] files = {
                new File("text"),
                new File("text2"),
                new File("text3")
        };

        MaxLengthWord sumOfDigits = new MaxLengthWord(files);

        ForkJoinPool pool = new ForkJoinPool();

        final List<String> maxWords = pool.invoke(sumOfDigits);
        System.out.println(maxWords);

    }
}

class MaxLengthWord extends RecursiveTask<List<String>> {
    File[] files;

    public MaxLengthWord(File[] files) {
        this.files = files;
    }

    @Override
    protected List<String> compute() {
        if (files.length > 1) {
            return ForkJoinTask.invokeAll(createSubtasks())
                    .stream()
                    .flatMap(maxLengthWord -> maxLengthWord.join().stream())
                    .collect(Collectors.toList());
        } else {
            return processing(files);
        }
    }

    private Collection<MaxLengthWord> createSubtasks() {
        List<MaxLengthWord> subTasks = new ArrayList<>();
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, 0, files.length / 2)));
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, files.length / 2, files.length)));
        return subTasks;
    }

    private List<String> processing(File[] files) {
        List<String> result = new ArrayList<>();
        String longest_word = "";
        try (Scanner sc = new Scanner(files[0])) {
            while (sc.hasNext()) {
                String word = sc.next();

                if (word.length() > longest_word.length()) {
                    longest_word = word;
                    result.clear();
                    result.add(longest_word);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result + " " + Thread.currentThread() + " " + files[0]);
        return result;
    }
}
</code>```

答:
If you have 3 files that have big difference in sizes this could be not ideal approach.
For example, if you have file A with 1 word, file B with 1 word and file C with 10,000,000 words , the sub tasks are unbalanced.

You can try different approach, and create sub task for each line in each file returning the max length word in each line.
Then aggregate the results to find the longest words overall.

Body:
Using the resources of the Fork-Join framework, create an asynchronous multithreaded system to form a collection of words of maximum length from three text files.

How to find the longest words in all files?

In my case, I'm looking for each file separately, but I don't understand how to do it together, and I need to use ForkJoin framework.

import java.io.File;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class loop {
    public static void main(String[] args) {

        File[] files = {
                new File("text"),
                new File("text2"),
                new File("text3")
        };

        MaxLengthWord sumOfDigits = new MaxLengthWord(files);

        ForkJoinPool pool = new ForkJoinPool();

        final List<String> maxWords = pool.invoke(sumOfDigits);
        System.out.println(maxWords);

    }
}

class MaxLengthWord extends RecursiveTask<List<String>> {
    File[] files;

    public MaxLengthWord(File[] files) {
        this.files = files;
    }

    @Override
    protected List<String> compute() {
        if (files.length > 1) {
            return ForkJoinTask.invokeAll(createSubtasks())
                    .stream()
                    .flatMap(maxLengthWord -> maxLengthWord.join().stream())
                    .collect(Collectors.toList());
        } else {
            return processing(files);
        }
    }

    private Collection<MaxLengthWord> createSubtasks() {
        List<MaxLengthWord> subTasks = new ArrayList<>();
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, 0, files.length / 2)));
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, files.length / 2, files.length)));
        return subTasks;
    }

    private List<String> processing(File[] files) {
        List<String> result = new ArrayList<>();
        String longest_word = "";
        try (Scanner sc = new Scanner(files[0])) {
            while (sc.hasNext()) {
                String word = sc.next();

                if (word.length() > longest_word.length()) {
                    longest_word = word;
                    result.clear();
                    result.add(longest_word);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result + " " + Thread.currentThread() + " " + files[0]);
        return result;
    }
}


问:
Run one specific function inside observe only when we get data not when activity is recreated
I have this observer inside an activity and I want to make part of it run only when we have new data and not when the activity is recreated (like when you rotate screen)

```<code>signInViewModel.signInResponse.observe(this, {
                response->  when(response){
            is NetworkResult.Success ->{
                response.data?.let {
                    signInViewModel.saveJwt(it)

                }
            }

            is NetworkResult.Error ->{
                errorMsg.text = response.message.toString()

            }

            is NetworkResult.Loading -> {

            }
        }
        })
</code>```

I want to run this signInViewModel.saveJwt(it) only when we get new data and other part run when we get new data and when we recreate the activity.

答:
You should use Kotlin StateFlow instead of liveData

StateFlow will emit new data only (not any duplicate)

Only change required is

```<code>private val _signInResponse = MutableStateFlow<NetworkResult>(NetworkResult.Loading)
val signInResponse : StateFlow<NetworkResult> = _signInResponse
</code>```

When you have the data simply call

```<code>_signInResponse.value = NetworkResult.Success(jwt)
</code>```

And Handle like this

```<code>signInViewModel.signInResponse.collect{ response->

        when(response){

        is NetworkResult.Success ->{
            response.data?.let {
                signInViewModel.saveJwt(it)

            }
        }

        is NetworkResult.Error ->{
            errorMsg.text = response.message.toString()

        }

        is NetworkResult.Loading -> {

        }
    }
    }
</code>```

Body:
I have this observer inside an activity and I want to make part of it run only when we have new data and not when the activity is recreated (like when you rotate screen)

signInViewModel.signInResponse.observe(this, {
                response->  when(response){
            is NetworkResult.Success ->{
                response.data?.let {
                    signInViewModel.saveJwt(it)

                }
            }

            is NetworkResult.Error ->{
                errorMsg.text = response.message.toString()

            }

            is NetworkResult.Loading -> {

            }
        }
        })

I want to run this signInViewModel.saveJwt(it) only when we get new data and other part run when we get new data and when we recreate the activity.

Body:
You should use Kotlin StateFlow instead of liveData

StateFlow will emit new data only (not any duplicate)

Only change required is

private val _signInResponse = MutableStateFlow<NetworkResult>(NetworkResult.Loading)
val signInResponse : StateFlow<NetworkResult> = _signInResponse

When you have the data simply call

_signInResponse.value = NetworkResult.Success(jwt)

And Handle like this

signInViewModel.signInResponse.collect{ response->

        when(response){

        is NetworkResult.Success ->{
            response.data?.let {
                signInViewModel.saveJwt(it)

            }
        }

        is NetworkResult.Error ->{
            errorMsg.text = response.message.toString()

        }

        is NetworkResult.Loading -> {

        }
    }
    }


问:
TypeError: Cannot read property 'getFullYear' of undefined (REACT)
Whenever I try adding a new element to the array I'm getting a TypeError: Cannot read property 'getFullYear' of undefined error hence why I'm not able to any new elements to the array

import React, { useState } from "react";

import ExpenseItem from "./ExpenseItem";
import Card from "../UI/Card";
import ExpensesFilter from "./ExpensesFilter";
import "./Expenses.css";

const Expenses = (props) => {
  const [filteredYear, setFilteredYear] = useState("2020");

  const filterChangeHandler = (selectedYear) => {
    setFilteredYear(selectedYear);
  };

  const filteredExpenses = props.items.filter(expense => {
    return expense.date.getFullYear().toString() === filteredYear;
  });

  return (

      <Card className='expenses'>
        <ExpensesFilter
          selected={filteredYear}
          onChangeFilter={filterChangeHandler}
        />
        {filteredExpenses.map((expense) => (
          <ExpenseItem
            title={expense.title}
            amount={expense.amount}
            date={expense.date}
          />
        ))}
      </Card>

  );
};

export default Expenses;
```

答:
you would get this error if your new Date() id name doesn't corresponds what you have before you call your .getFullYear method

for example
{id: a1, name: repair, amount:6000, dates: new Date(2021-10-24)} - if your object looks like this and your code is this

```<code>const filteredExpenses = props.items.filter(expense => {
return expense.date.getFullYear().toString() === filteredYear;
</code>```

});

you would get this error because the id name is dates and your calling a method with date instead of dates

Body:
you would get this error if your new Date() id name doesn't corresponds what you have before you call your .getFullYear method

for example
{id: a1, name: repair, amount:6000, dates: new Date(2021-10-24)} - if your object looks like this and your code is this

const filteredExpenses = props.items.filter(expense => {
return expense.date.getFullYear().toString() === filteredYear;

});

you would get this error because the id name is dates and your calling a method with date instead of dates


问:
Python threading parallelizing simple operations over 2D grid array
I have the following code structure which I want to take advantage of multi-threading to speed up results, as every computation is independent. For every point in a 2D grid, I call a compute_at_point() function and get the result.

How can I parallelize this with threads? I know the computers that will be used have at least 4 cores. Code below:

```<code>for i in range(0, grid_rows):
        for j in range(0, grid_cols):

            grid_point = input_grid[i, j]
            res_at_point = compute_at_point(input_grid, grid_point)
            output_grid[i, j] = res_at_point
</code>```

Where input_grid and output_grid have the same shape, and every computation is independent.

答:
Using multiprocessing.Pool and functools.partial, we can do the following:

import numpy as np
from functools import partial
from multiprocessing import Pool

input_grid = np.random.random((3,4))
grid_rows = input_grid.shape[0]
grid_cols = input_grid.shape[1]

def compute_at_point(input_grid, grid_point):
    return np.mean(input_grid) + grid_point

with Pool(processes=4) as p:
    output_grid = p.map(partial(compute_at_point, input_grid), input_grid.flatten())
    output_grid = np.array(output_grid).reshape(grid_rows, grid_cols)
```

The simplest way to solve multiprocessing problems is by having one iterable, and allowing the the multiprocessing library to iterate over it.  In this instance, we could pass the input_grid indices, or just flatten the array and iterate over its values.

Body:
I have the following code structure which I want to take advantage of multi-threading to speed up results, as every computation is independent. For every point in a 2D grid, I call a compute_at_point() function and get the result.

How can I parallelize this with threads? I know the computers that will be used have at least 4 cores. Code below:

for i in range(0, grid_rows):
        for j in range(0, grid_cols):

            grid_point = input_grid[i, j]
            res_at_point = compute_at_point(input_grid, grid_point)
            output_grid[i, j] = res_at_point

Where input_grid and output_grid have the same shape, and every computation is independent.

Body:
Using multiprocessing.Pool and functools.partial, we can do the following:

import numpy as np
from functools import partial
from multiprocessing import Pool

input_grid = np.random.random((3,4))
grid_rows = input_grid.shape[0]
grid_cols = input_grid.shape[1]

def compute_at_point(input_grid, grid_point):
    return np.mean(input_grid) + grid_point

with Pool(processes=4) as p:
    output_grid = p.map(partial(compute_at_point, input_grid), input_grid.flatten())
    output_grid = np.array(output_grid).reshape(grid_rows, grid_cols)

The simplest way to solve multiprocessing problems is by having one iterable, and allowing the the multiprocessing library to iterate over it.  In this instance, we could pass the input_grid indices, or just flatten the array and iterate over its values.


问:
Is it possible to run an asynchronous function without making the main function as async?
Is it possible to run an asynchronous function without making the main function as async?

```<code>function index() {
    console.log('1');
    aaa();
    console.log('3');
}

async function aaa() {
    return await bbb().then((value) => {
        console.log(value);
    });
}

async function bbb() {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2');
        }, 1000);
    });
}

index();
</code>```

It is possible to display:

1

2

3

Without making the index function as async?

答:
Since aaa returns a Promise, you can always interact directly with that Promise instead of using await.  For example:

```<code>function index() {
  console.log('1');
  aaa().then(() => console.log('3'));
}
</code>```

That way the code in the .then() callback won't execute until after the Promise returned by aaa() resolves.

For the most part, without peeking under the hood to the inner workings of JavaScript, async and await tends to just be a cleaner and simpler way of expressing this same thing.  For this simple example, there really shouldn't be a meaningful difference between this:

```<code>function index() {
  console.log('1');
  return aaa().then(() => console.log('3'));
}
</code>```

And this:

```<code>async function index() {
  console.log('1');
  await aaa();
  console.log('3');
}
</code>```

The main difference between these and the function at the top of this answer is that the one at the top doesn't advertise that it internally has asynchronous operations.  So it can't be awaited.  If that's not an issue for your needs, no big deal.  But even then, going with async and await still does the same thing and consuming code can simply choose not to await this function.

Body:
Is it possible to run an asynchronous function without making the main function as async?

function index() {
    console.log('1');
    aaa();
    console.log('3');
}

async function aaa() {
    return await bbb().then((value) => {
        console.log(value);
    });
}

async function bbb() {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2');
        }, 1000);
    });
}

index();

It is possible to display:

1

2

3

Without making the index function as async?

Body:
Since aaa returns a Promise, you can always interact directly with that Promise instead of using await.  For example:

function index() {
  console.log('1');
  aaa().then(() => console.log('3'));
}

That way the code in the .then() callback won't execute until after the Promise returned by aaa() resolves.

For the most part, without peeking under the hood to the inner workings of JavaScript, async and await tends to just be a cleaner and simpler way of expressing this same thing.  For this simple example, there really shouldn't be a meaningful difference between this:

function index() {
  console.log('1');
  return aaa().then(() => console.log('3'));
}

And this:

async function index() {
  console.log('1');
  await aaa();
  console.log('3');
}

The main difference between these and the function at the top of this answer is that the one at the top doesn't advertise that it internally has asynchronous operations.  So it can't be awaited.  If that's not an issue for your needs, no big deal.  But even then, going with async and await still does the same thing and consuming code can simply choose not to await this function.


答:
override onChange method, that should only run when the data changes.

By far this should solve your problem

Title: Run one specific function inside observe only when we get data not when activity is recreated


问:
How to Insert an HTML file into a VUE component?
I'm new to VueJS, so far everything is going well. But I have a few already made HTML templates that I want to insert into my components.

I've seen examples showing:

enter image description here

But that doesn't work (at least not for me).

Any ideas would help, thanks :)

答:
You are not supposed to import external html files into your vue templates.

The recommended way to author Vue component is using the vue SFC format with a build tool like Vite or Webpack. If you have a lot of static templates that you want to migrate to Vue SFCs you should probably copy/paste them into the <template> tags of your components manually.

You can also use Vue in a standalone format requiring no build tools but this won't allow you to import html files in your component's template either.