问:
Why am I getting undefined in the output?
```<code>unction spinWords(string){
    let newArr = string.split(' ')
    let reversedWord = "";
    for(let i = 0; i < newArr.length; i++){
        let curr = newArr[i];
        if (curr.length >= 4){
            for(let j = curr.length; j >= 0; j--){
               reversedWord += curr[j];
            }

        }
    }
    return reversedWord;
  }
  console.log(spinWords("Hey fellow warriors"))
output:  undefinedwollefundefinedsroirraw
</code>```

I am trying to retun the reverseWord string concatenated with the words has more than 5 letters.

Body:
unction spinWords(string){
    let newArr = string.split(' ')
    let reversedWord = "";
    for(let i = 0; i < newArr.length; i++){
        let curr = newArr[i];
        if (curr.length >= 4){
            for(let j = curr.length; j >= 0; j--){
               reversedWord += curr[j];
            }

        }
    }
    return reversedWord;
  }
  console.log(spinWords("Hey fellow warriors"))
output:  undefinedwollefundefinedsroirraw

I am trying to retun the reverseWord string concatenated with the words has more than 5 letters.


来源: stackexchange

问:
FirebaseAuthInvalidCredentialsException: The supplied auth credential is malformed or has expired. [ Invalid access_token, error code 43 ]
I am receiving this error in my application while trying to login using facebook with Firebase.
I did research the error and all suggestions were to check firebase and ensure that the AppId and AppSecret are copied correctly as well as in the android app. Do you have any other recommendations to check because i have no clue why i have this error. Noting that i tried creating a new facebook app and it worked perfectly</p>

ContentLicense: CC BY-SA 4.0


问:
Why does CloudFront pointing to S3 static website works, but not when it's a "Redirect request" bucket?
Background: I'm trying to configure a static website hosting on S3 for adomain.com. Specifically, I want to redirect http://adomain.com, http://www.adomain.com and https://www.adomain.com all to https://adomain.com. For that, I've been following this answer.

Very shortly, it says to create a Bucket with the name adomain.com to host the website. And then, another bucket, with name www.adomain.com, and set "Hosting type: Redirect request" pointing to the adomain.com bucket. Everything works fine until this.

However, I got stuck on step #3. I created the CloudFront distribution with the origin set to the URL of the www.adomain.com bucket (ie. full bucket URL www.adomain.com.s3-website.eu-central-1.amazonaws.com). Let's call this CloudFront Dist WWW.

[I also created a second CloudFront distribution, with origin set to the URL of the adomain.com bucket, let's call it CloudFront Dist non-WWW].

But when try to access that CloudFront Dist WWW's Distribution domain name (eg. https://lotsofchars123.cloudfront.net), it doesn't load.

On the other hand, when I try the CloudFront Dist non-WWW's Distribution domain name, it does load. Why is that?

I must also point out that both S3's URLs work perfectly (ie. both adomain.com.s3-website.eu-central-1.amazonaws.com and www.adomain.com.s3-website.eu-central-1.amazonaws.com load)

Also, when I set the Route 53 hosted zone www.adomain.com to route traffic to CloudFront Dist WWW's Distribution domain name, it does load (except for http, ie. http://www.adomain.com works, but https://www.adomain.com doesn't)

edit:

Cloudfront Distribution Config


问:
Plotly Express px.line() parameter color_discrete_map not working correctly
I'm trying to assign specific colors to different lines on my plotly line graph and when specifying key/color pairs using the color_discrete_map parameter I do not get the correct output. For example, the hex code I have used for the Mcdonal'ds attribute is a yellow but the final graph shows that line as a blue color.

```<code>import pandas as pd
import plotly.express as px

df = pd.read_csv("fastfood.csv")
df.drop(df[df["Year"] < 2018].index, inplace = True)
df["Percent Change"] = df.groupby("Corporation")["Total Revenue"].apply(lambda x: ((x-x.iloc[0]) / x.iloc[0]) * 100)

fig = px.line(df,
    x="Date",
    y="Percent Change",
    title="Fast Food Company Revenue Growth",
    render_mode="svg",
    color="Corporation",
    color_discrete_map={"Mcdonald's":"#FFFF00",
            "Wendy's": "#DD1438",
            "Burger King": "#F2A900",
            "Taco Bell": "#36399A",
            "KFC": "#f5d4b7"},
    width=800,
    height=600,
    )

fig.show()
</code>```

Am I missing something here? Why are my colors from color_discrete_map all messed up?

I tried playing around with the color attributes a bit but they are always coming back as different than the hex value codes I specify.

Body:
I'm trying to assign specific colors to different lines on my plotly line graph and when specifying key/color pairs using the color_discrete_map parameter I do not get the correct output. For example, the hex code I have used for the Mcdonal'ds attribute is a yellow but the final graph shows that line as a blue color.

import pandas as pd
import plotly.express as px

df = pd.read_csv("fastfood.csv")
df.drop(df[df["Year"] < 2018].index, inplace = True)
df["Percent Change"] = df.groupby("Corporation")["Total Revenue"].apply(lambda x: ((x-x.iloc[0]) / x.iloc[0]) * 100)

fig = px.line(df,
    x="Date",
    y="Percent Change",
    title="Fast Food Company Revenue Growth",
    render_mode="svg",
    color="Corporation",
    color_discrete_map={"Mcdonald's":"#FFFF00",
            "Wendy's": "#DD1438",
            "Burger King": "#F2A900",
            "Taco Bell": "#36399A",
            "KFC": "#f5d4b7"},
    width=800,
    height=600,
    )

fig.show()

Am I missing something here? Why are my colors from color_discrete_map all messed up?

I tried playing around with the color attributes a bit but they are always coming back as different than the hex value codes I specify.


问:
react next Js create JSON url
i want to use grafana platform that display data
i need to create route patch that contain the data as json and use is on grafana
on react i can do it with app.get request and send it res.json()
but with next js it wont work as it should be
adding code

*** i am in the middle of project so all this request/database configuration work
so there is no problem with kind of configuration

i just want when i go to the correct url i could get the users json and use this url something like in the picture that i upload

```<code>import user from "../../models/userModel";
import mongoose from "mongoose";
const handler = async(req, res) => {
    await mongoose.connect(
      database url that i deleted
      );
  const fetchAllUser = async () => {

      const users = await user.find();
    res.json(users);
  };
 if( req.method === "GET"){

      fetchAllUser();
  }
};
export default handler;

//send request to get all the users from the db and i get it!
  const allUsers = async()=>{
   const users =  await axios.get(`${herokuUrl}user4`)
   return users.data

  }

// users components that run on the routes of "users"
import React, { useEffect } from "react";
import { useDataProvider } from "../context/Data";

const Users = () => {
  const { allUsers } = useDataProvider();

  useEffect(() => {
    allUsers();
  }, []);

  return <></>;
};

export default Users;

</code>```

Title: react next Js create JSON url

Body:
i want to use grafana platform that display data
i need to create route patch that contain the data as json and use is on grafana
on react i can do it with app.get request and send it res.json()
but with next js it wont work as it should be
adding code

*** i am in the middle of project so all this request/database configuration work
so there is no problem with kind of configuration

i just want when i go to the correct url i could get the users json and use this url something like in the picture that i upload

import user from "../../models/userModel";
import mongoose from "mongoose";
const handler = async(req, res) => {
    await mongoose.connect(
      database url that i deleted
      );
  const fetchAllUser = async () => {

      const users = await user.find();
    res.json(users);
  };
 if( req.method === "GET"){

      fetchAllUser();
  }
};
export default handler;

//send request to get all the users from the db and i get it!
  const allUsers = async()=>{
   const users =  await axios.get(`${herokuUrl}user4`)
   return users.data

  }

// users components that run on the routes of "users"
import React, { useEffect } from "react";
import { useDataProvider } from "../context/Data";

const Users = () => {
  const { allUsers } = useDataProvider();

  useEffect(() => {
    allUsers();
  }, []);

  return <></>;
};

export default Users;


问:
1px Gray Border Shape Change Problem with Theia Sticky Sidebar v1.7.0
When I used Theia Sticky Sidebar v1.7.0 my 1px gray border shape changed and I want to solve this problem.

CodePen

This is my HTML code:

```<code><div class="container">
  <div class="side-bar1">
    <div class="theiaStickySidebar">
      <div class="box2">
        <h1>TEST</h1>
        <h2>Scroll</h2>
      </div>
    </div>
  </div>
  <div class="content">
    <div class="box1">
      <h1>The Problem</h1>
      <h3>Before It Becomes Sticky</h3>
      <img src="https://i.postimg.cc/D0kgLKrT/Before.png" alt="Before It Becomes Sticky"/>
      <h3>After It Becomes Sticky</h3>
      <img src="https://i.postimg.cc/LsS2CqmY/After.png" alt="After It Becomes Sticky"/>
    </div>
  </div>
</div>
</code>```

Body:
When I used Theia Sticky Sidebar v1.7.0 my 1px gray border shape changed and I want to solve this problem.

CodePen

This is my HTML code:

TEST

Scroll

The Problem

Before It Becomes Sticky

After It Becomes Sticky


问:
How to shard input to Sagemaker ProcessingJob based on S3 folder?
I'm trying to use Sagemaker ProcessingJob to process a huge s3 bucket on multiple instances.

The s3 bucket is structured to have multiple input files of each job in the same folder, e.g.

```<code>job1/
  a.jpg
  b.json
  c.proto
job2/
  a.jpg
  b.json
  c.proto
...
</code>```

Where a.jpg,b.json,c.proto are required together for processing.

How can i force Sagemaker to shard jobs according to the folder structure, instead of individual files?

I tried looking for appropriate sharding strategy, but found only ShardByS3Key or FullyReplicated.

Body:
I'm trying to use Sagemaker ProcessingJob to process a huge s3 bucket on multiple instances.

The s3 bucket is structured to have multiple input files of each job in the same folder, e.g.

job1/
  a.jpg
  b.json
  c.proto
job2/
  a.jpg
  b.json
  c.proto
...

Where a.jpg,b.json,c.proto are required together for processing.

How can i force Sagemaker to shard jobs according to the folder structure, instead of individual files?

I tried looking for appropriate sharding strategy, but found only ShardByS3Key or FullyReplicated.


问:
Aggrid react wrapper unable to create multiple instances and access grid API
I have a AGGRID Wrapper defined this way

```<code>    function DataTable({
    columns = [],
    data = [],
    context = {},
    rowIdGetter
  },
  ref
) {

  const [apiRef, setApiRef] = useState(null)

  useImperativeHandle(ref, () => ({
    api: () => apiRef
  }))

  useEffect(() => {
    if (apiRef) {
      apiRef.setRowData(data)
    }
  }, [data, apiRef])

  const onGridReady = function ({ api }) {
    setApiRef(api)
    api.setRowData(data)
    if (sizeColumnsToFit) {
      api.sizeColumnsToFit()
    }
  }
  return (
    <div className={'ag-theme-alpine'} style={{ width: '100%' }}>
      <AgGridReact
        domLayout='autoHeight'
        onGridReady={onGridReady}
        ...
      >
        {columns
          .filter(c => !c.fullWidth)
          .map((c, index) => {
            return (
              <AgGridColumn
                ....
              />
            )
          })}
      </AgGridReact>
    </div>
  )
}

export default React.memo(forwardRef(DataTable))
</code>```

Now I am using a map to iterate over some data and load multiple instances of the table with different data.
But when I try to access the Grid Options (tableRef.current.api()) it always points to the last instance of the table but not any other table created before that. How to handle this? I want to use the Grid options to perform some actions on individual tables created. How to achieve this?The number of tables on a given page will vary with the data and I dont have control over it.

Body:
I have a AGGRID Wrapper defined this way

    function DataTable({
    columns = [],
    data = [],
    context = {},
    rowIdGetter
  },
  ref
) {

  const [apiRef, setApiRef] = useState(null)

  useImperativeHandle(ref, () => ({
    api: () => apiRef
  }))

  useEffect(() => {
    if (apiRef) {
      apiRef.setRowData(data)
    }
  }, [data, apiRef])

  const onGridReady = function ({ api }) {
    setApiRef(api)
    api.setRowData(data)
    if (sizeColumnsToFit) {
      api.sizeColumnsToFit()
    }
  }
  return (

      <AgGridReact
        domLayout='autoHeight'
        onGridReady={onGridReady}
        ...
      >
        {columns
          .filter(c => !c.fullWidth)
          .map((c, index) => {
            return (
              <AgGridColumn
                ....
              />
            )
          })}
      </AgGridReact>

  )
}

export default React.memo(forwardRef(DataTable))

Now I am using a map to iterate over some data and load multiple instances of the table with different data.
But when I try to access the Grid Options (tableRef.current.api()) it always points to the last instance of the table but not any other table created before that. How to handle this? I want to use the Grid options to perform some actions on individual tables created. How to achieve this?The number of tables on a given page will vary with the data and I dont have control over it.


问:
Azure RecoveryServicesBackupClient Restore disks begin_trigger method returns ResourceNotFoundError
I am attempting to recover an VM disk from backup vault recovery point to a different resource group and storage account.
When using CLI, it works properly. But when using python SDK, I got a ResourceNotFound Error. However, there are no details on the not-found resource exception.

CLI ( result: disk created properly and deleted after to reuse the same recovery point in python):

```<code>az backup restore restore-disks --vault-name <MASKED VAULT NAME> --item-name "VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01" --resource-group "<MASKED RGNAME>" --rp-name 933115606147395682 --storage-account stscn0equdevscn --storage-account-resource-group <MASKED TARGET RG> --container-name "IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01" —target-resource-group <MASKED TARGET RG>
</code>```

Python SDK (failed with stack trace below):

```<code>trigger_restore_properties = IaasVMRestoreRequest(
    recovery_type = "RestoreDisks",
    restore_with_managed_disks = True,
    recovery_point_id = '/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED RGNAME>/providers/Microsoft.RecoveryServices/vaults/<MASKED VAULT NAME>/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/protectedItems/VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/recoveryPoints/933115606147395682',
    storage_account_id = "/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED TARGET RG>/providers/Microsoft.Storage/storageAccounts/stscn0equdevscn",
    target_resource_group_id = "/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED TARGET RG>")`
    `trigger_restore_request = RestoreRequestResource(properties=trigger_restore_properties)`
    `poller=rsbc.restores.begin_trigger(
    vault_name = "<MASKED VAULT NAME>",
    resource_group_name = "<MASKED RGNAME>",
    fabric_name = "Azure",
    container_name = "iaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01",
    protected_item_name = "VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01",
    recovery_point_id = '/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED RGNAME>/providers/Microsoft.RecoveryServices/vaults/<MASKED VAULT NAME>/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/protectedItems/VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/recoveryPoints/933115606147395682',
    parameters=trigger_restore_request,
    polling = False)
</code>```

Traceback (most recent call last):

```<code>  File "<stdin>", line 1, in <module>
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
    return func(*args, **kwargs)
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/mgmt/recoveryservicesbackup/activestamp/operations/_restores_operations.py", line 212, in begin_trigger
    raw_result = self._trigger_initial(
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/mgmt/recoveryservicesbackup/activestamp/operations/_restores_operations.py", line 150, in _trigger_initial
    map_error(status_code=response.status_code, response=response, error_map=error_map)
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/core/exceptions.py", line 107, in map_error
    raise error
azure.core.exceptions.ResourceNotFoundError: Operation returned an invalid status 'Not Found
</code>```

expecting python SDK to also create the disks successfully

Body:
I am attempting to recover an VM disk from backup vault recovery point to a different resource group and storage account.
When using CLI, it works properly. But when using python SDK, I got a ResourceNotFound Error. However, there are no details on the not-found resource exception.

CLI ( result: disk created properly and deleted after to reuse the same recovery point in python):

az backup restore restore-disks --vault-name <MASKED VAULT NAME> --item-name "VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01" --resource-group "<MASKED RGNAME>" --rp-name 933115606147395682 --storage-account stscn0equdevscn --storage-account-resource-group <MASKED TARGET RG> --container-name "IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01" —target-resource-group <MASKED TARGET RG>

Python SDK (failed with stack trace below):

trigger_restore_properties = IaasVMRestoreRequest(
    recovery_type = "RestoreDisks",
    restore_with_managed_disks = True,
    recovery_point_id = '/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED RGNAME>/providers/Microsoft.RecoveryServices/vaults/<MASKED VAULT NAME>/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/protectedItems/VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/recoveryPoints/933115606147395682',
    storage_account_id = "/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED TARGET RG>/providers/Microsoft.Storage/storageAccounts/stscn0equdevscn",
    target_resource_group_id = "/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED TARGET RG>")`
    `trigger_restore_request = RestoreRequestResource(properties=trigger_restore_properties)`
    `poller=rsbc.restores.begin_trigger(
    vault_name = "<MASKED VAULT NAME>",
    resource_group_name = "<MASKED RGNAME>",
    fabric_name = "Azure",
    container_name = "iaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01",
    protected_item_name = "VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01",
    recovery_point_id = '/subscriptions/<MASKED SUBSCRIPTION##########>/resourceGroups/<MASKED RGNAME>/providers/Microsoft.RecoveryServices/vaults/<MASKED VAULT NAME>/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/protectedItems/VM;iaasvmcontainerv2;<MASKED RGNAME>;lvmarctest01/recoveryPoints/933115606147395682',
    parameters=trigger_restore_request,
    polling = False)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
    return func(*args, **kwargs)
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/mgmt/recoveryservicesbackup/activestamp/operations/_restores_operations.py", line 212, in begin_trigger
    raw_result = self._trigger_initial(
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/mgmt/recoveryservicesbackup/activestamp/operations/_restores_operations.py", line 150, in _trigger_initial
    map_error(status_code=response.status_code, response=response, error_map=error_map)
  File "/Users/suibin/Desktop/Projects/DXC/BunkerProject/venv/lib/python3.10/site-packages/azure/core/exceptions.py", line 107, in map_error
    raise error
azure.core.exceptions.ResourceNotFoundError: Operation returned an invalid status 'Not Found

expecting python SDK to also create the disks successfully


问:
NPM version incompatible with node version
I am currently using Node.js on Debian 10. I was trying to upgrade my node and npm versions so that I can deploy to firebase, because the firebase commands apparently are no longer compatible with the node version I was using. I ran npm install -g npm to upgrade npm. Now, every time I try to do an npm install, I get this error:

```<code>ERROR: npm v9.2.0 is known not to run on Node.js v12.22.12. You'll need to
upgrade to a newer Node.js version in order to use this version of npm. This
version of npm supports the following node versions: `^14.17.0 || ^16.13.0 ||
>=18.0.0`. You can find the latest version at https://nodejs.org/.

ERROR:
/usr/local/lib/node_modules/npm/lib/utils/exit-handler.js:22
  const hasLoadedNpm = npm?.config.loaded
                       ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at module.exports (/usr/local/lib/node_modules/npm/lib/cli.js:76:23)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:2:25)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
</code>```

But when I run npm -v, I still get 7.5.2, which is the version of npm that I had before. I have tried uninstalling and reinstalling both node and npm (using sudo apt-get remove and sudo apt-get install), but the issue still persists.

How do I revert back to my old npm version? (7.5.2)

Body:
I am currently using Node.js on Debian 10. I was trying to upgrade my node and npm versions so that I can deploy to firebase, because the firebase commands apparently are no longer compatible with the node version I was using. I ran npm install -g npm to upgrade npm. Now, every time I try to do an npm install, I get this error:

ERROR: npm v9.2.0 is known not to run on Node.js v12.22.12. You'll need to
upgrade to a newer Node.js version in order to use this version of npm. This
version of npm supports the following node versions: `^14.17.0 || ^16.13.0 ||
>=18.0.0`. You can find the latest version at https://nodejs.org/.

ERROR:
/usr/local/lib/node_modules/npm/lib/utils/exit-handler.js:22
  const hasLoadedNpm = npm?.config.loaded
                       ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at module.exports (/usr/local/lib/node_modules/npm/lib/cli.js:76:23)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:2:25)
    at Module._compile (internal/modules/cjs/loader.js:999:30)

But when I run npm -v, I still get 7.5.2, which is the version of npm that I had before. I have tried uninstalling and reinstalling both node and npm (using sudo apt-get remove and sudo apt-get install), but the issue still persists.

How do I revert back to my old npm version? (7.5.2)


问:
How to tag a code from gitlab yaml file using API tag commands but not using the gitlab credentials?
I wat to tag code after build and deploy job in yaml file and exclude a file from the tag.

I don't want to create tags using these one of these:
Using Gitlab’s username and password
Using Gitlab Personal Access Token

Is there any api command that can be used to tag code?


问:
Make overlay button with transparent background color
I try to create overlay button with transparent background, but it's not fully transparent.
I set a transparent background color and transparent theme, but still I can observe background of this button. Ideally, it should be oval overlay button without additional background.

```<code>    @SuppressLint("ResourceAsColor")
    private fun createButton(){
        overlayButton = ImageButton(this)
        overlayButton.setBackgroundColor(R.color.transparentColor)
        overlayButton.setImageResource(R.drawable.ready_button)
        overlayButton.setOnTouchListener(this)
        overlayButton.setOnClickListener(this)

        val layoutFlag = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        }
        else {
            Toast.makeText(this,"Old-fashioned model", Toast.LENGTH_SHORT).show()
            WindowManager.LayoutParams.TYPE_APPLICATION
        }
        params = WindowManager.LayoutParams()
        params.gravity = Gravity.TOP or Gravity.START
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        params.type = layoutFlag
        params.width = (mWidth*0.2).roundToInt()
        params.height = (mWidth*0.2).roundToInt()
        params.x = mWidth
        params.y = (mHeight*0.15).roundToInt()
        params.format = PixelFormat.TRANSPARENT

        wmgr.addView(overlayButton,params)
    }
</code>```

ready_button.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:background="#0000000">
<gradient
    android:angle="90"
    android:startColor="@color/readyColor1"
    android:endColor="@color/readyColor2" />

<corners android:radius="1000dp" />
</shape>
</code>```

in colors I have this color:

```<code><color name="transparentColor" >#00000000</color>
</code>```

Used style in this service window:

```<code><style name="Theme.AppCompat.Translucent" parent="Theme.AppCompat.NoActionBar">
    <item name="android:background">@color/transparentColor</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>
</code>```

Body:
I try to create overlay button with transparent background, but it's not fully transparent.
I set a transparent background color and transparent theme, but still I can observe background of this button. Ideally, it should be oval overlay button without additional background.

    @SuppressLint("ResourceAsColor")
    private fun createButton(){
        overlayButton = ImageButton(this)
        overlayButton.setBackgroundColor(R.color.transparentColor)
        overlayButton.setImageResource(R.drawable.ready_button)
        overlayButton.setOnTouchListener(this)
        overlayButton.setOnClickListener(this)

        val layoutFlag = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        }
        else {
            Toast.makeText(this,"Old-fashioned model", Toast.LENGTH_SHORT).show()
            WindowManager.LayoutParams.TYPE_APPLICATION
        }
        params = WindowManager.LayoutParams()
        params.gravity = Gravity.TOP or Gravity.START
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        params.type = layoutFlag
        params.width = (mWidth*0.2).roundToInt()
        params.height = (mWidth*0.2).roundToInt()
        params.x = mWidth
        params.y = (mHeight*0.15).roundToInt()
        params.format = PixelFormat.TRANSPARENT

        wmgr.addView(overlayButton,params)
    }

ready_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:background="#0000000">
<gradient
    android:angle="90"
    android:startColor="@color/readyColor1"
    android:endColor="@color/readyColor2" />

<corners android:radius="1000dp" />
</shape>

in colors I have this color:

<color name="transparentColor" >#00000000</color>

Used style in this service window:


问:
Is There a function which converts an audio file into array of hz?
I'm working on a project and try to compare audio file with another one.
I want to know the hz height of each signal in the audio and than check if it is accurate note or not.

For this I have tried librosa library but with it you need to crate mel spectogram and than work on the spec in order to find notes...
is there a simpler way?I prefer without CNN
Thanks
*maybe it's not so complicated to convert the spectogram as I thought...waiting to your help.


问:
concatenate filtered results in google sheets
i am trying to have some of my filtered results joined in the same cell without having to do this in 2 steps (filter the data, then join it). As my data will fluctuate (volume of rows) I want to do this in 1 coded step.

my data:
can be seen here

shown in the spreadsheet are the formula (below), the results I received, the results I am looking for.

among many tries, this was one of them:
=CONCATENATE(filter({A4:A11,E4:E11},F4:F11="Production Management"))


问:
Proper usage of install_name_tool
I am building an application on OSX with Xcode.

I am using an external library that I build myself (wxWidgets). I didn't run make install for it, and so it is still located in my home directory where I build it.

Now in order to run the AppBundle independently I'm copying the dylib's inside the Bundle and running install_name_tool in order for the linker to pick up the proper directory. This is the code I'm running at the end of the build:

```<code>cp -f ~/wxWidgets/buildC11/lib/libwx_baseu-3.2.dylib "$TARGET_BUILD_DIR/$TARGET_NAME.app/Contents/Frameworks/libwx_baseu-3.2.dylib"

install_name_tool -change /usr/local/lib/libwx_baseu-3.2.dylib @executable_path/../Frameworks/libwx_baseu-3.2.dylib "$TARGET_BUILD_DIR/$TARGET_NAME.app/Contents/MacOS/$PRODUCT_NAME"
</code>```

My question would be:

Is my install_name_tool command good? It is executing successfully, but gives problems during the run-time.

Title: Proper usage of install_name_tool

Body:
I am building an application on OSX with Xcode.

I am using an external library that I build myself (wxWidgets). I didn't run make install for it, and so it is still located in my home directory where I build it.

Now in order to run the AppBundle independently I'm copying the dylib's inside the Bundle and running install_name_tool in order for the linker to pick up the proper directory. This is the code I'm running at the end of the build:

cp -f ~/wxWidgets/buildC11/lib/libwx_baseu-3.2.dylib "$TARGET_BUILD_DIR/$TARGET_NAME.app/Contents/Frameworks/libwx_baseu-3.2.dylib"

install_name_tool -change /usr/local/lib/libwx_baseu-3.2.dylib @executable_path/../Frameworks/libwx_baseu-3.2.dylib "$TARGET_BUILD_DIR/$TARGET_NAME.app/Contents/MacOS/$PRODUCT_NAME"

My question would be:

Is my install_name_tool command good? It is executing successfully, but gives problems during the run-time.


问:
C# Vector3 Rotation with Quaternion / Matrix4x4
I've got a sensor that delivers object data in a coordinate system according to ISO 8855-2011.
My sensor is positioned at [0, 0, 0] but can be "misaligned". Therefore I want to compensate for roll, pitch and yaw.

In my App I perform the necessary rotations with the System.Numerics Lib and more specifically with a vector3 as the data point ([x, y, z]) and tried either a Matrix4x4 or a Quaternion as the rotation matrix.

Without having evaluated this final result a rotation in three steps seems to work quite well (at first glance looks like to be expected in my visualization). To perform the rotation I start by specifying three Quaternions for each axis and perform the rotation one after the other.

```<code>Vector3 vecMeas = new Vector3(x, y, z);
Quaternion rotRoll = Quaternion.CreateFromAxisAngle(new Vector3(1.0f, 0.0f, 0.0f), rollAngle);
Quaternion rotPitch = Quaternion.CreateFromAxisAngle(new Vector3(0.0f, 1.0f, 0.0f), pitchAngle);
Quaternion rotYaw = Quaternion.CreateFromAxisAngle(new Vector3(0.0f, 0.0f, 1.0f), yawAngle);

var vecRolled = Vector3.Transform(vecMeas, rotRoll);
var vecPitched = Vector3.Transform(vecRolled, rotPitch);
var vecResult = Vector3.Transform(vecPitched, rotYaw);
</code>```

While this seems to work, it looks clumsy to me as the class Matrix4x4 and Quaternion offers a method called "CreateFromYawPitchRoll". I tried every combination of inputs for this method (if I remember correctly 6 combinations for the order of pitch, roll, yaw combined with 48 combinations of inputs for the order and sign of [x, y, z]), but was not able to produce the same as my rotation in 3 steps.

Example (one of ~288 combinations):

```<code>Vector3 vecMeas = new Vector3(x, y, z);
Quaternion rot = Quaternion.CreateFromYawPitchRoll(pitch, roll, yaw);
var vecResult = Vector3.Transform(vecMeas, rot);
</code>```

The above shown "one step" solutions always looks off.

Unfortunately I was not able to find a a lot of information about the handedness (or the absence thereof) of the expected inputs for Matrix4x4 / Quaternion or the order in which the rotation of "CreateFromYawPitchRoll" is being performed. Do you have any idea, how I could refactor my code to be more elegant (aka maybe a one step solution) or how to properly use CreateFromYawPitchRoll? A multiplication of the rotation elements did not deliver the expected results (rotRoll * rotPitch * rotYaw).

Thanks in advance!

Update:
Sorry, I think I figured it out.
In my case I have to do the following:

```<code>Quaternion rot = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle);
var vecRot = Vector3.Transform(new Vector3(Y, Z, X), rot);
</code>```

The result will be:

```<code>var vecRes = new Vector3(vecRot.Z, vecRot.X, vecRot.Y);
</code>```

Body:
I've got a sensor that delivers object data in a coordinate system according to ISO 8855-2011.
My sensor is positioned at [0, 0, 0] but can be "misaligned". Therefore I want to compensate for roll, pitch and yaw.

In my App I perform the necessary rotations with the System.Numerics Lib and more specifically with a vector3 as the data point ([x, y, z]) and tried either a Matrix4x4 or a Quaternion as the rotation matrix.

Without having evaluated this final result a rotation in three steps seems to work quite well (at first glance looks like to be expected in my visualization). To perform the rotation I start by specifying three Quaternions for each axis and perform the rotation one after the other.

Vector3 vecMeas = new Vector3(x, y, z);
Quaternion rotRoll = Quaternion.CreateFromAxisAngle(new Vector3(1.0f, 0.0f, 0.0f), rollAngle);
Quaternion rotPitch = Quaternion.CreateFromAxisAngle(new Vector3(0.0f, 1.0f, 0.0f), pitchAngle);
Quaternion rotYaw = Quaternion.CreateFromAxisAngle(new Vector3(0.0f, 0.0f, 1.0f), yawAngle);

var vecRolled = Vector3.Transform(vecMeas, rotRoll);
var vecPitched = Vector3.Transform(vecRolled, rotPitch);
var vecResult = Vector3.Transform(vecPitched, rotYaw);

While this seems to work, it looks clumsy to me as the class Matrix4x4 and Quaternion offers a method called "CreateFromYawPitchRoll". I tried every combination of inputs for this method (if I remember correctly 6 combinations for the order of pitch, roll, yaw combined with 48 combinations of inputs for the order and sign of [x, y, z]), but was not able to produce the same as my rotation in 3 steps.

Example (one of ~288 combinations):

Vector3 vecMeas = new Vector3(x, y, z);
Quaternion rot = Quaternion.CreateFromYawPitchRoll(pitch, roll, yaw);
var vecResult = Vector3.Transform(vecMeas, rot);

The above shown "one step" solutions always looks off.

Unfortunately I was not able to find a a lot of information about the handedness (or the absence thereof) of the expected inputs for Matrix4x4 / Quaternion or the order in which the rotation of "CreateFromYawPitchRoll" is being performed. Do you have any idea, how I could refactor my code to be more elegant (aka maybe a one step solution) or how to properly use CreateFromYawPitchRoll? A multiplication of the rotation elements did not deliver the expected results (rotRoll * rotPitch * rotYaw).

Thanks in advance!

Update:
Sorry, I think I figured it out.
In my case I have to do the following:

Quaternion rot = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle);
var vecRot = Vector3.Transform(new Vector3(Y, Z, X), rot);

The result will be:

var vecRes = new Vector3(vecRot.Z, vecRot.X, vecRot.Y);


问:
How to only fetch the document with changes made form firebase with snapshot listener in swift?
I have a collection that I attach a snapshot listener to. Problem is when I change a document in this collection it refetch all the documents in the collection, not just the one that changed.
This is my code when I set the snapshot listener

```<code>let docRef = db.collection("users").document(userID).collection("Platser")
        docRef.addSnapshotListener { [weak self] snapshot, error in
            guard let data = snapshot, error == nil else {
                return
            }
</code>```

Inside .collection("Platser") is the collection for each "Plats" That have an auto-generated id from firebase as name.

If I change one document I just want to refetch that specific document, else the reads will go up way to high on a real app with users.

Been trying different ways to solve this and tried to read the firebase docs for this but I'm new to firebase and I really can't solve this one right now.

Body:
I have a collection that I attach a snapshot listener to. Problem is when I change a document in this collection it refetch all the documents in the collection, not just the one that changed.
This is my code when I set the snapshot listener

let docRef = db.collection("users").document(userID).collection("Platser")
        docRef.addSnapshotListener { [weak self] snapshot, error in
            guard let data = snapshot, error == nil else {
                return
            }

Inside .collection("Platser") is the collection for each "Plats" That have an auto-generated id from firebase as name.

If I change one document I just want to refetch that specific document, else the reads will go up way to high on a real app with users.

Been trying different ways to solve this and tried to read the firebase docs for this but I'm new to firebase and I really can't solve this one right now.


问:
FreeBSD open syscall returning 2 instead of -1 on error
I am writing a program in C for FreeBSD where the whole idea is that I don't use Libc or any libraries at all. For now, I have manually written some small wrappers for syscalls in order to use them in my code.

For some reason, my sys_open wrapper is returning 2 instead of -1 when I attempt to open a file that does not exist.

```<code>.global sys_open
sys_open:
    mov $5, %eax
    int $0x80
    ret
</code>```

        fd = sys_open(argv[i], O_RDONLY);

        /* weird bug where passing a non-existing file to sys_open returns 2 instead of -1.
         * here is a temporary fix, since 0, 1, and 2 will always be taken anyway. */
        if (fd < 3) {
            const char* errmessage = "error: failed to open file\n";
            sys_write(STDERR_FILENO, errmessage, strlen(errmessage));
            return errno;
        }
```

Yes, I am using a 32-bit FreeBSD system, don't ask why.

Here is a link to the whole project. The relevant files should be lib/syscalls/syscalls_i386.s and src/cat.c
https://github.com/minneelyyyy/uutils

This question really is just a shot in the dark, since I have no clue what could possibly be going on. My syscall wrappers work otherwise, including the open one. I've single stepped it in the debugger, checking to make sure that it is actually passing what I expect it to be passing (it is), and checking the return value, which is always 2 when the file does not exist.

Body:
I am writing a program in C for FreeBSD where the whole idea is that I don't use Libc or any libraries at all. For now, I have manually written some small wrappers for syscalls in order to use them in my code.

For some reason, my sys_open wrapper is returning 2 instead of -1 when I attempt to open a file that does not exist.

.global sys_open
sys_open:
    mov $5, %eax
    int $0x80
    ret

        fd = sys_open(argv[i], O_RDONLY);

        /* weird bug where passing a non-existing file to sys_open returns 2 instead of -1.
         * here is a temporary fix, since 0, 1, and 2 will always be taken anyway. */
        if (fd < 3) {
            const char* errmessage = "error: failed to open file\n";
            sys_write(STDERR_FILENO, errmessage, strlen(errmessage));
            return errno;
        }

Yes, I am using a 32-bit FreeBSD system, don't ask why.

Here is a link to the whole project. The relevant files should be lib/syscalls/syscalls_i386.s and src/cat.c
https://github.com/minneelyyyy/uutils

This question really is just a shot in the dark, since I have no clue what could possibly be going on. My syscall wrappers work otherwise, including the open one. I've single stepped it in the debugger, checking to make sure that it is actually passing what I expect it to be passing (it is), and checking the return value, which is always 2 when the file does not exist.


问:
PackagesNotFoundError: The following packages are not available from current channels:
I am trying to create a new python enviroment with python=3.6 by using the following command conda create --prefix ./env python=3.6 but every time i am getting this error Following packages are not available from current channels. But when i try with different python version like Python=3.8, 3.9 it works

```<code>    (base) hassaanzahid@Hassaans-MacBook-Pro VTuber_Unity-master % conda create --prefix ./env python=3.6
Collecting package metadata (current_repodata.json): done
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - python=3.6

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://conda.anaconda.org/conda-forge/osx-arm64
  - https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

I am also getting the same error while trying some of the python packages with these specific versions numpy<1.17, opencv-python>4, torch<=1.2.0, scipy>0.16

```<code>PackagesNotFoundError: The following packages are not available from current channels:

  - opencv-python[version='>4']
  - numpy[version='<1.17']
  - torch[version='<=1.2.0']

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://conda.anaconda.org/conda-forge/osx-arm64
  - https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

I have tried some of the solutions provided online but doesn't worked for me

```<code>conda config --append channels conda-forge
conda install -c conda-forge <package>
</code>```

Body:
I am trying to create a new python enviroment with python=3.6 by using the following command conda create --prefix ./env python=3.6 but every time i am getting this error Following packages are not available from current channels. But when i try with different python version like Python=3.8, 3.9 it works

    (base) hassaanzahid@Hassaans-MacBook-Pro VTuber_Unity-master % conda create --prefix ./env python=3.6
Collecting package metadata (current_repodata.json): done
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - python=3.6

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://conda.anaconda.org/conda-forge/osx-arm64
  - https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

I am also getting the same error while trying some of the python packages with these specific versions numpy<1.17, opencv-python>4, torch<=1.2.0, scipy>0.16

PackagesNotFoundError: The following packages are not available from current channels:

  - opencv-python[version='>4']
  - numpy[version='<1.17']
  - torch[version='<=1.2.0']

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://conda.anaconda.org/conda-forge/osx-arm64
  - https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

I have tried some of the solutions provided online but doesn't worked for me

conda config --append channels conda-forge
conda install -c conda-forge <package>


问:
Error: The incoming JSON object does not contain a client_email field GMAIL API
I'm trying to get my gmail API all setup and working but I'm getting this error: Error: The incoming JSON object does not contain a client_email field. I created the proper credentials from the GCS console and downloaded the JSON file, put the path to it inside an ENV variable GOOGLE_APPLICATION_CREDENTIALS=credentials.json (I'm keeping my json file in root). My file looks like this:

{
  "installed": {
    "client_id": "<id>.apps.googleusercontent.com",
    "project_id": "<name>",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "<client_secret>",
    "redirect_uris": ["http://localhost"]
  }
}
```
<p>Which is why the error confuses me because google didn't provide a <code>client_email</code> field. I looked at some other possible answers and one said to create an email from a service account. I did that and updated my JSON file to add this line <code>"client_email": "<service_account_name>@<project_name>.iam.gserviceaccount.com"</code>
And I'm still getting the error.</p>
<p>I can't auth from the gcloud CLI tool either because I'm running this on docker so it doesn't have access to the root folders of my mac.</p>
<p>Here is the full error:</p>
```slots-api       | node:events:491
slots-api       |       throw er; // Unhandled 'error' event
slots-api       |       ^
slots-api       |
slots-api       | Error: The incoming JSON object does not contain a client_email field
slots-api       |     at JWT.fromJSON (/app/node_modules/google-auth-library/build/src/auth/jwtclient.js:210:19)
slots-api       |     at GoogleAuth._cacheClientFromJSON (/app/node_modules/google-auth-library/build/src/auth/googleauth.js:410:20)
slots-api       |     at ReadStream.<anonymous> (/app/node_modules/google-auth-library/build/src/auth/googleauth.js:446:40)
slots-api       |     at ReadStream.emit (node:events:513:28)
slots-api       |     at endReadableNT (node:internal/streams/readable:1358:12)
slots-api       |     at processTicksAndRejections (node:internal/process/task_queues:83:21)
slots-api       | Emitted 'error' event on Subscription instance at:
slots-api       |     at Subscriber.<anonymous> (/app/node_modules/@google-cloud/pubsub/build/src/subscription.js:253:38)
slots-api       |     at Subscriber.emit (node:events:513:28)
slots-api       |     at MessageStream.<anonymous> (/app/node_modules/@google-cloud/pubsub/build/src/subscriber.js:545:38)
slots-api       |     at MessageStream.emit (node:events:513:28)
slots-api       |     at emitErrorNT (node:internal/streams/destroy:157:8)
slots-api       |     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
slots-api       |     at processTicksAndRejections (node:internal/process/task_queues:83:21)
slots-api       | error Command failed with exit code 1.
```

Body:
I'm trying to get my gmail API all setup and working but I'm getting this error: Error: The incoming JSON object does not contain a client_email field. I created the proper credentials from the GCS console and downloaded the JSON file, put the path to it inside an ENV variable GOOGLE_APPLICATION_CREDENTIALS=credentials.json (I'm keeping my json file in root). My file looks like this:

{
  "installed": {
    "client_id": "<id>.apps.googleusercontent.com",
    "project_id": "<name>",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "<client_secret>",
    "redirect_uris": ["http://localhost"]
  }
}

Which is why the error confuses me because google didn't provide a client_email field. I looked at some other possible answers and one said to create an email from a service account. I did that and updated my JSON file to add this line "client_email": "<service_account_name>@<project_name>.iam.gserviceaccount.com"
And I'm still getting the error.

I can't auth from the gcloud CLI tool either because I'm running this on docker so it doesn't have access to the root folders of my mac.

Here is the full error:

slots-api       | node:events:491
slots-api       |       throw er; // Unhandled 'error' event
slots-api       |       ^
slots-api       |
slots-api       | Error: The incoming JSON object does not contain a client_email field
slots-api       |     at JWT.fromJSON (/app/node_modules/google-auth-library/build/src/auth/jwtclient.js:210:19)
slots-api       |     at GoogleAuth._cacheClientFromJSON (/app/node_modules/google-auth-library/build/src/auth/googleauth.js:410:20)
slots-api       |     at ReadStream.<anonymous> (/app/node_modules/google-auth-library/build/src/auth/googleauth.js:446:40)
slots-api       |     at ReadStream.emit (node:events:513:28)
slots-api       |     at endReadableNT (node:internal/streams/readable:1358:12)
slots-api       |     at processTicksAndRejections (node:internal/process/task_queues:83:21)
slots-api       | Emitted 'error' event on Subscription instance at:
slots-api       |     at Subscriber.<anonymous> (/app/node_modules/@google-cloud/pubsub/build/src/subscription.js:253:38)
slots-api       |     at Subscriber.emit (node:events:513:28)
slots-api       |     at MessageStream.<anonymous> (/app/node_modules/@google-cloud/pubsub/build/src/subscriber.js:545:38)
slots-api       |     at MessageStream.emit (node:events:513:28)
slots-api       |     at emitErrorNT (node:internal/streams/destroy:157:8)
slots-api       |     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
slots-api       |     at processTicksAndRejections (node:internal/process/task_queues:83:21)
slots-api       | error Command failed with exit code 1.


问:
Laravel Token Preventing access to a page
I struggled implementing a search form on my website. I  finally got it done. But the problem is that if I click on the students link in the website, it doesn't let me. I have to manually type the address in the address bar to be able to visit this page.

```<code>http://127.0.0.1:8000/students //this is the actual link. but I have  manually type it like this.
</code>```

When I type http://127.0.0.1:8000/students , a token automatically adds to the link.

127.0.0.1:8000/students?_token=XLUB5ku5LenkhkMSuBv1Ibs4ElgdGiGxaeajOGkK&search

I think the reason the reason is because of the get method. But how do I get this problem solved so that I can just click the link and visit the page without going through the token

Body:
I struggled implementing a search form on my website. I  finally got it done. But the problem is that if I click on the students link in the website, it doesn't let me. I have to manually type the address in the address bar to be able to visit this page.

http://127.0.0.1:8000/students //this is the actual link. but I have  manually type it like this.

When I type http://127.0.0.1:8000/students , a token automatically adds to the link.

127.0.0.1:8000/students?_token=XLUB5ku5LenkhkMSuBv1Ibs4ElgdGiGxaeajOGkK&search

I think the reason the reason is because of the get method. But how do I get this problem solved so that I can just click the link and visit the page without going through the token


问:
Creating a B+ Tree from a REDO log file
Write a function in python "from_log(log)"to create a B+ Tree from a REDO log file.

Example log file:

log = Log([Record.start_transaction(1),\

Record.update(1,1,1),\

Record.update(1,2,2),\

Record.commit_transaction(1),\

Record.start_transaction(2),\

Record.update(2,1,2),\

Record.commit_transaction(2)])

class Log:

def init(self, records = None):

self.records = records if records else []

def str(self):

return str(self.records)

def repr(self):

return str(self)

def eq(self, other):

return self.records == other.records

class Record:

def start_transaction( transaction_id ):

return ("START", transaction_id)

def rollback_transaction( transaction_id ):

return ("ABORT", transaction_id)

def commit_transaction( transaction_id ):

return ("COMMIT", transaction_id)

def update( transaction_id, tuple_id, val ):

return (transaction_id, tuple_id, val)

Function Call:

from_log(log)

How B+-Tree looks like:

leaf4 = Node(\

KeySet([97,99]),\

PointerSet([None]*Index.FAN_OUT))

leaf3 = Node(\

KeySet([87, None]),\

PointerSet([None,None,leaf4]))

leaf2 = Node(\

KeySet([66,None]),\

PointerSet([None,None,leaf3]))

leaf1 = Node(\

KeySet([27,None]),\

PointerSet([None,None,leaf2]))

leaf0 = Node(\

KeySet([7,9]),\

PointerSet([None,None,leaf1]))

parent1 = Node(\

KeySet([97,None]),\

PointerSet([leaf3,leaf4,None]))

parent0 = Node(\

KeySet([27,66]),\

PointerSet([leaf0,leaf1,leaf2]))

root = Node(\

KeySet([87,None]),\

PointerSet([parent0,parent1,None]))

btree = Index(root)

Classes:

class KeySet:

NUM_KEYS = 2

def init(self, keys = None):

self.keys = keys if keys else [None]*KeySet.NUM_KEYS

def str(self):

return str(self.keys)

def repr(self):

return str(self)

def hash(self):

if keys[ 0 ] is None:

return 0

return reduce(lambda x, y: x^y, [x * Constants.a_prime for x in keys if x is not None])

def eq(self, other):

return self.keys == other.keys

class Node:

def init(self, keys = None, pointers = None):

self.keys = keys if keys else KeySet()

self.pointers = pointers if pointers else PointerSet()

def str(self):

return "Node(" + str(self.keys) + "|" + str(self.pointers) +")"

def repr(self):

return str(self)

def hash(self):

return hash(keys) ^ hash(pointers)

def eq(self, other):

return self.keys == other.keys and self.pointers == other.pointers

@staticmethod

def get_num_keys():

return KeySet.NUM_KEYS

@staticmethod

def get_fan_out():

return KeySet.NUM_KEYS + 1

class PointerSet:

FAN_OUT = 3

def init(self, pointers = None):

self.pointers = pointers if pointers else [None]*PointerSet.FAN_OUT

def str(self):

return str(self.pointers)

def repr(self):

return str(self)

def hash(self):

if pointers[ 0 ] is None:

return 0

return reduce(lambda x, y: x^y, [hash(x) * Constants.a_prime for x in pointers if x is not None])

def eq(self, other):

return self.pointers == other.pointers

Write the function from_log(log).

Title: Creating a B+ Tree from a REDO log file


问:
Why is OpenGL telling me that terminate called after throwing an instance of 'int' after running it?
So I tried to make an OpenGL project with GLFW and glad in visual studio code, but it would throw and error when I would compile and run the program.

I tried to make 3 triangles in a window, it worked so I tried organizing the VBO, VAO, EBO, shaderProgram, vertexShaderSource, and fragmentShaderSource into individual files, and compiled and ran it, I expected the usual result but would give me a window that is not responding, then it would terminate and give out an error. I'm not sure witch of the files are causing this, but my guess is the main.cpp file:

```<code>#include"header/shaderClass.h"
#include"header/VAO.h"
#include"header/VBO.h"
#include"header/EBO.h"

//some vertex and indices arrays here

int main()
{
    // Initialize GLFW
    glfwInit();

    // Tell GLFW what version of OpenGL we are using
    // In this case we are using OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // Tell GLFW we are using the CORE profile
    // So that means we only have the modern functions
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Create a GLFWwindow object of 800 by 800 pixels, naming it "YoutubeOpenGL"
    GLFWwindow* window = glfwCreateWindow(800, 800, "YoutubeOpenGL", NULL, NULL);
    // Error check if the window fails to create
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    // Introduce the window into the current context
    glfwMakeContextCurrent(window);

    //Load GLAD so it configures OpenGL
    gladLoadGL();
    // Specify the viewport of OpenGL in the Window
    // In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
    glViewport(0, 0, 800, 800);

    // Generates Shader object using shaders defualt.vert and default.frag
    Shader shaderProgram("default.vert", "default.frag");

    // Generates Vertex Array Object and binds it
    VAO VAO1;
    VAO1.Bind();

    // Generates Vertex Buffer Object and links it to vertices
    VBO VBO1(vertices, sizeof(vertices));
    // Generates Element Buffer Object and links it to indices
    EBO EBO1(indices, sizeof(indices));

    // Links VBO to VAO
    VAO1.LinkVBO(VBO1, 0);
    // Unbind all to prevent accidentally modifying them
    VAO1.Unbind();
    VBO1.Unbind();
    EBO1.Unbind();

    // Main while loop
    while (!glfwWindowShouldClose(window))
    {
        // Specify the color of the background
        glClearColor(0.07f, 0.13f, 0.17f, 1.0f);
        // Clean the back buffer and assign the new color to it
        glClear(GL_COLOR_BUFFER_BIT);
        // Tell OpenGL which Shader Program we want to use
        shaderProgram.Activate();
        // Bind the VAO so OpenGL knows to use it
        VAO1.Bind();
        // Draw primitives, number of indices, datatype of indices, index of indices
        glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);
        // Swap the back buffer with the front buffer
        glfwSwapBuffers(window);
        // Take care of all GLFW events
        glfwPollEvents();
    }

    // Delete all the objects we've created
    VAO1.Delete();
    VBO1.Delete();
    EBO1.Delete();
    shaderProgram.Delete();
    // Delete window before ending the program
    glfwDestroyWindow(window);
    // Terminate GLFW before ending the program
    glfwTerminate();
    return 0;
}
</code>```

Body:
So I tried to make an OpenGL project with GLFW and glad in visual studio code, but it would throw and error when I would compile and run the program.

I tried to make 3 triangles in a window, it worked so I tried organizing the VBO, VAO, EBO, shaderProgram, vertexShaderSource, and fragmentShaderSource into individual files, and compiled and ran it, I expected the usual result but would give me a window that is not responding, then it would terminate and give out an error. I'm not sure witch of the files are causing this, but my guess is the main.cpp file:

#include"header/shaderClass.h"
#include"header/VAO.h"
#include"header/VBO.h"
#include"header/EBO.h"

//some vertex and indices arrays here

int main()
{
    // Initialize GLFW
    glfwInit();

    // Tell GLFW what version of OpenGL we are using
    // In this case we are using OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // Tell GLFW we are using the CORE profile
    // So that means we only have the modern functions
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Create a GLFWwindow object of 800 by 800 pixels, naming it "YoutubeOpenGL"
    GLFWwindow* window = glfwCreateWindow(800, 800, "YoutubeOpenGL", NULL, NULL);
    // Error check if the window fails to create
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    // Introduce the window into the current context
    glfwMakeContextCurrent(window);

    //Load GLAD so it configures OpenGL
    gladLoadGL();
    // Specify the viewport of OpenGL in the Window
    // In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
    glViewport(0, 0, 800, 800);

    // Generates Shader object using shaders defualt.vert and default.frag
    Shader shaderProgram("default.vert", "default.frag");

    // Generates Vertex Array Object and binds it
    VAO VAO1;
    VAO1.Bind();

    // Generates Vertex Buffer Object and links it to vertices
    VBO VBO1(vertices, sizeof(vertices));
    // Generates Element Buffer Object and links it to indices
    EBO EBO1(indices, sizeof(indices));

    // Links VBO to VAO
    VAO1.LinkVBO(VBO1, 0);
    // Unbind all to prevent accidentally modifying them
    VAO1.Unbind();
    VBO1.Unbind();
    EBO1.Unbind();

    // Main while loop
    while (!glfwWindowShouldClose(window))
    {
        // Specify the color of the background
        glClearColor(0.07f, 0.13f, 0.17f, 1.0f);
        // Clean the back buffer and assign the new color to it
        glClear(GL_COLOR_BUFFER_BIT);
        // Tell OpenGL which Shader Program we want to use
        shaderProgram.Activate();
        // Bind the VAO so OpenGL knows to use it
        VAO1.Bind();
        // Draw primitives, number of indices, datatype of indices, index of indices
        glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);
        // Swap the back buffer with the front buffer
        glfwSwapBuffers(window);
        // Take care of all GLFW events
        glfwPollEvents();
    }

    // Delete all the objects we've created
    VAO1.Delete();
    VBO1.Delete();
    EBO1.Delete();
    shaderProgram.Delete();
    // Delete window before ending the program
    glfwDestroyWindow(window);
    // Terminate GLFW before ending the program
    glfwTerminate();
    return 0;
}


问:
android.app.Application cannot be cast to com.example.skillit.data.InventoryApplication(DATA BASE)
```<code>2022-12-11 02:50:28.862 24393-24393/com.example.skillit E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.skillit, PID: 24393
    java.lang.ClassCastException: android.app.Application cannot be cast to com.example.skillit.data.InventoryApplication
        at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:22)
        at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:21)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:47)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
        at com.example.skillit.ProfileActivity.getViewModel(ProfileActivity.kt:21)
        at com.example.skillit.ProfileActivity.onCreate$lambda$3(ProfileActivity.kt:51)
        at com.example.skillit.ProfileActivity.$r8$lambda$733-BBVTFBdHTXlcl6xFIzJMP3c(Unknown Source:0)
        at com.example.skillit.ProfileActivity$$ExternalSyntheticLambda3.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7881)
        at android.widget.TextView.performClick(TextView.java:16201)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
        at android.view.View.performClickInternal(View.java:7858)
        at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
        at android.view.View$PerformClick.run(View.java:30863)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:226)
        at android.os.Looper.loop(Looper.java:313)
        at android.app.ActivityThread.main(ActivityThread.java:8741)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)

</code>```

THIS IS THE ProfileActivity.kt code:

```<code>package com.example.skillit

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Button
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.activityViewModels
import com.example.skillit.data.InventoryApplication
import com.example.skillit.databinding.FragmentItemDetailBinding
import com.example.skillit.databinding.ProfileActivityBinding

class ProfileActivity : AppCompatActivity() {

    //private var _binding: ProfileActivityBinding? = null
    //private val binding get() = _binding!!

    private val viewModel: InventoryViewModel by viewModels {
        InventoryViewModelFactory((application as InventoryApplication).database.itemDao())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.supportActionBar?.hide()
        //_binding = ProfileActivityBinding.inflate(LayoutInflater.from(this))
        //setContentView(binding.root)
        setContentView(R.layout.profile_activity)
        val explore_button = findViewById(R.id.explore_button) as CardView
        val profile_button = findViewById(R.id.profile_button) as CardView
        val home_button = findViewById(R.id.home_button) as CardView
        val upload_button = findViewById<Button>(R.id.upload)
        home_button.setOnClickListener{
            intent = Intent(this, HomeActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }
        explore_button.setOnClickListener{
            intent = Intent(this, ExploreActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }
        profile_button.setOnClickListener{
            intent = Intent(this, ProfileActivity::class.java)
            startActivity(intent)
        }

        upload_button.setOnClickListener{
            viewModel.addNewItem("name", "link")
        }

    }
}
</code>```

THIS IS THE InventoryAplication.kt code:

```<code>package com.example.skillit.data

import android.app.Application

class InventoryApplication : Application() {
    val database: ItemRoomDatabase by lazy { ItemRoomDatabase.getDatabase(this) }
}
</code>```

THIS IS THE ItemRoomDatabase.kt code:

```<code>package com.example.skillit.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class ItemRoomDatabase : RoomDatabase() {

    abstract fun itemDao(): ItemDao

    companion object {
        @Volatile
        private var INSTANCE: ItemRoomDatabase? = null

        fun getDatabase(context: Context): ItemRoomDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ItemRoomDatabase::class.java,
                    "item_database"
                )
                    // Wipes and rebuilds instead of migrating if no Migration object.
                    // Migration is not part of this codelab.
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                // return instance
                instance
            }
        }
    }
}
</code>```

I tried to upload data to a database when you press the upload_button in the ProfileActivity.kt file but when you do, in the "Logcat" tab it keeps showing me the error mentioned above, I think the problem is with the ItemRoomDatabase but I cant figure out what doesn't work .

Body:
2022-12-11 02:50:28.862 24393-24393/com.example.skillit E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.skillit, PID: 24393
    java.lang.ClassCastException: android.app.Application cannot be cast to com.example.skillit.data.InventoryApplication
        at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:22)
        at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:21)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:47)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
        at com.example.skillit.ProfileActivity.getViewModel(ProfileActivity.kt:21)
        at com.example.skillit.ProfileActivity.onCreate$lambda$3(ProfileActivity.kt:51)
        at com.example.skillit.ProfileActivity.$r8$lambda$733-BBVTFBdHTXlcl6xFIzJMP3c(Unknown Source:0)
        at com.example.skillit.ProfileActivity$$ExternalSyntheticLambda3.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7881)
        at android.widget.TextView.performClick(TextView.java:16201)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
        at android.view.View.performClickInternal(View.java:7858)
        at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
        at android.view.View$PerformClick.run(View.java:30863)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:226)
        at android.os.Looper.loop(Looper.java:313)
        at android.app.ActivityThread.main(ActivityThread.java:8741)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)

THIS IS THE ProfileActivity.kt code:

package com.example.skillit

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Button
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.activityViewModels
import com.example.skillit.data.InventoryApplication
import com.example.skillit.databinding.FragmentItemDetailBinding
import com.example.skillit.databinding.ProfileActivityBinding

class ProfileActivity : AppCompatActivity() {

    //private var _binding: ProfileActivityBinding? = null
    //private val binding get() = _binding!!

    private val viewModel: InventoryViewModel by viewModels {
        InventoryViewModelFactory((application as InventoryApplication).database.itemDao())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.supportActionBar?.hide()
        //_binding = ProfileActivityBinding.inflate(LayoutInflater.from(this))
        //setContentView(binding.root)
        setContentView(R.layout.profile_activity)
        val explore_button = findViewById(R.id.explore_button) as CardView
        val profile_button = findViewById(R.id.profile_button) as CardView
        val home_button = findViewById(R.id.home_button) as CardView
        val upload_button = findViewById<Button>(R.id.upload)
        home_button.setOnClickListener{
            intent = Intent(this, HomeActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }
        explore_button.setOnClickListener{
            intent = Intent(this, ExploreActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }
        profile_button.setOnClickListener{
            intent = Intent(this, ProfileActivity::class.java)
            startActivity(intent)
        }

        upload_button.setOnClickListener{
            viewModel.addNewItem("name", "link")
        }

    }
}

THIS IS THE InventoryAplication.kt code:

package com.example.skillit.data

import android.app.Application

class InventoryApplication : Application() {
    val database: ItemRoomDatabase by lazy { ItemRoomDatabase.getDatabase(this) }
}

THIS IS THE ItemRoomDatabase.kt code:

package com.example.skillit.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class ItemRoomDatabase : RoomDatabase() {

    abstract fun itemDao(): ItemDao

    companion object {
        @Volatile
        private var INSTANCE: ItemRoomDatabase? = null

        fun getDatabase(context: Context): ItemRoomDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ItemRoomDatabase::class.java,
                    "item_database"
                )
                    // Wipes and rebuilds instead of migrating if no Migration object.
                    // Migration is not part of this codelab.
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                // return instance
                instance
            }
        }
    }
}

I tried to upload data to a database when you press the upload_button in the ProfileActivity.kt file but when you do, in the "Logcat" tab it keeps showing me the error mentioned above, I think the problem is with the ItemRoomDatabase but I cant figure out what doesn't work .


问:
Discord JDA keeps printing [Finalizer] WARN RestAction - Found unclosed resources in MessageAction instance
I send an image file to a specific discord channel every minute with Quartz Scheduler.
However, when image file is sent, my bot's console outputs the log below.

```<code>[Finalizer] WARN RestAction - Found unclosed resources in MessageAction instance, closing on finalization step!
</code>```

Is it possible to disable log? Or did I do something wrong?

Files are sent well, but this log is very annoying because it prints out every time a file is sent to the console.

Here is my code (If you need):

ImageSendingJob.java

```<code>public class ImageSendingJob implements Job {
    @Override
    public void execute(JobExecutionContext context) {
        TextChannel textChannel = JDA.guild.getTextChannelById("ID");
        InputStream image = // Image
        textChannel
                .sendFile(image, String.format("%s.png", context.getFireTime()))
                .complete();
    }
}
</code>```

SchedulerManager.java

```<code>private void startScheduler() {
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    try {
        Scheduler scheduler = schedulerFactory.getScheduler();

        JobDetail job = newJob(ImageSendingJob.class)
                .withIdentity("Job", Scheduler.DEFAULT_GROUP)
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("JobTrigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(60)
                        .repeatForever())
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    } catch (SchedulerException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Body:
I send an image file to a specific discord channel every minute with Quartz Scheduler.
However, when image file is sent, my bot's console outputs the log below.

[Finalizer] WARN RestAction - Found unclosed resources in MessageAction instance, closing on finalization step!

Is it possible to disable log? Or did I do something wrong?

Files are sent well, but this log is very annoying because it prints out every time a file is sent to the console.

Here is my code (If you need):

ImageSendingJob.java

public class ImageSendingJob implements Job {
    @Override
    public void execute(JobExecutionContext context) {
        TextChannel textChannel = JDA.guild.getTextChannelById("ID");
        InputStream image = // Image
        textChannel
                .sendFile(image, String.format("%s.png", context.getFireTime()))
                .complete();
    }
}

SchedulerManager.java

private void startScheduler() {
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    try {
        Scheduler scheduler = schedulerFactory.getScheduler();

        JobDetail job = newJob(ImageSendingJob.class)
                .withIdentity("Job", Scheduler.DEFAULT_GROUP)
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("JobTrigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(60)
                        .repeatForever())
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    } catch (SchedulerException e) {
        throw new RuntimeException(e);
    }
}


问:
error: expected expression in variadic macros
I want to write a macros to print pairs of {variable name, variable value}. The variables are supposed to be arguments of variadic macros.
I made a simple code, that produces compilation error: "expected expression" in cases when number of variables to print is less than maximum possible number.

```<code>#define IS_EMPTY(...) ( sizeof( (char[]){#__VA_ARGS__} ) == 1 )
#define PRINT_VAR(x) std::cout << "\"" << #x << "\": " << (x) << " ";

#define PRINT_VARS3(x, ...) {PRINT_VAR(x); }

#define PRINT_VARS2(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS3(__VA_ARGS__); }
#define PRINT_VARS1(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS2(__VA_ARGS__); }
#define PRINT_VARS(x, ...)  {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) {\
                             PRINT_VARS1(__VA_ARGS__); \
                             } \
                             std::cout << "\n";}

int i = 100;
float j = 200.5;
int k = 300;
float l = -0.576f;

PRINT_VARS(i, j, k, l); // works fine
//PRINT_VARS(i, j); // compilation error

</code>```

Thing that I cant understand, if I remove << (x) from second line, PRINT_VARS work with different number of arguments.
What is the reason and how to fix it?
Thank you!

Removing << (x) from the second line makes code compliable and working except it cant printout the variables values.

I expect the compiler not to check if constexpr branches at 0 condition. But it looks like empty
VA_ARGS passed to PRINT_VAR macros that leads to this error.

I have tried this code with gcc12 and clang14 compilers.

Body:
I want to write a macros to print pairs of {variable name, variable value}. The variables are supposed to be arguments of variadic macros.
I made a simple code, that produces compilation error: "expected expression" in cases when number of variables to print is less than maximum possible number.

#define IS_EMPTY(...) ( sizeof( (char[]){#__VA_ARGS__} ) == 1 )
#define PRINT_VAR(x) std::cout << "\"" << #x << "\": " << (x) << " ";

#define PRINT_VARS3(x, ...) {PRINT_VAR(x); }

#define PRINT_VARS2(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS3(__VA_ARGS__); }
#define PRINT_VARS1(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS2(__VA_ARGS__); }
#define PRINT_VARS(x, ...)  {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) {\
                             PRINT_VARS1(__VA_ARGS__); \
                             } \
                             std::cout << "\n";}

int i = 100;
float j = 200.5;
int k = 300;
float l = -0.576f;

PRINT_VARS(i, j, k, l); // works fine
//PRINT_VARS(i, j); // compilation error

Thing that I cant understand, if I remove << (x) from second line, PRINT_VARS work with different number of arguments.
What is the reason and how to fix it?
Thank you!

Removing << (x) from the second line makes code compliable and working except it cant printout the variables values.

I expect the compiler not to check if constexpr branches at 0 condition. But it looks like empty
VA_ARGS passed to PRINT_VAR macros that leads to this error.

I have tried this code with gcc12 and clang14 compilers.


问:
ICS Event with Status:Cancelled is Being Re-Added to the Mac Outlook Calendar?
I sent this .ics event with an email:

```<code>BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:adamgibbons/ics
METHOD:REQUEST
X-PUBLISHED-TTL:PT1H
BEGIN:VEVENT
UID:RUo-Akvn-dNj7pve87fNv
SUMMARY:Appointment with your Nurse at mywebapp.com
DTSTAMP:20221211T001700Z
DTSTART:20221208T170400Z
SEQUENCE:2
DESCRIPTION:12/8 12:04pm
URL:https://www.mywebapp.com/
STATUS:CANCELLED
ORGANIZER;CN=John Smith
CLASS:PRIVATE
ATTENDEE;RSVP=FALSE;CN=John Smith
ATTENDEE;RSVP=FALSE;CN=Jane Smith
DURATION:PT15M
END:VEVENT
END:VCALENDAR
</code>```

I have sent it via NodeMailer with a MailComposer object that looks like this:

Notice that the method is set in the icalEvent, to CANCEL. NodeMailer says that this is the way to set the method here.

According to this SO post, the event should be marked in Outlook as cancelled.

The .ics file I send is being received, but instead of cancelling the event, the event is re-added to the Outlook Calendar.

How can I correct this?

Body:
I sent this .ics event with an email:

BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:adamgibbons/ics
METHOD:REQUEST
X-PUBLISHED-TTL:PT1H
BEGIN:VEVENT
UID:RUo-Akvn-dNj7pve87fNv
SUMMARY:Appointment with your Nurse at mywebapp.com
DTSTAMP:20221211T001700Z
DTSTART:20221208T170400Z
SEQUENCE:2
DESCRIPTION:12/8 12:04pm
URL:https://www.mywebapp.com/
STATUS:CANCELLED
ORGANIZER;CN=John Smith
CLASS:PRIVATE
ATTENDEE;RSVP=FALSE;CN=John Smith
ATTENDEE;RSVP=FALSE;CN=Jane Smith
DURATION:PT15M
END:VEVENT
END:VCALENDAR

I have sent it via NodeMailer with a MailComposer object that looks like this:

Notice that the method is set in the icalEvent, to CANCEL. NodeMailer says that this is the way to set the method here.

According to this SO post, the event should be marked in Outlook as cancelled.

The .ics file I send is being received, but instead of cancelling the event, the event is re-added to the Outlook Calendar.

How can I correct this?


问:
Recommended protections disabled
I see a lot of questions around "recommended protections disabled", but I haven't been able to find anything about "recommended protections" in the NPM documentation. Does anyone have a source what recommended protections are or how to enable them?</p>

Title: Recommended protections disabled


问:
Laravel JWT makes new request insted of sending status
I'm making an API in laravel with tymon/jwt-auth package. based on https://jwt-auth.readthedocs.io/en/develop/

Login works fine.

Sending GET request with right token works fine.

BUT when I send a GET request with incorrect/no token it redirects me to POST login (wants me to login) rather than send a 401

GET /api/reviews with no Auth:

```<code>The GET method is not supported for this route. Supported methods: POST.
</code>```

api.php

```<code>Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group([

    'prefix' => 'auth',

], function ($router) {
    Route::post('login', [AuthController::class, 'login'])->name('login');
});

Route::get('reviews',[ReviewController::class, 'index']);
</code>```

AuthController.php

```<code>class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (!$token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            "user" => auth()->user(),
            "access_token" => $token,
        ]);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }
}
</code>```

ReviewController.php

```<code>class ReviewController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function index()
    {

        $reviews = Review::all();

        return response()->json([
            'status' => 200,
            'reviews' => $reviews
        ]);
    }
}

</code>```

Should I remove the auth middleware and do it manually?

Body:
I'm making an API in laravel with tymon/jwt-auth package. based on https://jwt-auth.readthedocs.io/en/develop/

Login works fine.

Sending GET request with right token works fine.

BUT when I send a GET request with incorrect/no token it redirects me to POST login (wants me to login) rather than send a 401

GET /api/reviews with no Auth:

The GET method is not supported for this route. Supported methods: POST.

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group([

    'prefix' => 'auth',

], function ($router) {
    Route::post('login', [AuthController::class, 'login'])->name('login');
});

Route::get('reviews',[ReviewController::class, 'index']);

AuthController.php

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (!$token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            "user" => auth()->user(),
            "access_token" => $token,
        ]);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }
}

ReviewController.php

class ReviewController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function index()
    {

        $reviews = Review::all();

        return response()->json([
            'status' => 200,
            'reviews' => $reviews
        ]);
    }
}

Should I remove the auth middleware and do it manually?


问:
Next.js 13 appDir: Fetch user on the server using express session cookie
I have an API using express-session and I wanted to get the user in a server component / create a middleware for Next.js to check if the user is authenticated.

Fetching the user in a server component didn't work because the server doesn't know my session cookie / id and the fetch result is always null:

```<code>// app/dashboard/page.tsx
import React, { Suspense } from "react";

async function getUser() {
    const user = await fetch("http://localhost:3100/trpc/user.me", {credentials: "include"}).then((res)=> res.json())
    console.log(user) // null
    return user
}

const Comp = async ({ children }: { children: React.ReactNode }) => {
    const user = await getUser()
    return (
        <>
            <Suspense fallback={<div>Loading user...</div>}>
                <div>{user.displayName}</div>
            </Suspense>
        </>
    );
}

export default Comp;
</code>```

So then I thought I could create a middleware and pass on my session cookie, but this also didn't work:

```<code>// middleware.tsx
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {

    const sCookie = "xid";

    const session = request.cookies.get(sCookie)?.value
    console.log(session) // s:w43gRjd whatever

    async function getUser() {
        const user = await fetch("http://localhost:3100/trpc/user.me", {credentials: "include"}).then((res)=> res.json())
        console.log(user) // null
    }
    getUser()

    const response = NextResponse.next()

    // Add session cookie to response
    if (request.cookies.has(sCookie)) {
        response.cookies.set(sCookie, session!)
    }
    return response
}

export const config = {
    matcher: [
        "/((?!api|_next/static|favicon.ico).*)", // don't execute middleware when hitting static assets
    ],
}
</code>```

Has anyone got any idea on how to solve this?
Thanks! :)

Body:
I have an API using express-session and I wanted to get the user in a server component / create a middleware for Next.js to check if the user is authenticated.

Fetching the user in a server component didn't work because the server doesn't know my session cookie / id and the fetch result is always null:

// app/dashboard/page.tsx
import React, { Suspense } from "react";

async function getUser() {
    const user = await fetch("http://localhost:3100/trpc/user.me", {credentials: "include"}).then((res)=> res.json())
    console.log(user) // null
    return user
}

const Comp = async ({ children }: { children: React.ReactNode }) => {
    const user = await getUser()
    return (
        <>
            <Suspense fallback={
Loading user...
}>

{user.displayName}

            </Suspense>
        </>
    );
}

export default Comp;

So then I thought I could create a middleware and pass on my session cookie, but this also didn't work:

// middleware.tsx
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {

    const sCookie = "xid";

    const session = request.cookies.get(sCookie)?.value
    console.log(session) // s:w43gRjd whatever

    async function getUser() {
        const user = await fetch("http://localhost:3100/trpc/user.me", {credentials: "include"}).then((res)=> res.json())
        console.log(user) // null
    }
    getUser()

    const response = NextResponse.next()

    // Add session cookie to response
    if (request.cookies.has(sCookie)) {
        response.cookies.set(sCookie, session!)
    }
    return response
}

export const config = {
    matcher: [
        "/((?!api|_next/static|favicon.ico).*)", // don't execute middleware when hitting static assets
    ],
}

Has anyone got any idea on how to solve this?
Thanks! :)