问:
redis.lrange is not a function running in node.js and redis
I am working on the latest redis with node.js.

I have run the similar code as below which works out.

```<code>const client = redis.createClient();
await client.connect();
let lastMsg = await client.get("device:"+id);
await client.disconnect();
</code>```

But running the code below troubles me

```<code>const redis = require("redis");
const id = 1;
const client = redis.createClient();
await client.connect();
let results = await client.lrange(`device:messages:${id}`, 0, -1);
await client.disconnect();
</code>```

when running the code, it throws out an error saying "TypeError: client.lrange is not a function". I don't figure out what goes wrong .

Body:
I am working on the latest redis with node.js.

I have run the similar code as below which works out.

const client = redis.createClient();
await client.connect();
let lastMsg = await client.get("device:"+id);
await client.disconnect();

But running the code below troubles me

const redis = require("redis");
const id = 1;
const client = redis.createClient();
await client.connect();
let results = await client.lrange(`device:messages:${id}`, 0, -1);
await client.disconnect();

when running the code, it throws out an error saying "TypeError: client.lrange is not a function". I don't figure out what goes wrong .


来源: stackexchange

问:
How to force an event to be executed right after animation has ended in React
I'm trying to work on responsiveness of my react project. When it comes to a mobile screen I used a hamburger icon to show and hide the navigation bar (translating from -150px to 0 along x when showing and from 0 to -150px when hiding),and I use animation dynamically for that, when it comes to showing the naviation bar the animation is executed perfectly in the duration I specified, but when I hide it it happens immediately eventhough I created an eventListener on an animation end.

here is the code:

```<code>const [isHamburgerClicked, setIsHamburgerClicked] = useState(false);
let keyFrames = [];

const handleClick = () => {
  if (isHamburgerClicked) {
    setIsHamburgerClicked(!isHamburgerClicked);
  } else {
    setIsHamburgerClicked(!isHamburgerClicked);
  }
};

useEffect(() => {
  const menu = document.getElementById("navbarcontainer");
  const duration = 500;
  if (isHamburgerClicked) {
    keyFrames = [
      { transform: "translateX(-150px)" },
      { transform: "translateX(0)" }
    ];
    menu.animate(keyFrames, duration);
    menu.style.left = "0";
  } else {
    keyFrames = [
      { transform: "translateX(0)" },
      { transform: "translateX(-150px)" }
    ];
    menu.animate(keyFrames, duration);
    menu.addEventListener("animationend", animationEnded(menu));
  }
}, [isHamburgerClicked]);

function animationEnded(menu) {
  console.log("animationend fired");
  menu.style.left = "-150px";
}
</code>```

css:

```<code>.navBarContainer {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  background-color: #006bff;
  position: fixed;
  top: 0;
  z-index: 5;
}

@media only screen and (max-width: 320px) {
  .navBarContainer {
    display: block;
    width: 150px;
    opacity: 0.8;
    padding: 0;
    margin: 0;
    top: 0;
    left: -150px;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to work on responsiveness of my react project. When it comes to a mobile screen I used a hamburger icon to show and hide the navigation bar (translating from -150px to 0 along x when showing and from 0 to -150px when hiding),and I use animation dynamically for that, when it comes to showing the naviation bar the animation is executed perfectly in the duration I specified, but when I hide it it happens immediately eventhough I created an eventListener on an animation end.

here is the code:

const [isHamburgerClicked, setIsHamburgerClicked] = useState(false);
let keyFrames = [];

const handleClick = () => {
  if (isHamburgerClicked) {
    setIsHamburgerClicked(!isHamburgerClicked);
  } else {
    setIsHamburgerClicked(!isHamburgerClicked);
  }
};

useEffect(() => {
  const menu = document.getElementById("navbarcontainer");
  const duration = 500;
  if (isHamburgerClicked) {
    keyFrames = [
      { transform: "translateX(-150px)" },
      { transform: "translateX(0)" }
    ];
    menu.animate(keyFrames, duration);
    menu.style.left = "0";
  } else {
    keyFrames = [
      { transform: "translateX(0)" },
      { transform: "translateX(-150px)" }
    ];
    menu.animate(keyFrames, duration);
    menu.addEventListener("animationend", animationEnded(menu));
  }
}, [isHamburgerClicked]);

function animationEnded(menu) {
  console.log("animationend fired");
  menu.style.left = "-150px";
}

css:

.navBarContainer {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  background-color: #006bff;
  position: fixed;
  top: 0;
  z-index: 5;
}

@media only screen and (max-width: 320px) {
  .navBarContainer {
    display: block;
    width: 150px;
    opacity: 0.8;
    padding: 0;
    margin: 0;
    top: 0;
    left: -150px;
  }
}


问:
How to attaching automation test results to ms teams channel?
I am currently running my automation (UI) tests on azure devops release pipeline using Playwright. Whenever the test run finishes I Need a notification to my teams using bot. but i face some issue like this enter image description here i am using playwright test runner

Now my question is: is it possible to use this https://www.npmjs.com/package/test-results-reporter NPM Package for playwright testing fream work


问:
How to implement this mentioned validation in Laravel 9 Validation?
I am trying to achieve certain laravel validation criteria which I am having hard time to implement. Please help me in the same. I am using laravel 9 & PHP 8.1

Description:

I have an API which has below mentioned inputs:

a. company_name - required

b. company_number - required as per condition

c. gst_number - required as per condition

d. county - required

e. state - required as per condition

f. source - required

//Scenario #1 - Small intro into Field Condition

where 'company_number' and 'gst_number' are 2 parameter which change from:

a. where both are not required at all

b. where either one of the field being required

c. to one of the either field being mandatory

based on source value entered.

//Scenario #1 - Detailed intro into Field Condition

a. If its source 1 then neither of them is required

b. If its source 2 then either one of them is required but not both & if both are present then it should throw validation error

c. If its any other source value then it should be company_number only and if other one is present then it show validation error

d. Unwanted field should throw validation error

//Scenario #2 - Country State Validation

a. There are 3 countries i.e. x,y,z in which state field is required else not & it should throw validation error if someone mentions it when not required

b. It should validate if the state mentioned belongs to that country or not. I have that state array list of those 3 countries

c. Here country & state are of 2 character in length which is ISO format, thus it should be of 2 digit only & in upper case only.

d. It should properly validate in both the cases of where the state is required & not required when state field is mentioned with blank value.

Now I know the Scenario #2, point 'c' can be done via regex but my main point is how to achieve all this with the all scenario points mentioned such that if all the points of both the scenarios fail then it should that many validation errors together.

//Example #1:

```<code>company_name:    //blank
company_number: 123
gst_number: 456 //This field is not required as per source value, thus it should throw validation error
country: AB   //Country in which state is not required, thus state not required validation should be triggered
state: cde    //This should trigger uppercase only validation & 2 char only validation
source: 3

//Intended output #1:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter company name."
        ]
    ],
    "gst_number": [
        [
            "gst_number is not required in this case"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}
</code>```

//Example #2:

```<code>company_name: ABC
company_number: //Blank
gst_number:   //Blank
country: AB   //Valid
state: CD    //Valid
source: 2

//Intended output #2:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "gst_number": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}
</code>```

//My Problem:

I am facing problem implementing country state mapping validation including its length & casing check. Is it valid country & state or not? Is it the country which can have state value?

Enabling, disabling the company number, gst_number validation depending upon source value.

//My current validation rule:

```<code> $rule = [
        'company_name' => ['required'],
            'country' => ['required', 'string', 'regex:/^[A-Z]{2}+$/', 'exists:table_name,field_name'],
            'company_number'=> ['required_without:gst_number'],
            'gst_number' => ['required_without:company_number', 'regex:/^([0-9]{2}[a-zA-z]{5}[0-9]{4}[a-zA-z]{1}[0-9]{1}Z{1}[0-9A-Za-z]{1})$/'],
            'state' => ['sometimes','regex:/^[A-Z]{2}+$/'],
            'source' => ['required', 'numeric', 'exists:table_name,field_name'],

        ];
</code>```

If someone is suggesting custom validation, I know the commands & how to get started but as I have never used it, it will be helpful if someone gives me example of using it with respective the validation criteria mentioned in this post.

Body:
I am trying to achieve certain laravel validation criteria which I am having hard time to implement. Please help me in the same. I am using laravel 9 & PHP 8.1

Description:

I have an API which has below mentioned inputs:

a. company_name - required

b. company_number - required as per condition

c. gst_number - required as per condition

d. county - required

e. state - required as per condition

f. source - required

//Scenario #1 - Small intro into Field Condition

where 'company_number' and 'gst_number' are 2 parameter which change from:

a. where both are not required at all

b. where either one of the field being required

c. to one of the either field being mandatory

based on source value entered.

//Scenario #1 - Detailed intro into Field Condition

a. If its source 1 then neither of them is required

b. If its source 2 then either one of them is required but not both & if both are present then it should throw validation error

c. If its any other source value then it should be company_number only and if other one is present then it show validation error

d. Unwanted field should throw validation error

//Scenario #2 - Country State Validation

a. There are 3 countries i.e. x,y,z in which state field is required else not & it should throw validation error if someone mentions it when not required

b. It should validate if the state mentioned belongs to that country or not. I have that state array list of those 3 countries

c. Here country & state are of 2 character in length which is ISO format, thus it should be of 2 digit only & in upper case only.

d. It should properly validate in both the cases of where the state is required & not required when state field is mentioned with blank value.

Now I know the Scenario #2, point 'c' can be done via regex but my main point is how to achieve all this with the all scenario points mentioned such that if all the points of both the scenarios fail then it should that many validation errors together.

//Example #1:

company_name:    //blank
company_number: 123
gst_number: 456 //This field is not required as per source value, thus it should throw validation error
country: AB   //Country in which state is not required, thus state not required validation should be triggered
state: cde    //This should trigger uppercase only validation & 2 char only validation
source: 3

//Intended output #1:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter company name."
        ]
    ],
    "gst_number": [
        [
            "gst_number is not required in this case"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}

//Example #2:

company_name: ABC
company_number: //Blank
gst_number:   //Blank
country: AB   //Valid
state: CD    //Valid
source: 2

//Intended output #2:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "gst_number": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}

//My Problem:

I am facing problem implementing country state mapping validation including its length & casing check. Is it valid country & state or not? Is it the country which can have state value?

Enabling, disabling the company number, gst_number validation depending upon source value.

//My current validation rule:

 $rule = [
        'company_name' => ['required'],
            'country' => ['required', 'string', 'regex:/^[A-Z]{2}+$/', 'exists:table_name,field_name'],
            'company_number'=> ['required_without:gst_number'],
            'gst_number' => ['required_without:company_number', 'regex:/^([0-9]{2}[a-zA-z]{5}[0-9]{4}[a-zA-z]{1}[0-9]{1}Z{1}[0-9A-Za-z]{1})$/'],
            'state' => ['sometimes','regex:/^[A-Z]{2}+$/'],
            'source' => ['required', 'numeric', 'exists:table_name,field_name'],

        ];

If someone is suggesting custom validation, I know the commands & how to get started but as I have never used it, it will be helpful if someone gives me example of using it with respective the validation criteria mentioned in this post.


问:
mysqli::real_connect(): (HY000/1045): Access denied for user '***'@'localhost' (using password: YES)
I installed the database on VDS (Linux Ubuntu 22.04), but I get an authorization error. As I understand it, you need to change "localhost" to my IP address. But in which file, what is the path of this file.

Help me please

Tried editing the config.inc.php file but it's not enough.


问:
Apple Pay - Recurring Payment
I am trying utilize recurring payments through Apple Pay. It appears that the payment session is setup correctly. The correct popup appears, indicating a immediate charge and a recurring payment, the the payment is successfully submitted to NMI and the response is sent back to the client.

Frontend Code:

```<code>function subscribe() {
        var request = {
          countryCode: 'US',
          currencyCode: 'USD',
          supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
          merchantCapabilities: ['supports3DS'],
          total: { label: 'Budmember', amount: packages?.Package_Amount__c.toFixed(2).toString()},
          recurringPaymentRequest: {
            managementURL:"https://7d50e9ae5e20.ngrok.io/billing",
            tokenNotificationURL:"https://webhook.site/8bb38a60-be08-47f5-82ba-2bdccc7ec4cf/",
            paymentDescription: "VIP Membership",
            regularBilling: {
              label: {amount: packages?.Package_Amount__c.toFixed(2).toString(), type: "final"},
              amount: packages?.Package_Amount__c.toFixed(2).toString(),
              paymentTiming: "recurring",
              recurringPaymentIntervalUnit: "month",
              recurringPaymentStartDate: moment().format("YYYY-MM-DD"),
            }},
          }

        //start apple Pay session
        var session = new window.ApplePaySession(3, request);
        session.begin()
        session.onvalidatemerchant = async (event) => {
            const res = await applePaySessionRequest(event.validationURL)
            console.log(res.data)
            session.completeMerchantValidation(res.data)
        }

        //submit payment to backend
        session.onpaymentauthorized = async (event) => {
          const dataPackage= {
          onboardingStep: '7',
          salesForceId: cognitoUser.salesForceId,
          packageId: packages?.Id,
            billingPackage: {
              first_name: currentUser.firstName,
              last_name:  currentUser.lastName,
              company: "",
              address1: "",
              address2: "",
              city: "",
              state: "",
              zip: "",
              country:"USA",
              phone: "",
              fax: "",
              email: currentUser.email,
          }
        }

            const res = await applePayInitialSub(event.payment, dataPackage )

            if (res?.data?.success) {
              //update token for new field in the token
              setOnboardingStep("7");
              localStorage.setItem("token", res.data.token || localStorage.getItem("token"));
              notification("Membership Payment Received","success","Payment Success");
              handleBillingAddress()

            } else {
              notification(res.data.msg || "Card Declined" , "danger" , "Error");
              setLoading(false)

            }
            session.completePayment({status: res.data.applePayMsg})

        }
      }
</code>```

Backend Code (Apple Pay Session):

```<code>async function applePaySession(req, res, next) {
const sessionURL = req.body.sessionURL
let response = {};
try {
function promisifyRequest(options) {
    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (body) {
          return resolve(res.send(body));
        }
        if (error) {
          return reject(error);
        }
      });
    });
}
  const options = {
    url: sessionURL,
    agentOptions: {
      pfx: fs.readFileSync("./merchant_id.p12"),
      passphrase: "SECRET",
    },
    method: 'post',
    body: {
        merchantIdentifier: "merchant.com.some.app",
        displayName: "NAME",
        initiative: "web",
        initiativeContext: "some.url" // Frontend url as registered
    },
    json: true,
  };
  response = await promisifyRequest(options);
  console.log(response)
} catch (error) {
  console.log(error)
}
return response;
</code>```

}

Backend Code (Payment and Subscribe):

```<code>async function appleSubProcessor(req, res, next) {
    try {
      const conn = sfConn();
      const { cognitoUserId, accessToken, email } = req.user.data
      const {billingPackage} = req.body
      const {onboardingStep, salesForceId, packageId} = billingPackage
      const member = await conn.sobject("Contact").find({"Email": email})
      const response = await NMI.getSubscriptionById(member[0].Subscription_ID__c)

      // PROCESSING CODE!!!!!
      //encodes data object to buffer
      const data = req.body.paymentObject.token.paymentData
      var buf = Buffer.from(JSON.stringify(data))
      //encodes buffer to hex string
      const hexCode = buf.toString("hex")

      //if subscription is present on NMI only charge
      if(response?.nm_response?.subscription?.subscription_id) {
        await applePaymentOnly(member, hexCode, billingPackage, email, res)
      } else {
        await applePayInitialSub(req, member, hexCode, res, cognitoUserId, accessToken, email, billingPackage)
      }
    } catch(err) {
      console.log(err)
    }
  }

async function applePayInitialSub(req, member, paymentToken, res, cognitoUserId, accessToken, email, billingPackage) {

try {
  const conn = sfConn()
  // const { cognitoUserId, accessToken, email } = req.user.data
  // const {billingPackage} = req.body
  const {onboardingStep, salesForceId, packageId} = billingPackage
  const subsc_data = await conn.sobject("Packages__c").find({"Id": packageId})
  const dueNow = subsc_data[0].Package_Amount__c.toFixed(2).toString()

  //Error handling - no package available
  if(!subsc_data || !subsc_data.length){
    console.log("Error")
    Sentry.withScope((scope) => {
      scope.setLevel("fatal");
      Sentry.captureException("Internal Error, Unable to get subscription data");
    })
    return res.json({
      success: false,
      message:"Internal Error. Unable to get subscription data"
    })
  }

  //sends request
  const response = await NMI.applePayInitialSubscription(billingPackage.billingPackage, paymentToken, dueNow, email, billingPackage.billingPackage.email)
  console.log(response)

onboarding logic ...
    }
</code>```

What I have tried so far:

Recharge the initial token. NMI returned "DO NOT HONOR". This indicated that Apple Pay was blocking the transaction. The card didn't have any fraud alert and I was able to charge it with a new token.

Set the subscription interval with Apple Pay to "minute" and attempted to re-charge the token after 60 seconds. Again, "DO NOT HONOR".

I set the tokenNotificationURL to an endpoint on my server. I tunneled to my localhost via NGROK for https. I was able to call the endpoint via postman. I followed the Apple Developer Docs. But didn't receive any hook calls from Apple.

I did step 3 with my webhook.site pro subscription. Postman call succeeded, no calls from Apple.

I searched StackOverflow for answers and found this post for Stripe. Here it is described that (with Stripe SDK) the paymentRequest comes with a "paymentmethod" listener which should return paymentMethod.id. I attempted to utilize AppleJS's onpaymentmethodselected to get access to the id but I only got paymentMethod: {type: "Credit"} as a response:

session.onpaymentmethodselected = async (event) => {
session.completePaymentMethodSelection({newTotal: { amount:"49.00", label:'VIP Membership'}})
}

I decrypted the payment token on the backend. I followed this guide to create the certificate and key (.pem) files. His package uses an outdated dependency that doesn't work on newer versions of Node. I used this package to decrypt the token. However, I was not able to charge the applicationPrimaryAccountNumber. AVS seems to be not allowed so providing the zip code doesn't yield a successful transaction either. Below is the decrypted token as well as the NMI response:

I searched on SO and in the Apple Developer forums but wasn't able to get anywhere with this. I have been working on this issue for the past 3 days. Any help is greatly appreciated!

Title: Apple Pay - Recurring Payment

Body:
I am trying utilize recurring payments through Apple Pay. It appears that the payment session is setup correctly. The correct popup appears, indicating a immediate charge and a recurring payment, the the payment is successfully submitted to NMI and the response is sent back to the client.

Frontend Code:

function subscribe() {
        var request = {
          countryCode: 'US',
          currencyCode: 'USD',
          supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
          merchantCapabilities: ['supports3DS'],
          total: { label: 'Budmember', amount: packages?.Package_Amount__c.toFixed(2).toString()},
          recurringPaymentRequest: {
            managementURL:"https://7d50e9ae5e20.ngrok.io/billing",
            tokenNotificationURL:"https://webhook.site/8bb38a60-be08-47f5-82ba-2bdccc7ec4cf/",
            paymentDescription: "VIP Membership",
            regularBilling: {
              label: {amount: packages?.Package_Amount__c.toFixed(2).toString(), type: "final"},
              amount: packages?.Package_Amount__c.toFixed(2).toString(),
              paymentTiming: "recurring",
              recurringPaymentIntervalUnit: "month",
              recurringPaymentStartDate: moment().format("YYYY-MM-DD"),
            }},
          }

        //start apple Pay session
        var session = new window.ApplePaySession(3, request);
        session.begin()
        session.onvalidatemerchant = async (event) => {
            const res = await applePaySessionRequest(event.validationURL)
            console.log(res.data)
            session.completeMerchantValidation(res.data)
        }

        //submit payment to backend
        session.onpaymentauthorized = async (event) => {
          const dataPackage= {
          onboardingStep: '7',
          salesForceId: cognitoUser.salesForceId,
          packageId: packages?.Id,
            billingPackage: {
              first_name: currentUser.firstName,
              last_name:  currentUser.lastName,
              company: "",
              address1: "",
              address2: "",
              city: "",
              state: "",
              zip: "",
              country:"USA",
              phone: "",
              fax: "",
              email: currentUser.email,
          }
        }

            const res = await applePayInitialSub(event.payment, dataPackage )

            if (res?.data?.success) {
              //update token for new field in the token
              setOnboardingStep("7");
              localStorage.setItem("token", res.data.token || localStorage.getItem("token"));
              notification("Membership Payment Received","success","Payment Success");
              handleBillingAddress()

            } else {
              notification(res.data.msg || "Card Declined" , "danger" , "Error");
              setLoading(false)

            }
            session.completePayment({status: res.data.applePayMsg})

        }
      }

Backend Code (Apple Pay Session):

async function applePaySession(req, res, next) {
const sessionURL = req.body.sessionURL
let response = {};
try {
function promisifyRequest(options) {
    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (body) {
          return resolve(res.send(body));
        }
        if (error) {
          return reject(error);
        }
      });
    });
}
  const options = {
    url: sessionURL,
    agentOptions: {
      pfx: fs.readFileSync("./merchant_id.p12"),
      passphrase: "SECRET",
    },
    method: 'post',
    body: {
        merchantIdentifier: "merchant.com.some.app",
        displayName: "NAME",
        initiative: "web",
        initiativeContext: "some.url" // Frontend url as registered
    },
    json: true,
  };
  response = await promisifyRequest(options);
  console.log(response)
} catch (error) {
  console.log(error)
}
return response;

}

Backend Code (Payment and Subscribe):

async function appleSubProcessor(req, res, next) {
    try {
      const conn = sfConn();
      const { cognitoUserId, accessToken, email } = req.user.data
      const {billingPackage} = req.body
      const {onboardingStep, salesForceId, packageId} = billingPackage
      const member = await conn.sobject("Contact").find({"Email": email})
      const response = await NMI.getSubscriptionById(member[0].Subscription_ID__c)

      // PROCESSING CODE!!!!!
      //encodes data object to buffer
      const data = req.body.paymentObject.token.paymentData
      var buf = Buffer.from(JSON.stringify(data))
      //encodes buffer to hex string
      const hexCode = buf.toString("hex")

      //if subscription is present on NMI only charge
      if(response?.nm_response?.subscription?.subscription_id) {
        await applePaymentOnly(member, hexCode, billingPackage, email, res)
      } else {
        await applePayInitialSub(req, member, hexCode, res, cognitoUserId, accessToken, email, billingPackage)
      }
    } catch(err) {
      console.log(err)
    }
  }

async function applePayInitialSub(req, member, paymentToken, res, cognitoUserId, accessToken, email, billingPackage) {

try {
  const conn = sfConn()
  // const { cognitoUserId, accessToken, email } = req.user.data
  // const {billingPackage} = req.body
  const {onboardingStep, salesForceId, packageId} = billingPackage
  const subsc_data = await conn.sobject("Packages__c").find({"Id": packageId})
  const dueNow = subsc_data[0].Package_Amount__c.toFixed(2).toString()

  //Error handling - no package available
  if(!subsc_data || !subsc_data.length){
    console.log("Error")
    Sentry.withScope((scope) => {
      scope.setLevel("fatal");
      Sentry.captureException("Internal Error, Unable to get subscription data");
    })
    return res.json({
      success: false,
      message:"Internal Error. Unable to get subscription data"
    })
  }

  //sends request
  const response = await NMI.applePayInitialSubscription(billingPackage.billingPackage, paymentToken, dueNow, email, billingPackage.billingPackage.email)
  console.log(response)

onboarding logic ...
    }

What I have tried so far:

Recharge the initial token. NMI returned "DO NOT HONOR". This indicated that Apple Pay was blocking the transaction. The card didn't have any fraud alert and I was able to charge it with a new token.

Set the subscription interval with Apple Pay to "minute" and attempted to re-charge the token after 60 seconds. Again, "DO NOT HONOR".

I set the tokenNotificationURL to an endpoint on my server. I tunneled to my localhost via NGROK for https. I was able to call the endpoint via postman. I followed the Apple Developer Docs. But didn't receive any hook calls from Apple.

I did step 3 with my webhook.site pro subscription. Postman call succeeded, no calls from Apple.

I searched StackOverflow for answers and found this post for Stripe. Here it is described that (with Stripe SDK) the paymentRequest comes with a "paymentmethod" listener which should return paymentMethod.id. I attempted to utilize AppleJS's onpaymentmethodselected to get access to the id but I only got paymentMethod: {type: "Credit"} as a response:

session.onpaymentmethodselected = async (event) => {
session.completePaymentMethodSelection({newTotal: { amount:"49.00", label:'VIP Membership'}})
}

I decrypted the payment token on the backend. I followed this guide to create the certificate and key (.pem) files. His package uses an outdated dependency that doesn't work on newer versions of Node. I used this package to decrypt the token. However, I was not able to charge the applicationPrimaryAccountNumber. AVS seems to be not allowed so providing the zip code doesn't yield a successful transaction either. Below is the decrypted token as well as the NMI response:

I searched on SO and in the Apple Developer forums but wasn't able to get anywhere with this. I have been working on this issue for the past 3 days. Any help is greatly appreciated!


问:
Magento 2 - MasterCard Payment Gateway Services
https://ontap.wiki/magento-mastercard-payment-gateway-services/

I added this extension on my website but trasaction is declined.

giving this response

'response' =>
array (
'error' =>
array (
'cause' => 'INVALID_REQUEST',
'explanation' => 'Value 'AUTHORIZE' is invalid. Authorization request not permitted for this merchant.',
'field' => 'apiOperation',
'validationType' => 'INVALID',
),
'result' => 'ERROR',
),

```<code>https://ontap.wiki/magento-mastercard-payment-gateway-services/
I added this extension on my website but trasaction is declined.

giving this response

'response' =>
  array (
    'error' =>
    array (
      'cause' => 'INVALID_REQUEST',
      'explanation' => 'Value \'AUTHORIZE\' is invalid. Authorization request not permitted for this merchant.',
      'field' => 'apiOperation',
      'validationType' => 'INVALID',
    ),
    'result' => 'ERROR',
  ),
</code>```

Body:
https://ontap.wiki/magento-mastercard-payment-gateway-services/

I added this extension on my website but trasaction is declined.

giving this response

'response' =>
array (
'error' =>
array (
'cause' => 'INVALID_REQUEST',
'explanation' => 'Value 'AUTHORIZE' is invalid. Authorization request not permitted for this merchant.',
'field' => 'apiOperation',
'validationType' => 'INVALID',
),
'result' => 'ERROR',
),

https://ontap.wiki/magento-mastercard-payment-gateway-services/
I added this extension on my website but trasaction is declined.

giving this response

'response' =>
  array (
    'error' =>
    array (
      'cause' => 'INVALID_REQUEST',
      'explanation' => 'Value \'AUTHORIZE\' is invalid. Authorization request not permitted for this merchant.',
      'field' => 'apiOperation',
      'validationType' => 'INVALID',
    ),
    'result' => 'ERROR',
  ),


问:
Why function BCryptImportKey generate exeption?
```<code>class Decrypt : Filefunc
{
public:
    Decrypt(std::string password)
    {
        fill_paths(paths);
        log.open("W:\\log.txt", std::ios::in | std::ios::out | std::ios::trunc);
        szPass = new TCHAR[passphrase.size() + 1];
        copy(passphrase.begin(), passphrase.end(), szPass);
        szPass[passphrase.size()] = 0;
        std::ifstream iFkey("W:\\key.key", std::ios_base::in | std::ios_base::binary);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_SHA256_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbHashObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHashObject);
        status = BCryptCreateHash
        (
            hAlg,
            &hHash,
            pbHashObject,
            cbHashObject,
            NULL,
            NULL,
            NULL
        );
        log << test_status("BCryptCreateHash", status);

        status = BCryptHashData
        (
            hHash,
            (PBYTE)szPass,
            _tcslen(szPass) * sizeof(TCHAR),
            NULL
            );
        log << test_status("BCryptHashData", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_HASH_LENGTH,
            (PBYTE)&cbHash,
            sizeof(DWORD),
            &cbData,
            NULL
        );
        log << test_status("BCryptGetProperty", status);

        pbHash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHash);

        status = BCryptFinishHash
        (
            hHash,
            pbHash,
            cbHash,
            0
        );
        log << test_status("BCryptFinishHash", status);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_AES_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbKeyObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbKeyObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbKeyObject);

        status = BCryptGenerateSymmetricKey
        (
            hAlg,
            &hKey,
            pbKeyObject,
            cbKeyObject,
            (PBYTE)pbHash,
            cbHash,
            NULL
        );
        log << test_status("BCryptGenerateSymmetricKey", status);

        iFkey.seekg(0, iFkey.end);
        length = iFkey.tellg();
        iFkey.seekg(0, iFkey.beg);
        impKeyBuf = new UCHAR[length];

        iFkey.read((char*)impKeyBuf, length);

         BCryptImportKey
        (
            hAlg,
            hKey,
            BCRYPT_AES_WRAP_KEY_BLOB,
            &hKeyImp,
            NULL,
            NULL,
            impKeyBuf,
            length,
            NULL
        );

        log << test_status("BCryptImportKey", status);
    }
}
</code>```

I am creating a program that encrypts all files on a USB flash drive. At the stage of importing the key, I get an exception that I can't analyze in any way. Exception text in the memcpy.asm file:

An exception was raised at 0x7C103B3F (vcruntime140d.dll ) in Zed_TEst.exe : 0xC0000005: violation of access rights when reading at 0x01010101.

The test_status function simply returns a string in which the status of functions from bcrypt is written
when I try to display the status in the console I get something strange

output: ╢
¶    ╖
"     э$♦"♦`☼}☺╕
     ♣  ♣╣
    ║
§     ь$☺§☺⌂♦╗
a     ↕А♦a♦╝
<     ь$♣<♣╜
▼     ь$♣▼♣1!.┐
w     ☺w☺♦а     →ЁЖ☻└
¶     ☼¶☼☺┴
♦    ┬
   ├
♥     ь$♣♥♣─
☺     ь$♣☺♣┼
   ╞
     ь$♣♣╟

Body:
class Decrypt : Filefunc
{
public:
    Decrypt(std::string password)
    {
        fill_paths(paths);
        log.open("W:\\log.txt", std::ios::in | std::ios::out | std::ios::trunc);
        szPass = new TCHAR[passphrase.size() + 1];
        copy(passphrase.begin(), passphrase.end(), szPass);
        szPass[passphrase.size()] = 0;
        std::ifstream iFkey("W:\\key.key", std::ios_base::in | std::ios_base::binary);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_SHA256_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbHashObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHashObject);
        status = BCryptCreateHash
        (
            hAlg,
            &hHash,
            pbHashObject,
            cbHashObject,
            NULL,
            NULL,
            NULL
        );
        log << test_status("BCryptCreateHash", status);

        status = BCryptHashData
        (
            hHash,
            (PBYTE)szPass,
            _tcslen(szPass) * sizeof(TCHAR),
            NULL
            );
        log << test_status("BCryptHashData", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_HASH_LENGTH,
            (PBYTE)&cbHash,
            sizeof(DWORD),
            &cbData,
            NULL
        );
        log << test_status("BCryptGetProperty", status);

        pbHash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHash);

        status = BCryptFinishHash
        (
            hHash,
            pbHash,
            cbHash,
            0
        );
        log << test_status("BCryptFinishHash", status);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_AES_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbKeyObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbKeyObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbKeyObject);

        status = BCryptGenerateSymmetricKey
        (
            hAlg,
            &hKey,
            pbKeyObject,
            cbKeyObject,
            (PBYTE)pbHash,
            cbHash,
            NULL
        );
        log << test_status("BCryptGenerateSymmetricKey", status);

        iFkey.seekg(0, iFkey.end);
        length = iFkey.tellg();
        iFkey.seekg(0, iFkey.beg);
        impKeyBuf = new UCHAR[length];

        iFkey.read((char*)impKeyBuf, length);

         BCryptImportKey
        (
            hAlg,
            hKey,
            BCRYPT_AES_WRAP_KEY_BLOB,
            &hKeyImp,
            NULL,
            NULL,
            impKeyBuf,
            length,
            NULL
        );

        log << test_status("BCryptImportKey", status);
    }
}

I am creating a program that encrypts all files on a USB flash drive. At the stage of importing the key, I get an exception that I can't analyze in any way. Exception text in the memcpy.asm file:

An exception was raised at 0x7C103B3F (vcruntime140d.dll ) in Zed_TEst.exe : 0xC0000005: violation of access rights when reading at 0x01010101.

The test_status function simply returns a string in which the status of functions from bcrypt is written
when I try to display the status in the console I get something strange

output: ╢
¶    ╖
"     э$♦"♦`☼}☺╕
     ♣  ♣╣
    ║
§     ь$☺§☺⌂♦╗
a     ↕А♦a♦╝
<     ь$♣<♣╜
▼     ь$♣▼♣1!.┐
w     ☺w☺♦а     →ЁЖ☻└
¶     ☼¶☼☺┴
♦    ┬
   ├
♥     ь$♣♥♣─
☺     ь$♣☺♣┼
   ╞
     ь$♣♣╟


问:
I am trying to code in glow script an accurate simulation of the orbit of the comet Haley around the sun, but how do i scale up the pace of the simul?
```<code># Scene and Objects for Animation
scene = display(title='Orbital Motion', width=500, height=300, background=color.black)
sun = sphere(pos=vector(0,0,0), color=color.yellow, radius=6.96342e9)
comet = sphere(pos=vector(8.59E10,0,0), radius=4.0E9, make_trail=True,
  trail_radius=6E8, interval=10, retain=1000)
# Parameters and Initial Conditions
G = 6.67408e-11 # universal gravitational constant (Nm^2/kg^2)
sun.mass = 1.989e30 # Sun's mass (kg)
comet.pos = vector(8.59E10, 0, 0) # initial vector position (m), starting at perigee on the x axis
comet.v = vector(0,54.55E3, 0) # initial vector velocity (m/s), starting at perigee
comet.a = vector(0,0,0)  # just to initialize - this gets updated later
t = 0.0 # start time (s)
dt = 3600*6 # time step (s)
tsteps = 27375*24/6 # total number of iterations to run simulation
tmax = dt * tsteps # end time of simulation

# Plot
f1 = graph(ytitle='r [m]',xtitle='time [days]',width=500,height=200,xmax=tmax/(3600*24),ymax=4.1E8)
f1 = series(color=color.blue)

# Calculation loop
last_r = comet.r
last_t = 0
while t < tmax + dt:        # tabbed lines that  follow repeat until t <= tmax

    rate(1e9)                # set how fast the animation runs (frames/second)

    comet.r = mag(comet.pos)  # Sun-Comet distance

    ## ADD APPROPRIATE PHYSICS:
    comet.a =        vector(-G*sun.mass*comet.pos.x/(((comet.pos.x*comet.pos.x)+(comet.pos.y*comet.pos.y))**(3/2)),-G*sun.mass*comet.pos.y/(((comet.pos.x*comet.pos.x)+(comet.pos.y*comet.pos.y))**(3/2)),0)    # acceleration
    #halley.pos = halley.pos  +  halley.v*dt     # update the position for Euler method, comment out for Euler-Cromer
    comet.v =      comet.v  +  comet.a*dt          # update the velocity
    comet.pos =   comet.pos + comet.v*dt          # update the position for Euler-Cromer method
    tdays = t/(3600*24)
    f1.plot(tdays,comet.r)

    t=t+dt
    print('time =', tdays, 'days')             # print time, velocity,
    print('velocity =', comet.v, 'm/s')         # and position at each step
    print("Semi-major axis = ", comet.r)
    print("Acceleration x vs y: ", comet.a)

    f1.plot(tdays,comet.r)

</code>```

This is my code, when I try to increase dt, the comets doesn't seem to come back.When dt is small enough that it stays accurate, the simulation of the orbit takes too much time

I tried to increase dt, which resulted in a faster simulation, but it was inaccurate as the comet didn't seem to be in its orbit anymore. I want to be able to simulate an actual 75 year orbital period in the program, but I do not want it to take more than 5 minutes.

Body:
# Scene and Objects for Animation
scene = display(title='Orbital Motion', width=500, height=300, background=color.black)
sun = sphere(pos=vector(0,0,0), color=color.yellow, radius=6.96342e9)
comet = sphere(pos=vector(8.59E10,0,0), radius=4.0E9, make_trail=True,
  trail_radius=6E8, interval=10, retain=1000)
# Parameters and Initial Conditions
G = 6.67408e-11 # universal gravitational constant (Nm^2/kg^2)
sun.mass = 1.989e30 # Sun's mass (kg)
comet.pos = vector(8.59E10, 0, 0) # initial vector position (m), starting at perigee on the x axis
comet.v = vector(0,54.55E3, 0) # initial vector velocity (m/s), starting at perigee
comet.a = vector(0,0,0)  # just to initialize - this gets updated later
t = 0.0 # start time (s)
dt = 3600*6 # time step (s)
tsteps = 27375*24/6 # total number of iterations to run simulation
tmax = dt * tsteps # end time of simulation

# Plot
f1 = graph(ytitle='r [m]',xtitle='time [days]',width=500,height=200,xmax=tmax/(3600*24),ymax=4.1E8)
f1 = series(color=color.blue)

# Calculation loop
last_r = comet.r
last_t = 0
while t < tmax + dt:        # tabbed lines that  follow repeat until t <= tmax

    rate(1e9)                # set how fast the animation runs (frames/second)

    comet.r = mag(comet.pos)  # Sun-Comet distance

    ## ADD APPROPRIATE PHYSICS:
    comet.a =        vector(-G*sun.mass*comet.pos.x/(((comet.pos.x*comet.pos.x)+(comet.pos.y*comet.pos.y))**(3/2)),-G*sun.mass*comet.pos.y/(((comet.pos.x*comet.pos.x)+(comet.pos.y*comet.pos.y))**(3/2)),0)    # acceleration
    #halley.pos = halley.pos  +  halley.v*dt     # update the position for Euler method, comment out for Euler-Cromer
    comet.v =      comet.v  +  comet.a*dt          # update the velocity
    comet.pos =   comet.pos + comet.v*dt          # update the position for Euler-Cromer method
    tdays = t/(3600*24)
    f1.plot(tdays,comet.r)

    t=t+dt
    print('time =', tdays, 'days')             # print time, velocity,
    print('velocity =', comet.v, 'm/s')         # and position at each step
    print("Semi-major axis = ", comet.r)
    print("Acceleration x vs y: ", comet.a)

    f1.plot(tdays,comet.r)

This is my code, when I try to increase dt, the comets doesn't seem to come back.When dt is small enough that it stays accurate, the simulation of the orbit takes too much time

I tried to increase dt, which resulted in a faster simulation, but it was inaccurate as the comet didn't seem to be in its orbit anymore. I want to be able to simulate an actual 75 year orbital period in the program, but I do not want it to take more than 5 minutes.


问:
ReactDataGrid - focus filter editor by keyboard press hotkey
Hi How i can do this on ReactDataGrid (</p>
```<code>inovua/reactdatagrid
```)

i try set the ref props to filter editor
</code>```

Body:
Hi How i can do this on ReactDataGrid (

inovua/reactdatagrid
```)

i try set the ref props to filter editor


问:
I'm newbie with pyautogui and I have a problem
```<code>import pyautogui as gui
import time

time.sleep(2)

def click(x,y):
    gui.click((x,y))
    time.sleep(0.1)

mino =  gui.locateOnScreen("mino1.png",region=(436,282, 150, 70))
life =  gui.locateOnScreen("vidabaixa.png",region=(0,0, 300, 300))
if mino != None:
    click (471,315)
if life != None:
    click (88, 547)
    click (88, 547)

</code>```

The pngs are on screen, and the script do nothing.
And it didn't show any error, just nothing.

Body:
import pyautogui as gui
import time

time.sleep(2)

def click(x,y):
    gui.click((x,y))
    time.sleep(0.1)

mino =  gui.locateOnScreen("mino1.png",region=(436,282, 150, 70))
life =  gui.locateOnScreen("vidabaixa.png",region=(0,0, 300, 300))
if mino != None:
    click (471,315)
if life != None:
    click (88, 547)
    click (88, 547)

The pngs are on screen, and the script do nothing.
And it didn't show any error, just nothing.


问:
I want to call the string property through the function to the console, see if you can suggest
The console says the value is undefined

const pc = {
    brandname: "hp",
    modelName: "hp-221Gt",
    cpu: {
        brandname: "hp",
        motherBoard: "inteLiCore",
        raminGB: 4,
        rominGB: 1024,
        processore: "Octacore",
        processorMaxSpeedinGHz: 3.8,
    },
    powerOn: "yes",
    // powerOff : false,
    newPowerStatus: function (on) {
        this.powerOn = on;
        // this.powerOff = off;
    },
    run: function () {
        return this.newPowerStatus(on);
    }
}

console.log(pc);
console.log("The cpu I use has following specs : ", pc.cpu)
console.log("Is the pc running : ", pc.newPowerStatus.on);

var show = "powerOn";

console.log(pc[show])
console.log(pc.run);
```

I tried to call the string value of a property in the console through the function.

Body:
The console says the value is undefined

const pc = {
    brandname: "hp",
    modelName: "hp-221Gt",
    cpu: {
        brandname: "hp",
        motherBoard: "inteLiCore",
        raminGB: 4,
        rominGB: 1024,
        processore: "Octacore",
        processorMaxSpeedinGHz: 3.8,
    },
    powerOn: "yes",
    // powerOff : false,
    newPowerStatus: function (on) {
        this.powerOn = on;
        // this.powerOff = off;
    },
    run: function () {
        return this.newPowerStatus(on);
    }
}

console.log(pc);
console.log("The cpu I use has following specs : ", pc.cpu)
console.log("Is the pc running : ", pc.newPowerStatus.on);

var show = "powerOn";

console.log(pc[show])
console.log(pc.run);

I tried to call the string value of a property in the console through the function.


问:
How to reset React Hook Form without triggering Watch
I have a complicated setup that I created a proxy case of here: https://codesandbox.io/s/bold-khayyam-hc1j8u?file=/src/Form.tsx

Long story short, I have an iframe which talks to a parent and sends data back and forth. It's semi complicated so I've just abstracted it for the above example. The parent keeps the overall state and sends it to the iframe when it updates. But the iframe also sends updates upwards, which are then rolled into the parent state.

The problem is that that in turn triggers the parent to want to tell the child that the state changed, so it sends down the state, the child receives it and sets out to reset the form with the 'new' data. But this causes watch to fire, which then sets the whole thing in motion again and it starts recursively looping.

The reason I want to reset is because the data the iframe uses can also be changed in various other ways, so the form needs to be reset when new data comes in, to ensure it's up to date, but of course I don't want that to trigger the watch, but I'll be damned if I can figure out what to do


问:
React - Uncaught Invariant Violation: item type must be defined in react-dnd@13.1.3
I've seen many examples here but couldn't solve with them.

I'm using this example https://codesandbox.io/s/github/annezhou920/react-dnd-example/ to integrate to my project.

In the example it uses React@16.8.4 and react-dnd@10.0.2.

I currently passed everything to my project and got the following error.

```<code> Uncaught Invariant Violation: item type must be defined
    at invariant (http://localhost:3000/static/js/bundle.js:4954:15)
    at useDrag (http://localhost:3000/static/js/bundle.js:27853:66)
    at SideBarItem (http://localhost:3000/static/js/bundle.js:2963:64)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:42238:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:45524:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:46820:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:31830:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:31874:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:31931:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:51805:11)

The above error occurred in the <SideBarItem> component:
    at SideBarItem (http://localhost:3000/static/js/bundle.js:2957:5)
    at div
    at div
    at Template (http://localhost:3000/static/js/bundle.js:3600:78)
    at http://localhost:3000/static/js/bundle.js:26477:23
    at div
    at RenderTemplate
    at RenderedRoute (http://localhost:3000/static/js/bundle.js:56222:5)
    at Routes (http://localhost:3000/static/js/bundle.js:56644:5)
    at main
    at Router (http://localhost:3000/static/js/bundle.js:56582:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:54940:5)
    at App
</code>```

I know that after v14 in react-dnd there are some changes about asking the type. That's why, to don't deal with it, I install react-dnd@11.1.3 and using React@18.2.0.

Only how to render the page is different in my project due to react-router-dom@6 changes.

The thing that I don't understand, why this error comes up to me while I'm still using previous v14 of react-dnd which is 11.1.3?? Where am I doing wrong? If I clone the git repo of the example and start in VSCode, it works perfectly.. Even if I use the same version of the example, still get the same error.

RenderTemplate.jsx

```<code>import {HTML5Backend} from 'react-dnd-html5-backend';
import { DndProvider } from "react-dnd";

import Example from "./Example";

import "./Draggable.css";

export default function RenderTemplate() {
 return (
   <div className="App">
     <DndProvider backend={HTML5Backend}>
       <Example />
     </DndProvider>
   </div>
 );
}
</code>```

App.js

```<code>return (
    <BrowserRouter>
      <MainNavigation></MainNavigation>
      <main>
        <Routes>
          <Route path="/template" element={<RenderTemplate />} />
        </Routes>
      </main>
    </BrowserRouter>
  );
</code>```

Body:
I've seen many examples here but couldn't solve with them.

I'm using this example https://codesandbox.io/s/github/annezhou920/react-dnd-example/ to integrate to my project.

In the example it uses React@16.8.4 and react-dnd@10.0.2.

I currently passed everything to my project and got the following error.

 Uncaught Invariant Violation: item type must be defined
    at invariant (http://localhost:3000/static/js/bundle.js:4954:15)
    at useDrag (http://localhost:3000/static/js/bundle.js:27853:66)
    at SideBarItem (http://localhost:3000/static/js/bundle.js:2963:64)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:42238:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:45524:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:46820:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:31830:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:31874:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:31931:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:51805:11)

The above error occurred in the <SideBarItem> component:
    at SideBarItem (http://localhost:3000/static/js/bundle.js:2957:5)
    at div
    at div
    at Template (http://localhost:3000/static/js/bundle.js:3600:78)
    at http://localhost:3000/static/js/bundle.js:26477:23
    at div
    at RenderTemplate
    at RenderedRoute (http://localhost:3000/static/js/bundle.js:56222:5)
    at Routes (http://localhost:3000/static/js/bundle.js:56644:5)
    at main
    at Router (http://localhost:3000/static/js/bundle.js:56582:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:54940:5)
    at App

I know that after v14 in react-dnd there are some changes about asking the type. That's why, to don't deal with it, I install react-dnd@11.1.3 and using React@18.2.0.

Only how to render the page is different in my project due to react-router-dom@6 changes.

The thing that I don't understand, why this error comes up to me while I'm still using previous v14 of react-dnd which is 11.1.3?? Where am I doing wrong? If I clone the git repo of the example and start in VSCode, it works perfectly.. Even if I use the same version of the example, still get the same error.

RenderTemplate.jsx

import {HTML5Backend} from 'react-dnd-html5-backend';
import { DndProvider } from "react-dnd";

import Example from "./Example";

import "./Draggable.css";

export default function RenderTemplate() {
 return (

     <DndProvider backend={HTML5Backend}>
       <Example />
     </DndProvider>

 );
}

App.js

return (
    <BrowserRouter>
      <MainNavigation></MainNavigation>

        <Routes>
          <Route path="/template" element={<RenderTemplate />} />
        </Routes>

    </BrowserRouter>
  );


问:
I want to ad new lang but i get Abstract classes can't be instantiated
I want to ad new lang but i get Abstract classes can't be instantiated.
I need to add my app lang. But i can't.
When i tr i get 'Abstract classes can't be instantiated.'
I search or answer but i can not find.

Here my code;

```<code>import 'package:booking_system_flutter/locale/language_ar.dart';
import 'package:booking_system_flutter/locale/language_en.dart';
import 'package:booking_system_flutter/locale/language_hi.dart';
import 'package:booking_system_flutter/locale/languages.dart';
import 'package:flutter/material.dart';
import 'package:nb_utils/nb_utils.dart';
import 'languages_de.dart';
import 'languages_fr.dart';
import 'languages_tr.dart';
class AppLocalizations extends LocalizationsDelegate<BaseLanguage> {
  const AppLocalizations();

  @override
  Future<BaseLanguage> load(Locale locale) async {
    switch (locale.languageCode) {
      case 'en':
        return LanguageEn();
      case 'ar':
        return LanguageAr();
      case 'hi':
        return LanguageHi();
      case 'fr':
        return LanguageFr();
      case 'de':
        return LanguageDe();
      case 'tr':
        return LanguageTr();

      default:
        return LanguageEn();
    }
  }

  @override
  bool isSupported(Locale locale) => LanguageDataModel.languages().contains(locale.languageCode);

  @override
  bool shouldReload(LocalizationsDelegate<BaseLanguage> old) => false;
}

</code>```

Body:
I want to ad new lang but i get Abstract classes can't be instantiated.
I need to add my app lang. But i can't.
When i tr i get 'Abstract classes can't be instantiated.'
I search or answer but i can not find.

Here my code;

import 'package:booking_system_flutter/locale/language_ar.dart';
import 'package:booking_system_flutter/locale/language_en.dart';
import 'package:booking_system_flutter/locale/language_hi.dart';
import 'package:booking_system_flutter/locale/languages.dart';
import 'package:flutter/material.dart';
import 'package:nb_utils/nb_utils.dart';
import 'languages_de.dart';
import 'languages_fr.dart';
import 'languages_tr.dart';
class AppLocalizations extends LocalizationsDelegate<BaseLanguage> {
  const AppLocalizations();

  @override
  Future<BaseLanguage> load(Locale locale) async {
    switch (locale.languageCode) {
      case 'en':
        return LanguageEn();
      case 'ar':
        return LanguageAr();
      case 'hi':
        return LanguageHi();
      case 'fr':
        return LanguageFr();
      case 'de':
        return LanguageDe();
      case 'tr':
        return LanguageTr();

      default:
        return LanguageEn();
    }
  }

  @override
  bool isSupported(Locale locale) => LanguageDataModel.languages().contains(locale.languageCode);

  @override
  bool shouldReload(LocalizationsDelegate<BaseLanguage> old) => false;
}


问:
How to add Control to a flowlayoutpanel with the same size without the control getting cut?
I have a Control layout panel with the size of (68*68) and I have a control with the same size. but when I add the control to the panel the right side of the control and the bottom side are trimmed. IDK how to make it so the control fits perfectly without it getting cut

(My applications is a winform app using the .Net Core)


问:
Is there a way to detect terminal scroll in Nodejs
I'm writing a CLI application in Node.js, and I want to see if there's a way to detect whether the user scrolled in the terminal. I'm only interested in whether the scrolling starts or stops.

I found process.stdout.on('resize', () => {}) as a way to detect terminal resize events. Is there a scroll event?


问:
Can´t add Firestore to Angular Project
I wanted to add Firestore to my Angular Project. I already saw, when I only type in

```<code>ng add @angular/fire
</code>```

the Installation failed. With

```<code>ng add @angular/fire@latest
</code>```

I was able to add Firebase to the Angular App. Then a Wizard appears, where I wanted to select Firestore.
If I select Firestore, this error message appears:

```<code>The package @angular/fire@latest will be installed and executed.
Would you like to proceed? Yes
√ Packages successfully installed.
UPDATE package.json (1231 bytes)
√ Packages installed successfully.
? What features would you like to setup? ng deploy -- hosting
√ firebase-tools installed globally.
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'node:net'
Require stack:
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\portUtils.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\registry.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\controller.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\commandUtils.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\commands\database-get.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\commands\index.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\index.js
- C:\Users\baumann\Desktop\markb.de\node_modules\@angular\fire\schematics\firebaseTools.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\portUtils.js:6:20)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\portUtils.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\registry.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\controller.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\commandUtils.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\commands\\database-get.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\commands\\index.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\index.js',
    'C:\\Users\\baumann\\Desktop\\markb.de\\node_modules\\@angular\\fire\\schematics\\firebaseTools.js'
  ]
}
</code>```

This are  my versions:
Angular CLI: 14.1.3 Node: 14.15.4 Package Manager: npm 6.14.10 OS: win32 x64

I expected it installs Firebase/Firestore in my Angular Project

Title: Can´t add Firestore to Angular Project

Body:
I wanted to add Firestore to my Angular Project. I already saw, when I only type in

ng add @angular/fire

the Installation failed. With

ng add @angular/fire@latest

I was able to add Firebase to the Angular App. Then a Wizard appears, where I wanted to select Firestore.
If I select Firestore, this error message appears:

The package @angular/fire@latest will be installed and executed.
Would you like to proceed? Yes
√ Packages successfully installed.
UPDATE package.json (1231 bytes)
√ Packages installed successfully.
? What features would you like to setup? ng deploy -- hosting
√ firebase-tools installed globally.
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'node:net'
Require stack:
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\portUtils.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\registry.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\controller.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\commandUtils.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\commands\database-get.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\commands\index.js
- C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\index.js
- C:\Users\baumann\Desktop\markb.de\node_modules\@angular\fire\schematics\firebaseTools.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\baumann\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\portUtils.js:6:20)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\portUtils.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\registry.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\controller.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\commandUtils.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\commands\\database-get.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\commands\\index.js',
    'C:\\Users\\baumann\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\index.js',
    'C:\\Users\\baumann\\Desktop\\markb.de\\node_modules\\@angular\\fire\\schematics\\firebaseTools.js'
  ]
}

This are  my versions:
Angular CLI: 14.1.3 Node: 14.15.4 Package Manager: npm 6.14.10 OS: win32 x64

I expected it installs Firebase/Firestore in my Angular Project


问:
Graphical Views +2.7.2 disabled
I cannot access the Graphical Views +2.7.2 in modern interface, the icon is disabled. Is it because the beta version is not ready?

enter image description here

I try to install version 2.7.1 but it is also disabled, I can not access in the modern interface. I try to recreate the container several times in Docker but no success so far.

Title: Graphical Views +2.7.2 disabled


问:
firebase Failed to load function definition from source error

"Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:\Users\bora_\OneDrive\Masaüstü\socialape-functions\functions\node_modules\firebase\package.json."

I get this error when I tdo firebase deploy I npm install firebase@latest --save and few things but couldnt fix

```<code>const functions = require("firebase-functions");
const admin =require('firebase-admin')
admin.initializeApp()

const config ={
    apiKey: "AIzaSyCwq6NV4Txhc5V6pX7in5Ds2Y9agQErafo",
    authDomain: "blog-app-1b41b.firebaseapp.com",
    projectId: "blog-app-1b41b",
    storageBucket: "blog-app-1b41b.appspot.com",
    messagingSenderId: "802123380235",
    appId: "1:802123380235:web:e6c65283b6a2060721f90e"
}
const express = require('express')
const app = express()

const firebase =require('firebase');
firebase.initializeApp(config)

app.get('/screams',(req,res) =>{
    admin
.firestore()
.collection('screams')
.orderBy('createdAt','desc')
.get()
.then(data => {
    let screams =[];
    data.forEach(doc =>{
        screams.push({
            screamId: doc.id,
            body: doc.data().body,
            userHandle: doc.data().userHandle,
            createdAt: doc.data().createdAt
        });
    })
    return res.json(screams)
})
.catch(err => console.error(err))
})

app.post('/scream',(req, res)=> {

    const newScream ={
        body: req.body.body,
        userHandle: req.body.userHandle,
        createdAt: new Date().toISOString()
    }

    admin.firestore()
    .collection('screams')
    .add(newScream)
    .then(doc =>{
        res.json({message:`document ${doc.id} created successfully` })
    })
    .catch(err => {
        res.status(500).json({error: 'something went wrong'});
        console.error(err);
    })
})

//signup route

app.post('/signup',(req, res) => {
    const newUser ={
        email: req.body.email,
        password: req.body.password,
        confirmPassword: req.body.confirmPassword,
        handle: req.body.handle,
    }

    //todo validate data

    firebase.auth()
    .createUserWithEmailAndPassword(newUser.email, newUser.password)
    .then(data =>{
        return res
        .status(201)
        .json({message: `user ${data.user.uid} signed up succesfully`})
    })
    .catch(err =>{
        console.error(err)
        return res.status(500).json({error: err.code});
    })
})

exports.api = functions.https.onRequest(app);
</code>```

I tried to do firebase deploy and firebase serve and get the error above

Body:
"Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:\Users\bora_\OneDrive\Masaüstü\socialape-functions\functions\node_modules\firebase\package.json."

I get this error when I tdo firebase deploy I npm install firebase@latest --save and few things but couldnt fix

const functions = require("firebase-functions");
const admin =require('firebase-admin')
admin.initializeApp()

const config ={
    apiKey: "AIzaSyCwq6NV4Txhc5V6pX7in5Ds2Y9agQErafo",
    authDomain: "blog-app-1b41b.firebaseapp.com",
    projectId: "blog-app-1b41b",
    storageBucket: "blog-app-1b41b.appspot.com",
    messagingSenderId: "802123380235",
    appId: "1:802123380235:web:e6c65283b6a2060721f90e"
}
const express = require('express')
const app = express()

const firebase =require('firebase');
firebase.initializeApp(config)

app.get('/screams',(req,res) =>{
    admin
.firestore()
.collection('screams')
.orderBy('createdAt','desc')
.get()
.then(data => {
    let screams =[];
    data.forEach(doc =>{
        screams.push({
            screamId: doc.id,
            body: doc.data().body,
            userHandle: doc.data().userHandle,
            createdAt: doc.data().createdAt
        });
    })
    return res.json(screams)
})
.catch(err => console.error(err))
})

app.post('/scream',(req, res)=> {

    const newScream ={
        body: req.body.body,
        userHandle: req.body.userHandle,
        createdAt: new Date().toISOString()
    }

    admin.firestore()
    .collection('screams')
    .add(newScream)
    .then(doc =>{
        res.json({message:`document ${doc.id} created successfully` })
    })
    .catch(err => {
        res.status(500).json({error: 'something went wrong'});
        console.error(err);
    })
})

//signup route

app.post('/signup',(req, res) => {
    const newUser ={
        email: req.body.email,
        password: req.body.password,
        confirmPassword: req.body.confirmPassword,
        handle: req.body.handle,
    }

    //todo validate data

    firebase.auth()
    .createUserWithEmailAndPassword(newUser.email, newUser.password)
    .then(data =>{
        return res
        .status(201)
        .json({message: `user ${data.user.uid} signed up succesfully`})
    })
    .catch(err =>{
        console.error(err)
        return res.status(500).json({error: err.code});
    })
})

exports.api = functions.https.onRequest(app);

I tried to do firebase deploy and firebase serve and get the error above


Title: My Pygame crashes after it tries to run my program

Body:
So I'm kinda new to programming and I'm trying to recreate Pac-Mac. So far I'm trying to create the board, but it crashes every time I try to run it. Here is the code. Or is there any better alternative to create the board?

import pygame
import math
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
vyska = 1000
sirka = 1000
pole1 = 30
run = True
plocha = [[6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5],
[3, 6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 3, 1, 6, 4, 4, 5, 1, 6, 4, 4, 4, 5, 1, 3, 3, 1, 6, 4, 4, 4, 5, 1, 6, 4, 4, 5, 1, 3, 3],
[3, 3, 2, 3, 0, 0, 3, 1, 3, 0, 0, 0, 3, 1, 3, 3, 1, 3, 0, 0, 0, 3, 1, 3, 0, 0, 3, 2, 3, 3],
[3, 3, 1, 7, 4, 4, 8, 1, 7, 4, 4, 4, 8, 1, 7, 8, 1, 7, 4, 4, 4, 8, 1, 7, 4, 4, 8, 1, 3, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 3, 1, 6, 4, 4, 5, 1, 6, 5, 1, 6, 4, 4, 4, 4, 4, 4, 5, 1, 6, 5, 1, 6, 4, 4, 5, 1, 3, 3],
[3, 3, 1, 7, 4, 4, 8, 1, 3, 3, 1, 7, 4, 4, 5, 6, 4, 4, 8, 1, 3, 3, 1, 7, 4, 4, 8, 1, 3, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 7, 4, 4, 4, 4, 5, 1, 3, 7, 4, 4, 5, 0, 3, 3, 0, 6, 4, 4, 8, 3, 1, 6, 4, 4, 4, 4, 8, 3],
[3, 0, 0, 0, 0, 0, 3, 1, 3, 6, 4, 4, 8, 0, 7, 8, 0, 7, 4, 4, 5, 3, 1, 3, 0, 0, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 0, 3, 1, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 1, 3, 0, 0, 0, 0, 0, 3],
[8, 0, 0, 0, 0, 0, 3, 1, 3, 3, 0, 6, 4, 4, 9, 9, 4, 4, 5, 0, 3, 3, 1, 3, 0, 0, 0, 0, 0, 7],
[4, 4, 4, 4, 4, 4, 8, 1, 7, 8, 0, 3, 0, 0, 0, 0, 0, 0, 3, 0, 7, 8, 1, 7, 4, 4, 4, 4, 4, 4],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 4, 4, 5, 1, 6, 5, 0, 3, 0, 0, 0, 0, 0, 0, 3, 0, 6, 5, 1, 6, 4, 4, 4, 4, 4, 4],
[5, 0, 0, 0, 0, 0, 3, 1, 3, 3, 0, 7, 4, 4, 4, 4, 4, 4, 8, 0, 3, 3, 1, 3, 0, 0, 0, 0, 0, 6],
[3, 0, 0, 0, 0, 0, 3, 1, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 1, 3, 0, 0, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 0, 3, 1, 3, 3, 0, 6, 4, 4, 4, 4, 4, 4, 5, 0, 3, 3, 1, 3, 0, 0, 0, 0, 0, 3],
[3, 6, 4, 4, 4, 4, 8, 1, 7, 8, 0, 7, 4, 4, 5, 6, 4, 4, 8, 0, 7, 8, 1, 7, 4, 4, 4, 4, 5, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 3, 1, 6, 4, 4, 5, 1, 6, 4, 4, 4, 5, 1, 3, 3, 1, 6, 4, 4, 4, 5, 1, 6, 4, 4, 5, 1, 3, 3],
[3, 3, 1, 7, 4, 5, 3, 1, 7, 4, 4, 4, 8, 1, 7, 8, 1, 7, 4, 4, 4, 8, 1, 3, 6, 4, 8, 1, 3, 3],
[3, 3, 2, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 2, 3, 3],
[3, 7, 4, 5, 1, 3, 3, 1, 6, 5, 1, 6, 4, 4, 4, 4, 4, 4, 5, 1, 6, 5, 1, 3, 3, 1, 6, 4, 8, 3],
[3, 6, 4, 8, 1, 7, 8, 1, 3, 3, 1, 7, 4, 4, 5, 6, 4, 4, 8, 1, 3, 3, 1, 7, 8, 1, 7, 4, 5, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 3, 1, 6, 4, 4, 4, 4, 8, 7, 4, 4, 5, 1, 3, 3, 1, 6, 4, 4, 8, 7, 4, 4, 4, 4, 5, 1, 3, 3],
[3, 3, 1, 7, 4, 4, 4, 4, 4, 4, 4, 4, 8, 1, 7, 8, 1, 7, 4, 4, 4, 4, 4, 4, 4, 4, 8, 1, 3, 3],
[3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3],
[3, 7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 3],
[7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8]]

obrazky = []
obrazky.append(pygame.image.load("Bodka (2).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka.png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (1).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (3).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (4).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (5).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (6).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (7).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (8).png").convert_alpha())
obrazky.append(pygame.image.load("Bodka (9).png").convert_alpha())

while run:
    for i in range(len(plocha)):
        for j in range(len(plocha[i])):
            for k in range(9):
                if plocha[i][j] == k+1:
                    screen.blit(obrazky[k+1], (j * pole1 + (0.5 * pole1), i * pole1 + (0.5 * pole1)))

pygame.display.update()

Each number represents a single image so I expected that the program would draw the board but probably because its in while loop it constantly blit the images and crashes. I cant figure out how to fix it.


问:
I cannot open my Jupyter Notebook, it keeps crashing on memory
As stated in the title I have a jupyter notebook that won't open.
I just start with programming and so it might be something silly.

I get an error message that says states: "Out of memory".
I cannot clear the output or shut down the kernel since it just won't open.
The used this Jupyter Notebook for work, where it opens some a very large excel document which is 100mb.
When I look into the directory I see that the Jupyter Notebook itself is 200mb.
I know Excel files shouldn't be that large but I am forced to work with them for work.
I already did quite some work in this Jupyter Notebook, is there a way to atleast save the code that I wrote?


问:
Gaussian filter in Python
I have a 3d array and I took a central slice of it (the slice [:,:,64]) and I made a contour plot (x,y) with these data. It gives me a density field. Now, I need to smooth this density field by applying a Gaussian filter. I am new to Python and I don't know, what should I do?
a)Smooth my data and make a contour plot again with the smoothed data?
b)Smooth the contour plot I already have?
And in any case, which is the code doing it?
If anybody could help with that I would appreciate that.
I also attach my density field (represented by a contour plot).

Title: Gaussian filter in Python


问:
Pygame Package Not Found
I have installed pygame using pip3 install pygame command for my python3, but my progam couldn't find it when I imported the module.

```<code>Traceback (most recent call last):
  File "/Users/zhuoyangmeng/Desktop/Alien_Invasion/alien_invasion.py", line 2, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'
</code>```

I checked the locations of my python3, pygame, and pip3, which are shown below.

```<code>pip3 show pygame
Name: pygame
Version: 2.1.2
Summary: Python Game Development
Home-page: https://www.pygame.org
Author: A community project.
Author-email: pygame@pygame.org
License: LGPL
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires:
Required-by:

which python3
/usr/local/bin/python3

which pip3
/usr/local/bin/pip3

</code>```

I'm always confused by python installation path related issues and I have no idea what's going on here. Any help is appreciated!

Title: Pygame Package Not Found

Body:
I have installed pygame using pip3 install pygame command for my python3, but my progam couldn't find it when I imported the module.

Traceback (most recent call last):
  File "/Users/zhuoyangmeng/Desktop/Alien_Invasion/alien_invasion.py", line 2, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'

I checked the locations of my python3, pygame, and pip3, which are shown below.

pip3 show pygame
Name: pygame
Version: 2.1.2
Summary: Python Game Development
Home-page: https://www.pygame.org
Author: A community project.
Author-email: pygame@pygame.org
License: LGPL
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires:
Required-by:

which python3
/usr/local/bin/python3

which pip3
/usr/local/bin/pip3

I'm always confused by python installation path related issues and I have no idea what's going on here. Any help is appreciated!


问:
Stop previous video and play next video on scroll
I am trying to create a component similar to how youtube shorts works what i have done is mapped some iframe and applied overflow:scroll with scroll-snap-type to give the effect of scrolling through videos the problem i am facing is to stop the previous video and play the next video on scrolling. I have mapped the videos like this:

```<code><div className={styles.col} id="reel-block">
   <div className={styles.reelsContainer}>
      {youtubeShortsUrlList.map((short, key) => (
        <Reels
          key={i}
          url={list.url}
           isMobileView={false}
        />
   </div>
</div>
</code>```

Here is what i tried:

```<code>    const reelRef = useRef();
    useEffect(() => {
        const scroll = document.getElementById("reel-block");
        if (scroll) {
            scroll.addEventListener("scroll", () => {
                reelRef.current.contentWindow.postMessage(
                    '{"event":"command", "func":"stopVideo", "args":""}',
                    "*",
                );
            });
        }
    }, []);
    return (
        <div className={styles.videoReel}>
            <iframe
                ref={reelRef}
                id={props.url}
                loading="lazy"
                className={`${
                    props.isMobileView
                        ? styles.playerMobile
                        : styles.videoPlayer
                }`}
                src={`https://www.youtube.com/embed/${props.url}?autplay=1&loop=1&controls=1&&enablejsapi=1&disablekb=1&&playsinline=1&color=red&showinfo=0&modestbranding=1&rel=0`}
                allow="accelerometer;clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            ></iframe>
        </div>
    );
</code>```

this has not helped me much as i wanted it altogether stops all the videos and also the "scroll" event listener is not always working
I have read about the Intersection Observer API but not sure how to implement it

Body:
I am trying to create a component similar to how youtube shorts works what i have done is mapped some iframe and applied overflow:scroll with scroll-snap-type to give the effect of scrolling through videos the problem i am facing is to stop the previous video and play the next video on scrolling. I have mapped the videos like this:

      {youtubeShortsUrlList.map((short, key) => (
        <Reels
          key={i}
          url={list.url}
           isMobileView={false}
        />

Here is what i tried:

    const reelRef = useRef();
    useEffect(() => {
        const scroll = document.getElementById("reel-block");
        if (scroll) {
            scroll.addEventListener("scroll", () => {
                reelRef.current.contentWindow.postMessage(
                    '{"event":"command", "func":"stopVideo", "args":""}',
                    "*",
                );
            });
        }
    }, []);
    return (

            <iframe
                ref={reelRef}
                id={props.url}
                loading="lazy"
                className={`${
                    props.isMobileView
                        ? styles.playerMobile
                        : styles.videoPlayer
                }`}
                src={`https://www.youtube.com/embed/${props.url}?autplay=1&loop=1&controls=1&&enablejsapi=1&disablekb=1&&playsinline=1&color=red&showinfo=0&modestbranding=1&rel=0`}
                allow="accelerometer;clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            >

    );

this has not helped me much as i wanted it altogether stops all the videos and also the "scroll" event listener is not always working
I have read about the Intersection Observer API but not sure how to implement it


问:
how to use waveform from andorid visulizer
lately I want to visualize the sound from a music file (in simple words create a visualizer). I learned to get some numbers from the visualizer (I read an article about the visualizer, the link will be here) and there is something like

```<code>int n = audioVisualizer.getCaptureSize();
waveAV = new byte[n];
audioVisualizer.getWaveForm(waveAV);
</code>```

and this byte array (waveAV) has something like this:

[-83, -115, 114, 114, 110, 101, 99, 98, 116,...]

problem 1 : how to use these numbers

problem 2 : am I moving in the right direction to create a visualizer?

I will be very grateful to you for your answer, best regards, Orest!

Body:
lately I want to visualize the sound from a music file (in simple words create a visualizer). I learned to get some numbers from the visualizer (I read an article about the visualizer, the link will be here) and there is something like

int n = audioVisualizer.getCaptureSize();
waveAV = new byte[n];
audioVisualizer.getWaveForm(waveAV);

and this byte array (waveAV) has something like this:

[-83, -115, 114, 114, 110, 101, 99, 98, 116,...]

problem 1 : how to use these numbers

problem 2 : am I moving in the right direction to create a visualizer?

I will be very grateful to you for your answer, best regards, Orest!


问:
how to use tesseract or tesserocr on gpu python? It does not work
how to use tesseract or tesserocr on gpu? python
did not find information on the Internet

tried it doesn't work


问:
How do I parse a Promise JS Object to a singluar variable?
I write Python 99% of the time but decided to start playing with Amazon Cloudscape and therefore started to write some React. It's been a slog...

I have a backend service (flask) that returns a JSON object of data I want to use in order to create a line-chart (using the Cloudscape Linechart component). However, the JSON data is within a promise (Async fetch statements) and for the life of me I cannot figure out how to assign it to a variable that can be used as an export for my Linechart component class.

How do I:

Get rid of the Promise object (parse it)

Get a valid array in its own variable

Be able to consume the variable (export) in a different class (e.g., import {my_var} from "./my_class").

I need to do some math on this data which complicates this.

Fetch Function that returns a Promise

export async function GetRegionRidecounts(region) {
   try {
      var response = await fetch('http://localhost:5000/get_region_ridecounts?region_name=' + region, {
         method: 'GET',
         mode: 'cors',
         headers: {
            'Content-Type': 'application/json',
         },
      });
      return await response.json()
   } catch (error) {
      return { "error": error };
   }
}
```
<p><strong>Consumer function that returns a Linechart</strong></p>
<pre class="lang-js prettyprint-override"><code>export default function RidersLineChart(region) {
    console.log(region)
    GetRegionRidecounts("west-lake-marion-park")
    .then(data => {
    return <LineChart
        height={200}
        series={data}
        xDomain={[data[0].date,data[data.length -1].data]}
        yDomain={[0, 500]}
        xScaleType="time"
        xTitle="Time (UTC)"
        yTitle="Data transferred"
        ariaLabel="Network traffic"
        ariaDescription={`Line chart showing transferred data of all your instances.`}
    />
    });
}
</code>```

Edit 1: I've tried to use the useState capabilities but get the following errors:

```<code>Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

Example Function that throws error

export async function GetRegionRidecounts(region) {
   const [data, setData] = useState([]);
   try {
      await fetch('http://localhost:5000/get_region_ridecounts?region_name=' + region, {
         method: 'GET',
         mode: 'cors',
         headers: {
            'Content-Type': 'application/json',
         },
      }).then(response => {return response.json()})
      .then(data => {setData(data)});
      console.log(data)
      return data
   } catch (error) {
      return { "error": error };
   }
}
```

Body:
I write Python 99% of the time but decided to start playing with Amazon Cloudscape and therefore started to write some React. It's been a slog...

I have a backend service (flask) that returns a JSON object of data I want to use in order to create a line-chart (using the Cloudscape Linechart component). However, the JSON data is within a promise (Async fetch statements) and for the life of me I cannot figure out how to assign it to a variable that can be used as an export for my Linechart component class.

How do I:

Get rid of the Promise object (parse it)

Get a valid array in its own variable

Be able to consume the variable (export) in a different class (e.g., import {my_var} from "./my_class").

I need to do some math on this data which complicates this.

Fetch Function that returns a Promise

export async function GetRegionRidecounts(region) {
   try {
      var response = await fetch('http://localhost:5000/get_region_ridecounts?region_name=' + region, {
         method: 'GET',
         mode: 'cors',
         headers: {
            'Content-Type': 'application/json',
         },
      });
      return await response.json()
   } catch (error) {
      return { "error": error };
   }
}

Consumer function that returns a Linechart

export default function RidersLineChart(region) {
    console.log(region)
    GetRegionRidecounts("west-lake-marion-park")
    .then(data => {
    return <LineChart
        height={200}
        series={data}
        xDomain={[data[0].date,data[data.length -1].data]}
        yDomain={[0, 500]}
        xScaleType="time"
        xTitle="Time (UTC)"
        yTitle="Data transferred"
        ariaLabel="Network traffic"
        ariaDescription={`Line chart showing transferred data of all your instances.`}
    />
    });
}

Edit 1: I've tried to use the useState capabilities but get the following errors:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Example Function that throws error

export async function GetRegionRidecounts(region) {
   const [data, setData] = useState([]);
   try {
      await fetch('http://localhost:5000/get_region_ridecounts?region_name=' + region, {
         method: 'GET',
         mode: 'cors',
         headers: {
            'Content-Type': 'application/json',
         },
      }).then(response => {return response.json()})
      .then(data => {setData(data)});
      console.log(data)
      return data
   } catch (error) {
      return { "error": error };
   }
}


问:
Null check operator used on a null value flutter in stream builder
I am using Stream Builder to check wether the user has logged in or not it was working just fine but all of a sudden its giving the error</p>
```<code> `return StreamBuilder<User?>(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return Scaffold(
          //backgroundColor: Color(0xffFF686B),
            appBar: AppBar(
              backgroundColor: Colors.redAccent,
              centerTitle: true,
              title: const Text("CHAT APP"),
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SingleChildScrollView(
                child:

        );
      } else {
        return homepage(url: auth,);
      }
    });`
</code>```

Body:
I am using Stream Builder to check wether the user has logged in or not it was working just fine but all of a sudden its giving the error

 `return StreamBuilder<User?>(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return Scaffold(
          //backgroundColor: Color(0xffFF686B),
            appBar: AppBar(
              backgroundColor: Colors.redAccent,
              centerTitle: true,
              title: const Text("CHAT APP"),
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SingleChildScrollView(
                child:

        );
      } else {
        return homepage(url: auth,);
      }
    });`