问:
How to use singlechildscroll view for Gridview.builder
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

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

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

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

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

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
Hi Please try this-</p>
```<code>Expanded(
            child: GridView.builder(

            primary: false,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: dataList.length,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                childAspectRatio: 0.95,
                crossAxisSpacing: 15.0,
                mainAxisSpacing: 10.0,
                mainAxisExtent: 200,
                crossAxisCount: 2),
          )
</code>```

Body:
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

  import 'package:flutter/material.dart';

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

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

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

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Body:
Hi Please try this-

Expanded(
            child: GridView.builder(

            primary: false,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: dataList.length,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                childAspectRatio: 0.95,
                crossAxisSpacing: 15.0,
                mainAxisSpacing: 10.0,
                mainAxisExtent: 200,
                crossAxisCount: 2),
          )


来源: stackexchange

问:
Outlook VSTO attach meta data
I am writing an Outlook addin that inserts content into an email, and I have a emailSent event that I would like send an event back to my server letting me know some content was shared.

Is there a way to attach some meta information to the email (or the word doc, which is what you are creating in outlook)  so that I can grab that meta info so I can send it back to my server.

Right now, the only way I think I can do it is to search through the email on the send event looking for my content with regex and pull out the info i need, but that seems cumbersome, and also means I need to run the regex for every email sent, even when they haven't added my content.

答:
There is the concept of MAPI user properties, which you can add to an Outlook item. Since Office 2007 the object model allows access to them. If your add-in must run also with older Outlook version, you should recurr to use Redemption (which I prefer also for higher office versions because it has more flexibility, albeit a greater footprint in distribution).

See UserProperties Interface on MSDN.

ContentLicense: CC BY-SA 3.0

Title: Outlook VSTO attach meta data


问:
Force AWS EC2 Instance to Use Private IP for Local Traffic
Forgive me if this question is off-topic for this community; I couldn't find a more appropriate one and StackOverflow has always come through when I need it!

I am trying to set up a bastion host with Amazon EC2.  I want the only way to connect to any of my instances to be an SSH from this bastion instance.  The public subnet containing the bastion uses CIDR block 10.0.128.0/17, and the subnet containing my other instances uses CIDR block 10.0.0.0/17.  I have network ACL and security group rules permitting SSH egress from the bastion to the other subnet, and permitting SSH ingress to the other subnet from the bastion.  Everything should work.  Unfortunately, my bastion is trying to communicate with the other instances using their public IPs, which of course is not in the 10.0.0.0/17 block, and therefore the traffic is being blocked.  How can I ensure that my bastion uses private IP addresses while communicating with other instances in the private subnet?  This seems like it should be the default behavior for local traffic in a VPC but apparently its not!

EDIT:

I left out some key info.  The "private" instance giving me trouble is actually public; it is a Wordpress web server with public IP 52.14.20.167 (please don't spam it lol) and a custom www DNS name.  However, while I want my bastion to be able to SSH into it using that DNS name, I still want all SSH traffic be local so that my security groups and network ACLs can be very restrictive.  According to this AWS doc:

We resolve a public DNS hostname to the public IPv4 address of the
  instance outside the network of the instance, and to the private IPv4
  address of the instance from within the network of the instance.

However, I think this rule only applies to the AWS-provided (IP-like) public DNS names.  My custom DNS always resolves to the public IP, not the private one, as seen in the flow log from my bastion's subnet below.  10.0.128.6 is the bastion and 52.14.20.167 is the web server.  Idk what the 190. and 14. addresses are.  So my more educated question is, how can I have custom DNS names resolve to private IPs for a bastion host and second instance in the same VPC?

```<code>10.0.128.6  52.14.20.167    56008   22  6   7   420 1485465879  1485465996  REJECT  OK
190.173.143.165 10.0.128.6  27754   22  6   1   40  1485466241  1485466296  REJECT  OK
10.0.128.6  52.14.20.167    56012   22  6   7   420 1485466903  1485467016  REJECT  OK
190.13.10.206   10.0.128.6  28583   22  6   1   40  1485467140  1485467197  REJECT  OK
10.0.128.6  52.14.20.167    56014   22  6   7   420 1485467437  1485467557  REJECT  OK
14.158.51.244   10.0.128.6  55532   22  6   1   44  1485467500  1485467557  REJECT  OK
</code>```

答:
You need to use CNAME records instead of A records when you setup DNS for your ec2 instance. Assume that you have a www site with url my-site.com. If you put DNS records my-site.com A your_public_ip example my-site.com A 52.14.20.167
your traffic will go outside the aws VPC if you try to reach that url from any server from inside your VPC.

To avoid this you need to change that record to
my-site.com CNAME your_EC2_instance_AWS_DNS_address

Example:
my-site.com CNAME ec2-XX-YY-ZZZ-17.eu-west-1.compute.amazonaws.com

With this if you access your www service outside AWS you will get your public ip resolved, and inside the AWS VPC you will get the private address of your service and traffic will stay inside AWS VPC.

Body:
Forgive me if this question is off-topic for this community; I couldn't find a more appropriate one and StackOverflow has always come through when I need it!

I am trying to set up a bastion host with Amazon EC2.  I want the only way to connect to any of my instances to be an SSH from this bastion instance.  The public subnet containing the bastion uses CIDR block 10.0.128.0/17, and the subnet containing my other instances uses CIDR block 10.0.0.0/17.  I have network ACL and security group rules permitting SSH egress from the bastion to the other subnet, and permitting SSH ingress to the other subnet from the bastion.  Everything should work.  Unfortunately, my bastion is trying to communicate with the other instances using their public IPs, which of course is not in the 10.0.0.0/17 block, and therefore the traffic is being blocked.  How can I ensure that my bastion uses private IP addresses while communicating with other instances in the private subnet?  This seems like it should be the default behavior for local traffic in a VPC but apparently its not!

EDIT:

I left out some key info.  The "private" instance giving me trouble is actually public; it is a Wordpress web server with public IP 52.14.20.167 (please don't spam it lol) and a custom www DNS name.  However, while I want my bastion to be able to SSH into it using that DNS name, I still want all SSH traffic be local so that my security groups and network ACLs can be very restrictive.  According to this AWS doc:

We resolve a public DNS hostname to the public IPv4 address of the
  instance outside the network of the instance, and to the private IPv4
  address of the instance from within the network of the instance.

However, I think this rule only applies to the AWS-provided (IP-like) public DNS names.  My custom DNS always resolves to the public IP, not the private one, as seen in the flow log from my bastion's subnet below.  10.0.128.6 is the bastion and 52.14.20.167 is the web server.  Idk what the 190. and 14. addresses are.  So my more educated question is, how can I have custom DNS names resolve to private IPs for a bastion host and second instance in the same VPC?

10.0.128.6  52.14.20.167    56008   22  6   7   420 1485465879  1485465996  REJECT  OK
190.173.143.165 10.0.128.6  27754   22  6   1   40  1485466241  1485466296  REJECT  OK
10.0.128.6  52.14.20.167    56012   22  6   7   420 1485466903  1485467016  REJECT  OK
190.13.10.206   10.0.128.6  28583   22  6   1   40  1485467140  1485467197  REJECT  OK
10.0.128.6  52.14.20.167    56014   22  6   7   420 1485467437  1485467557  REJECT  OK
14.158.51.244   10.0.128.6  55532   22  6   1   44  1485467500  1485467557  REJECT  OK

ContentLicense: CC BY-SA 4.0


问:
RN-Gesture-Handler Swipeable issue with maximum call stack size exceeded
I can't make the Swipeable component work with a button. It seems like it calls all button to render the action everything I click on one of them. Any idea what is wrong here ? Thank you

```<code>import { RectButton, Swipeable } from 'react-native-gesture-handler';
....
cars.map((car: any, index: number) => {
                    if(car.is_cancellable) {
                        return(
                            <Swipeable
                                key={index}
                                renderRightActions={() => {
                                    return(
                                        <RectButton style={styles.swipeable} onPress={() => cancelOrder(car.uuid)}>
                                           <Feather style={styles.icon} name="trash-2" size={32} color="white" />
                                        </RectButton>
                                    )
                                }}
                                rightThreshold={-300}
                                key={order.uuid}>
                                <TouchableOpacity onPress={() => selectOrder(car)}>
                                    <PortfolioOrder car={car} />
                                </TouchableOpacity>
                            </Swipeable>
                        )
                    })
}})

const cancelOrder = (id: string) => {
    console.log('press', id)
    cancelOrder({id})
}
</code>```

Gives me this error after logging the same message 100+ times

RangeError: Maximum call stack size exceeded

答:
```<code>const cancelOrder = (id: string) => {
    console.log('press', id)
    cancelOrder({id})// this line is causing problem because of recursion.
}
</code>```

Body:
I can't make the Swipeable component work with a button. It seems like it calls all button to render the action everything I click on one of them. Any idea what is wrong here ? Thank you

import { RectButton, Swipeable } from 'react-native-gesture-handler';
....
cars.map((car: any, index: number) => {
                    if(car.is_cancellable) {
                        return(
                            <Swipeable
                                key={index}
                                renderRightActions={() => {
                                    return(
                                        <RectButton style={styles.swipeable} onPress={() => cancelOrder(car.uuid)}>
                                           <Feather style={styles.icon} name="trash-2" size={32} color="white" />
                                        </RectButton>
                                    )
                                }}
                                rightThreshold={-300}
                                key={order.uuid}>
                                <TouchableOpacity onPress={() => selectOrder(car)}>
                                    <PortfolioOrder car={car} />
                                </TouchableOpacity>
                            </Swipeable>
                        )
                    })
}})

const cancelOrder = (id: string) => {
    console.log('press', id)
    cancelOrder({id})
}

Gives me this error after logging the same message 100+ times

RangeError: Maximum call stack size exceeded


问:
iOS, Universal links, Swift. continueUserActivity not calling
I working on Universal links implementation for our iOS app.

Here is my small piece of AppDelegate:

```<code>private func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    DeepLinkHelpers.handleUniversalLink(url.absoluteString)
    return true
}

private func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    DeepLinkHelpers.handleUniversalLink(userActivity.webpageURL?.absoluteString)
    return true
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    signalRConnector.launch()

    NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.processRestartSignalRNotification(_:)), name: NSNotification.Name(rawValue: "restartSignalR"), object: nil)

    NotificationCenter.default.addObserver(self,                            selector: #selector(AppDelegate.reachabilityChanged(_:)),
                                           name: ReachabilityChangedNotification,
                                           object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        Logger.save(text: "Unable to start notifier")
    }
    return true
}
</code>```

I have processed all other steps for universal links integration:

Published apple-app-site-association file in our Web application

Switched on Associated domains feature on developers.apple.com

Specified associated domains in xcode

Checked Target Membership for entitlements file

Said xcode to wait until app will be started manually (instead of
autostart)

I doing following to debug:

Connecting ipad

Starting project in xcode

In ipad opening Calendar and click on link contained in some event.
Link has following format: app.domain.com/#/123456789

Ipad opens app but continueUserActivity not calling and i can't
handle code from the url for navigate to exact state within an app.

According documentation continueUserActivity should be executed. It is not executing both when app is running in background and when app not running.

Thank you in advance! Any help appreciated.

答:
after ios 13 you should use ScenDelegate:</p>
```<code>//when app is running

func scene(_ scene: UIScene, continue userActivity: NSUserActivity)

//when app is not running
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
</code>```

Body:
I working on Universal links implementation for our iOS app.

Here is my small piece of AppDelegate:

private func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    DeepLinkHelpers.handleUniversalLink(url.absoluteString)
    return true
}

private func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    DeepLinkHelpers.handleUniversalLink(userActivity.webpageURL?.absoluteString)
    return true
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    signalRConnector.launch()

    NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.processRestartSignalRNotification(_:)), name: NSNotification.Name(rawValue: "restartSignalR"), object: nil)

    NotificationCenter.default.addObserver(self,                            selector: #selector(AppDelegate.reachabilityChanged(_:)),
                                           name: ReachabilityChangedNotification,
                                           object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        Logger.save(text: "Unable to start notifier")
    }
    return true
}

I have processed all other steps for universal links integration:

Published apple-app-site-association file in our Web application

Switched on Associated domains feature on developers.apple.com

Specified associated domains in xcode

Checked Target Membership for entitlements file

Said xcode to wait until app will be started manually (instead of
autostart)

I doing following to debug:

Connecting ipad

Starting project in xcode

In ipad opening Calendar and click on link contained in some event.
Link has following format: app.domain.com/#/123456789

Ipad opens app but continueUserActivity not calling and i can't
handle code from the url for navigate to exact state within an app.

According documentation continueUserActivity should be executed. It is not executing both when app is running in background and when app not running.

Thank you in advance! Any help appreciated.

Body:
after ios 13 you should use ScenDelegate:

//when app is running

func scene(_ scene: UIScene, continue userActivity: NSUserActivity)

//when app is not running
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)


问:
How to run relevant methods using annotation?
Maybe this question title is not up to my queries but I am searching for the answers for so long.

After adding Lombok to a project, we can use getter, setter, Slf4j, etc. Like

```<code>@Getter
@Setter
public class Example {}
</code>```

My query is After adding @Slf4j we can access an instance of a class "log".Like

```<code>@Slf4j
@Getter
@Setter
public class Example {

  public void do() {
        log.debug("doing");
    }
}
</code>```

So how can I build this kind of annotation that will provide "log" like implementation in java?

答:
Lombok developer here: Lombok is a bit more complicated than that.

Lombok is a unique kind of tool. Yes, it is an annotation processor in the sense that you can specify lombok as being one and lombok then runs as as annotation processor and sets itself up during the init() call (javac will, once its ready to run the processors, first initialize them all).

Lombok is not an annotation processor in the sense that other than the init() step and interacting with the 'rounds' system (specifically: Causing another round to fire in certain cases, in order to ensure javac 'sees' the stuff lombok made. Usually this isn't needed, as it takes a little bit of extra time so we don't do it unless absolutely neccessary) – lombok doesn't use the annotation API at all.

If you are asking how to make your own: That's very complicated. Best route is to fork lombok on github, and have a look at e.g. both HandleSetter.java files in the source to know what to do (there's one for ecj/eclipse and one for javac). Then, you'll be ready to write your own.

Note that intellij support is done via a separate intellij plugin so if you're interested in having lombok work there, you'd also need to fork that plugin and add support there. You only need to mess with intellij if you want new 'signatures' to be visible (you want to add or remove fields or methods, or you want to change the signature parts of one of those: The name, return type, field type, parameter type, or throws line, or you want to add a new type, though that last part can be done with a simple annotation processor).

Body:
Maybe this question title is not up to my queries but I am searching for the answers for so long.

After adding Lombok to a project, we can use getter, setter, Slf4j, etc. Like

@Getter
@Setter
public class Example {}

My query is After adding @Slf4j we can access an instance of a class "log".Like

@Slf4j
@Getter
@Setter
public class Example {

  public void do() {
        log.debug("doing");
    }
}

So how can I build this kind of annotation that will provide "log" like implementation in java?


问:
Best practices to build multi room (video and chat) with permissions in django and flutter
So past couple of days I have been looking into building multi room, where users are able to either chat, spectate or make a video calls dependent on their permissions in Django(DRF) backend and flutter frontend.

For Django I found that I need to use, channels and web socket.
Alternatively for flutter I found about stream platform (getstream.io) that helps to do that.

At the end of the day I got overwhelmed and confused. I do not know where to begin, or what is the best approach to what I am looking for. I am very comfortable with working DRF and using dryrestpermissions to permit users some actions, however I am not sure how to integrate that with the multi room, websockets and then access that through flutter...

Either way please give me your ideas about this, best practices and where should I begin?

Thank you!

答:
You could use Django backend as room server, which is named signaling server for WebRTC. The room server used to create and manage rooms, to allow flutter clients to list the room, to enter the room and get the streams of other clients.

While from the point of view of streaming, you should use WebRTC, rather than live streaming. Because for video chat, the lagging should <400ms, which is easy for WebRTC to do this, generally ~100ms.

Never use live streaming, whatever neither RTMP/HLS nor LLHLS/DASH, normally >1s latency.

If you want a fast overview, please try the demo of SRS: VideoRoom, or other WebRTC sfu like mediasoup or janus.


问:
Getting the are the ISS is flying over using reverse geocoder
I use the following code in order to get the city the iss is flying over. I used the code from the astro-pi tutorial(https://projects.raspberrypi.org/en/projects/code-for-your-astro-pi-mission-space-lab-experiment/2):

```<code>import reverse_geocoder
from orbit import ISS

coordinates = ISS.coordinates()
coordinate_pair = (
    coordinates.latitude.degrees,
    coordinates.longitude.degrees)
location = reverse_geocoder.search(coordinate_pair)
print(location)
</code>```

This is what i get

```<code>[OrderedDict([
    ('lat', '42.82701'),
    ('lon', '-75.54462'),
    ('name', 'Hamilton'),
    ('admin1', 'New York'),
    ('admin2', 'Madison County'),
    ('cc', 'US')
])]
</code>```

What kind of data is this ? and how can i for example print out only name and get Hamilton

答:
Maurice Meyer helped me solve the issue</p>
```<code>print(location[0]['name'])
</code>```

Body:
I use the following code in order to get the city the iss is flying over. I used the code from the astro-pi tutorial(https://projects.raspberrypi.org/en/projects/code-for-your-astro-pi-mission-space-lab-experiment/2):

import reverse_geocoder
from orbit import ISS

coordinates = ISS.coordinates()
coordinate_pair = (
    coordinates.latitude.degrees,
    coordinates.longitude.degrees)
location = reverse_geocoder.search(coordinate_pair)
print(location)

This is what i get

[OrderedDict([
    ('lat', '42.82701'),
    ('lon', '-75.54462'),
    ('name', 'Hamilton'),
    ('admin1', 'New York'),
    ('admin2', 'Madison County'),
    ('cc', 'US')
])]

What kind of data is this ? and how can i for example print out only name and get Hamilton

Body:
Maurice Meyer helped me solve the issue

print(location[0]['name'])


问:
Is AWS Access Key / Secret Key encrypted during transport and Is it safe to be used on public WIFI hotspot?
I was connected to a public WIFI hotspot and I executed this command:

```<code>aws ec2 describe-instances
</code>```

and it successfully returned all my EC2 instance information.(since I have my AWS Access Key / Secret Key configured in my local machine)

To prepare for the worst, let us assume this public wifi is not safe and hacked, now does my action above expose the AWS Access Key / Secret Key?

P.S. If on public WIFI, I only visit HTTPS websites, is there still any security risks regarding my credentials to these websites?

答:
You don't really have to worry about your key being stolen in transit -- HTTPS will do a reasonably good job of ensuring that you're really talking to AWS, and all communication will be encrypted.

If your computer is hacked, though, then all bets are off.  The danger of this is significantly increased on a public network.

Body:
I was connected to a public WIFI hotspot and I executed this command:

aws ec2 describe-instances

and it successfully returned all my EC2 instance information.(since I have my AWS Access Key / Secret Key configured in my local machine)

To prepare for the worst, let us assume this public wifi is not safe and hacked, now does my action above expose the AWS Access Key / Secret Key?

P.S. If on public WIFI, I only visit HTTPS websites, is there still any security risks regarding my credentials to these websites?


问:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

```<code>int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;
</code>```

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

答:
Casting to uintptr_t only works if this type is defined, which may not be the case on legacy systems using ancient compilers. Note however that uintptr_t must be large enough for any object pointer, especially char * or void *, but may be smaller than function pointers. Such architectures are rare today and Microsoft compilers probably no longer support them, but they were common place in the 16-bit world (MS/DOS, Windows 1, 2 and 3.x) where the medium model had 32-bit segmented code pointers and 16-bit data pointers.

Note also that the C Standard allows for int * and void * to have a different size and representation albeit no Microsoft compiler supports such exotic targets.

On current systems with modern compilers, all data pointers and code pointers have almost always the same size and representation. This is actually a requirement for POSIX compatibility, so the recommendation to use an intermediary cast to (uintptr_t) is valid and effective.

For complete portability, if the goal is to pass a function pointer via an opaque void *, you can always allocate an object of the proper function pointer type, initialize it with pfunc and pass its address:

```<code>// setting up the void *
int (*pfunc)();
void *pdata = malloc(sizeof pfunc);
memcpy(pdata, &pfunc, sizeof pfunc);

// using the void *
int (**ppfunc)() = pdata;
(*ppfunc)();     // equivalent to (**ppfunc)();
</code>```

Body:
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

Body:
Casting to uintptr_t only works if this type is defined, which may not be the case on legacy systems using ancient compilers. Note however that uintptr_t must be large enough for any object pointer, especially char * or void *, but may be smaller than function pointers. Such architectures are rare today and Microsoft compilers probably no longer support them, but they were common place in the 16-bit world (MS/DOS, Windows 1, 2 and 3.x) where the medium model had 32-bit segmented code pointers and 16-bit data pointers.

Note also that the C Standard allows for int * and void * to have a different size and representation albeit no Microsoft compiler supports such exotic targets.

On current systems with modern compilers, all data pointers and code pointers have almost always the same size and representation. This is actually a requirement for POSIX compatibility, so the recommendation to use an intermediary cast to (uintptr_t) is valid and effective.

For complete portability, if the goal is to pass a function pointer via an opaque void *, you can always allocate an object of the proper function pointer type, initialize it with pfunc and pass its address:

// setting up the void *
int (*pfunc)();
void *pdata = malloc(sizeof pfunc);
memcpy(pdata, &pfunc, sizeof pfunc);

// using the void *
int (**ppfunc)() = pdata;
(*ppfunc)();     // equivalent to (**ppfunc)();


问:
this.state.articles.map is not a function
Why is this not working? I get data from parseData but it says map isn't a function. Why?

Uncaught TypeError: this.state.articles.map is not a function

```<code>  constructor() {
    super();
    this.state = {
      articles: {},
      loading: false,
    };
  }
  async componentDidMount() {
    let url =
      "https://newsapi.org/v2/top-headlines?country=in&apiKey=<API_KEY>";
    let data = await fetch(url);
    let parseData = await data.json();
    console.log(parseData);
    this.setState({ articles: parseData.articles });
  }
  render() {
    return (
      <div className="container my-3">
        <h2>NewsHunters -Headlines</h2>
        <div className="row">
          {this.state.articles.map((e) => {
            return (
              <div className="col-md-4" key={e.url}>
                <NewsItem
                  title={e.title ? e.title.slice(0, 45) : ""}
                  description={e.description ? e.description.slice(0, 88) : ""}
                  imageUrl={e.urlToImage}
                  newsUrl={e.url}
                />
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}```
```

答:
Because your articles is Object, not Array. Use [] as initial state for articles, to be able to use Array methods.

P.S. This is where Typescript could be helpful, I would recommend to consider using it in the future.

Body:
Why is this not working? I get data from parseData but it says map isn't a function. Why?

Uncaught TypeError: this.state.articles.map is not a function

  constructor() {
    super();
    this.state = {
      articles: {},
      loading: false,
    };
  }
  async componentDidMount() {
    let url =
      "https://newsapi.org/v2/top-headlines?country=in&apiKey=<API_KEY>";
    let data = await fetch(url);
    let parseData = await data.json();
    console.log(parseData);
    this.setState({ articles: parseData.articles });
  }
  render() {
    return (

NewsHunters -Headlines

          {this.state.articles.map((e) => {
            return (

                <NewsItem
                  title={e.title ? e.title.slice(0, 45) : ""}
                  description={e.description ? e.description.slice(0, 88) : ""}
                  imageUrl={e.urlToImage}
                  newsUrl={e.url}
                />

            );
          })}

    );
  }
}```


问:
Reversing a hash, getting its keys, and sorting
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

```<code>foreach my $key (sort keys reverse %hash){

...}
</code>```

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

答:
I think you're describing exactly the situation in this example:</p>

```<code>#!/usr/local/bin/perl

use strict;
use warnings;

my %hash = (one   => 1, two  => 2, three => 3, four => 4);

%hash = reverse %hash;

foreach my $key (sort {$a <=> $b} keys %hash) {
    print "$key=>$hash{$key}, ";
}
print "\n";

# it displays: 1=>one, 2=>two, 3=>three, 4=>four
</code>```

Body:
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

foreach my $key (sort keys reverse %hash){

...}

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

Body:
I think you're describing exactly the situation in this example:

#!/usr/local/bin/perl

use strict;
use warnings;

my %hash = (one   => 1, two  => 2, three => 3, four => 4);

%hash = reverse %hash;

foreach my $key (sort {$a <=> $b} keys %hash) {
    print "$key=>$hash{$key}, ";
}
print "\n";

# it displays: 1=>one, 2=>two, 3=>three, 4=>four


问:
add a title and remove whitespace from wordcloud2
I'm trying to add a title to a wordcloud2 plot. I found a way to add the title, but it really makes the plot look ugly because the whitespace is way too much.

Here is a dataframe for example:

```<code>df <- structure(list(key = c("Hello", "Okay", "Apple", "Orange", "Cheerios",
"Today", "Tomorrow", "Water", "Steve", "Basket"), count = c(52L,
51L, 25L, 21L, 20L, 12L, 12L, 12L, 11L, 9L)), row.names = c(57L,
53L, 20L, 36L, 18L, 3L, 16L, 50L, 13L, 15L), class = "data.frame")
</code>```

I managed to add a title with htmlwidgets::prependContent, but,there is just way too much whitespace. What can I do to make this look better and remove whitespace?

```<code>library(wordcloud2)

wordcloud2(data = df, size=.5, color='random-dark') %>%
htmlwidgets::prependContent(htmltools::tags$h1("Title"))
</code>```

答:
I tried these codes below on my own wordcloud (unfortunately I didn't use wordcloud2 but I hope this work too on the function).

Use cex to scale up the font, i.e. 150% is cex = 1.5, 200% is cex = 2

```<code>## codes for creating canvas for the text (placeholder)
layout(matrix(c(1, 2), nrow=2), heights=c(1, 4))
par(mar=rep(0, 4))
plot.new()
text(x = 0.5, y = 0.5, "The intended title", cex = 1.5, font = 2)

## then your wordcloud
wordcloud2(data = df, size=.5, color='random-dark')
</code>```

Body:
I'm trying to add a title to a wordcloud2 plot. I found a way to add the title, but it really makes the plot look ugly because the whitespace is way too much.

Here is a dataframe for example:

df <- structure(list(key = c("Hello", "Okay", "Apple", "Orange", "Cheerios",
"Today", "Tomorrow", "Water", "Steve", "Basket"), count = c(52L,
51L, 25L, 21L, 20L, 12L, 12L, 12L, 11L, 9L)), row.names = c(57L,
53L, 20L, 36L, 18L, 3L, 16L, 50L, 13L, 15L), class = "data.frame")

I managed to add a title with htmlwidgets::prependContent, but,there is just way too much whitespace. What can I do to make this look better and remove whitespace?

library(wordcloud2)

wordcloud2(data = df, size=.5, color='random-dark') %>%
htmlwidgets::prependContent(htmltools::tags$h1("Title"))

Body:
I tried these codes below on my own wordcloud (unfortunately I didn't use wordcloud2 but I hope this work too on the function).

Use cex to scale up the font, i.e. 150% is cex = 1.5, 200% is cex = 2

## codes for creating canvas for the text (placeholder)
layout(matrix(c(1, 2), nrow=2), heights=c(1, 4))
par(mar=rep(0, 4))
plot.new()
text(x = 0.5, y = 0.5, "The intended title", cex = 1.5, font = 2)

## then your wordcloud
wordcloud2(data = df, size=.5, color='random-dark')


问:
how to convert windows system timezone to uk timezone
i'm trying to convert "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time" to uk timzone. I found the solution using this "Asia/Kolkata" but I should either pass "(UTC+05:30)" or "Chennai, Kolkata, Mumbai, New Delhi" or "India Standard Time" to my function to convert it into uk time.

Here is my code:

```<code>from datetime import datetime
from pytz import timezone

def get_uk_time(time_zone):
    try:
        country_tz = timezone(time_zone)
        format = "%Y, %m, %d, %H, %M, %S"
        time_now = datetime.now(timezone(time_zone))
        format_time = time_now.strftime(format)
        london_tz = timezone('Europe/London')

        local_time = country_tz.localize(datetime.strptime(format_time, format))
        convert_to_london_time = local_time.astimezone(london_tz)
        uk_time = convert_to_london_time.strftime('%H:%M')
        return uk_time
    except:
        print('unable to find the timezone')

#my_json = {'timezone': 'Asia/Kolkata'}
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}
time_zone = my_json['timezone']
time_in_london = get_uk_time(time_zone)
print(time_in_london)
</code>```

答:
If we remove the try/except, the error is :

```<code>  File "/home/stack_overflow/so71012475.py", line 6, in get_uk_time
    country_tz = timezone(time_zone)
pytz.exceptions.UnknownTimeZoneError: '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'
</code>```

Because (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time is not a correct identifier. I could not find which identifiers it corresponds to, but I can suggest another approach.

Because you know the UTC offset, you can create a timezone object with it, and use it to compute the UK time :

import datetime
import re

import pytz

# the data you provided
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}

# a regex to extract relevant info from your data
pattern = re.compile(r"\(UTC(?P<sign>[+-])(?P<hours>\d\d):(?P<minutes>\d\d)\)(?P<name>.*)")

# extract the info
match = pattern.match(my_json["timezone"])
assert match is not None
tz_name = match.group("name").strip()
hours, minutes = int(match.group("hours")), int(match.group("minutes"))
is_negative = match.group("sign") == "-"

# build the timezone object
my_tz = datetime.timezone(offset=datetime.timedelta(hours=hours, minutes=minutes), name=tz_name)
if is_negative:
    my_tz = -my_tz

# use the timezone object to localize the current time
my_time = datetime.datetime.now().replace(tzinfo=my_tz)
print(my_time)

# and convert it to UK time
uk_tz = pytz.timezone('Europe/London')
uk_time = my_time.astimezone(uk_tz)
print(uk_time)
```
```2022-02-07 14:33:12.463372+05:30
2022-02-07 09:03:12.463372+00:00
```

(it is actually 14:30 at my local time when I am writing this answer, and if I was in India, it would mean that it is 09:00 in London.

Body:
i'm trying to convert "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time" to uk timzone. I found the solution using this "Asia/Kolkata" but I should either pass "(UTC+05:30)" or "Chennai, Kolkata, Mumbai, New Delhi" or "India Standard Time" to my function to convert it into uk time.

Here is my code:

from datetime import datetime
from pytz import timezone

def get_uk_time(time_zone):
    try:
        country_tz = timezone(time_zone)
        format = "%Y, %m, %d, %H, %M, %S"
        time_now = datetime.now(timezone(time_zone))
        format_time = time_now.strftime(format)
        london_tz = timezone('Europe/London')

        local_time = country_tz.localize(datetime.strptime(format_time, format))
        convert_to_london_time = local_time.astimezone(london_tz)
        uk_time = convert_to_london_time.strftime('%H:%M')
        return uk_time
    except:
        print('unable to find the timezone')

#my_json = {'timezone': 'Asia/Kolkata'}
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}
time_zone = my_json['timezone']
time_in_london = get_uk_time(time_zone)
print(time_in_london)

Body:
If we remove the try/except, the error is :

  File "/home/stack_overflow/so71012475.py", line 6, in get_uk_time
    country_tz = timezone(time_zone)
pytz.exceptions.UnknownTimeZoneError: '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'

Because (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time is not a correct identifier. I could not find which identifiers it corresponds to, but I can suggest another approach.

Because you know the UTC offset, you can create a timezone object with it, and use it to compute the UK time :

import datetime
import re

import pytz

# the data you provided
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}

# a regex to extract relevant info from your data
pattern = re.compile(r"\(UTC(?P<sign>[+-])(?P<hours>\d\d):(?P<minutes>\d\d)\)(?P<name>.*)")

# extract the info
match = pattern.match(my_json["timezone"])
assert match is not None
tz_name = match.group("name").strip()
hours, minutes = int(match.group("hours")), int(match.group("minutes"))
is_negative = match.group("sign") == "-"

# build the timezone object
my_tz = datetime.timezone(offset=datetime.timedelta(hours=hours, minutes=minutes), name=tz_name)
if is_negative:
    my_tz = -my_tz

# use the timezone object to localize the current time
my_time = datetime.datetime.now().replace(tzinfo=my_tz)
print(my_time)

# and convert it to UK time
uk_tz = pytz.timezone('Europe/London')
uk_time = my_time.astimezone(uk_tz)
print(uk_time)

2022-02-07 14:33:12.463372+05:30
2022-02-07 09:03:12.463372+00:00

(it is actually 14:30 at my local time when I am writing this answer, and if I was in India, it would mean that it is 09:00 in London.


答:
No, It will not expose anything, until you will not share your username with a hacker to ease his job of hacking your account.

Your Access key is like a username and the secret key is like a password.
The Access/Secret key use a secure protocol to call the AWS information/API.

You can also create and use temporary access keys, known as temporary security credentials. The advantage of temporary security credentials is that they are short term. After they expire, they're no longer valid.

Title: Is AWS Access Key / Secret Key encrypted during transport and Is it safe to be used on public WIFI hotspot?


问:
Building array from object of arrays returns undefined
So I have this originalArray:

```<code>[
  [
    {
       “name”: “Selena”,
       “lastName”: “Gomez”,
       “likes”: {
           “color”: “red”,
           “country”: “Argentina”,
           “state”: {
                “name”: “Buenos Aires”
           }
        },
        “phoneNumber”: “5555555555”,
        “isAvailable”: false
    }
  ],
   [
    {
       “name”: “Nick”,
       “lastName”: “Jonnas”,
       “likes”: {
          “color”: “blue”,
          “country”: “Argentina”,
          “state”: {
            “name”: “Buenos Aires”
          }
        },
        “phoneNumber”: “7777777777”,
        “isAvailable”: true
      },
       {
       “name”: “Joe”,
       “lastName”: “Jonnas”,
       “likes”: {
            “color”: “yellow”,
            “country”: “Argentina”,
            “state”: {
                 “name”: “Buenos Aires”
            }
        },
        “phoneNumber”: “9999999999”,
        “isAvailable”: false
      }
    ]
]
</code>```

As you can see is an Object that has the form of (2) [Array(1), Array(2)] and I want to iterate over the object and get only the phoneNumbers items.

Expected output:

```<code>['55555555555', '7777777777', '9999999999']
</code>```

I've tried:

```<code>const newArray= originalArray.map(element => element.phoneNumber);
</code>```

But it returns undefined, actually I tried accessing with . like originalArray.phoneNumber and shows undefined too.

I also tried with this approach with no result:

```<code>var newArray = originalArray.filter(obj => {
  return obj.phoneNumber != null
})
</code>```

Is there a way to iterate over the object, look up the phoneNumber key, and add those results to a new array?

答:
We can achieve this by :

Flattening the multidimensional array into single array.

looping through each object using Array.map() to fetch the phone number.

This step is for safe side to eliminate the empty or null phone numbers using Array.filter()

Working Demo :

let originalArray = [
  [
    {
       "name": "Selena",
       "lastName": "Gomez",
       "likes": {
           "color": "red",
           "country": "Argentina",
           "state": {
                "name": "Buenos Aires"
           }
        },
        "phoneNumber": "5555555555",
        "isAvailable": false
    }
  ],
   [
    {
       "name": "Nick",
       "lastName": "Jonnas",
       "likes": {
          "color": "blue",
          "country": "Argentina",
          "state": {
            "name": "Buenos Aires"
          }
        },
        "phoneNumber": "7777777777",
        "isAvailable": true
      },
       {
       "name": "Joe",
       "lastName": "Jonnas",
       "likes": {
            "color": "yellow",
            "country": "Argentina",
            "state": {
                 "name": "Buenos Aires"
            }
        },
        "phoneNumber": "9999999999",
        "isAvailable": false
      }
    ]
];

const flatArray = originalArray.flat().map((obj) => obj.phoneNumber).filter((item) => item);

console.log(flatArray);```

Body:
So I have this originalArray:

[
  [
    {
       “name”: “Selena”,
       “lastName”: “Gomez”,
       “likes”: {
           “color”: “red”,
           “country”: “Argentina”,
           “state”: {
                “name”: “Buenos Aires”
           }
        },
        “phoneNumber”: “5555555555”,
        “isAvailable”: false
    }
  ],
   [
    {
       “name”: “Nick”,
       “lastName”: “Jonnas”,
       “likes”: {
          “color”: “blue”,
          “country”: “Argentina”,
          “state”: {
            “name”: “Buenos Aires”
          }
        },
        “phoneNumber”: “7777777777”,
        “isAvailable”: true
      },
       {
       “name”: “Joe”,
       “lastName”: “Jonnas”,
       “likes”: {
            “color”: “yellow”,
            “country”: “Argentina”,
            “state”: {
                 “name”: “Buenos Aires”
            }
        },
        “phoneNumber”: “9999999999”,
        “isAvailable”: false
      }
    ]
]

As you can see is an Object that has the form of (2) [Array(1), Array(2)] and I want to iterate over the object and get only the phoneNumbers items.

Expected output:

['55555555555', '7777777777', '9999999999']

I've tried:

const newArray= originalArray.map(element => element.phoneNumber);

But it returns undefined, actually I tried accessing with . like originalArray.phoneNumber and shows undefined too.

I also tried with this approach with no result:

var newArray = originalArray.filter(obj => {
  return obj.phoneNumber != null
})

Is there a way to iterate over the object, look up the phoneNumber key, and add those results to a new array?


问:
Is there an alternate to WebBrowser for windows forms?
I'd like to know if there is an alternate to the WebBrowser control for a .net Windows Forms application? I've suffered through one issue where a system changed to a newer version of IE and my application's HTML editor broke - the app started crashing. I'd be willing to pay for a commercial product if I can get better stability.</p>

答:
There is webkit dot net -- a wrapper over web kit. http://webkitdotnet.sourceforge.net/

More alternatives are listed here: vb 2008 webbrowser alternative


问:
update webdriver-manager errno: -54, code: 'ECONNRESET', syscall: 'read'
I work in a Lerna repo and want to do npx webdriver-manager update --versions.chrome=98.0.4758.80 for my e2e Tests

I tried as well npx webdriver-manager update
and npx ./packages/testing/node_modules/protractor/node_modules/webdriver-manager/bin/webdriver-manager update

I always get this result:

```<code>npx: installed 88 in 4.393s
webdriver-manager: using global installed version 12.1.8
[13:39:20] I/file_manager - creating folder /Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/standalone-response.xml https://selenium-release.storage.googleapis.com/
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/chrome-response.xml https://chromedriver.storage.googleapis.com/
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/gecko-response.json https://api.github.com/repos/mozilla/geckodriver/releases
events.js:377
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Request instance at:
    at Request.onRequestError (/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/node_modules/request/request.js:877:8)
    at ClientRequest.emit (events.js:412:35)
    at TLSSocket.socketErrorListener (_http_client.js:475:9)
    at TLSSocket.emit (events.js:400:28)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  errno: -54,
  code: 'ECONNRESET',
  syscall: 'read'
}
</code>```

What I already tried:

npx webdriver-manager clean

installed webdriver-manager globally for all users (and again uninstall)

removed all node_modules and ran again npm i

searched through npx webdriver-manager update-help

Does anyone has an idea what the problem could be?

答:
Ok I don't know why but it worked now
.. here what I've done:

npm uninstall webdriver-manager

npm i

npx webdriver-manager clean

and then npx ./packages/testing/node_modules/protractor/node_modules/webdriver-manager/bin/webdriver-manager update

Body:
I work in a Lerna repo and want to do npx webdriver-manager update --versions.chrome=98.0.4758.80 for my e2e Tests

I tried as well npx webdriver-manager update
and npx ./packages/testing/node_modules/protractor/node_modules/webdriver-manager/bin/webdriver-manager update

I always get this result:

npx: installed 88 in 4.393s
webdriver-manager: using global installed version 12.1.8
[13:39:20] I/file_manager - creating folder /Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/standalone-response.xml https://selenium-release.storage.googleapis.com/
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/chrome-response.xml https://chromedriver.storage.googleapis.com/
[13:39:20] I/config_source - curl -o/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/selenium/gecko-response.json https://api.github.com/repos/mozilla/geckodriver/releases
events.js:377
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Request instance at:
    at Request.onRequestError (/Users/Prename.Lastname/.npm/_npx/97900/lib/node_modules/webdriver-manager/node_modules/request/request.js:877:8)
    at ClientRequest.emit (events.js:412:35)
    at TLSSocket.socketErrorListener (_http_client.js:475:9)
    at TLSSocket.emit (events.js:400:28)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  errno: -54,
  code: 'ECONNRESET',
  syscall: 'read'
}

What I already tried:

npx webdriver-manager clean

installed webdriver-manager globally for all users (and again uninstall)

removed all node_modules and ran again npm i

searched through npx webdriver-manager update-help

Does anyone has an idea what the problem could be?


问:
Splitting igraph in components and drawing components separately
I have a graph that has a total of 14 components of which 13 are isolated nodes and the major component has 128 nodes. Obviously, this large component is all cluttered and overlapped and I am just not able to make any sense out of it.

Can someone suggest how I draw only this large component as a separate graph so that I have a better resolution and meaningful interpretation? I am using R and igraph package

SHRINIVAS
INDIA

答:
You can use decompse like below (given graph object g)

```<code>sapply(decompose(g), plot)
</code>```

Body:
You can use decompse like below (given graph object g)

sapply(decompose(g), plot)


问:
Error while installing pytq5 with pip: Preparing metadata (pyproject.toml) did not run successfully
I try to install pytq5 with pip and get this error

```<code>$ python3 -m pip install PyQt5
Collecting PyQt5
  Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 156, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        ...
        ...
        ...
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

I still can install other packages like lxml but can't install pytq5. I'm installing everything in virtual environment.

Any ideas ??

答:
Like @Ken1124 i tackeled the same issue when trying to download the tools (aka pyqt5-tools). After many tries I found it helpful to downgrade python to version 3.9.x (specifically to 3.9.9) from 3.10.x.
If you currently have python 3.10 it might help, but otherwise idk...

Other methods that I tried which I didn't see to fix the issue, but perhaps fixed other problem assosicated with the issue as well:

Changing from Microsoft Store version of python to the site's verstion.

using only pyqt5 (I first had both 5 & 6).

Downgrading pip (right after upgrading).

That's all I know,
wish you good luck :)

Body:
I try to install pytq5 with pip and get this error

$ python3 -m pip install PyQt5
Collecting PyQt5
  Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 156, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Users/olivierskonieczny/Desktop/app/python/ObjectDetection/envs/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        ...
        ...
        ...
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I still can install other packages like lxml but can't install pytq5. I'm installing everything in virtual environment.

Any ideas ??


问:
How to get min and max value of primitives?
How can I store the minimum value of i32 in a variable?

// Java Example :
int min = Integer.MIN_VALUE;
```
<pre class="lang-cpp prettyprint-override"><code>// C++ example
int min = INT_MIN;
</code>```

I want to do something like:

let min: i32 = i32_MIN_VALUE;
```

答:
You have some const defined:

MIN

MAX

let min: u32 = u32::MIN;
```

They are also defined for other primitive numeric types.

Body:
How can I store the minimum value of i32 in a variable?

// Java Example :
int min = Integer.MIN_VALUE;

// C++ example
int min = INT_MIN;

I want to do something like:

let min: i32 = i32_MIN_VALUE;

Body:
You have some const defined:

MIN

MAX

let min: u32 = u32::MIN;

They are also defined for other primitive numeric types.


问:
Resulting array is zero when jax.numpy is used
I wrote the code below using numpy and got the correct output as shown in program 1. However when I switch to jax.numpy as jnp (in Program 2) the resulting output is an array of zeros. My MWE is shown below. I would like to know where I got the computation wrong?
PS: the codes were run in different python files.</p>
```<code>#Program 1 (using numpy as np):
import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

k = 0
for i in range(num_rows):

    arr_1[i, :] = (par_log[kvals[i]:kvals[i+1]])
    arr_2[i, :] = 10**par_log[kvals[i]:kvals[i+1]]

print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

# Program 2 (using jax.numpy as jnp):

import jax
import jax.numpy as jnp
jax.config.update("jax_enable_x64", True)

smf = jnp.array([jnp.inf, 0.1, 0.1, 0.1, 0.1])
par_init = jnp.array([1.0,2.0,3.0,4.0,5.0])
lb = jnp.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = jnp.array([10.0, 10.0, 10.0, 10.0, 10.0])
par = jnp.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = jnp.where(jnp.isinf(smf), 1, num_cols)
kvals = jnp.insert(kvals, 0, 0)
kvals = jnp.cumsum(kvals)

par0_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
lb_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
ub_col = jnp.zeros(num_rows*num_cols- (num_cols-1) * jnp.sum(jnp.isinf(smf)))

for i in range(num_rows):
    par0_col.at[kvals[i]:kvals[i+1]].set(par[i, :kvals[i+1]-kvals[i]])
    lb_col.at[kvals[i]:kvals[i+1]].set(lb[i])
    ub_col.at[kvals[i]:kvals[i+1]].set(ub[i])

arr_1 = jnp.zeros(shape = (num_rows, num_cols))
arr_2 = jnp.zeros(shape = (num_rows, num_cols))

par_log = jnp.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

for i in range(num_rows):

    arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
    arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

print(arr_1)

# #[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

</code>```

答:
The issue is that ndarray.at expressions don't operate in-place, but rather return a modified value.

So instead of this:

```<code>arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])
</code>```

You should write this:

```<code>arr_1 = arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
arr_2 = arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])
</code>```

Read more at JAX sharp bits: in-place updates.

Body:
I wrote the code below using numpy and got the correct output as shown in program 1. However when I switch to jax.numpy as jnp (in Program 2) the resulting output is an array of zeros. My MWE is shown below. I would like to know where I got the computation wrong?
PS: the codes were run in different python files.

#Program 1 (using numpy as np):
import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

k = 0
for i in range(num_rows):

    arr_1[i, :] = (par_log[kvals[i]:kvals[i+1]])
    arr_2[i, :] = 10**par_log[kvals[i]:kvals[i+1]]

print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

# Program 2 (using jax.numpy as jnp):

import jax
import jax.numpy as jnp
jax.config.update("jax_enable_x64", True)

smf = jnp.array([jnp.inf, 0.1, 0.1, 0.1, 0.1])
par_init = jnp.array([1.0,2.0,3.0,4.0,5.0])
lb = jnp.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = jnp.array([10.0, 10.0, 10.0, 10.0, 10.0])
par = jnp.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = jnp.where(jnp.isinf(smf), 1, num_cols)
kvals = jnp.insert(kvals, 0, 0)
kvals = jnp.cumsum(kvals)

par0_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
lb_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
ub_col = jnp.zeros(num_rows*num_cols- (num_cols-1) * jnp.sum(jnp.isinf(smf)))

for i in range(num_rows):
    par0_col.at[kvals[i]:kvals[i+1]].set(par[i, :kvals[i+1]-kvals[i]])
    lb_col.at[kvals[i]:kvals[i+1]].set(lb[i])
    ub_col.at[kvals[i]:kvals[i+1]].set(ub[i])

arr_1 = jnp.zeros(shape = (num_rows, num_cols))
arr_2 = jnp.zeros(shape = (num_rows, num_cols))

par_log = jnp.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

for i in range(num_rows):

    arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
    arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

print(arr_1)

# #[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

Body:
The issue is that ndarray.at expressions don't operate in-place, but rather return a modified value.

So instead of this:

arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

You should write this:

arr_1 = arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
arr_2 = arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

Read more at JAX sharp bits: in-place updates.


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
We had the same issue with my co-worker today.

What worked for us was removing any language from the Chrome settings, but the English (I'm using the Polish language as well and it seems like it's not causing the issue).

Machine: MacBook Pro with macOS Monterey 12.1; Test Framework: Java 11/Selenium

Chrome v.98 - Language settings

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?