问:
Excel Macro to search a tab in a worksheet for text enclosed in "%%", copy & paste the wildcard text to a separate tab
I have one (1) worksheet with multiple tabs.
Each tab = multiple columns and rows.

I would like to be able to run a macro to search for all "%%*%%" text strings by column and list somewhere (separate tab/section by column - i.e. name of the column can be cell name of column/header).

Sample of macro results n separate section/tab:

Worksheet #1 Info
Column1 - name could be from data in Column1 Row 63
%%Name%%
%%Country%%
%%LanguagePreference%%
and so on....

Column2- name could be from data in Column2 Row 63
%%NickName%%
%%Appliance%%
%%LanguagePreference%%
and so on until all columns are compiled

Thank you.

I have searched and couldn't find a macro that worked.


来源: stackexchange

问:
How do I use Python with Google APIs to request a list of delegates, and to also add and remove delegates?
People in our environment think if they can not see a group, or user, it is okay to request that email address as a group. For whatever purpose, not realizing that it may already be created, they just do not have access. I am attempting to design a website where my help desk can do a lookup of an email alias, return if it's a group or an email.  If it's a group, return the managers for the group, if it's an email account, return any delegates to the account.  I have most of this already worked out...  but I am having difficulty with the delegate list, add, delete code.  I can't find any working examples online (like I seem to be able to find for everything else).

What I am searching for:

The scope for this lookup (listing) and possibly modification (create\delete delegates)
The code for the lookup (please see below for what has NOT worked for me)
It may also require a separate credentials call...  but I can't seem to find concrete evidence of this.

For example, I have been attempting to create a function, which is not currently working.

```<code>#!/usr/bin/env python3
# Test delegation code - or Listing Delegates to an account
import sys
sys.dont_write_bytecode = True
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient import discovery
from google.oauth2 import service_account

# Global Variables
lCreds = os.path.expanduser('~/python-google-data/ldap-creds')
gCreds = os.path.expanduser('~/python-google-data/credentials.json')
gToken = os.path.expanduser('~/python-google-data/token.json')
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/gmail.settings.basic']

# Create connection to Google through scopes and OAuth2
# include needed: from googleLib import getCredentials
# service = getCredentials()
def getCredentials():
  creds = None
  if os.path.exists(gToken):
    creds = Credentials.from_authorized_user_file(gToken, SCOPES)
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(gCreds, SCOPES)
      creds = flow.run_local_server(port=0)
    with open(gToken, 'w') as token:
      token.write(creds.to_json())
  service = build('gmail', 'v1', credentials=creds)
  return service

# Code not working yet
def getDelegates(email):
  print('running getDelegates')
  service = getCredentials()
  delegateDump = service.users().settings().delegates().list(userId='me', body={'delegateEmail': email}).execute()
  return delegateDump

def main():
  email = "email@domain.com"
  delegateDump = getDelegates(email)
  print(delegateDump)

if __name__ == '__main__':
  main()
</code>```

I am getting the following error, which leads me to believe my command is not formatted properly.

```<code>Traceback (most recent call last):
  File "./delegate", line 50, in <module>
    main()
  File "./delegate", line 46, in main
    delegateDump = getDelegates(email)
  File "./delegate", line 41, in getDelegates
    delegateDump = service.users().settings().delegates().list(userId='me', body={'delegateEmail': email}).execute()
  File "/home/kmelillo/.local/lib/python3.8/site-packages/googleapiclient/discovery.py", line 1025, in method
    raise TypeError("Got an unexpected keyword argument {}".format(name))
TypeError: Got an unexpected keyword argument body
</code>```

I would expect the delegateDump variable to be the successful list of delegates on the account I replace email@domain.com with. The account I am replacing it with does have a few delegates assigned.

ContentLicense: CC BY-SA 4.0

Body:
People in our environment think if they can not see a group, or user, it is okay to request that email address as a group. For whatever purpose, not realizing that it may already be created, they just do not have access. I am attempting to design a website where my help desk can do a lookup of an email alias, return if it's a group or an email.  If it's a group, return the managers for the group, if it's an email account, return any delegates to the account.  I have most of this already worked out...  but I am having difficulty with the delegate list, add, delete code.  I can't find any working examples online (like I seem to be able to find for everything else).

What I am searching for:

The scope for this lookup (listing) and possibly modification (create\delete delegates)
The code for the lookup (please see below for what has NOT worked for me)
It may also require a separate credentials call...  but I can't seem to find concrete evidence of this.

For example, I have been attempting to create a function, which is not currently working.

#!/usr/bin/env python3
# Test delegation code - or Listing Delegates to an account
import sys
sys.dont_write_bytecode = True
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient import discovery
from google.oauth2 import service_account

# Global Variables
lCreds = os.path.expanduser('~/python-google-data/ldap-creds')
gCreds = os.path.expanduser('~/python-google-data/credentials.json')
gToken = os.path.expanduser('~/python-google-data/token.json')
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/gmail.settings.basic']

# Create connection to Google through scopes and OAuth2
# include needed: from googleLib import getCredentials
# service = getCredentials()
def getCredentials():
  creds = None
  if os.path.exists(gToken):
    creds = Credentials.from_authorized_user_file(gToken, SCOPES)
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(gCreds, SCOPES)
      creds = flow.run_local_server(port=0)
    with open(gToken, 'w') as token:
      token.write(creds.to_json())
  service = build('gmail', 'v1', credentials=creds)
  return service

# Code not working yet
def getDelegates(email):
  print('running getDelegates')
  service = getCredentials()
  delegateDump = service.users().settings().delegates().list(userId='me', body={'delegateEmail': email}).execute()
  return delegateDump

def main():
  email = "email@domain.com"
  delegateDump = getDelegates(email)
  print(delegateDump)

if __name__ == '__main__':
  main()

I am getting the following error, which leads me to believe my command is not formatted properly.

Traceback (most recent call last):
  File "./delegate", line 50, in <module>
    main()
  File "./delegate", line 46, in main
    delegateDump = getDelegates(email)
  File "./delegate", line 41, in getDelegates
    delegateDump = service.users().settings().delegates().list(userId='me', body={'delegateEmail': email}).execute()
  File "/home/kmelillo/.local/lib/python3.8/site-packages/googleapiclient/discovery.py", line 1025, in method
    raise TypeError("Got an unexpected keyword argument {}".format(name))
TypeError: Got an unexpected keyword argument body

I would expect the delegateDump variable to be the successful list of delegates on the account I replace email@domain.com with. The account I am replacing it with does have a few delegates assigned.


问:
Python pypresence discord
It does not give errors, but the statute simply does not appear in the discord.

```<code>from pypresence import Presence
from time import time

RPC = Presence("848861630226104320")
btns = [
    {
        "label": "YouTube",
        "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    }
]

RPC.connect()
# noinspection PyTypeChecker
RPC.update(
    start=time(),
    buttons=btns,
)

input()
</code>```

I reinstalled the library many times and wrote that everything is there, but nothing works. Any suggestions?

Title: Python pypresence discord

Body:
It does not give errors, but the statute simply does not appear in the discord.

from pypresence import Presence
from time import time

RPC = Presence("848861630226104320")
btns = [
    {
        "label": "YouTube",
        "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    }
]

RPC.connect()
# noinspection PyTypeChecker
RPC.update(
    start=time(),
    buttons=btns,
)

input()

I reinstalled the library many times and wrote that everything is there, but nothing works. Any suggestions?


问:
React - React router v6, how to redirect setting state
I am doing a react app that brings some data when app is mounted, in a component I want to redirect the user to a url and also pass the state in order to render the data in the state, for this I saw that in v6 you can't use the this.props.history.push('/url') and instead you must create a service and decorate the export of the component you want to use the redirect so I did it like this:

withNavigateService.js

```<code>import { useNavigate } from "react-router-dom";

export const withNavigate = (Component) => {
  const Wrapper = (props) => {
    const navigate = useNavigate();

    return (
      <Component
      {...props}
        navigate={navigate}
        />
    );
  };

  return Wrapper;
};
</code>```

in the component from where I am trying to redirect I want to set as state the data fetched based on the input in a form and then redirect so the new state is the defined in the redirect and not the one that was defined the first time the app was mounted.
this is the code I have to redirect

```<code>import { withNavigate } from '../../services/withNavigate';
.
.
.

    handleSubmit(event){
        event.preventDefault()

        // redirect to the component with the search criteria
        // the search criteria will be passed as query parameters
        var tipo  = this.state.tipo
        var marca = toTitleCase(this.state.marca)
        var linea = this.state.linea
        axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )
        .then((response) => {

            // this is my try to redirect with the new state but when the new page is loaded                // the data that is rendered is the one that was first defined when the app was mounted and //not the new state defined here
            this.props.navigate("/store",{
                state:{
                    product:response.data
                }
            });
        })
        .catch((error) => {
            console.log(error)
        })

    }
.
.
.
export default withNavigate(Finder);
</code>```

but when the redirected page is loaded I saw the data rendered with the state defined the first time the app was mounted and not the defined in the redirect.

how can i achieve my objective i.e set the state in the redirect?

Edit: the component from where I am redirecting is a class component and turn this to a functional one would cost me as the logic works better in a class component rather in a functional one

Body:
I am doing a react app that brings some data when app is mounted, in a component I want to redirect the user to a url and also pass the state in order to render the data in the state, for this I saw that in v6 you can't use the this.props.history.push('/url') and instead you must create a service and decorate the export of the component you want to use the redirect so I did it like this:

withNavigateService.js

import { useNavigate } from "react-router-dom";

export const withNavigate = (Component) => {
  const Wrapper = (props) => {
    const navigate = useNavigate();

    return (
      <Component
      {...props}
        navigate={navigate}
        />
    );
  };

  return Wrapper;
};

in the component from where I am trying to redirect I want to set as state the data fetched based on the input in a form and then redirect so the new state is the defined in the redirect and not the one that was defined the first time the app was mounted.
this is the code I have to redirect

import { withNavigate } from '../../services/withNavigate';
.
.
.

    handleSubmit(event){
        event.preventDefault()

        // redirect to the component with the search criteria
        // the search criteria will be passed as query parameters
        var tipo  = this.state.tipo
        var marca = toTitleCase(this.state.marca)
        var linea = this.state.linea
        axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )
        .then((response) => {

            // this is my try to redirect with the new state but when the new page is loaded                // the data that is rendered is the one that was first defined when the app was mounted and //not the new state defined here
            this.props.navigate("/store",{
                state:{
                    product:response.data
                }
            });
        })
        .catch((error) => {
            console.log(error)
        })

    }
.
.
.
export default withNavigate(Finder);

but when the redirected page is loaded I saw the data rendered with the state defined the first time the app was mounted and not the defined in the redirect.

how can i achieve my objective i.e set the state in the redirect?

Edit: the component from where I am redirecting is a class component and turn this to a functional one would cost me as the logic works better in a class component rather in a functional one


问:
How to wait for function to finish with axios
I'm trying to run a function inside an axios call, however, the res.json is being called before the function can finish and the result is empty. I logged in the function, and I'm sure that everything is running fine, I do see what I need in the console, but not in the res.json. I believe the main function should be enough, as the other ones are working properly and are very veeery long. In short, they update the global variable articles.

The code follows:

Updated code

```<code>const newspapers = [{
    "name": "CNN",
    "address": "https://edition.cnn.com/specials/world/cnn-climate",
    "base": "https://edition.cnn.com"
  },
  {
    "name": "The Guardian",
    "address": "https://www.theguardian.com/environment/climate-crisis",
    "base": "https://www.theguardian.com"
  }, etc...]
const articles = [];

app.get("/news", (req, res) => {
  // Query String
  const query = checkForQuery(req);
  const wordsToSearch = query ? verifyQuery(query) : "";

  Promise.all(
    newspapers.map(({ name, address, base }) =>
      axios
        .get(address, {
          headers: { "Accept-Encoding": "gzip,deflate,compress" },
        })
        .then((res) => {
          const html = res.data;
          console.log({ name, address, base });
// Logs correctly all newspapers, one by one, but the two first articles from the first newspaper is logged after

          getElementsCheerio(html, base, name, wordsToSearch);
          return articles;
        })
    )
  ).then((articles) => {
    res.json(articles);
  });
});
</code>```

I'm wondering if I should output res.json() somewhere else, or if async/await would help somehow, but I tried different combinations of the latter and nothing works.

So the question is, how can I make axios wait for that function inside .then() to finish before moving ahead and returning the empty res.json(). Actually, I'm not even sure that's axios fault, it's probably mine. (:

Update: I've adapted the code to run with map instead of forEach. Although I do get some response now, it's only 2 news from the same newspaper repeatedly. I logged the map info, and it's indeed going through all newspaper objects. Maybe I'm returning something wrong somewhere? I don't understand :(

Body:
I'm trying to run a function inside an axios call, however, the res.json is being called before the function can finish and the result is empty. I logged in the function, and I'm sure that everything is running fine, I do see what I need in the console, but not in the res.json. I believe the main function should be enough, as the other ones are working properly and are very veeery long. In short, they update the global variable articles.

The code follows:

Updated code

const newspapers = [{
    "name": "CNN",
    "address": "https://edition.cnn.com/specials/world/cnn-climate",
    "base": "https://edition.cnn.com"
  },
  {
    "name": "The Guardian",
    "address": "https://www.theguardian.com/environment/climate-crisis",
    "base": "https://www.theguardian.com"
  }, etc...]
const articles = [];

app.get("/news", (req, res) => {
  // Query String
  const query = checkForQuery(req);
  const wordsToSearch = query ? verifyQuery(query) : "";

  Promise.all(
    newspapers.map(({ name, address, base }) =>
      axios
        .get(address, {
          headers: { "Accept-Encoding": "gzip,deflate,compress" },
        })
        .then((res) => {
          const html = res.data;
          console.log({ name, address, base });
// Logs correctly all newspapers, one by one, but the two first articles from the first newspaper is logged after

          getElementsCheerio(html, base, name, wordsToSearch);
          return articles;
        })
    )
  ).then((articles) => {
    res.json(articles);
  });
});

I'm wondering if I should output res.json() somewhere else, or if async/await would help somehow, but I tried different combinations of the latter and nothing works.

So the question is, how can I make axios wait for that function inside .then() to finish before moving ahead and returning the empty res.json(). Actually, I'm not even sure that's axios fault, it's probably mine. (:

Update: I've adapted the code to run with map instead of forEach. Although I do get some response now, it's only 2 news from the same newspaper repeatedly. I logged the map info, and it's indeed going through all newspaper objects. Maybe I'm returning something wrong somewhere? I don't understand :(


问:
Is there a way to make GraphicsPath.IsVisible faster?
```<code>private void FindPoints()
        {
            GraphicsPath gp = new GraphicsPath();
            int x, y, p, j, wdthHght;
            int bytes;
            byte[] rgbValuesWithClouds;
            byte[] rgbValuesWithoutClouds;
            IntPtr ptr;
            Rectangle rect;
            BitmapData bitmap_Data;

            Bitmap bmpWithClouds; //No memory is allocated
            Bitmap bmpWithoutClouds; //No memory is allocated

            gp.AddEllipse(new RectangleF(73, 72, 367, 367));

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithClouds = new Bitmap(mymem))
            {
                rect = new Rectangle(0, 0, bmpWithClouds.Width, bmpWithClouds.Height);
                wdthHght = bmpWithClouds.Width;

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithClouds.Height;

                rgbValuesWithClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithClouds.UnlockBits(bitmap_Data);
            }

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithoutClouds = new Bitmap(@"F:\Drive Backup\Samsung Galaxy S9\Danny Backup\Recovered data 02-10 18_32_36\1  (D) NTFS\C-Sharp\Weather Radar\WithoutClouds.bmp")) //24 bit bitmap
            {
                rect = new Rectangle(0, 0, bmpWithoutClouds.Width, bmpWithoutClouds.Height);

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithoutClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithoutClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithoutClouds.Height;

                rgbValuesWithoutClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithoutClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithoutClouds.UnlockBits(bitmap_Data);
            }

            // Each position in these arrays, rgbValuesWithoutClouds and rgbValuesWithClouds, corresponds a color. eg
            // First pixel   Second pixel   Third pixel   Forth pixel .... // bitmaps
            //    B G R          B G R         B G R         B G R    .... // rgbValues arrays
            bmptest = new Bitmap(512, 512);
            cloudPoints = new List<Point>();

            for (y = 0; y < wdthHght; y++)
            {
                j = 0;
                for (x = 0; x < wdthHght; x++)
                {
                    p = y * wdthHght * 3 + j;

                    if (rgbValuesWithClouds[p] != rgbValuesWithoutClouds[p])
                    {
                        cloudPoints.Add(new Point(x, y));

                        if (graphicsPath.IsVisible(x, y))
                        {
                            bmptest.SetPixel(x, y, Color.Yellow);
                        }
                    }

                    j += 3;
                }
            }
            bmptest.Save(@"d:\bmptest1.bmp");
        }
</code>```

this method is being called in paint event

```<code>private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.DrawRectangle(Pens.Green, 0, 0, pictureBox1.Width - 1, pictureBox1.Height - 1);

            Pen p = new Pen(Color.Red);
            e.Graphics.DrawLine(p, 256, 0, 256, 512);
            e.Graphics.DrawLine(p, 0, 256, 512, 256);

            FindPoints();
            DrawPieOnPicturebox(e.Graphics);
        }
</code>```

i found that if i'm not using or removing the part :

```<code>if (graphicsPath.IsVisible(x, y))
</code>```

it will working fast but then it will color the pixels in yellow at once and i want it to color the pixels in yellow only if the graphicsPath is visible which make the whole application working very slow.

this is where and how i'm using the graphicsPath

```<code>public void DrawPieOnPicturebox(Graphics myPieGraphic)
        {
            Color myPieColors = Color.FromArgb(150, Color.LightGreen);
            Size myPieSize = new Size((int)distanceFromCenterPixels, (int)distanceFromCenterPixels);
            Point myPieLocation = new Point((pictureBox1.Width - myPieSize.Width) / 2, (pictureBox1.Height - myPieSize.Height) / 2);
            DrawMyPie(myPiePercent, myPieColors, myPieGraphic, myPieLocation, myPieSize);
        }

        public void DrawMyPie(int myPiePerecent, Color myPieColor, Graphics myPieGraphic, Point
      myPieLocation, Size myPieSize)
        {
            using (SolidBrush brush = new SolidBrush(myPieColor))
            {
                myPieGraphic.FillPie(brush, new Rectangle(myPieLocation, myPieSize), Convert.ToSingle(myPiePerecent * 360 / 100), Convert.ToSingle(15 * 360 / 100));
            }

            myPieGraphic.DrawImage(bmptest, Point.Empty);
            graphicsPath.AddPie(new Rectangle(myPieLocation, myPieSize), Convert.ToSingle(myPiePerecent * 360 / 100), Convert.ToSingle(15 * 360 / 100));
        }
</code>```

Body:
private void FindPoints()
        {
            GraphicsPath gp = new GraphicsPath();
            int x, y, p, j, wdthHght;
            int bytes;
            byte[] rgbValuesWithClouds;
            byte[] rgbValuesWithoutClouds;
            IntPtr ptr;
            Rectangle rect;
            BitmapData bitmap_Data;

            Bitmap bmpWithClouds; //No memory is allocated
            Bitmap bmpWithoutClouds; //No memory is allocated

            gp.AddEllipse(new RectangleF(73, 72, 367, 367));

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithClouds = new Bitmap(mymem))
            {
                rect = new Rectangle(0, 0, bmpWithClouds.Width, bmpWithClouds.Height);
                wdthHght = bmpWithClouds.Width;

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithClouds.Height;

                rgbValuesWithClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithClouds.UnlockBits(bitmap_Data);
            }

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithoutClouds = new Bitmap(@"F:\Drive Backup\Samsung Galaxy S9\Danny Backup\Recovered data 02-10 18_32_36\1  (D) NTFS\C-Sharp\Weather Radar\WithoutClouds.bmp")) //24 bit bitmap
            {
                rect = new Rectangle(0, 0, bmpWithoutClouds.Width, bmpWithoutClouds.Height);

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithoutClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithoutClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithoutClouds.Height;

                rgbValuesWithoutClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithoutClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithoutClouds.UnlockBits(bitmap_Data);
            }

            // Each position in these arrays, rgbValuesWithoutClouds and rgbValuesWithClouds, corresponds a color. eg
            // First pixel   Second pixel   Third pixel   Forth pixel .... // bitmaps
            //    B G R          B G R         B G R         B G R    .... // rgbValues arrays
            bmptest = new Bitmap(512, 512);
            cloudPoints = new List<Point>();

            for (y = 0; y < wdthHght; y++)
            {
                j = 0;
                for (x = 0; x < wdthHght; x++)
                {
                    p = y * wdthHght * 3 + j;

                    if (rgbValuesWithClouds[p] != rgbValuesWithoutClouds[p])
                    {
                        cloudPoints.Add(new Point(x, y));

                        if (graphicsPath.IsVisible(x, y))
                        {
                            bmptest.SetPixel(x, y, Color.Yellow);
                        }
                    }

                    j += 3;
                }
            }
            bmptest.Save(@"d:\bmptest1.bmp");
        }

this method is being called in paint event

private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.DrawRectangle(Pens.Green, 0, 0, pictureBox1.Width - 1, pictureBox1.Height - 1);

            Pen p = new Pen(Color.Red);
            e.Graphics.DrawLine(p, 256, 0, 256, 512);
            e.Graphics.DrawLine(p, 0, 256, 512, 256);

            FindPoints();
            DrawPieOnPicturebox(e.Graphics);
        }

i found that if i'm not using or removing the part :

if (graphicsPath.IsVisible(x, y))

it will working fast but then it will color the pixels in yellow at once and i want it to color the pixels in yellow only if the graphicsPath is visible which make the whole application working very slow.

this is where and how i'm using the graphicsPath

public void DrawPieOnPicturebox(Graphics myPieGraphic)
        {
            Color myPieColors = Color.FromArgb(150, Color.LightGreen);
            Size myPieSize = new Size((int)distanceFromCenterPixels, (int)distanceFromCenterPixels);
            Point myPieLocation = new Point((pictureBox1.Width - myPieSize.Width) / 2, (pictureBox1.Height - myPieSize.Height) / 2);
            DrawMyPie(myPiePercent, myPieColors, myPieGraphic, myPieLocation, myPieSize);
        }

        public void DrawMyPie(int myPiePerecent, Color myPieColor, Graphics myPieGraphic, Point
      myPieLocation, Size myPieSize)
        {
            using (SolidBrush brush = new SolidBrush(myPieColor))
            {
                myPieGraphic.FillPie(brush, new Rectangle(myPieLocation, myPieSize), Convert.ToSingle(myPiePerecent * 360 / 100), Convert.ToSingle(15 * 360 / 100));
            }

            myPieGraphic.DrawImage(bmptest, Point.Empty);
            graphicsPath.AddPie(new Rectangle(myPieLocation, myPieSize), Convert.ToSingle(myPiePerecent * 360 / 100), Convert.ToSingle(15 * 360 / 100));
        }


问:
Can we use constructor functions in typescript?
Can we use constructor functions in TypeScript without converting them to classes? I'm guessing we have to declare the value of this here:

function Car() {
    this.name = 'first'; // 'this' implicitly has type 'any'...
}
```


问:
Unable to change Flatsome's menu responsiveness breakpoint
I'm trying to toggle my mobile menu at 1172px as the default is 850px but it's not working.

My web is: www.maria-educandoconamor.com

I'm current using the following css to achieve it:

```<code>@media only screen and (max-width: 1172px) {
.header-nav, .header-nav-main, .nav-line-grow, .nav-size-small, .nav-spacing-medium, .nav-uppercase {
display: none !important;
}

.mobile-nav, .nav.nav-left {
display: flex !important;
}
}
</code>```

But unfortunately it's not working.

Does somebody know what I'm doing wrong?

Thanks.

Body:
I'm trying to toggle my mobile menu at 1172px as the default is 850px but it's not working.

My web is: www.maria-educandoconamor.com

I'm current using the following css to achieve it:

@media only screen and (max-width: 1172px) {
.header-nav, .header-nav-main, .nav-line-grow, .nav-size-small, .nav-spacing-medium, .nav-uppercase {
display: none !important;
}

.mobile-nav, .nav.nav-left {
display: flex !important;
}
}

But unfortunately it's not working.

Does somebody know what I'm doing wrong?

Thanks.


问:
How should i fix the Warning C6308 '
im getting an warning message which says.  Warning  C6308   'realloc' might return null pointer: assigning null pointer to '*destination', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.  and im wondering if some of you could help me to fix this problem.

My code:

```<code>void dstring_truncate(DString* destination, unsigned int truncatedLength)
{
    assert(destination != NULL);
    assert(*destination != NULL);
    assert(truncatedLength >= 0);

    *destination = realloc(*destination, truncatedLength + 1);  // +1 för nollterminatorn
    if (*destination == NULL) {
        fprintf(stderr, "Memory allocation faild\n");
    }
}
</code>```

Title: How should i fix the Warning C6308 '

Body:
im getting an warning message which says.  Warning  C6308   'realloc' might return null pointer: assigning null pointer to '*destination', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.  and im wondering if some of you could help me to fix this problem.

My code:

void dstring_truncate(DString* destination, unsigned int truncatedLength)
{
    assert(destination != NULL);
    assert(*destination != NULL);
    assert(truncatedLength >= 0);

    *destination = realloc(*destination, truncatedLength + 1);  // +1 för nollterminatorn
    if (*destination == NULL) {
        fprintf(stderr, "Memory allocation faild\n");
    }
}


问:
is there a more efficient way of applying this lambda func to all rows
in my dataframe i have a column 'amenities' and for each row this column contains a list of amenities.

My goal is basically to manually one-hot-encode this, i dont think what ive done is the most efficient way to write this code as it takes a little bit of time to run.

`

```<code>for amenity in amenities_list:
    amenities_df[amenity] = amenities_df['amenities'].apply(lambda x: 1 if amenity in str(x) else 0)
</code>```

`

amenities_list is a list of all the amenities. The loop creates a new column for the amenity and then checks the amenities column  and if that amenity is in the list then the individual column will show 1 otherwise 0.

I tried the above for loop but i'm  thinking there's some better and more efficient way to preform the same action.

thanks

Body:
in my dataframe i have a column 'amenities' and for each row this column contains a list of amenities.

My goal is basically to manually one-hot-encode this, i dont think what ive done is the most efficient way to write this code as it takes a little bit of time to run.

`

for amenity in amenities_list:
    amenities_df[amenity] = amenities_df['amenities'].apply(lambda x: 1 if amenity in str(x) else 0)

`

amenities_list is a list of all the amenities. The loop creates a new column for the amenity and then checks the amenities column  and if that amenity is in the list then the individual column will show 1 otherwise 0.

I tried the above for loop but i'm  thinking there's some better and more efficient way to preform the same action.

thanks


问:
Error in the importing keras in raspberry pi 4
I followed this Link: https://www.youtube.com/watch?v=a1BmKSYZUi8 and started to make a model of 3 traffic signs and i followed the same steps as shown in the video and generated the python file and model

I was so excited that my camera would detect these 3 road signs but to my surprise, I got some errors related to TensorFlow and Keras. I hope you don't mind helping me or giving me some direction. I think this is related to importing TensorFlow for Keras or something else.

Does Keras or Google have some tech support for solving this problem? like this

My installed versions are

Python 3.9.2

Keras 2.11.0

Tensorflow 1.9.0

```<code>Traceback (most recent call last):
  line 6, in <module>
    import tensorflow.keras
  line 22, in <module>
    from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
  line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  line 114
    def TFE_ContextOptionsSetAsync(arg1, async):
</code>```

I am expecting the code to run, I tried differently  methods, Import "tensorflow.keras" could not be resolved after upgrading to TensorFlow 2.8.0

but, this is for visual basics do you have some steps like this for the Raspberry pi 4, Python

Body:
I followed this Link: https://www.youtube.com/watch?v=a1BmKSYZUi8 and started to make a model of 3 traffic signs and i followed the same steps as shown in the video and generated the python file and model

I was so excited that my camera would detect these 3 road signs but to my surprise, I got some errors related to TensorFlow and Keras. I hope you don't mind helping me or giving me some direction. I think this is related to importing TensorFlow for Keras or something else.

Does Keras or Google have some tech support for solving this problem? like this

My installed versions are

Python 3.9.2

Keras 2.11.0

Tensorflow 1.9.0

Traceback (most recent call last):
  line 6, in <module>
    import tensorflow.keras
  line 22, in <module>
    from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
  line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  line 114
    def TFE_ContextOptionsSetAsync(arg1, async):

I am expecting the code to run, I tried differently  methods, Import "tensorflow.keras" could not be resolved after upgrading to TensorFlow 2.8.0

but, this is for visual basics do you have some steps like this for the Raspberry pi 4, Python


问:
Passing 2D Array As Formal Parameter, Getting Single String
I'm passing a 2D array as an argument. Reviewing the array in main shows that I have 4 separate strings of words each being stored in words[1][], words[2][], etc. However, when I pass that array to the function I am using to append plural endings, I only seem to be able to access the first string in the array.

```<code>#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define ROWS 50
#define COLS 50

void readFileFormat(char words[ROWS][COLS]);
void determinePlurals(char words[ROWS][COLS]);

int main()
{
    char words[ROWS][COLS];

    readFileFormat(words);
    determinePlurals(words);

    return 0;
}

void readFileFormat(char words[ROWS][COLS])
{
    int cols = 0;//consistent cols for 2d array

    FILE* nounFile;

    fopen_s(&nounFile, "plural.txt", "r");

    if (nounFile == NULL)
    {
        printf("Error reading file; try again.");
        return 1;
    }

    while (!feof(nounFile))
    {
        for (int rows = 0; rows < ROWS; ++rows)
        {
            fgets(&words[rows][cols], 50, nounFile);
            words[rows][strcspn(words[rows], "\n")] = 0;
        }
    }

    fclose(nounFile);
}

void determinePlurals(char words[ROWS][COLS])
{
    char* iesEnd = "ies";
    char* esEnd = "es";
    char* sEnd = "s";

    for (int rows = 0; rows < ROWS; ++rows)
    {
        if (strcmp(words[rows] + strlen(words[rows]) - 1, "y") == 0)
        {
            printf("%s: ", words);
            words[rows][strlen(words[rows]) - 1] = '\0';
            strncat(words[rows], iesEnd, 3);
            printf("%s\n", words);
            rows++;

        }
        else if (strcmp(words[rows] + strlen(words[rows]) - 2, "ch") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "ss") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "x") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "sh") == 0)
        {
            printf("%s: ", words);
            strncat(words[rows], esEnd, 2);
            printf("%s\n", words);
            rows++;
        }
        else
        {
            printf("%s: ", words);
            strncat(words[rows], sEnd, 1);
            printf("%s\n", words);
            rows++;
        }
    }
}
</code>```

I've tried iterating through each row, but don't seem to have acccess to the rest of words[][]. I've struggled with multidimensional arrays so I'm looking for a bit of assistance.

Body:
I'm passing a 2D array as an argument. Reviewing the array in main shows that I have 4 separate strings of words each being stored in words[1][], words[2][], etc. However, when I pass that array to the function I am using to append plural endings, I only seem to be able to access the first string in the array.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define ROWS 50
#define COLS 50

void readFileFormat(char words[ROWS][COLS]);
void determinePlurals(char words[ROWS][COLS]);

int main()
{
    char words[ROWS][COLS];

    readFileFormat(words);
    determinePlurals(words);

    return 0;
}

void readFileFormat(char words[ROWS][COLS])
{
    int cols = 0;//consistent cols for 2d array

    FILE* nounFile;

    fopen_s(&nounFile, "plural.txt", "r");

    if (nounFile == NULL)
    {
        printf("Error reading file; try again.");
        return 1;
    }

    while (!feof(nounFile))
    {
        for (int rows = 0; rows < ROWS; ++rows)
        {
            fgets(&words[rows][cols], 50, nounFile);
            words[rows][strcspn(words[rows], "\n")] = 0;
        }
    }

    fclose(nounFile);
}

void determinePlurals(char words[ROWS][COLS])
{
    char* iesEnd = "ies";
    char* esEnd = "es";
    char* sEnd = "s";

    for (int rows = 0; rows < ROWS; ++rows)
    {
        if (strcmp(words[rows] + strlen(words[rows]) - 1, "y") == 0)
        {
            printf("%s: ", words);
            words[rows][strlen(words[rows]) - 1] = '\0';
            strncat(words[rows], iesEnd, 3);
            printf("%s\n", words);
            rows++;

        }
        else if (strcmp(words[rows] + strlen(words[rows]) - 2, "ch") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "ss") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "x") == 0
            || strcmp(words[rows] + strlen(words[rows]) - 2, "sh") == 0)
        {
            printf("%s: ", words);
            strncat(words[rows], esEnd, 2);
            printf("%s\n", words);
            rows++;
        }
        else
        {
            printf("%s: ", words);
            strncat(words[rows], sEnd, 1);
            printf("%s\n", words);
            rows++;
        }
    }
}

I've tried iterating through each row, but don't seem to have acccess to the rest of words[][]. I've struggled with multidimensional arrays so I'm looking for a bit of assistance.


问:
retitle ubuntu linux terminal immediately
I wish to retitle an Ubuntu terminal and then run a script which is very long term.  I can successfully retitle, at which point I could enter a second command to perform the task, but I have not been able to do both in one step.  If I try to to both with one step, the retitling only happens after the second task exit.

For example, in the .bashrc script I have entered:

```<code>function retitle(){
PS1="\[\e]0;HELLO\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$"
read temp
}
</code>```

The read temp is just to simulate my long task.  I would actually wish to call another script at that point.  So, I want to change the environment PS1 and have the change reflected in the title right away so that the user knows that this terminal is working on a long term task.

I am working with Ubuntu 22.04.1 LTS.

I have tried:

Using scripts for changing PS1.

Ending the first script with &&.

Sourcing the first script that changes PS1 (this is necessary if the scripts are to successfully change the PS1 variable in this 'scope'

Adding a sleep in between.

Thanks so much!

Body:
I wish to retitle an Ubuntu terminal and then run a script which is very long term.  I can successfully retitle, at which point I could enter a second command to perform the task, but I have not been able to do both in one step.  If I try to to both with one step, the retitling only happens after the second task exit.

For example, in the .bashrc script I have entered:

function retitle(){
PS1="\[\e]0;HELLO\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$"
read temp
}

The read temp is just to simulate my long task.  I would actually wish to call another script at that point.  So, I want to change the environment PS1 and have the change reflected in the title right away so that the user knows that this terminal is working on a long term task.

I am working with Ubuntu 22.04.1 LTS.

I have tried:

Using scripts for changing PS1.

Ending the first script with &&.

Sourcing the first script that changes PS1 (this is necessary if the scripts are to successfully change the PS1 variable in this 'scope'

Adding a sleep in between.

Thanks so much!


问:
Where can I find a pub/ sub schema for cloud-builds and gcr topics?
Where can I find a pub/ sub schema for cloud-builds and gcr topics?

The gcr topic is explained in https://cloud.google.com/container-registry/docs/configuring-notifications#notification_examples, while ´cloud-builds´ is described at https://cloud.google.com/build/docs/subscribe-build-notifications .

Unfortunately both miss a schema and especially regarding the enums I would like to be sure to cover every case.

I tried to find them via Google, but unfortunately failed.

I would have expected to find these even pre-defined for standard topics.


问:
How to increase the speed of a motor when the joystick is move in the forward position.(first robotics blocks/java)
I am in FIRST ROBOTICS and trying to get the motors on my robots to move faster than they currently are. At the moment, the wheels move fairly slow and we want them to move faster by increasing the motor speed based on the positive and negative position of the stick.

Here is our original code, which works but does not move faster:
`

```<code>package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;

@TeleOp(name = "v221 (Blocks to Java)")
public class v221 extends LinearOpMode {

  private DcMotor Back_Right;
  private DcMotor Back_Left;
  private DcMotor Front_Right;
  private DcMotor Front_Left;

  /**
   * This function is executed when this Op Mode is selected from the Driver Station.
   */
  @Override
  public void runOpMode() {
    float Back_Right2;
    float Back_Left2;
    float Front_Right2;
    float Front_Left2;

    Back_Right = hardwareMap.get(DcMotor.class, "Back_Right");
    Back_Left = hardwareMap.get(DcMotor.class, "Back_Left");
    Front_Right = hardwareMap.get(DcMotor.class, "Front_Right");
    Front_Left = hardwareMap.get(DcMotor.class, "Front_Left");

    // put initizalion blocks here
    waitForStart();
    if (opModeIsActive()) {
      // Put run blocks here.
      while (opModeIsActive()) {
        // Put loop blocks here.
        Back_Right2 = gamepad1.right_stick_y;
        Back_Right.setPower(Back_Right2);
        telemetry.addData("rightWheelpwr", Back_Right2);
        Back_Left2 = -gamepad1.left_stick_y;
        Back_Left.setPower(Back_Left2);
        telemetry.addData("leftWheelpwr", Back_Left2);
        Front_Right2 = -gamepad1.right_stick_y;
        Front_Right.setPower(Front_Right2);
        telemetry.addData("rightWheelpwr", Front_Right2);
        Front_Left2 = -gamepad1.left_stick_y;
        Front_Left.setPower(Front_Left2);
        telemetry.addData("leftWheelpwr", Front_Left2);
      }
    }
  }
}
</code>```

Here is the code we made to try and make it faster:

```<code>package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;

@TeleOp(name = "v2215 (Blocks to Java)")
public class v2215 extends LinearOpMode {

  private DcMotor Back_Right;
  private DcMotor Back_Left;
  private DcMotor Front_Right;
  private DcMotor Front_Left;

  /**
   * This function is executed when this Op Mode is selected from the Driver Station.
   */
  @Override
  public void runOpMode() {
    float Back_Right2;
    float Back_Left2;
    float Front_Right2;
    float Front_Left2;

    Back_Right = hardwareMap.get(DcMotor.class, "Back_Right");
    Back_Left = hardwareMap.get(DcMotor.class, "Back_Left");
    Front_Right = hardwareMap.get(DcMotor.class, "Front_Right");
    Front_Left = hardwareMap.get(DcMotor.class, "Front_Left");

    // put initizalion blocks here
    waitForStart();
    if (opModeIsActive()) {
      // Put run blocks here.
      while (opModeIsActive()) {
        // Put loop blocks here.
        Back_Right2 = gamepad1.right_stick_y;
        Back_Right.setPower(Back_Right2);
        telemetry.addData("rightWheelpwr", Back_Right2 * 5);
        Back_Left2 = -gamepad1.left_stick_y;
        Back_Left.setPower(Back_Left2);
        telemetry.addData("leftWheelpwr", Back_Left2);
        Front_Right2 = -gamepad1.right_stick_y;
        Front_Right.setPower(Front_Right2);
        telemetry.addData("rightWheelpwr", Front_Right2);
        Front_Left2 = -gamepad1.left_stick_y;
        Front_Left.setPower(Front_Left2);
        telemetry.addData("leftWheelpwr", Front_Left2);
      }
    }
  }
}
</code>```

If you know how to make it faster, please let us know.

Multiplying the power input to the motor by adding a multiplier - Expected it to multiply how far you pushed the stick by the power given to the motor.

We did more of course, but can't think of them to add

Body:
I am in FIRST ROBOTICS and trying to get the motors on my robots to move faster than they currently are. At the moment, the wheels move fairly slow and we want them to move faster by increasing the motor speed based on the positive and negative position of the stick.

Here is our original code, which works but does not move faster:
`

package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;

@TeleOp(name = "v221 (Blocks to Java)")
public class v221 extends LinearOpMode {

  private DcMotor Back_Right;
  private DcMotor Back_Left;
  private DcMotor Front_Right;
  private DcMotor Front_Left;

  /**
   * This function is executed when this Op Mode is selected from the Driver Station.
   */
  @Override
  public void runOpMode() {
    float Back_Right2;
    float Back_Left2;
    float Front_Right2;
    float Front_Left2;

    Back_Right = hardwareMap.get(DcMotor.class, "Back_Right");
    Back_Left = hardwareMap.get(DcMotor.class, "Back_Left");
    Front_Right = hardwareMap.get(DcMotor.class, "Front_Right");
    Front_Left = hardwareMap.get(DcMotor.class, "Front_Left");

    // put initizalion blocks here
    waitForStart();
    if (opModeIsActive()) {
      // Put run blocks here.
      while (opModeIsActive()) {
        // Put loop blocks here.
        Back_Right2 = gamepad1.right_stick_y;
        Back_Right.setPower(Back_Right2);
        telemetry.addData("rightWheelpwr", Back_Right2);
        Back_Left2 = -gamepad1.left_stick_y;
        Back_Left.setPower(Back_Left2);
        telemetry.addData("leftWheelpwr", Back_Left2);
        Front_Right2 = -gamepad1.right_stick_y;
        Front_Right.setPower(Front_Right2);
        telemetry.addData("rightWheelpwr", Front_Right2);
        Front_Left2 = -gamepad1.left_stick_y;
        Front_Left.setPower(Front_Left2);
        telemetry.addData("leftWheelpwr", Front_Left2);
      }
    }
  }
}

Here is the code we made to try and make it faster:

package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;

@TeleOp(name = "v2215 (Blocks to Java)")
public class v2215 extends LinearOpMode {

  private DcMotor Back_Right;
  private DcMotor Back_Left;
  private DcMotor Front_Right;
  private DcMotor Front_Left;

  /**
   * This function is executed when this Op Mode is selected from the Driver Station.
   */
  @Override
  public void runOpMode() {
    float Back_Right2;
    float Back_Left2;
    float Front_Right2;
    float Front_Left2;

    Back_Right = hardwareMap.get(DcMotor.class, "Back_Right");
    Back_Left = hardwareMap.get(DcMotor.class, "Back_Left");
    Front_Right = hardwareMap.get(DcMotor.class, "Front_Right");
    Front_Left = hardwareMap.get(DcMotor.class, "Front_Left");

    // put initizalion blocks here
    waitForStart();
    if (opModeIsActive()) {
      // Put run blocks here.
      while (opModeIsActive()) {
        // Put loop blocks here.
        Back_Right2 = gamepad1.right_stick_y;
        Back_Right.setPower(Back_Right2);
        telemetry.addData("rightWheelpwr", Back_Right2 * 5);
        Back_Left2 = -gamepad1.left_stick_y;
        Back_Left.setPower(Back_Left2);
        telemetry.addData("leftWheelpwr", Back_Left2);
        Front_Right2 = -gamepad1.right_stick_y;
        Front_Right.setPower(Front_Right2);
        telemetry.addData("rightWheelpwr", Front_Right2);
        Front_Left2 = -gamepad1.left_stick_y;
        Front_Left.setPower(Front_Left2);
        telemetry.addData("leftWheelpwr", Front_Left2);
      }
    }
  }
}

If you know how to make it faster, please let us know.

Multiplying the power input to the motor by adding a multiplier - Expected it to multiply how far you pushed the stick by the power given to the motor.

We did more of course, but can't think of them to add


问:
Error When Importing TensorFlow on Mac M1 Pro. MacOs version 13.0. Python 3.10
**Things I did / run:
**

Downloaded MiniConda

Created Virtual env

Inside env, installed ipykernel

created new kernel for use in jupyter

**TensorFlow Installation following: https://developer.apple.com/metal/tensorflow-plugin/
**

conda install -c apple tensorflow-deps

python -m pip install tensorflow-macos

python -m pip install tensorflow-metal

Then I created a jupyter lab notebook, selected previously created kernel, and did: import tensorflow as tf, and it gave this error:

```<code>NotFoundError                             Traceback (most recent call last)
Cell In[1], line 1
----> 1 import tensorflow as tf

File ~/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow/__init__.py:443
    441 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
    442 if _os.path.exists(_plugin_dir):
--> 443   _ll.load_library(_plugin_dir)
    444   # Load Pluggable Device Library
    445   _ll.load_pluggable_device_library(_plugin_dir)

File ~/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
    148     kernel_libraries = [library_location]
    150   for lib in kernel_libraries:
--> 151     py_tf.TF_LoadLibrary(lib)
    153 else:
    154   raise OSError(
    155       errno.ENOENT,
    156       'The file or folder to load kernel libraries from does not exist.',
    157       library_location)

NotFoundError: dlopen(/Users/felix/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '__ZN3tsl8internal10LogMessage16VmoduleActivatedEPKci'
</code>```

**THINGS I HAVE TRIED:
**

Tried what was instructed here - https://developer.apple.com/forums/thread/702851

Also here:

Installing Tensorflow in M1 Mac

Tensorflow on M1

What is the proper way to install TensorFlow on Apple M1 in 2022

Re-installed Miniconda and created everything again. Made sure that TensorFlow deps and TensorFlow macos were both in latest version, then re-tried with both in 2.9.0 version.

Also tried deleting miniconda completely, and trying everything with miniforge instead, but ran into the same problem.

Overall, I look at all available stack overflow's relevant questions regarding problems with TensorFlow and Mac M1s, but solutions did not solve my requirements and problems.

THINGS I DON´T WANT TO DO:

Use Miniforge

Not install tensorflow deps

Use mamba

I have no idea at this point, I've been trying to make it work for quite a few hours.

I'd appreciate some help!

Body:
**Things I did / run:
**

Downloaded MiniConda

Created Virtual env

Inside env, installed ipykernel

created new kernel for use in jupyter

**TensorFlow Installation following: https://developer.apple.com/metal/tensorflow-plugin/
**

conda install -c apple tensorflow-deps

python -m pip install tensorflow-macos

python -m pip install tensorflow-metal

Then I created a jupyter lab notebook, selected previously created kernel, and did: import tensorflow as tf, and it gave this error:

NotFoundError                             Traceback (most recent call last)
Cell In[1], line 1
----> 1 import tensorflow as tf

File ~/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow/__init__.py:443
    441 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
    442 if _os.path.exists(_plugin_dir):
--> 443   _ll.load_library(_plugin_dir)
    444   # Load Pluggable Device Library
    445   _ll.load_pluggable_device_library(_plugin_dir)

File ~/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
    148     kernel_libraries = [library_location]
    150   for lib in kernel_libraries:
--> 151     py_tf.TF_LoadLibrary(lib)
    153 else:
    154   raise OSError(
    155       errno.ENOENT,
    156       'The file or folder to load kernel libraries from does not exist.',
    157       library_location)

NotFoundError: dlopen(/Users/felix/opt/miniconda3/envs/ImageClassification/lib/python3.10/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '__ZN3tsl8internal10LogMessage16VmoduleActivatedEPKci'

**THINGS I HAVE TRIED:
**

Tried what was instructed here - https://developer.apple.com/forums/thread/702851

Also here:

Installing Tensorflow in M1 Mac

Tensorflow on M1

What is the proper way to install TensorFlow on Apple M1 in 2022

Re-installed Miniconda and created everything again. Made sure that TensorFlow deps and TensorFlow macos were both in latest version, then re-tried with both in 2.9.0 version.

Also tried deleting miniconda completely, and trying everything with miniforge instead, but ran into the same problem.

Overall, I look at all available stack overflow's relevant questions regarding problems with TensorFlow and Mac M1s, but solutions did not solve my requirements and problems.

THINGS I DON´T WANT TO DO:

Use Miniforge

Not install tensorflow deps

Use mamba

I have no idea at this point, I've been trying to make it work for quite a few hours.

I'd appreciate some help!


问:
How to pass lambda as intent to start an activity in android using kotlin
I am writing a library that allow user to start my activity with pass in params and callbacks.

The architecture I been following is the MVVM. I dont have any issue with the MVVM pattern however, I am running into an occasional issue with the callback pass in from my caller.

```<code>   class mainActivity :Activity {

// standard lifecycle
    override fun onCreate(savedInstanceState: Bundle?) {
     ...
    }

    override fun onResume() {
    // here I am accessing the static callback from companion object.
    // but sometimes I am getting lateinit property callback has not been initialized
    //exception.
    callback.invoke()
    }

   companion object {
   lateinit var callback: () -> Unit

    //user will call my library from this method and provide me the callback
    fun play(
       callback: () -> Unit
    ){
      callback = callback // here I assigned the callback so that my activity can use it later.
     }
   }
}

</code>```

inside onResume I am accessing the callback. sometimes I am getting

 lateinit property callback has not been initialized

however, I am not available to reproduce it 100% at all. What can be an issue? can you please shed some lights with me please?

Body:
I am writing a library that allow user to start my activity with pass in params and callbacks.

The architecture I been following is the MVVM. I dont have any issue with the MVVM pattern however, I am running into an occasional issue with the callback pass in from my caller.

   class mainActivity :Activity {

// standard lifecycle
    override fun onCreate(savedInstanceState: Bundle?) {
     ...
    }

    override fun onResume() {
    // here I am accessing the static callback from companion object.
    // but sometimes I am getting lateinit property callback has not been initialized
    //exception.
    callback.invoke()
    }

   companion object {
   lateinit var callback: () -> Unit

    //user will call my library from this method and provide me the callback
    fun play(
       callback: () -> Unit
    ){
      callback = callback // here I assigned the callback so that my activity can use it later.
     }
   }
}

inside onResume I am accessing the callback. sometimes I am getting

 lateinit property callback has not been initialized

however, I am not available to reproduce it 100% at all. What can be an issue? can you please shed some lights with me please?


问:
I am getting chrome://invalid when I use __MSG_@@extension_id__ in my CSS file
I am building a chrome extension with Manifest V3. I am using the below-given snippet in my CSS file to load local fonts.

```<code>@font-face {
    font-family: 'PoppinsLight';
    src: url('chrome-extension://__MSG_@@extension_id__/assets/Fonts/Poppins-Light.ttf');
}
</code>```

When I load it into my browser, I get this error

```<code>Request URL: chrome-extension://invalid/
Referrer Policy: strict-origin-when-cross-origin
</code>```

I have also added web_accessible_resources in my Manifest. So, no problem at that end.

I would really appreciate some help. Thanks!

Body:
I am building a chrome extension with Manifest V3. I am using the below-given snippet in my CSS file to load local fonts.

@font-face {
    font-family: 'PoppinsLight';
    src: url('chrome-extension://__MSG_@@extension_id__/assets/Fonts/Poppins-Light.ttf');
}

When I load it into my browser, I get this error

Request URL: chrome-extension://invalid/
Referrer Policy: strict-origin-when-cross-origin

I have also added web_accessible_resources in my Manifest. So, no problem at that end.

I would really appreciate some help. Thanks!


问:
How can I use 'piplite' in jupyter notebook?
I want to use 'piplite' in my system (VS-Code and jupyter Notebook) but I have an Error. I installed pip and my system is Mac.</p>
```<code>import piplite
await piplite.install(['pandas'])
await piplite.install(['matplotlib'])
await piplite.install(['numpy'])
await piplite.install(['scikit-learn'])
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 import piplite
      2 await piplite.install(['pandas'])
      3 await piplite.install(['matplotlib'])

ModuleNotFoundError: No module named 'piplite'
</code>```

Body:
I want to use 'piplite' in my system (VS-Code and jupyter Notebook) but I have an Error. I installed pip and my system is Mac.

import piplite
await piplite.install(['pandas'])
await piplite.install(['matplotlib'])
await piplite.install(['numpy'])
await piplite.install(['scikit-learn'])
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 import piplite
      2 await piplite.install(['pandas'])
      3 await piplite.install(['matplotlib'])

ModuleNotFoundError: No module named 'piplite'


问:
How to get actual PTS and DTS after frame decoding with libavcodec of FFmpeg
C++, FFmpeg, libavcodec, video frames decoding.

To parse data from the network and split it into frames, I use the av_parser_parse2(_parser, _context, &_packet_encoded_frame->data, &_packet_encoded_frame->size, data, data_size, pts ? pts : AV_NOPTS_VALUE, dts ? dts : AV_NOPTS_VALUE, 0) function to which I pass non-zero values PTS and DTS as inputs.

Next, I use the avcodec_send_packet(_context, _packet_encoded_frame) and avcodec_receive_frame(_context, _frame) functions to decode the frames.

Why do I ALWAYS have PTS(_frame->pts) and DTS(_frame->pkt_dts) equal to AV_NOPTS_VALUE after SUCCESSFUL frame decoding? How can I get the actual PTS and DTS values of that frame after decoding a frame? What am I doing wrong?

OwnerDisplayName: Elija


问:
How to get props value displayed on a page?
```<code>useEffect(() => {
  axios("http://localhost:8080/all")
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.log(err))
}, []);
</code>```

For one of my column headers I have:

```<code>const columns = useMemo(
  () => [
    {
      Header: "Stock search",
      columns: [
        {
          Header: "Symbol",
          accessor: "symbol",
          Cell: (props) => (
            <a href={`/code/${props.value}`}>{props.value}</a>
          ),
        },
</code>```

And just a table that uses the useTable hook with React-Table-v7 (not tanstack) that returns this:

```<code>return (
  <div className="Stocks">
    <Table columns={columns} data={data} />
  </div>
);
</code>```

All I'm trying to do is: when the user clicks on any "symbol" value in the table, it updates the table and new columns appear, with data based on that symbol that was clicked which I already have in my external API link above. So the default columns are: "Symbol | Name | Field", and if you click on any symbol, it updates the table with relevant data and only the columns "Date | Volumes | Type" appear. I have tried so many variations like ag-grid, material-table, even using html only but I don't know what else to do here.

Body:
useEffect(() => {
  axios("http://localhost:8080/all")
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.log(err))
}, []);

For one of my column headers I have:

const columns = useMemo(
  () => [
    {
      Header: "Stock search",
      columns: [
        {
          Header: "Symbol",
          accessor: "symbol",
          Cell: (props) => (
            <a href={`/code/${props.value}`}>{props.value}
          ),
        },

And just a table that uses the useTable hook with React-Table-v7 (not tanstack) that returns this:

return (

);

All I'm trying to do is: when the user clicks on any "symbol" value in the table, it updates the table and new columns appear, with data based on that symbol that was clicked which I already have in my external API link above. So the default columns are: "Symbol | Name | Field", and if you click on any symbol, it updates the table with relevant data and only the columns "Date | Volumes | Type" appear. I have tried so many variations like ag-grid, material-table, even using html only but I don't know what else to do here.


问:
useContext auth hook returning null
I have created a useAuth hook in order to allow the user access to the private route once authorised the authorising cookie is stored properly but the useAuth hook seems to be returning null. I also tried printing the value of setUser but it doesn't seem to print after the line setUser(res.data.currentUser) but the one before is printed I cannot figure out why.

The cookies are stored and set properly it just seems to be the auth hook that return setUser as null even though the line console.log("RES>DATA = ", res.data.currentUser); logs the correct details of the cookie but when I try to manually change the url to the private route after the cookie is stored it returns a null for the setUser returned from the auth hook and so access to private route isn't granted. This is done using react for frontend with node js and express for the backend. If any more context is necessary please let me know.

useAuth hook:

```<code>import { useState, useContext, useEffect } from "react";
import { UserContext } from "./UserContext";
import axios from "axios";

export default function useAuth() {
  const { setUser } = useContext(UserContext);
  const [error, setError] = useState(null);

  useEffect(() => {
    console.log("USE effect");
    setUserContext();
  });

  //set user in context and push them home
  const setUserContext = async () => {
    console.log("In here");
    return await axios
      .get("auth/checkAuth")
      .then((res) => {
        console.log("RES>DATA = ", res.data.currentUser); // PRINTS THE CORRECT COOKIE VALUES
        setUser(res.data.currentUser); // THIS SEEMS TO BE NULL?????
        console.log("SET USER + ", setUser);  // THIS DOES NOT PRINT
      })
      .catch((err) => {
        setError(err);
      });
  };

  return {
    setUser,
  };
}

</code>```

Private route:

```<code>import React, { useContext } from 'react';
import {Route, Redirect, Navigate} from 'react-router-dom';
import { UserContext } from '../hooks/UserContext';
import useAuth from '../hooks/useAuth';

export default function PrivateRoute({children}) {
   const auth = useAuth();
   console.log("aUTH in priv = ", auth);
   return auth ? children : <Navigate to="/"/>
}

</code>```

App.js:

```<code>import "./App.css";
import { Redirect, Route, Routes, Switch } from "react-router-dom";
import useFetch from "./useFetch";
import { useEffect, useState, useRef } from "react";
import axios from "axios";
import Activities from "./components/Activities";
import HomePage from "./components/Home";
import Map from "./components/Map";

import checkUser from "./hooks/checkUser";

import { UserContext } from "./hooks/UserContext";
import useFindUser from "./hooks/checkUser";
import PrivateRoute from "./components/PrivateRoute";

function App() {
  const [auth, setAuth] = useState(false);
  const [activities, setActivities] = useState([]);
  const notInitialRender = useRef(false);
  const { user, setUser, isLoading } = useFindUser(); // works as expected

  return (
    <div className="App">
      <UserContext.Provider value={{ user, setUser, isLoading }}>
        <Routes>
          <Route path="/" element={<HomePage />}></Route>
          <Route path="/Activities" element={<Activities />} />
          <Route
            path="/Private"
            element={
              <PrivateRoute>
                <Map />
              </PrivateRoute>
            }
          />
        </Routes>
      </UserContext.Provider>
    </div>
  );
}

export default App;

</code>```

auth/checkAuth express route:

```<code>export const checkAuth = (req, res) => {

  let currentUser;
  console.log("res.cookies = ", req);
  if (req.cookies.currentUser) {
    // res.send(200);
    currentUser = req.cookies.currentUser; // set to user object in cookies
    console.log("current user = ", currentUser);
    // return 200 status code
  } else {
    currentUser = null;
  }
  //res.json(currentUser);
  res.status(200).send({ currentUser });
};
</code>```

Map component which is private route component:

```<code>import react from 'react';

function Map() {
    <div>
        <p style={{color:'red'}}>You have access to the private route</p>
    </div>
}

export default Map;
</code>```

UserContext file:

```<code>import { createContext } from "react";

export const UserContext = createContext("null");
</code>```

I tried logging values and using useEffect to call the function when the useAuth hook is called but couldn't figure it out

Title: useContext auth hook returning null

Body:
I have created a useAuth hook in order to allow the user access to the private route once authorised the authorising cookie is stored properly but the useAuth hook seems to be returning null. I also tried printing the value of setUser but it doesn't seem to print after the line setUser(res.data.currentUser) but the one before is printed I cannot figure out why.

The cookies are stored and set properly it just seems to be the auth hook that return setUser as null even though the line console.log("RES>DATA = ", res.data.currentUser); logs the correct details of the cookie but when I try to manually change the url to the private route after the cookie is stored it returns a null for the setUser returned from the auth hook and so access to private route isn't granted. This is done using react for frontend with node js and express for the backend. If any more context is necessary please let me know.

useAuth hook:

import { useState, useContext, useEffect } from "react";
import { UserContext } from "./UserContext";
import axios from "axios";

export default function useAuth() {
  const { setUser } = useContext(UserContext);
  const [error, setError] = useState(null);

  useEffect(() => {
    console.log("USE effect");
    setUserContext();
  });

  //set user in context and push them home
  const setUserContext = async () => {
    console.log("In here");
    return await axios
      .get("auth/checkAuth")
      .then((res) => {
        console.log("RES>DATA = ", res.data.currentUser); // PRINTS THE CORRECT COOKIE VALUES
        setUser(res.data.currentUser); // THIS SEEMS TO BE NULL?????
        console.log("SET USER + ", setUser);  // THIS DOES NOT PRINT
      })
      .catch((err) => {
        setError(err);
      });
  };

  return {
    setUser,
  };
}

Private route:

import React, { useContext } from 'react';
import {Route, Redirect, Navigate} from 'react-router-dom';
import { UserContext } from '../hooks/UserContext';
import useAuth from '../hooks/useAuth';

export default function PrivateRoute({children}) {
   const auth = useAuth();
   console.log("aUTH in priv = ", auth);
   return auth ? children : <Navigate to="/"/>
}

App.js:

import "./App.css";
import { Redirect, Route, Routes, Switch } from "react-router-dom";
import useFetch from "./useFetch";
import { useEffect, useState, useRef } from "react";
import axios from "axios";
import Activities from "./components/Activities";
import HomePage from "./components/Home";
import Map from "./components/Map";

import checkUser from "./hooks/checkUser";

import { UserContext } from "./hooks/UserContext";
import useFindUser from "./hooks/checkUser";
import PrivateRoute from "./components/PrivateRoute";

function App() {
  const [auth, setAuth] = useState(false);
  const [activities, setActivities] = useState([]);
  const notInitialRender = useRef(false);
  const { user, setUser, isLoading } = useFindUser(); // works as expected

  return (

      <UserContext.Provider value={{ user, setUser, isLoading }}>
        <Routes>
          <Route path="/" element={<HomePage />}></Route>
          <Route path="/Activities" element={<Activities />} />
          <Route
            path="/Private"
            element={
              <PrivateRoute>
                <Map />
              </PrivateRoute>
            }
          />
        </Routes>
      </UserContext.Provider>

  );
}

export default App;

auth/checkAuth express route:

export const checkAuth = (req, res) => {

  let currentUser;
  console.log("res.cookies = ", req);
  if (req.cookies.currentUser) {
    // res.send(200);
    currentUser = req.cookies.currentUser; // set to user object in cookies
    console.log("current user = ", currentUser);
    // return 200 status code
  } else {
    currentUser = null;
  }
  //res.json(currentUser);
  res.status(200).send({ currentUser });
};

Map component which is private route component:

import react from 'react';

function Map() {

You have access to the private route

}

export default Map;

UserContext file:

import { createContext } from "react";

export const UserContext = createContext("null");

I tried logging values and using useEffect to call the function when the useAuth hook is called but couldn't figure it out


问:
HTTP 502 Error in an AWS Amplify Project with an API Gateway and Node.js Lambda Function
I have an AWS Amplify project with an API Gateway and a node.js Lambda function. Whenever I hit the API and it makes a connection to the RDS PostgreSQL DB I'm getting back a HTTP 502 error. I'm not sure what to do next to resolve it. Can anyone suggest some potential causes of this error and how I can troubleshoot and fix it?

I've been trying to adjust something in the lambda with the hopes that it'll fix it but the problem could lie elsewhere in the flow such as the API Gateway or RDS DB..

NOTE: This is a sample project that I'm working on, it isn't perfect I know. Feedback is always appreciated. Thanks!

```<code>/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */

var pg = require('pg');

exports.handler = async (event) => {
    try {
        const rds_host  = "";
        const name = "";
        const password = "";
        const db_name = "";
        const port = 5432;
        const connString = `postgres://${name}:${password}@${rds_host}:${port}/${db_name}`;

        const client = new pg.Client(connString);
        await client.connect();

        const query = {
            text: 'SELECT * FROM projects'
        }
        const res = await client.query(query);
        const data = res.rows;
        await client.end();

        const response = {
            statusCode: 200,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "*"
            },
            body: JSON.stringify(data),
        };
        return response;
    } catch(error) {
        console.log('error: ', error);
    }
};
</code>```

Body:
I have an AWS Amplify project with an API Gateway and a node.js Lambda function. Whenever I hit the API and it makes a connection to the RDS PostgreSQL DB I'm getting back a HTTP 502 error. I'm not sure what to do next to resolve it. Can anyone suggest some potential causes of this error and how I can troubleshoot and fix it?

I've been trying to adjust something in the lambda with the hopes that it'll fix it but the problem could lie elsewhere in the flow such as the API Gateway or RDS DB..

NOTE: This is a sample project that I'm working on, it isn't perfect I know. Feedback is always appreciated. Thanks!

/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */

var pg = require('pg');

exports.handler = async (event) => {
    try {
        const rds_host  = "";
        const name = "";
        const password = "";
        const db_name = "";
        const port = 5432;
        const connString = `postgres://${name}:${password}@${rds_host}:${port}/${db_name}`;

        const client = new pg.Client(connString);
        await client.connect();

        const query = {
            text: 'SELECT * FROM projects'
        }
        const res = await client.query(query);
        const data = res.rows;
        await client.end();

        const response = {
            statusCode: 200,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "*"
            },
            body: JSON.stringify(data),
        };
        return response;
    } catch(error) {
        console.log('error: ', error);
    }
};


问:
Import mapping doesn't seems to be working with Node.JS
Import mapping is a new feature in Javascript that allows usage of absolute paths rather than relative paths, making restructuring projects easier.

According to the docs, I have to put a imports object to the package.json.

Here is a example file that has this imports:

{
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2"
  },
  "imports": {
    "#stuff": {
      "app": "./app.js"
    }
  },
  "type": "module"
}
```
<p>and a example minimal snippet of code that tries to use app.js by import mapping</p>
```import { app } from "#stuff/app"
```
<p>If I run the server with the code and the log:</p>
```[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:internal/errors:478
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_PACKAGE_IMPORT_NOT_DEFINED]: Package import specifier "#stuff/app" is not defined in package /home//Desktop//package.json imported from /home//Desktop//server.js
    at new NodeError (node:internal/errors:387:5)
    at throwImportNotDefined (node:internal/modules/esm/resolve:354:9)
    at packageImportsResolve (node:internal/modules/esm/resolve:737:3)
    at moduleResolve (node:internal/modules/esm/resolve:895:21)
    at defaultResolve (node:internal/modules/esm/resolve:1115:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:837:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36) {
  code: 'ERR_PACKAGE_IMPORT_NOT_DEFINED'
}
[nodemon] app crashed - waiting for file changes before starting...
```

Side note: app.js actually does exists but I don't include here due it contains my own private code.

Body:
Import mapping is a new feature in Javascript that allows usage of absolute paths rather than relative paths, making restructuring projects easier.

According to the docs, I have to put a imports object to the package.json.

Here is a example file that has this imports:

{
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2"
  },
  "imports": {
    "#stuff": {
      "app": "./app.js"
    }
  },
  "type": "module"
}

and a example minimal snippet of code that tries to use app.js by import mapping

import { app } from "#stuff/app"

If I run the server with the code and the log:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:internal/errors:478
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_PACKAGE_IMPORT_NOT_DEFINED]: Package import specifier "#stuff/app" is not defined in package /home//Desktop//package.json imported from /home//Desktop//server.js
    at new NodeError (node:internal/errors:387:5)
    at throwImportNotDefined (node:internal/modules/esm/resolve:354:9)
    at packageImportsResolve (node:internal/modules/esm/resolve:737:3)
    at moduleResolve (node:internal/modules/esm/resolve:895:21)
    at defaultResolve (node:internal/modules/esm/resolve:1115:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:837:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36) {
  code: 'ERR_PACKAGE_IMPORT_NOT_DEFINED'
}
[nodemon] app crashed - waiting for file changes before starting...

Side note: app.js actually does exists but I don't include here due it contains my own private code.


问:
Ignore Connection Error on Multiple Rtsp Stream in FFmpeg
Sorry for my bad English. My problem is;
ffmpeg command closes completely when one of the streams cannot be reached while multicasting. when it can't reach a single rtsp address, how can it ignore it and continue broadcasting from the others?

Example;

```<code>ffmpeg -i rtsp://5.63.151.4:443/atv/atv2 -map 0 c:\atv.flv -i rtsp://live.sabah.com.tr:443/ahaber/ahaber3 -map 1 c:\ahaber.flv
</code>```

if it can't reach the 2nd link, keep playing the first one

Thank you!

Body:
Sorry for my bad English. My problem is;
ffmpeg command closes completely when one of the streams cannot be reached while multicasting. when it can't reach a single rtsp address, how can it ignore it and continue broadcasting from the others?

Example;

ffmpeg -i rtsp://5.63.151.4:443/atv/atv2 -map 0 c:\atv.flv -i rtsp://live.sabah.com.tr:443/ahaber/ahaber3 -map 1 c:\ahaber.flv

if it can't reach the 2nd link, keep playing the first one

Thank you!


问:
Auth0 FGA blocked resource on organization type
I have 4 types, the business subscribes to the plan and gets the plan's features, the feature provides access to resources. I want to add a blocked relation to the Resources type. I don't want the user to access the can_access relationship if they have a relationship with blocked.

```<code>type user
type plan
  relations
    define subscriber as self
    define subscriber_member as member from subscriber
type business
  relations
    define member as self and user_in_context
    define user_in_context as self
type feature
  relations
    define associated_plan as self
    define feature_member as subscriber_member from associated_plan
type resource
  relations
    define associated_feature as self
    define can_access as feature_member from associated_feature but not blocked
    define blocked as self
</code>```

If I define the following tuple to the user, it prevents access to this resource from all business memberships.

user: user:test

relation: blocked

object: resource:get_list

When this tuple is defined, the user is blocked from all businesses to the get_list resource. I want to prevent the user from accessing the resource in the business context, how can I do it?

Body:
I have 4 types, the business subscribes to the plan and gets the plan's features, the feature provides access to resources. I want to add a blocked relation to the Resources type. I don't want the user to access the can_access relationship if they have a relationship with blocked.

type user
type plan
  relations
    define subscriber as self
    define subscriber_member as member from subscriber
type business
  relations
    define member as self and user_in_context
    define user_in_context as self
type feature
  relations
    define associated_plan as self
    define feature_member as subscriber_member from associated_plan
type resource
  relations
    define associated_feature as self
    define can_access as feature_member from associated_feature but not blocked
    define blocked as self

If I define the following tuple to the user, it prevents access to this resource from all business memberships.

user: user:test

relation: blocked

object: resource:get_list

When this tuple is defined, the user is blocked from all businesses to the get_list resource. I want to prevent the user from accessing the resource in the business context, how can I do it?


问:
How do i decode a link from an email using imaplib and Python?
I have got a code that uses "imaplib" to search for a specific email and link, everything works fine, it successfully gets the link but once I actually try to use the link extracted from the email to make a get request, it doesn't work.

I belive it's something to do with encoding/decoding?
Any help would be appreciated!

This is the code:

```<code>def get_email_token(box):
    status, messages = mail.select(box)
    messages = int(messages[0])

    for i in range(messages, messages-10, -1):
        res, msg = mail.fetch(str(i), "(RFC822)")

        for __ in msg:
            raw_email = msg[0][1]
            raw_email_string = raw_email.decode('utf-8')
            email_message = email.message_from_string(raw_email_string)
            email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
            subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))

            if "noreply@discord.com" in  email_from and "Password Reset Request for Discord" in subject:
                # Body details
                for part in email_message.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True).decode()

                        for url in re.findall(r"https:\/\/click\.discord\.com\/ls\/click\?upn=.+", body):
                            return str(url)

url = get_email_token("inbox")

response = requests.head(url, allow_redirects=True).url
print(response)
</code>```

It should return something in the lines of "https://discord.com/reset#token=" but instead I get the same link back.

Body:
I have got a code that uses "imaplib" to search for a specific email and link, everything works fine, it successfully gets the link but once I actually try to use the link extracted from the email to make a get request, it doesn't work.

I belive it's something to do with encoding/decoding?
Any help would be appreciated!

This is the code:

def get_email_token(box):
    status, messages = mail.select(box)
    messages = int(messages[0])

    for i in range(messages, messages-10, -1):
        res, msg = mail.fetch(str(i), "(RFC822)")

        for __ in msg:
            raw_email = msg[0][1]
            raw_email_string = raw_email.decode('utf-8')
            email_message = email.message_from_string(raw_email_string)
            email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
            subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))

            if "noreply@discord.com" in  email_from and "Password Reset Request for Discord" in subject:
                # Body details
                for part in email_message.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True).decode()

                        for url in re.findall(r"https:\/\/click\.discord\.com\/ls\/click\?upn=.+", body):
                            return str(url)

url = get_email_token("inbox")

response = requests.head(url, allow_redirects=True).url
print(response)

It should return something in the lines of "https://discord.com/reset#token=" but instead I get the same link back.