问:
Animation library is giving me this error about lifecycle state
Animation library is giving me this error about lifecycle state-- 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4519 pos 12: '_lifecycleState != _ElementLifecycle.defunct': is not true. is was getting this error when i used animation controller.

After the error my flutter application crashed and i have to reload everytime.

```<code>// ignore_for_file: depend_on_referenced_packages, sized_box_for_whitespace, avoid_print

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:habbit_app/controllers/timer_tab_controller.dart';
import 'package:habbit_app/screens/timer/set_timer_component.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:habbit_app/widgets/text_widget/label_text.dart';

class TimerTab extends StatefulWidget {
  const TimerTab({super.key});

  @override
  State<TimerTab> createState() => _TimerTabState();
}

class _TimerTabState extends State<TimerTab> with TickerProviderStateMixin {
  AnimationController? animationController;
  TimerTabController tabController =
      Get.put(TimerTabController(), permanent: false);

  late TabController _controller;

  bool isPlaying = false;

  // int get countText2 {
  //   int count = tabController.totalSeconds;
  //   return;
  // }

  String get countText {
    Duration count =
        animationController!.duration! * animationController!.value;
    return animationController!.isDismissed
        ? '${animationController!.duration!.inHours}:${(animationController!.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(animationController!.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
        : '${count.inHours}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void dispose() {
    animationController!.dispose();
    super.dispose();
  }

  double progress = 1.0;

  void notifiy() {
    if (countText == "0:00:00") {
      FlutterRingtonePlayer.playNotification();
    }
  }

  @override
  void initState() {
    // ignore: todo
    // TODO: implement initState
    TimerTabController tabController =
        Get.put(TimerTabController(), permanent: false);
    super.initState();
    _controller = TabController(length: 3, vsync: this);
    _controller.addListener(() {
      tabController.tabIndex.value = _controller.index;
      // print(tabController.tabIndex.value);
    });
    super.initState();
    animationController = AnimationController(
        vsync: this, duration: Duration(seconds: tabController.totalSeconds));
    animationController!.addListener(() {
      notifiy();
      if (animationController!.isAnimating) {
        setState(() {
          progress = animationController!.value;
        });
      } else {
        setState(() {
          progress = 1.0;
          isPlaying = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var color = Theme.of(context);
    return Obx(
      () => tabController.isFirst.value
          ? SetTimerComponent(
              changeAnimation: () {
                animationController!.duration =
                    Duration(seconds: tabController.totalSeconds);
                tabController.changeFirst();
              },
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // start timer screen
                Container(
                  height: 350,
                  width: MediaQuery.of(context).size.width,
                  // color: color.cardColor,
                  child: Column(children: [
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        SizedBox(
                            width: 300,
                            height: 300,
                            child: CircularProgressIndicator(
                              color: color.primaryColor,
                              backgroundColor:
                                  color.disabledColor.withOpacity(0.6),
                              value: progress,
                              strokeWidth: 10,
                            )),
                        GestureDetector(
                          onTap: () {
                            if (animationController!.isDismissed) {
                              showModalBottomSheet(
                                  context: context,
                                  builder: (context) => Container(
                                        height: 300,
                                        child: CupertinoTimerPicker(
                                          initialTimerDuration:
                                              animationController!.duration!,
                                          backgroundColor:
                                              color.backgroundColor,
                                          onTimerDurationChanged: (time) {
                                            setState(() {
                                              animationController!.duration =
                                                  time;
                                            });
                                          },
                                        ),
                                      ));
                            }
                          },
                          child: AnimatedBuilder(
                            animation: animationController!,
                            builder: ( context, child) => Text(
                              countText,
                              style: TextStyle(
                                  fontSize: 60,
                                  fontWeight: FontWeight.bold,
                                  color: color.primaryColor),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ]),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    GestureDetector(
                      onTap: () {
                        print(tabController.totalSeconds);
                        if (animationController!.isAnimating) {
                          animationController!.stop();
                          setState(() {
                            isPlaying = false;
                          });
                        } else {
                          animationController!.reverse(
                              from: animationController!.value == 0
                                  ? 1.0
                                  : animationController!.value);
                          setState(() {
                            isPlaying = true;
                          });
                        }
                      },
                      child: Container(
                        height: 35,
                        width: 90,
                        decoration: BoxDecoration(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(30)),
                            color: color.primaryColor),
                        child: Center(
                            child: LabelText(
                          text: isPlaying == true ? "PAUSE" : "RESUME",
                          isBold: true,
                          isColor: true,
                          color: Colors.white,
                        )),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        animationController!.reset();
                        tabController.currentvalueHour.value = 0;
                        tabController.currentvalueMin.value = 0;
                        tabController.currentvalueSec.value = 0;
                        setState(() {
                          isPlaying = false;
                        });
                        tabController.changeFirst2();
                      },
                      child: Container(
                        height: 35,
                        width: 90,
                        decoration: BoxDecoration(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(30)),
                            color: color.disabledColor.withOpacity(0.5)),
                        child: const Center(
                            child: LabelText(
                          text: "DELETE",
                          isColor: true,
                          color: Colors.white,
                          isBold: true,
                        )),
                      ),
                    )
                  ],
                )
              ],
            ),
    );
  }
}
</code>```

Body:
Animation library is giving me this error about lifecycle state-- 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4519 pos 12: '_lifecycleState != _ElementLifecycle.defunct': is not true. is was getting this error when i used animation controller.

After the error my flutter application crashed and i have to reload everytime.

// ignore_for_file: depend_on_referenced_packages, sized_box_for_whitespace, avoid_print

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:habbit_app/controllers/timer_tab_controller.dart';
import 'package:habbit_app/screens/timer/set_timer_component.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:habbit_app/widgets/text_widget/label_text.dart';

class TimerTab extends StatefulWidget {
  const TimerTab({super.key});

  @override
  State<TimerTab> createState() => _TimerTabState();
}

class _TimerTabState extends State<TimerTab> with TickerProviderStateMixin {
  AnimationController? animationController;
  TimerTabController tabController =
      Get.put(TimerTabController(), permanent: false);

  late TabController _controller;

  bool isPlaying = false;

  // int get countText2 {
  //   int count = tabController.totalSeconds;
  //   return;
  // }

  String get countText {
    Duration count =
        animationController!.duration! * animationController!.value;
    return animationController!.isDismissed
        ? '${animationController!.duration!.inHours}:${(animationController!.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(animationController!.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
        : '${count.inHours}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void dispose() {
    animationController!.dispose();
    super.dispose();
  }

  double progress = 1.0;

  void notifiy() {
    if (countText == "0:00:00") {
      FlutterRingtonePlayer.playNotification();
    }
  }

  @override
  void initState() {
    // ignore: todo
    // TODO: implement initState
    TimerTabController tabController =
        Get.put(TimerTabController(), permanent: false);
    super.initState();
    _controller = TabController(length: 3, vsync: this);
    _controller.addListener(() {
      tabController.tabIndex.value = _controller.index;
      // print(tabController.tabIndex.value);
    });
    super.initState();
    animationController = AnimationController(
        vsync: this, duration: Duration(seconds: tabController.totalSeconds));
    animationController!.addListener(() {
      notifiy();
      if (animationController!.isAnimating) {
        setState(() {
          progress = animationController!.value;
        });
      } else {
        setState(() {
          progress = 1.0;
          isPlaying = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var color = Theme.of(context);
    return Obx(
      () => tabController.isFirst.value
          ? SetTimerComponent(
              changeAnimation: () {
                animationController!.duration =
                    Duration(seconds: tabController.totalSeconds);
                tabController.changeFirst();
              },
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // start timer screen
                Container(
                  height: 350,
                  width: MediaQuery.of(context).size.width,
                  // color: color.cardColor,
                  child: Column(children: [
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        SizedBox(
                            width: 300,
                            height: 300,
                            child: CircularProgressIndicator(
                              color: color.primaryColor,
                              backgroundColor:
                                  color.disabledColor.withOpacity(0.6),
                              value: progress,
                              strokeWidth: 10,
                            )),
                        GestureDetector(
                          onTap: () {
                            if (animationController!.isDismissed) {
                              showModalBottomSheet(
                                  context: context,
                                  builder: (context) => Container(
                                        height: 300,
                                        child: CupertinoTimerPicker(
                                          initialTimerDuration:
                                              animationController!.duration!,
                                          backgroundColor:
                                              color.backgroundColor,
                                          onTimerDurationChanged: (time) {
                                            setState(() {
                                              animationController!.duration =
                                                  time;
                                            });
                                          },
                                        ),
                                      ));
                            }
                          },
                          child: AnimatedBuilder(
                            animation: animationController!,
                            builder: ( context, child) => Text(
                              countText,
                              style: TextStyle(
                                  fontSize: 60,
                                  fontWeight: FontWeight.bold,
                                  color: color.primaryColor),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ]),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    GestureDetector(
                      onTap: () {
                        print(tabController.totalSeconds);
                        if (animationController!.isAnimating) {
                          animationController!.stop();
                          setState(() {
                            isPlaying = false;
                          });
                        } else {
                          animationController!.reverse(
                              from: animationController!.value == 0
                                  ? 1.0
                                  : animationController!.value);
                          setState(() {
                            isPlaying = true;
                          });
                        }
                      },
                      child: Container(
                        height: 35,
                        width: 90,
                        decoration: BoxDecoration(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(30)),
                            color: color.primaryColor),
                        child: Center(
                            child: LabelText(
                          text: isPlaying == true ? "PAUSE" : "RESUME",
                          isBold: true,
                          isColor: true,
                          color: Colors.white,
                        )),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        animationController!.reset();
                        tabController.currentvalueHour.value = 0;
                        tabController.currentvalueMin.value = 0;
                        tabController.currentvalueSec.value = 0;
                        setState(() {
                          isPlaying = false;
                        });
                        tabController.changeFirst2();
                      },
                      child: Container(
                        height: 35,
                        width: 90,
                        decoration: BoxDecoration(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(30)),
                            color: color.disabledColor.withOpacity(0.5)),
                        child: const Center(
                            child: LabelText(
                          text: "DELETE",
                          isColor: true,
                          color: Colors.white,
                          isBold: true,
                        )),
                      ),
                    )
                  ],
                )
              ],
            ),
    );
  }
}


来源: stackexchange

问:
Poco c++ x64 stops after SecureSMTPClientSession.open()
I learn how to use C++ for network stuff, so first thing i tried is to send email with Poco C++ library. I used vcpkg to install poco with openssl, and it compiles fine

I take code like example from that question:

Sending HTML code in a mail using Poco library

Where dude could send text, but couldn't send file, so i thought that i could reproduce his result quickly, and send some text too, but it doesn't works at all
It Creates Secure SMTP session, but when i try to open it, program just stops

There's my code:

```<code>#include <Poco\Net\AcceptCertificateHandler.h>
#include <Poco\Net\FilePartSource.h>
#include <Poco\Net\InvalidCertificateHandler.h>
#include <Poco\Net\MailMessage.h>
#include <Poco\Net\NetException.h>
#include <Poco\Net\SecureSMTPClientSession.h>
#include <Poco\Net\SSLManager.h>
#include <iostream>
namespace pn = Poco::Net;

struct info
{
    std::string sender;
    std::string recipient;
    std::string password;
    std::string host;
    int port;
};

void MailSender(info a)
{
    Poco::Net::MailMessage mailMessage;

    mailMessage.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, a.recipient, "username"));

    mailMessage.setSubject("test");
    mailMessage.setSender(a.sender);
    mailMessage.setContent("Oh yeah!\r\n");

    Poco::Net::SecureSMTPClientSession session(a.host, a.port);
    std::cout << "> Session created\n";
    session.open();
    std::cout << "> Session opened\n";

    Poco::Net::initializeSSL();
    std::cout << "> SSL initialized\n";

    Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> ptrHandler = new Poco::Net::AcceptCertificateHandler(false);

    Poco::Net::Context::Ptr ptrContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", Poco::Net::Context::VERIFY_RELAXED, 9, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");

    Poco::Net::SSLManager::instance().initializeClient(NULL, ptrHandler, ptrContext);
    std::cout << "> Client initialized\n";
    try
    {
        session.login();
        std::cout << "> 1 login completed\n";
        if (session.startTLS(ptrContext))
        {

            session.login(Poco::Net::SecureSMTPClientSession::AUTH_LOGIN, a.sender, a.password);
            std::cout << "> 2 login\n";
            session.sendMessage(mailMessage);
            std::cout << "> Message sent\n";
        }
        session.close();
        std::cout << "> Session closed\n";
        Poco::Net::uninitializeSSL();
    }
    catch (Poco::Net::SMTPException& e)
    {
        std::cout << e.message() << std::endl;
        session.close();
        Poco::Net::uninitializeSSL();
    }
};

int main()
{
    info a{ "username@yandex.ru" , "username@yandex.ru" , "application_password" , "smtp.yandex.ru" , 465};
    /*
    *a.sender = "username@yandex.ru";
    *a.recipient = "username@yandex.ru";
    *a.password = "application_password";
    *a.host = "smtp.yandex.ru";
    *a.port = 465;
    */

    MailSender(a);
}
</code>```

Yandex provides instruction for their smtp usage:

https://yandex.ru/support/mail/mail-clients/others.html

Mail server address - smtp.yandex.ru

Port - 465

Security - ssl

I tried mail.ru and yandex.ru with the same result - nothing
I tried version without ssl, still nothing
I tried to turn off my antivirus

ContentLicense: CC BY-SA 4.0

Body:
I learn how to use C++ for network stuff, so first thing i tried is to send email with Poco C++ library. I used vcpkg to install poco with openssl, and it compiles fine

I take code like example from that question:

Sending HTML code in a mail using Poco library

Where dude could send text, but couldn't send file, so i thought that i could reproduce his result quickly, and send some text too, but it doesn't works at all
It Creates Secure SMTP session, but when i try to open it, program just stops

There's my code:

#include <Poco\Net\AcceptCertificateHandler.h>
#include <Poco\Net\FilePartSource.h>
#include <Poco\Net\InvalidCertificateHandler.h>
#include <Poco\Net\MailMessage.h>
#include <Poco\Net\NetException.h>
#include <Poco\Net\SecureSMTPClientSession.h>
#include <Poco\Net\SSLManager.h>
#include <iostream>
namespace pn = Poco::Net;

struct info
{
    std::string sender;
    std::string recipient;
    std::string password;
    std::string host;
    int port;
};

void MailSender(info a)
{
    Poco::Net::MailMessage mailMessage;

    mailMessage.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, a.recipient, "username"));

    mailMessage.setSubject("test");
    mailMessage.setSender(a.sender);
    mailMessage.setContent("Oh yeah!\r\n");

    Poco::Net::SecureSMTPClientSession session(a.host, a.port);
    std::cout << "> Session created\n";
    session.open();
    std::cout << "> Session opened\n";

    Poco::Net::initializeSSL();
    std::cout << "> SSL initialized\n";

    Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> ptrHandler = new Poco::Net::AcceptCertificateHandler(false);

    Poco::Net::Context::Ptr ptrContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", Poco::Net::Context::VERIFY_RELAXED, 9, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");

    Poco::Net::SSLManager::instance().initializeClient(NULL, ptrHandler, ptrContext);
    std::cout << "> Client initialized\n";
    try
    {
        session.login();
        std::cout << "> 1 login completed\n";
        if (session.startTLS(ptrContext))
        {

            session.login(Poco::Net::SecureSMTPClientSession::AUTH_LOGIN, a.sender, a.password);
            std::cout << "> 2 login\n";
            session.sendMessage(mailMessage);
            std::cout << "> Message sent\n";
        }
        session.close();
        std::cout << "> Session closed\n";
        Poco::Net::uninitializeSSL();
    }
    catch (Poco::Net::SMTPException& e)
    {
        std::cout << e.message() << std::endl;
        session.close();
        Poco::Net::uninitializeSSL();
    }
};

int main()
{
    info a{ "username@yandex.ru" , "username@yandex.ru" , "application_password" , "smtp.yandex.ru" , 465};
    /*
    *a.sender = "username@yandex.ru";
    *a.recipient = "username@yandex.ru";
    *a.password = "application_password";
    *a.host = "smtp.yandex.ru";
    *a.port = 465;
    */

    MailSender(a);
}

Yandex provides instruction for their smtp usage:

https://yandex.ru/support/mail/mail-clients/others.html

Mail server address - smtp.yandex.ru

Port - 465

Security - ssl

I tried mail.ru and yandex.ru with the same result - nothing
I tried version without ssl, still nothing
I tried to turn off my antivirus


问:
R plumber with future promise: assign variable to global environment
In a R plumber script in which I use future I need to assign some variables to the global environment (so that a variable created in one API can be retrieved from another API) but it does not work as expected.

I created a simple example. Here you can see the main script to run in R:

```<code>### Set the asynchronous coding
library(promises) ; library(future)
future::plan("multisession")

## Plumber app
library(plumber)

pr <- pr("APIs_TestAsync.R")
pr %>% pr_run()
</code>```

and here the script to save as "APIs_TestAsync.R":

```<code>#* Test 1
#* @get test1
#* @serializer unboxedJSON
#* @tag TestFuture
function() {

  # Create a dataset
  df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
  assign("Test1", df, .GlobalEnv)

  return(
    list(SUM=sum(df$B))
    )
  }

#* Test 2
#* @get test2
#* @serializer unboxedJSON
#* @tag TestFuture
function() {

  # Create a future promise
  Prom<-future({

      # Wait for 10 seconds (needed to test the asynchronous functions)
      Sys.sleep(10)

      # Create a dataset
      df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
      assign("Test2", df, .GlobalEnv)

      # Store the list in Prom
      return(
        list(SUM=sum(df$B))
      )

  }, seed=T) # Close future promise

  return(Prom) # Return Prom to the API

}
</code>```

You'll see that the first API (not using future) manages to assign Test1 to the global environment but that the second API does not assign Test2.

I tried several ways of assignment, different environment names, explored the futureAssign function but did not manage to make it work...

If you have any idea it would be greatly appreciated!

Body:
In a R plumber script in which I use future I need to assign some variables to the global environment (so that a variable created in one API can be retrieved from another API) but it does not work as expected.

I created a simple example. Here you can see the main script to run in R:

### Set the asynchronous coding
library(promises) ; library(future)
future::plan("multisession")

## Plumber app
library(plumber)

pr <- pr("APIs_TestAsync.R")
pr %>% pr_run()

and here the script to save as "APIs_TestAsync.R":

#* Test 1
#* @get test1
#* @serializer unboxedJSON
#* @tag TestFuture
function() {

  # Create a dataset
  df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
  assign("Test1", df, .GlobalEnv)

  return(
    list(SUM=sum(df$B))
    )
  }

#* Test 2
#* @get test2
#* @serializer unboxedJSON
#* @tag TestFuture
function() {

  # Create a future promise
  Prom<-future({

      # Wait for 10 seconds (needed to test the asynchronous functions)
      Sys.sleep(10)

      # Create a dataset
      df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
      assign("Test2", df, .GlobalEnv)

      # Store the list in Prom
      return(
        list(SUM=sum(df$B))
      )

  }, seed=T) # Close future promise

  return(Prom) # Return Prom to the API

}

You'll see that the first API (not using future) manages to assign Test1 to the global environment but that the second API does not assign Test2.

I tried several ways of assignment, different environment names, explored the futureAssign function but did not manage to make it work...

If you have any idea it would be greatly appreciated!


问:
Twitter Bot with Python and Tweeter API (tweepy)
```<code>import tweepy
from config import consumer_key, consumer_secret, access_token, access_token_secret, image_path, tweet_limit

# Authenticate
try:
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
except tweepy.error.TweepError as e:
    print("Error: Failed to authenticate with Twitter API. Check your credentials in config.py")
    print(e)
    exit()

# Create API object
api = tweepy.API(auth)

# Open the image file
try:
    image = open(image_path, "rb")
except FileNotFoundError as e:
    print("Error: Image file not found. Make sure image.jpg exist in the same directory as the script.")
    print(e)
    exit()

class MyStreamListener(tweepy.StreamListener):
    def __init__(self):
        self.tweet_count = 0
    def on_status(self, status):
        if "feur" in status.text or "feur!" in status.text or "f1ur" in status.text:
            if self.tweet_count < tweet_limit:
                try:
                    api.update_with_media(image_path, status=status.user.screen_name + " -me ta geule", in_reply_to_status_id=status.id)
                    self.tweet_count += 1
                except tweepy.error.TweepError as e:
                    print("Error: Failed to send tweet.")
                    print(e)
            else:
                stream.disconnect()

# Create stream
myStreamListener = MyStreamListener()
stream = tweepy.Stream(auth, myStreamListener)

# Start stream
try:
    stream.filter(track=["feur", "feur!", "f1ur"])
except tweepy.error.TweepError as e:
    print("Error: Failed to start stream.")
    print(e)

</code>```

Could you help me fixing it ?

Here is the error I get :
AttributeError: module 'tweepy' has no attribute 'StreamListener'

I've been trying to do a bot that automaticly respond to people saying : "quoi" "feur" (very bad french joke) in python with the tweeter API. (I'm not a python dev don't blame me, I'm a php dev)

Body:
import tweepy
from config import consumer_key, consumer_secret, access_token, access_token_secret, image_path, tweet_limit

# Authenticate
try:
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
except tweepy.error.TweepError as e:
    print("Error: Failed to authenticate with Twitter API. Check your credentials in config.py")
    print(e)
    exit()

# Create API object
api = tweepy.API(auth)

# Open the image file
try:
    image = open(image_path, "rb")
except FileNotFoundError as e:
    print("Error: Image file not found. Make sure image.jpg exist in the same directory as the script.")
    print(e)
    exit()

class MyStreamListener(tweepy.StreamListener):
    def __init__(self):
        self.tweet_count = 0
    def on_status(self, status):
        if "feur" in status.text or "feur!" in status.text or "f1ur" in status.text:
            if self.tweet_count < tweet_limit:
                try:
                    api.update_with_media(image_path, status=status.user.screen_name + " -me ta geule", in_reply_to_status_id=status.id)
                    self.tweet_count += 1
                except tweepy.error.TweepError as e:
                    print("Error: Failed to send tweet.")
                    print(e)
            else:
                stream.disconnect()

# Create stream
myStreamListener = MyStreamListener()
stream = tweepy.Stream(auth, myStreamListener)

# Start stream
try:
    stream.filter(track=["feur", "feur!", "f1ur"])
except tweepy.error.TweepError as e:
    print("Error: Failed to start stream.")
    print(e)

Could you help me fixing it ?

Here is the error I get :
AttributeError: module 'tweepy' has no attribute 'StreamListener'

I've been trying to do a bot that automaticly respond to people saying : "quoi" "feur" (very bad french joke) in python with the tweeter API. (I'm not a python dev don't blame me, I'm a php dev)


问:
xls Excel Set max number of bars in bar chart
My bar chart has a max of 8 bars:

For my X-Axis I have marked more years:

Unfortunatly my bar chart only shows 8 bars. When I leave 2004 out, my chart starts at 2006 and includes 2020.

That means that there is some kind of setup for 8 bars.

I have not found anything usefull in the Axis options.

When I tried to create the chart form the scratch it was not limited to 8. Unfortunatly I have almost one hunderd of this charts, so I would like to avoid building them new.

Please let me know if anyone knows how to chage that limitation of bars.


问:
Missing Realm constructor. Did you run "pod install" on ios
This issue is coming only in debugging mode, if we disable the chrome/step debugger issue is not coming
But it leads to difficulty in tracking other bugs.
I need step debugging enabled, help me on this, spent a lot of time on this.
Even the flipper Hermes debugger not showing up the files for step debugging

Is there any solution or workaround for this ?


问:
Hibernate Enverse in Java is using Proxies instead of Bags
Currently i'm worrking on a Java project which uses JPA and under the hood Hibernate as its ORM.
Furthermore we're using Enverse as our auditing Library.

Now, when i query an entity which contains a @ManyToMany or @OneToMany relation directly through Hibernate, the embedded collections will get mapped to "Bag-Types" (PersistentBag for Lists and PersistentSet for Sets).
These Wrapper implement the "PersistentCollection" Interface, which handles the lazy Loading.
When the parentobject ist accessed, no database query will be executed (seen in the debugger). Only when i access an element of the collection, a database query is submittet.

But when i query the Revision through an AuditReader, the Collections will be wrapped in a ListProxy or a SetProxy, this leads to an "unexpected" behaviour (since enverse is a core element of hibernate). In this case, when i just access the parent object, every element in the embedded collection is directly queried. This leads to an enormous performance drop.
The Response from the Revision Endpoint is wrapped into RepresntationModel (from the Spring Hateos project). This leads to the access of the parent object and the generell collection, to create the "_embedded" Object of the response. With the PersistentBag there is no problem, but with the ListProxy, every Element gets queried from the database, leading to thousands of requests.

Is there a way to "teach" enverse to use PeristentBag (or PersistentSet) instead of the internal Proxy Collections or is there another workaround to not load the entire Collection?

Ignoring the embedded Ressources in the Revision boosts the performance, but is no solution since the references are Lost.

Enverse ignores the "fetch" configurations on Collection-Annotations (every Collection is fetched lazy), so this also does not do the trick.

Since the revision endpoint is highly generic, using projections is not an option.


问:
How to use event listeners?
I'm implementing RPC procedures RabbitMQ message bus, but in their example code for the RPC Client class ...:

```<code>public RpcClient()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };

    connection = factory.CreateConnection();
    channel = connection.CreateModel();
    // declare a server-named queue
    replyQueueName = channel.QueueDeclare(queue: "").QueueName;
    consumer = new EventingBasicConsumer(channel);
    consumer.Received += (model, ea) =>
    {
        if (!callbackMapper.TryRemove(ea.BasicProperties.CorrelationId, out TaskCompletionSource<string> tcs))
            return;
        var body = ea.Body.ToArray();
        var response = Encoding.UTF8.GetString(body);
        tcs.TrySetResult(response);
    };

    channel.BasicConsume(
      consumer: consumer,
      queue: replyQueueName,
      autoAck: true);
}
</code>```

the event listener is declared inside the constructor, as you can see, and I want only one instance of this class.
Also, I've read that it is not very good practice to put event listeners in a constructor.

So, is this done so, only for the sake of the example and how should I use event listener?
Should it be a class, which inherits the BackgroundService class?

Title: How to use event listeners?

Body:
I'm implementing RPC procedures RabbitMQ message bus, but in their example code for the RPC Client class ...:

public RpcClient()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };

    connection = factory.CreateConnection();
    channel = connection.CreateModel();
    // declare a server-named queue
    replyQueueName = channel.QueueDeclare(queue: "").QueueName;
    consumer = new EventingBasicConsumer(channel);
    consumer.Received += (model, ea) =>
    {
        if (!callbackMapper.TryRemove(ea.BasicProperties.CorrelationId, out TaskCompletionSource<string> tcs))
            return;
        var body = ea.Body.ToArray();
        var response = Encoding.UTF8.GetString(body);
        tcs.TrySetResult(response);
    };

    channel.BasicConsume(
      consumer: consumer,
      queue: replyQueueName,
      autoAck: true);
}

the event listener is declared inside the constructor, as you can see, and I want only one instance of this class.
Also, I've read that it is not very good practice to put event listeners in a constructor.

So, is this done so, only for the sake of the example and how should I use event listener?
Should it be a class, which inherits the BackgroundService class?


问:
Migrating from OWIN .NET Framework to OpenIddict .NET Core
I have an existing .NET Framework Web API currently in production which is in the process of being upgraded to .NET 6.

The application uses the built-in .NET Framework OWIN solution for generating tokens and handles the authorisation for the client_credential flow.

We have a couple of custom MySql tables that hold the ClientId, ClientSecret info and another for granted token requests, e.g. storing the OWIN ticket, scope details etc.

One limitation we have is that we are using EF Core 3.1.x which we cannot upgrade.

I want to build a solution so that:

existing active OWIN tokens in the database can still be used for
authorisation into the new .NET Core API using OpenIddict, once it goes live. (so
that the end users are not impacted)

I also want to be able to generate new tokens using OpenIddict and
store those tokens in the same existing MySql tables.

I don't know if this is possible and if so how to tackle it.

Has anyone here achieved a similar migration?


问:
Error when I want to create react app: error Couldn't find package "jest-watch-typeahead@^1.0.0" required by "react-scripts" on the "npm" registry
I get this error when I use CRA and I start it with yarn. Although I searched for that on the stack I can't find a solution for that:

```<code>info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error Couldn't find package "jest-watch-typeahead@^1.0.0" required by "react-scripts" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Aborting installation.
  yarnpkg add --exact react react-dom react-scripts cra-template --cwd F:\projects\notes has failed.

Deleting generated file... package.json
Deleting notes/ from F:\projects
Done.
error Command failed.
Exit code: 1
Command: C:\Users\arman\AppData\Local\Yarn\bin\create-react-app
Arguments: notes
Directory: F:\projects
Output:

info Visit https://yarnpkg.com/en/docs/cli/create for documentation about this command.
</code>```

It says about network connections, but my connection doesn't have any problem and I ran it several times. Is it possible that my problem is sanctions against Iran?

What's the problem and what do I have to do for fixing it?

Body:
I get this error when I use CRA and I start it with yarn. Although I searched for that on the stack I can't find a solution for that:

info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error Couldn't find package "jest-watch-typeahead@^1.0.0" required by "react-scripts" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Aborting installation.
  yarnpkg add --exact react react-dom react-scripts cra-template --cwd F:\projects\notes has failed.

Deleting generated file... package.json
Deleting notes/ from F:\projects
Done.
error Command failed.
Exit code: 1
Command: C:\Users\arman\AppData\Local\Yarn\bin\create-react-app
Arguments: notes
Directory: F:\projects
Output:

info Visit https://yarnpkg.com/en/docs/cli/create for documentation about this command.

It says about network connections, but my connection doesn't have any problem and I ran it several times. Is it possible that my problem is sanctions against Iran?

What's the problem and what do I have to do for fixing it?


问:
How to draw rectangle on Qlabel of image with mouse in the PyQt5
I'm a rookie of python and I googled a lots but still can not find how to fix it.
My question is how to draw rectangle on Qlabel of image with mouse moving?
My code as below.

```<code>import sys
import QT5_draw_test as ui

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QMainWindow, ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.rect_begin = QPoint()
        self.rect_end = QPoint()

        self.image_show.setScaledContents(True)
        self.image_show.installEventFilter(self)

        self.img = QPixmap("0.png")
        self.image_show.setPixmap(self.img)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress:
            self.rect_begin = event.pos()

        elif event.type() == QEvent.MouseMove:
            self.rect_end = event.pos()
            self.update()

        return super().eventFilter(obj, event)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self.image_show.pixmap())
        painter.setPen(QPen(Qt.red, 5, Qt.SolidLine))

        print(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())
        painter.drawRect(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())
</code>```

If modify the parameter of painter.drawRect to constant, it's work. (As below)

But If the parameter is variable, it's not work.

```<code>import sys
import QT5_draw_test as ui

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QMainWindow, ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.rect_begin = QPoint()
        self.rect_end = QPoint()

        self.image_show.setScaledContents(True)
        self.image_show.installEventFilter(self)

        self.img = QPixmap("0.png")
        self.image_show.setPixmap(self.img)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress:
            self.rect_begin = event.pos()

        elif event.type() == QEvent.MouseMove:
            self.rect_end = event.pos()
            self.update()

        return super().eventFilter(obj, event)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self.image_show.pixmap())
        painter.setPen(QPen(Qt.red, 5, Qt.SolidLine))

        print(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())
        painter.drawRect(50, 50, 100, 100)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())
</code>```

enter image description here

Body:
I'm a rookie of python and I googled a lots but still can not find how to fix it.
My question is how to draw rectangle on Qlabel of image with mouse moving?
My code as below.

import sys
import QT5_draw_test as ui

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QMainWindow, ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.rect_begin = QPoint()
        self.rect_end = QPoint()

        self.image_show.setScaledContents(True)
        self.image_show.installEventFilter(self)

        self.img = QPixmap("0.png")
        self.image_show.setPixmap(self.img)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress:
            self.rect_begin = event.pos()

        elif event.type() == QEvent.MouseMove:
            self.rect_end = event.pos()
            self.update()

        return super().eventFilter(obj, event)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self.image_show.pixmap())
        painter.setPen(QPen(Qt.red, 5, Qt.SolidLine))

        print(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())
        painter.drawRect(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

If modify the parameter of painter.drawRect to constant, it's work. (As below)

But If the parameter is variable, it's not work.

import sys
import QT5_draw_test as ui

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QMainWindow, ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.rect_begin = QPoint()
        self.rect_end = QPoint()

        self.image_show.setScaledContents(True)
        self.image_show.installEventFilter(self)

        self.img = QPixmap("0.png")
        self.image_show.setPixmap(self.img)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress:
            self.rect_begin = event.pos()

        elif event.type() == QEvent.MouseMove:
            self.rect_end = event.pos()
            self.update()

        return super().eventFilter(obj, event)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self.image_show.pixmap())
        painter.setPen(QPen(Qt.red, 5, Qt.SolidLine))

        print(self.rect_begin.x(), self.rect_begin.y(), self.rect_end.x(), self.rect_end.y())
        painter.drawRect(50, 50, 100, 100)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

enter image description here


问:
Strapi athentication returns AxiosError: Request failed with status code 400
using Strapi with Next js. Trying to authenticate with following code

```<code>    const authenticate = () => {
        const paylaod = {data: {
            identifier: email,
            password: password
        }}
        console.log(paylaod)

        axios.post(`http://localhost:1337/api/auth/local`, paylaod).then((res, err) => {
            console.log(res, err)
            console.log(res,err)
            const { jwt, user } = res.data
            window.localStorage.setItem('jwt', jwt)
            window.localStorage.setItem('userData', JSON.stringify(user))
            router.push({
                pathname: '/calendar',
            });
        }).catch(err => {
            console.log(err)
        })
    }

</code>```

Response I'm getting is:

```<code>AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
</code>```

Dug every possible answer in forums and Stackoverflow, but nothing helped.

User I'm using is not super admin, registered fresh one in Strapi admin.

this is how my middleware list looks like

```<code>export default [
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];
</code>```

and here's my (scrappy) env

```<code>HOST='127.0.0.1'
PORT=1337
APP_KEYS="gfhgfhgfhg,hfghghgf"
API_TOKEN_SALT="adfasdfads"
ADMIN_JWT_SECRET="adfasdfasdf"
JWT_SECRET="sdasdadfasdf"
</code>```

Body:
using Strapi with Next js. Trying to authenticate with following code

    const authenticate = () => {
        const paylaod = {data: {
            identifier: email,
            password: password
        }}
        console.log(paylaod)

        axios.post(`http://localhost:1337/api/auth/local`, paylaod).then((res, err) => {
            console.log(res, err)
            console.log(res,err)
            const { jwt, user } = res.data
            window.localStorage.setItem('jwt', jwt)
            window.localStorage.setItem('userData', JSON.stringify(user))
            router.push({
                pathname: '/calendar',
            });
        }).catch(err => {
            console.log(err)
        })
    }

Response I'm getting is:

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

Dug every possible answer in forums and Stackoverflow, but nothing helped.

User I'm using is not super admin, registered fresh one in Strapi admin.

this is how my middleware list looks like

export default [
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];

and here's my (scrappy) env

HOST='127.0.0.1'
PORT=1337
APP_KEYS="gfhgfhgfhg,hfghghgf"
API_TOKEN_SALT="adfasdfads"
ADMIN_JWT_SECRET="adfasdfasdf"
JWT_SECRET="sdasdadfasdf"


问:
Difference between making an ArrayAdapter
im learning Android programming with Android Studio. A few days ago we made a Spinner and filled it with a list of different countries, who were stored as an String-Array in the Strings.xml file.

To implement the ArrayAdapter we used the createFromRessource() method:

```<code>adapter = ArrayAdapter.createFromResource(this, R.array.countries, android.R.layout.simple_list_item_1);
</code>```

Today i learned how to fill a ListView with items. But now, the teacher implemented the String array first, and then the Arrayadapter with new ArrayAdapter ....

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

    ListView list;
    ArrayAdapter <String> adapter;
    String countries[];

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

        list = findViewById(R.id.list);
        countries = getResources().getStringArray(R.array.countries);

        adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, countries);

        list.setAdapter(adapter);
</code>```

I dont understand two things: The first example would work with the ListView too, and its less code than the second one. Why would someone use the second one for making the ArrayAdapter?

Why do i need  Generics here? The ArrayAdapter can uses Strings anyway or not?

Tried to llok for an answer on Google.

Body:
im learning Android programming with Android Studio. A few days ago we made a Spinner and filled it with a list of different countries, who were stored as an String-Array in the Strings.xml file.

To implement the ArrayAdapter we used the createFromRessource() method:

adapter = ArrayAdapter.createFromResource(this, R.array.countries, android.R.layout.simple_list_item_1);

Today i learned how to fill a ListView with items. But now, the teacher implemented the String array first, and then the Arrayadapter with new ArrayAdapter ....

public class ConstraintLayout extends AppCompatActivity {

    ListView list;
    ArrayAdapter <String> adapter;
    String countries[];

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

        list = findViewById(R.id.list);
        countries = getResources().getStringArray(R.array.countries);

        adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, countries);

        list.setAdapter(adapter);

I dont understand two things: The first example would work with the ListView too, and its less code than the second one. Why would someone use the second one for making the ArrayAdapter?

Why do i need  Generics here? The ArrayAdapter can uses Strings anyway or not?

Tried to llok for an answer on Google.


问:
Call useSWR by previous useSWR data.map then got Error(useSWR to get google calendar event)
I write a hook named useGoogleCalendarEvents, Try to get users google calendar event,below is my code.

```<code>import { Schedule, User } from '../../types/commons.type';
import { useLocalStorage } from 'usehooks-ts';
import useSWR from 'swr';
import { FetchCalendarList } from '../../types/googleCalendarAPIResponse.type';
import { currentUTCMonthString } from '../../utils/DateUtils';

const baseURL = 'https://www.googleapis.com/calendar/v3';

const fetcher = ([path, method, body = {}, accessToken = '']: [string, string, object, string]) => {
  const headers = {
    'Content-Type': ['POST', 'PUT', 'PATCH'].includes(method) ? 'application/json' : '',
    Authorization: `Bearer ${accessToken}`,
  };
  const fetchOptions = {
    method,
    headers,
    body: method === 'GET' ? undefined : JSON.stringify(body),
  };
  const apiURL = `${baseURL}${path}`;
  return fetch(apiURL, fetchOptions).then((r) => r.json());
};

export const useGoogleCalendarEvents = () => {
  const [user, setUser] = useLocalStorage<User | undefined>('user', undefined);

  const events: Array<string> = [];

  if (user?.googleAccessToken) {
    // get user calendar list
    const { data: GoogleCalendarListResult } = useSWR<FetchCalendarList>(
      ['/users/me/calendarList', 'GET', {}, user?.googleAccessToken],
      fetcher,
    );

    const { startString, endString } = currentUTCMonthString();
    const parameters = `timeMin=${startString}&timeMax=${endString}`;
    // map loop to get event by calendar id
    GoogleCalendarListResult?.items?.map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );
    });
  }
  return { events };
};
</code>```

the code not yet finish but i got the error

"React has detected a change in the order of Hooks called by MySettingPage2."

I modify the code

```<code>GoogleCalendarListResult?.items?.map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );    });
</code>```

to

```<code>['calendarid1', 'calendarid2'].map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );
    });
</code>```

It is work, but not flexble. I want to get calendar id list first, then get envets by calendar id

Is anybody known why cause this error? Thank for any reply

Body:
I write a hook named useGoogleCalendarEvents, Try to get users google calendar event,below is my code.

import { Schedule, User } from '../../types/commons.type';
import { useLocalStorage } from 'usehooks-ts';
import useSWR from 'swr';
import { FetchCalendarList } from '../../types/googleCalendarAPIResponse.type';
import { currentUTCMonthString } from '../../utils/DateUtils';

const baseURL = 'https://www.googleapis.com/calendar/v3';

const fetcher = ([path, method, body = {}, accessToken = '']: [string, string, object, string]) => {
  const headers = {
    'Content-Type': ['POST', 'PUT', 'PATCH'].includes(method) ? 'application/json' : '',
    Authorization: `Bearer ${accessToken}`,
  };
  const fetchOptions = {
    method,
    headers,
    body: method === 'GET' ? undefined : JSON.stringify(body),
  };
  const apiURL = `${baseURL}${path}`;
  return fetch(apiURL, fetchOptions).then((r) => r.json());
};

export const useGoogleCalendarEvents = () => {
  const [user, setUser] = useLocalStorage<User | undefined>('user', undefined);

  const events: Array<string> = [];

  if (user?.googleAccessToken) {
    // get user calendar list
    const { data: GoogleCalendarListResult } = useSWR<FetchCalendarList>(
      ['/users/me/calendarList', 'GET', {}, user?.googleAccessToken],
      fetcher,
    );

    const { startString, endString } = currentUTCMonthString();
    const parameters = `timeMin=${startString}&timeMax=${endString}`;
    // map loop to get event by calendar id
    GoogleCalendarListResult?.items?.map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );
    });
  }
  return { events };
};

the code not yet finish but i got the error

"React has detected a change in the order of Hooks called by MySettingPage2."

I modify the code

GoogleCalendarListResult?.items?.map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );    });

to

['calendarid1', 'calendarid2'].map((calendar) => {
      const { data: GoogleCalendarEventResult } = useSWR(
        [`/calendars/${calendar.id}/events?${parameters}`],
        fetcher,
      );
    });

It is work, but not flexble. I want to get calendar id list first, then get envets by calendar id

Is anybody known why cause this error? Thank for any reply


问:
How To Make A Curved Chart with Custom Painter Which Include Custom Tool-tip with Moving Cursor?

I'm Learning Custom Paint and I'm Confused About Them i referred Few Documentation but Still i'm Lacking on it.

Referrence:Curved Chart,
Paths

Some of the Code I have Mentioned Here ..Pls Help Me out of This....

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

class ChartPainter extends CustomPainter {
  final List<String> x;
  final List<double> y;
  final double min, max;

  ChartPainter(this.x, this.y, this.min, this.max);

  final yLabelStyle = const TextStyle(color: Colors.white, fontSize: 14);
  final xLabelStyle = const TextStyle(
      color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold);
  static double border = 10.0;
  static double radius = 5.0;
  final dotPaintFill = Paint()
    ..color = Colors.black
    ..style = PaintingStyle.fill
    ..strokeWidth = 2;
  final linePaint = Paint()
    ..color = Colors.white
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;
  @override
  void paint(Canvas canvas, Size size) {
    final clipRect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.clipRect(clipRect);
    canvas.drawPaint(Paint()..color = Colors.black);

    final drawableHeight = size.height / 10.0 * border;
    final drawableWidth = size.width / 15 * border;
    final leftPadding = size.width / 6;
    final rightPadding = size.width / 1000;
    final hd = drawableHeight / 5.0;
    final wd = drawableWidth / x.length.toDouble();
    final height = hd * 3.0;
    final width = drawableWidth;
    if (height <= 0.0 || width <= 0.00) return;
    if (max - min < 1.0e-6) return;
    final hr = height / (max - min);
    final left = border;
    final top = border;
    final c = Offset(left + wd / 2.0, top + height / 2.0);

    _drawOutline(canvas, c, wd, height);
    final points = _computePoints(c, wd, height, hr);

    final fillpath = _computePath(
        points, drawableHeight, width, true, leftPadding, rightPadding);
    final labels = _computeLabels();

    canvas.drawPath(fillpath, linePaint);

    // drawvertical(canvas, c, wd, height, hr, wd);
    _drawDataPoints(canvas, points, dotPaintFill, linePaint);
    _drawYLabels(canvas, labels, points, wd, top);
    // final c1 = Offset(c.dx, top + 4 * hd);
    // _drawXLabels(canvas, c1, wd);
  }

  void _drawXLabels(Canvas canvas, Offset c, double wd) {
    x.forEach((xp) {
      drawTextCentered(canvas, c, xp, xLabelStyle, wd);
      c += Offset(wd, 0);
    });
  }

  void _drawYLabels(Canvas canvas, List<String> labels, List<Offset> points,
      double wd, double top) {
    var i = 0;
    labels.forEach((label) {
      final dp = points[i];
      final dy = (dp.dy - 15.0) < top ? 15.0 : -15.0;
      final ly = dp + Offset(0, dy);
      drawTextCentered(canvas, ly, label, yLabelStyle, wd);
      i++;
    });
  }

  void _drawDataPoints(
      Canvas canvas, List<Offset> points, Paint dotPaintFill, Paint linePaint) {
    points.forEach((dp) {
      canvas.drawCircle(dp, radius, dotPaintFill);
      canvas.drawCircle(dp, radius, linePaint);
    });
  }

  Path _computePath(List<Offset> points, double h, double w, bool cp,
      double leftPadding, double rightPadding) {

    Path path = Path();

    for (var i = 0; i < points.length; i++) {
      final p = points[i];
      if (i == 0) {
        path.moveTo(p.dx, p.dy);
        path.lineTo(p.dx, p.dy);
      } else {
        path.lineTo(p.dx, p.dy);
      }
    }

    return path;
  }

  List<Offset> _computePoints(
      Offset c, double width, double height, double hr) {
    List<Offset> points = [];
    y.forEach((yp) {
      final yy = height - (yp - min) * hr;
      final dp = Offset(c.dx, c.dy - height / 2.0 + yy);
      points.add(dp);
      c += Offset(width, 0);
    });
    return points;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  final Paint outlinePaint = Paint()
    ..strokeWidth = 1.0
    ..style = PaintingStyle.stroke
    ..color = Colors.white;
  void _drawOutline(Canvas canvas, Offset c, double width, double height) {
    y.forEach((p) {
      final rect = Rect.fromCenter(center: c, width: width, height: height);
      canvas.drawRect(rect, outlinePaint);
      c += Offset(width, 0);
    });
  }

  List<String> _computeLabels() {
    return y.map((yp) => yp.toStringAsFixed(1)).toList();
  }

  TextPainter measureText(
      String s, TextStyle style, double maxwidth, TextAlign align) {
    final span = TextSpan(text: s, style: style);
    final tp = TextPainter(
        text: span, textAlign: align, textDirection: TextDirection.ltr);
    tp.layout(minWidth: 0, maxWidth: maxwidth);
    return tp;
  }

  Size drawTextCentered(
      Canvas canvas, Offset c, String text, TextStyle style, double maxwidth) {
    final tp = measureText(text, style, maxwidth, TextAlign.center);
    final offset = c + Offset(-tp.width / 2.0, -tp.height / 2.0);
    tp.paint(canvas, offset);
    return tp.size;
  }
}
</code>```

In cubicTO() Method we assign 3 points one for control points to draw a curve . and One for Starting point and another for end point I'm confused about points and math

Body:
I'm Learning Custom Paint and I'm Confused About Them i referred Few Documentation but Still i'm Lacking on it.

Referrence:Curved Chart,
Paths

Some of the Code I have Mentioned Here ..Pls Help Me out of This....

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class ChartPainter extends CustomPainter {
  final List<String> x;
  final List<double> y;
  final double min, max;

  ChartPainter(this.x, this.y, this.min, this.max);

  final yLabelStyle = const TextStyle(color: Colors.white, fontSize: 14);
  final xLabelStyle = const TextStyle(
      color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold);
  static double border = 10.0;
  static double radius = 5.0;
  final dotPaintFill = Paint()
    ..color = Colors.black
    ..style = PaintingStyle.fill
    ..strokeWidth = 2;
  final linePaint = Paint()
    ..color = Colors.white
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;
  @override
  void paint(Canvas canvas, Size size) {
    final clipRect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.clipRect(clipRect);
    canvas.drawPaint(Paint()..color = Colors.black);

    final drawableHeight = size.height / 10.0 * border;
    final drawableWidth = size.width / 15 * border;
    final leftPadding = size.width / 6;
    final rightPadding = size.width / 1000;
    final hd = drawableHeight / 5.0;
    final wd = drawableWidth / x.length.toDouble();
    final height = hd * 3.0;
    final width = drawableWidth;
    if (height <= 0.0 || width <= 0.00) return;
    if (max - min < 1.0e-6) return;
    final hr = height / (max - min);
    final left = border;
    final top = border;
    final c = Offset(left + wd / 2.0, top + height / 2.0);

    _drawOutline(canvas, c, wd, height);
    final points = _computePoints(c, wd, height, hr);

    final fillpath = _computePath(
        points, drawableHeight, width, true, leftPadding, rightPadding);
    final labels = _computeLabels();

    canvas.drawPath(fillpath, linePaint);

    // drawvertical(canvas, c, wd, height, hr, wd);
    _drawDataPoints(canvas, points, dotPaintFill, linePaint);
    _drawYLabels(canvas, labels, points, wd, top);
    // final c1 = Offset(c.dx, top + 4 * hd);
    // _drawXLabels(canvas, c1, wd);
  }

  void _drawXLabels(Canvas canvas, Offset c, double wd) {
    x.forEach((xp) {
      drawTextCentered(canvas, c, xp, xLabelStyle, wd);
      c += Offset(wd, 0);
    });
  }

  void _drawYLabels(Canvas canvas, List<String> labels, List<Offset> points,
      double wd, double top) {
    var i = 0;
    labels.forEach((label) {
      final dp = points[i];
      final dy = (dp.dy - 15.0) < top ? 15.0 : -15.0;
      final ly = dp + Offset(0, dy);
      drawTextCentered(canvas, ly, label, yLabelStyle, wd);
      i++;
    });
  }

  void _drawDataPoints(
      Canvas canvas, List<Offset> points, Paint dotPaintFill, Paint linePaint) {
    points.forEach((dp) {
      canvas.drawCircle(dp, radius, dotPaintFill);
      canvas.drawCircle(dp, radius, linePaint);
    });
  }

  Path _computePath(List<Offset> points, double h, double w, bool cp,
      double leftPadding, double rightPadding) {

    Path path = Path();

    for (var i = 0; i < points.length; i++) {
      final p = points[i];
      if (i == 0) {
        path.moveTo(p.dx, p.dy);
        path.lineTo(p.dx, p.dy);
      } else {
        path.lineTo(p.dx, p.dy);
      }
    }

    return path;
  }

  List<Offset> _computePoints(
      Offset c, double width, double height, double hr) {
    List<Offset> points = [];
    y.forEach((yp) {
      final yy = height - (yp - min) * hr;
      final dp = Offset(c.dx, c.dy - height / 2.0 + yy);
      points.add(dp);
      c += Offset(width, 0);
    });
    return points;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  final Paint outlinePaint = Paint()
    ..strokeWidth = 1.0
    ..style = PaintingStyle.stroke
    ..color = Colors.white;
  void _drawOutline(Canvas canvas, Offset c, double width, double height) {
    y.forEach((p) {
      final rect = Rect.fromCenter(center: c, width: width, height: height);
      canvas.drawRect(rect, outlinePaint);
      c += Offset(width, 0);
    });
  }

  List<String> _computeLabels() {
    return y.map((yp) => yp.toStringAsFixed(1)).toList();
  }

  TextPainter measureText(
      String s, TextStyle style, double maxwidth, TextAlign align) {
    final span = TextSpan(text: s, style: style);
    final tp = TextPainter(
        text: span, textAlign: align, textDirection: TextDirection.ltr);
    tp.layout(minWidth: 0, maxWidth: maxwidth);
    return tp;
  }

  Size drawTextCentered(
      Canvas canvas, Offset c, String text, TextStyle style, double maxwidth) {
    final tp = measureText(text, style, maxwidth, TextAlign.center);
    final offset = c + Offset(-tp.width / 2.0, -tp.height / 2.0);
    tp.paint(canvas, offset);
    return tp.size;
  }
}

In cubicTO() Method we assign 3 points one for control points to draw a curve . and One for Starting point and another for end point I'm confused about points and math


问:
Problem to clearly differentiate contour levels in contourf
I try to get a useful plot with contourf using (107,107) arrays multiplying with a proportional factor. I use the following code:

```<code>con_sun_mass = 1.98892e+30
C=3.04

a=np.logspace(np.log10(0.02*1e-06),np.log10(10*1e-06),107)
b=np.linspace(con_sun_mass*1e-17,con_sun_mass*1e-13,107)

A, B= np.meshgrid(a,b )

fig,ax=plt.subplots(1,1)

test=B*np.abs(f1[:,7])/((B*np.abs(f2[:,7])+(B*f3[:,7]+C)))

cp = ax.contourf(A, B,test,levels=100,cmap="seismic",extend='both')
plt.colorbar(cp).set_label("P")
ax.set_xlabel("a")
ax.set_ylabel('b')
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useMathText=True)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)
plt.savefig("relation.png")
plt.show()

</code>```

The exact forms of the (107,107) arrays f1, f2 and f3 are not important, but they all should increase with increasing B so that according to the equation for test, test should increase with increasing values of b.
The result is:

But as you can see, it seems like constant contourlevels with increasing B which is strange. I also tried to use pcolormesh and imshow instead of contourf but they seem not to work with my numpy arrays. Does anyone know what could I possibly do to observe differences on the axis for "b"?

Body:
I try to get a useful plot with contourf using (107,107) arrays multiplying with a proportional factor. I use the following code:

con_sun_mass = 1.98892e+30
C=3.04

a=np.logspace(np.log10(0.02*1e-06),np.log10(10*1e-06),107)
b=np.linspace(con_sun_mass*1e-17,con_sun_mass*1e-13,107)

A, B= np.meshgrid(a,b )

fig,ax=plt.subplots(1,1)

test=B*np.abs(f1[:,7])/((B*np.abs(f2[:,7])+(B*f3[:,7]+C)))

cp = ax.contourf(A, B,test,levels=100,cmap="seismic",extend='both')
plt.colorbar(cp).set_label("P")
ax.set_xlabel("a")
ax.set_ylabel('b')
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useMathText=True)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)
plt.savefig("relation.png")
plt.show()

The exact forms of the (107,107) arrays f1, f2 and f3 are not important, but they all should increase with increasing B so that according to the equation for test, test should increase with increasing values of b.
The result is:

But as you can see, it seems like constant contourlevels with increasing B which is strange. I also tried to use pcolormesh and imshow instead of contourf but they seem not to work with my numpy arrays. Does anyone know what could I possibly do to observe differences on the axis for "b"?


问:
Odd error when adding target: 'es5' to webpack.config.js file
I have been trying to learn full stack web development and began learning webpack and babel. I was starting very slow, I haven't even added any non development dependencies like react or electron yet. I am just attempting to understand the basics of how babel and webpack operate when used in conjunction. I have gotten my webpack file and it worked perfectly fine before I added the target: "es5", line. It now looks like:

```<code>module.exports = {
  entry: './src/index.js',
  target: "es5",
  module: {
    rules: [{
      test: /\.js$/,
      use: {
        loader: 'babel-loader'
      }
    }]
  }
}
</code>```

which worked perfectly fine when it was converting the files to es5, but the webpack syntax used newer versions. When attempting to make webpack convert its own syntax to es5 - via the target: "es5", line - by running the command npx webpack --config webpack.config.js --mode=development it gives me the following error.

```<code>Error: For the selected environment is no default script chunk format available:
JSONP Array push can be chosen when 'document' or 'importScripts' is available.
CommonJs exports can be chosen when 'require' or node builtins are available.
Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.
</code>```

Why am I getting this error and how is it remedied?

I should also note that I do have a separate file called babel.config.js that includes the following.

```<code>module.exports = {
  presets: ["@babel/preset-env"]
}
</code>```

Body:
I have been trying to learn full stack web development and began learning webpack and babel. I was starting very slow, I haven't even added any non development dependencies like react or electron yet. I am just attempting to understand the basics of how babel and webpack operate when used in conjunction. I have gotten my webpack file and it worked perfectly fine before I added the target: "es5", line. It now looks like:

module.exports = {
  entry: './src/index.js',
  target: "es5",
  module: {
    rules: [{
      test: /\.js$/,
      use: {
        loader: 'babel-loader'
      }
    }]
  }
}

which worked perfectly fine when it was converting the files to es5, but the webpack syntax used newer versions. When attempting to make webpack convert its own syntax to es5 - via the target: "es5", line - by running the command npx webpack --config webpack.config.js --mode=development it gives me the following error.

Error: For the selected environment is no default script chunk format available:
JSONP Array push can be chosen when 'document' or 'importScripts' is available.
CommonJs exports can be chosen when 'require' or node builtins are available.
Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.

Why am I getting this error and how is it remedied?

I should also note that I do have a separate file called babel.config.js that includes the following.

module.exports = {
  presets: ["@babel/preset-env"]
}


问:
How to let multiple web address (http) point to the smae webpage
I want 3 or more web address (http) point to the smae webpage, how to do so

in python or html,css,javascript way

http://192.168.0.206:8080/english/index.html

http://192.168.0.206:8080/english/apple

http://192.168.0.206:8080/english?fruit_ID=001

I have done the learning about flask, can command in web address, but still need a hand

is a concept question so that I don't post the code, I just need the key word for this idea, so that I can look it up too, or luckily if someone know ho to do, thanks

I have read through the discussion, the Http Redirection code 3XX in python requests was the closest, but that one not slove my problem


问:
Grouped list as horizontal and it's item list as vertical list in Xamarin forms
I have a List with a grouped list with a key and items as a list.

```<code>public List<GeneralServiceLevelClaimPaidAriGroupData> ariGroupedData = new List<GeneralServiceLevelClaimPaidAriGroupData>();

public class GeneralServiceLevelClaimPaidAriGroupData : List<GeneralServiceLevelClaimPaidAriData>
    {
        public string yearMonth { get; private set; }

        public GeneralServiceLevelClaimPaidAriGroupData(string name, List<GeneralServiceLevelClaimPaidAriData> listData) : base(listData)
        {
            yearMonth = name;
        }
    }
</code>```

Here yearMonth is the grouped key/name.

What I want is to display grouped key/name as a horizontal list and each group key/name items as a vertical list. I am using CollectionView and I can only display everything horizontally. I don't know how to implement the vertical list.

Viewmodel

```<code> public List<GeneralServiceLevelClaimPaidAriGroupData> AriList
        {
            get => _ariList;
            set
            {
                _ariList = value;
                OnPropertyChanged();
            }
        }

        private List<GeneralServiceLevelClaimPaidAriGroupData> _ariList;

AriList = ariGroupedData;
</code>```

Xaml

```<code>    <CollectionView ItemsSource="{Binding AriList}" ItemsLayout="HorizontalList" IsGrouped="true">
        <CollectionView.GroupHeaderTemplate>
            <DataTemplate>
                <Frame BackgroundColor="LightGray" CornerRadius="10" Margin="5">
                    <Label Text="{Binding yearMonth}" FontAttributes="Bold" />
                </Frame>
            </DataTemplate>
        </CollectionView.GroupHeaderTemplate>
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Grid ColumnDefinitions="*,*" Padding="10">
                        <Label Grid.Column="0" Text="{Binding category}" TextColor="Black" />
                        <Label Grid.Column="1" Text="{Binding count}" TextColor="Black" />
                    </Grid>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</code>```

Body:
I have a List with a grouped list with a key and items as a list.

public List<GeneralServiceLevelClaimPaidAriGroupData> ariGroupedData = new List<GeneralServiceLevelClaimPaidAriGroupData>();

public class GeneralServiceLevelClaimPaidAriGroupData : List<GeneralServiceLevelClaimPaidAriData>
    {
        public string yearMonth { get; private set; }

        public GeneralServiceLevelClaimPaidAriGroupData(string name, List<GeneralServiceLevelClaimPaidAriData> listData) : base(listData)
        {
            yearMonth = name;
        }
    }

Here yearMonth is the grouped key/name.

What I want is to display grouped key/name as a horizontal list and each group key/name items as a vertical list. I am using CollectionView and I can only display everything horizontally. I don't know how to implement the vertical list.

Viewmodel

 public List<GeneralServiceLevelClaimPaidAriGroupData> AriList
        {
            get => _ariList;
            set
            {
                _ariList = value;
                OnPropertyChanged();
            }
        }

        private List<GeneralServiceLevelClaimPaidAriGroupData> _ariList;

AriList = ariGroupedData;

Xaml

    <CollectionView ItemsSource="{Binding AriList}" ItemsLayout="HorizontalList" IsGrouped="true">
        <CollectionView.GroupHeaderTemplate>
            <DataTemplate>
                <Frame BackgroundColor="LightGray" CornerRadius="10" Margin="5">

                </Frame>
            </DataTemplate>
        </CollectionView.GroupHeaderTemplate>
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Grid ColumnDefinitions="*,*" Padding="10">

                    </Grid>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>


问:
Is it possible to trace the last updated password in the embedded LDAP for Weblogic?
For security reason we want to see the last password change for each user within the embedded LDAP server on Weblogic.
Is that possible?</p>


问:
Parsing preferred phonenumbers with CNPhoneNumber from vcf-file
I try to parse a vcf-file. I use CNContact for this. That works quite well, but with the phonenumbers i have a problem.

With CNLabeledValue<CNPhoneNumber*>* I get the label (e. g. "home") and the phonenumber in the value.

Excerpt from the vCard:

TEL;TYPE=home:1234567890

But if the number is tagged with a "pref" i can't get this tag for the phonenumber.

Excerpt from the vCard:

TEL;TYPE=home,pref:0987654321

Is there anyway to find out, which numbers are the preferred numbers?

I use following code:

```<code>for (CNLabeledValue<CNPhoneNumber*>* number in cnContact.phoneNumbers) {
 NSString *label = number.label;
 NSString *number = ((CNPhoneNumber*)number).stringValue;

  //Do some work with label and number
}
</code>```

Body:
I try to parse a vcf-file. I use CNContact for this. That works quite well, but with the phonenumbers i have a problem.

With CNLabeledValue<CNPhoneNumber*>* I get the label (e. g. "home") and the phonenumber in the value.

Excerpt from the vCard:

TEL;TYPE=home:1234567890

But if the number is tagged with a "pref" i can't get this tag for the phonenumber.

Excerpt from the vCard:

TEL;TYPE=home,pref:0987654321

Is there anyway to find out, which numbers are the preferred numbers?

I use following code:

for (CNLabeledValue<CNPhoneNumber*>* number in cnContact.phoneNumbers) {
 NSString *label = number.label;
 NSString *number = ((CNPhoneNumber*)number).stringValue;

  //Do some work with label and number
}


问:
Flutter windows desktop application showing black screen on application launch
Flutter windows desktop application showing black screen on application launch

I am try to run windows desktop application in windows 64bit system but application showing black screen on application launch. please help me out


问:
Wrong encoding with gclid attribut in link from google ads
When we have an Google Ad linking to our site the encoding changes

This works: https://www.safeaid.se/utbildningskategori/hlr-utbildningar/

But not this: https://www.safeaid.se/utbildningskategori/hlr-utbildningar/?gclid=

Can I control that in some way?

We created a normal ad and linked it to our site. I expected the site to look normal but have never seen this problem before.


问:
Using the backtick key for snippet expansion in LaTeX Workshop, Hypersnips and VSCode
I have found hypersnips faster than native LaTeX Workshop snippets for typing greek symbols. I would like to use the backtick ` key followed by a mnemonic for some snippets such as:

```<code>context math(context)
snippet `a "alpha" iA
\alpha
endsnippet
</code>```

At present, in LaTeX Workshop, the backtick key gets autocompleted due to the following setting:

```<code>    "autoClosingPairs": [
         ["`", "'"]
    ]
</code>```

in latex-language-configuration.json. See here

As a result, when I press backtick, I end up with `|' where | is the cursor position.

Pressing a after this expands to:

\alpha '

After trigger expansion, is it possible to automatically delete the trailing ' so that one is left with \alpha  ?

Thank you.

Body:
I have found hypersnips faster than native LaTeX Workshop snippets for typing greek symbols. I would like to use the backtick ` key followed by a mnemonic for some snippets such as:

context math(context)
snippet `a "alpha" iA
\alpha
endsnippet

At present, in LaTeX Workshop, the backtick key gets autocompleted due to the following setting:

    "autoClosingPairs": [
         ["`", "'"]
    ]

in latex-language-configuration.json. See here

As a result, when I press backtick, I end up with `|' where | is the cursor position.

Pressing a after this expands to:

\alpha '

After trigger expansion, is it possible to automatically delete the trailing ' so that one is left with \alpha  ?

Thank you.


问:
SQLSTATE[HY000] [335544721] Unable to complete network request to host "localhost". (SQL: select * from "ADMIN" where "LOGIN" = admin)?
I want to connect the database using a remote server, but I get an error. I use Laravel and Firebird
enter image description here</p>
```<code>  'connections' => [
        'firebird' => [
            'driver' => 'firebird',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3050'),
            'database' => env('DB_DATABASE', 'C:\Reports\AVIA.FDB'),
            'username' => env('DB_USERNAME', 'SYSDBA'),
            'password' => env('DB_PASSWORD', 'masterkey'),
            'charset' => env('DB_CHARSET', 'UTF8'),
            'engine_version' => '3.0.0',
        ],
</code>```

Body:
I want to connect the database using a remote server, but I get an error. I use Laravel and Firebird
enter image description here

  'connections' => [
        'firebird' => [
            'driver' => 'firebird',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3050'),
            'database' => env('DB_DATABASE', 'C:\Reports\AVIA.FDB'),
            'username' => env('DB_USERNAME', 'SYSDBA'),
            'password' => env('DB_PASSWORD', 'masterkey'),
            'charset' => env('DB_CHARSET', 'UTF8'),
            'engine_version' => '3.0.0',
        ],


问:
I was checking pytest version after i installed it successfully
```<code>C:\Users\Asmita>pytest --version
Fatal error in launcher: Unable to create process using '"C:\Users\Asmita\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"  "C:\Users\Asmita\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts\pytest.exe" --version': The system cannot find the path specified.
</code>```

I wanted to check pytest version on my pc, it shows

```<code>C:\Users\Asmita>pytest --version
Fatal error in launcher: Unable to create process using '"C:\Users\Asmita\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"  "C:\Users\Asmita\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts\pytest.exe" --version': The system cannot find the path specified.
</code>```

Body:
C:\Users\Asmita>pytest --version
Fatal error in launcher: Unable to create process using '"C:\Users\Asmita\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"  "C:\Users\Asmita\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts\pytest.exe" --version': The system cannot find the path specified.

I wanted to check pytest version on my pc, it shows

C:\Users\Asmita>pytest --version
Fatal error in launcher: Unable to create process using '"C:\Users\Asmita\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"  "C:\Users\Asmita\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts\pytest.exe" --version': The system cannot find the path specified.


问:
AWS Cloudformation nested stacks templates - how do handle local development and versioning?
Just started a simple AWS serverless project to test it out, so I'm developing locally and hosting the project on GitLab.

Wanna try nested stacks just to split current template file into smaller pieces, but TemplateUrl property value must be an url to a template file located in an S3 bucket, so I can't simply move my stack resources to another local yaml file and just include it in the parent one.

Manually upload nested stacks template files to an S3 bucket and than running sam sync from my console looks too intricate IMHO, and setting up a pipeline that take care of all the process too looks too much work for a simple personal learning project.

The fastest solution seems to be replace a deplyment pipeline with a script that can be run locally.

I know AWS cloud services are meant for enterpries-grade projects, but I'm wondering if there is a simpler and built-in/official way to handle all of this.


问:
İdentityServer4 ResourceOwnerPassword granttype always return 401 unauthorized in api controller
I want to use identityserver4 in my api. But my controller always returns a 401 (unauthorized) response. What is the mistake here? I use localapiauthentication and .net6.0

```<code>public class Startup
{
    public IWebHostEnvironment Environment { get; }
    public IConfiguration Configuration { get; }

    public Startup(IWebHostEnvironment environment, IConfiguration configuration)
    {
        Environment = environment;
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        var builder = services.AddIdentityServer(options =>
        {
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;

            // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
            options.EmitStaticAudienceClaim = true;
        })
            .AddInMemoryIdentityResources(Config.IdentityResources)
            .AddInMemoryApiResources(Config.ApiResources)
            .AddInMemoryApiScopes(Config.ApiScopes)
            .AddInMemoryClients(Config.Clients)
            .AddAspNetIdentity<ApplicationUser>();

        // not recommended for production - you need to store your key material somewhere secure
        builder.AddDeveloperSigningCredential();

        services.AddAuthentication();
        services.AddLocalApiAuthentication();
    }

    public void Configure(IApplicationBuilder app)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
           // app.UseDatabaseErrorPage();
        }

        app.UseStaticFiles();

        app.UseRouting();
        app.UseIdentityServer();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
}

public static class Config
{
    public static IEnumerable<ApiResource> ApiResources => new ApiResource[]
    {
        new ApiResource(LocalApi.AuthenticationScheme)
    };
    public static IEnumerable<IdentityResource> IdentityResources =>
               new IdentityResource[]
               {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
               };

    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[]
        {
            new ApiScope("scope1"),
            new ApiScope("scope2"),
            new ApiScope(LocalApi.AuthenticationScheme)
        };

    public static IEnumerable<Client> Clients =>
        new Client[]
        {
           new Client
            {
                ClientId = "api",
                ClientName = "Client username and password",

                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                ClientSecrets = { new Secret("secret".Sha256()) },

                AllowedScopes = { "scope1", LocalApi.AuthenticationScheme }
            },
        };
}

[Authorize(LocalApi.AuthenticationScheme)]
[ApiController]
[Route("identity/users")]
public class UserController : ControllerBase
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet]
    public IActionResult GetUsers()
    {
        return Ok(_userManager.Users.ToList());
    }
}
</code>```

Body:
I want to use identityserver4 in my api. But my controller always returns a 401 (unauthorized) response. What is the mistake here? I use localapiauthentication and .net6.0

public class Startup
{
    public IWebHostEnvironment Environment { get; }
    public IConfiguration Configuration { get; }

    public Startup(IWebHostEnvironment environment, IConfiguration configuration)
    {
        Environment = environment;
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        var builder = services.AddIdentityServer(options =>
        {
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;

            // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
            options.EmitStaticAudienceClaim = true;
        })
            .AddInMemoryIdentityResources(Config.IdentityResources)
            .AddInMemoryApiResources(Config.ApiResources)
            .AddInMemoryApiScopes(Config.ApiScopes)
            .AddInMemoryClients(Config.Clients)
            .AddAspNetIdentity<ApplicationUser>();

        // not recommended for production - you need to store your key material somewhere secure
        builder.AddDeveloperSigningCredential();

        services.AddAuthentication();
        services.AddLocalApiAuthentication();
    }

    public void Configure(IApplicationBuilder app)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
           // app.UseDatabaseErrorPage();
        }

        app.UseStaticFiles();

        app.UseRouting();
        app.UseIdentityServer();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
}

public static class Config
{
    public static IEnumerable<ApiResource> ApiResources => new ApiResource[]
    {
        new ApiResource(LocalApi.AuthenticationScheme)
    };
    public static IEnumerable<IdentityResource> IdentityResources =>
               new IdentityResource[]
               {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
               };

    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[]
        {
            new ApiScope("scope1"),
            new ApiScope("scope2"),
            new ApiScope(LocalApi.AuthenticationScheme)
        };

    public static IEnumerable<Client> Clients =>
        new Client[]
        {
           new Client
            {
                ClientId = "api",
                ClientName = "Client username and password",

                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                ClientSecrets = { new Secret("secret".Sha256()) },

                AllowedScopes = { "scope1", LocalApi.AuthenticationScheme }
            },
        };
}

[Authorize(LocalApi.AuthenticationScheme)]
[ApiController]
[Route("identity/users")]
public class UserController : ControllerBase
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet]
    public IActionResult GetUsers()
    {
        return Ok(_userManager.Users.ToList());
    }
}


问:
NPM, force reinstall of a local package
I have an angular application that uses a local external package packaged with

```<code>npx webpack && npm pack
</code>```

that creates a [package]-[version].tgz and installs in the main application with

```<code>npm i [../relative/path/to]/[package]-[version].tgz
</code>```

The problem is, everytime I make a change to the package, to make NPM install the new version I have to change the version on the package, effectively swapping everytime from version A and version B, otherwise the changes are ignored.

Is there a way to force NPM to reinstall the package without changing version? I tried every combination I could find on the net (even npm uninstall [package] && npm cache clear --force && npm i [../relative/path/to]/[package]-[version].tgz --force  && npm cache clear --force) to no avail.

Node is v14.19.1, NPM is 6.14.16

Title: NPM, force reinstall of a local package

Body:
I have an angular application that uses a local external package packaged with

npx webpack && npm pack

that creates a [package]-[version].tgz and installs in the main application with

npm i [../relative/path/to]/[package]-[version].tgz

The problem is, everytime I make a change to the package, to make NPM install the new version I have to change the version on the package, effectively swapping everytime from version A and version B, otherwise the changes are ignored.

Is there a way to force NPM to reinstall the package without changing version? I tried every combination I could find on the net (even npm uninstall [package] && npm cache clear --force && npm i [../relative/path/to]/[package]-[version].tgz --force  && npm cache clear --force) to no avail.

Node is v14.19.1, NPM is 6.14.16


问:
unable to decode "STDIN" error on K8s YAML after adding labels
I have a k8s deployment yaml file that has a Deployment, 2 Services and an API Gateway. Prior to my edits I had just one label for all except the API Gateway. The edits I made are adding the following labels to all the documents:

```<code>labels:
  app: ${name}
  example.label.name/1: 250
  example.label.name/2: example-value
  example.label.name/3: ${exampleValue}
</code>```

NOTE: the app label already existed on all of them except the API Gateway.

I have tried wrapping the label names and/or its values in quotes but that hasn't fixed the issue. When I run the script that uses the YAML file it does it 4 times (its running 4 times in a loop per 4 applications). So when I run the script, I see this error 4 times:

unable to decode "STDIN": json: cannot unmarshal number into Go struct field ObjectMeta.metadata.labels of type string

Body:
I have a k8s deployment yaml file that has a Deployment, 2 Services and an API Gateway. Prior to my edits I had just one label for all except the API Gateway. The edits I made are adding the following labels to all the documents:

labels:
  app: ${name}
  example.label.name/1: 250
  example.label.name/2: example-value
  example.label.name/3: ${exampleValue}

NOTE: the app label already existed on all of them except the API Gateway.

I have tried wrapping the label names and/or its values in quotes but that hasn't fixed the issue. When I run the script that uses the YAML file it does it 4 times (its running 4 times in a loop per 4 applications). So when I run the script, I see this error 4 times:

unable to decode "STDIN": json: cannot unmarshal number into Go struct field ObjectMeta.metadata.labels of type string