问:
Makefile works on macos but doesn't on linux
I have a c program with a makefile that works perfectly on macos but when i try yo run it on linux it gives me a bunch of errors

```<code>gcc ./libft/libft.a srcs/main.o -o push_swap
/usr/bin/ld: srcs/main.o: in function `sa':
main.c:(.text+0x97): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `sb':
main.c:(.text+0x149): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `ss':
main.c:(.text+0x1eb): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `pa':
main.c:(.text+0x236): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `pb':
main.c:(.text+0x2df): undefined reference to `ft_putstr'
/usr/bin/ld: main.c:(.text+0x327): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: srcs/main.o: in function `printstack':
main.c:(.text+0x3b3): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: main.c:(.text+0x3bd): undefined reference to `ft_putchar'
/usr/bin/ld: main.c:(.text+0x3df): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: main.c:(.text+0x3e9): undefined reference to `ft_putchar'
/usr/bin/ld: main.c:(.text+0x404): undefined reference to `ft_putstr'
/usr/bin/ld: main.c:(.text+0x413): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `main':
main.c:(.text+0x4a9): undefined reference to `ft_atoi'
collect2: error: ld returned 1 exit status
make: *** [Makefile:23: push_swap] Error 1
</code>```

I believe the cause is the Makefile because it can't find the function that the makefile is suppose to compile too but im not sure about that.
Anyways here is my makefile:

```<code>NAME = push_swap
LIBFT_PATH = libft
LIBFT = libft.a

SRC_FILES = main.c
SRC_DIR = srcs/
SRC = ${addprefix ${SRC_DIR}, ${SRC_FILES}}
OBJ = ${SRC:.c=.o}

CC = gcc
CFLAGS = -Wall -Wextra -Werror -pg -g
AR = ar -rcs

%.o: %.c
    ${CC} -c -Imlx -c $< -o $@

all: ${NAME}

libft:
    @MAKE -sC ${LIBFT_PATH}

${NAME}: libft ${OBJ}
    ${CC} ${LIBFT_PATH}/${LIBFT} ${OBJ} -o ${NAME}

clean:
    rm -f ${OBJ}
    ${MAKE} -C ${LIBFT_PATH} clean

fclean: clean
    rm -f ${NAME}
    ${MAKE} -C ${LIBFT_PATH} fclean

re: fclean all

.PHONY: all clean flcean re
</code>```

Body:
I have a c program with a makefile that works perfectly on macos but when i try yo run it on linux it gives me a bunch of errors

gcc ./libft/libft.a srcs/main.o -o push_swap
/usr/bin/ld: srcs/main.o: in function `sa':
main.c:(.text+0x97): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `sb':
main.c:(.text+0x149): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `ss':
main.c:(.text+0x1eb): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `pa':
main.c:(.text+0x236): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `pb':
main.c:(.text+0x2df): undefined reference to `ft_putstr'
/usr/bin/ld: main.c:(.text+0x327): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: srcs/main.o: in function `printstack':
main.c:(.text+0x3b3): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: main.c:(.text+0x3bd): undefined reference to `ft_putchar'
/usr/bin/ld: main.c:(.text+0x3df): undefined reference to `ft_putnbr_fd'
/usr/bin/ld: main.c:(.text+0x3e9): undefined reference to `ft_putchar'
/usr/bin/ld: main.c:(.text+0x404): undefined reference to `ft_putstr'
/usr/bin/ld: main.c:(.text+0x413): undefined reference to `ft_putstr'
/usr/bin/ld: srcs/main.o: in function `main':
main.c:(.text+0x4a9): undefined reference to `ft_atoi'
collect2: error: ld returned 1 exit status
make: *** [Makefile:23: push_swap] Error 1

I believe the cause is the Makefile because it can't find the function that the makefile is suppose to compile too but im not sure about that.
Anyways here is my makefile:

NAME = push_swap
LIBFT_PATH = libft
LIBFT = libft.a

SRC_FILES = main.c
SRC_DIR = srcs/
SRC = ${addprefix ${SRC_DIR}, ${SRC_FILES}}
OBJ = ${SRC:.c=.o}

CC = gcc
CFLAGS = -Wall -Wextra -Werror -pg -g
AR = ar -rcs

%.o: %.c
    ${CC} -c -Imlx -c $< -o $@

all: ${NAME}

libft:
    @MAKE -sC ${LIBFT_PATH}

${NAME}: libft ${OBJ}
    ${CC} ${LIBFT_PATH}/${LIBFT} ${OBJ} -o ${NAME}

clean:
    rm -f ${OBJ}
    ${MAKE} -C ${LIBFT_PATH} clean

fclean: clean
    rm -f ${NAME}
    ${MAKE} -C ${LIBFT_PATH} fclean

re: fclean all

.PHONY: all clean flcean re


来源: stackexchange

问:
The Python Variables Value displayed by “watch” in vscode debuger are diffrent from those printed by function print()
I wrote the following program to test the behavior of Numpy array view：

import numpy as np

a = np.array(\[1, 2, 3, 4, 5, 6\])

b = a\[2:4\]

# print(type(a.data))

# print(dir(a.data))

print(a.data)
print(hex(id(a.data)))
print()

# print(type(b.data))

# print(dir(b.data))

print(b.data)
print(hex(id(b.data)))
print()

# print(hex(id(a.data)))

# print(hex(id(b.data)))

# print(b.base)

print()
```

But The address of ndarray's buffer displayed by “watch” in vscode debuger is always change，As shown in the following pictures.

vscode display1

vscode display2

vscode display3

vscode display4

vscode display5

It's also different from the function "print()" printed.

print() printed

In my opinion，I think the address printed by function print() is right.But I don't konw why this happend.

Who can tell me why.

ContentLicense: CC BY-SA 4.0

Body:
I wrote the following program to test the behavior of Numpy array view：

import numpy as np

a = np.array(\[1, 2, 3, 4, 5, 6\])

b = a\[2:4\]

# print(type(a.data))

# print(dir(a.data))

print(a.data)
print(hex(id(a.data)))
print()

# print(type(b.data))

# print(dir(b.data))

print(b.data)
print(hex(id(b.data)))
print()

# print(hex(id(a.data)))

# print(hex(id(b.data)))

# print(b.base)

print()

But The address of ndarray's buffer displayed by “watch” in vscode debuger is always change，As shown in the following pictures.

vscode display1

vscode display2

vscode display3

vscode display4

vscode display5

It's also different from the function "print()" printed.

print() printed

In my opinion，I think the address printed by function print() is right.But I don't konw why this happend.

Who can tell me why.


问:
speechbrain & CUDA out of memory
I am trying to enhance an audio file (3:16 minutes in length, available here) using Speechbrain. If I run the code below (from this tutorial), I get the error OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 0; 39.59 GiB total capacity; 33.60 GiB already allocated; 3.19 MiB free; 38.06 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF.

What is the recommended way to fix the issue? Should I just cut the audio file in pieces?

```<code>from speechbrain.pretrained import SepformerSeparation as separator
import torchaudio

model = separator.from_hparams(source="speechbrain/sepformer-wham-enhancement",
    savedir='pretrained_models/sepformer-wham-enhancement', run_opts={"device":"cuda"})

est_sources = model.separate_file(path=audio_file)

torchaudio.save("enhanced_wham.wav", est_sources[:, :, 0].detach().cpu(), 8000)
</code>```

Title: speechbrain & CUDA out of memory

Body:
I am trying to enhance an audio file (3:16 minutes in length, available here) using Speechbrain. If I run the code below (from this tutorial), I get the error OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 0; 39.59 GiB total capacity; 33.60 GiB already allocated; 3.19 MiB free; 38.06 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF.

What is the recommended way to fix the issue? Should I just cut the audio file in pieces?

from speechbrain.pretrained import SepformerSeparation as separator
import torchaudio

model = separator.from_hparams(source="speechbrain/sepformer-wham-enhancement",
    savedir='pretrained_models/sepformer-wham-enhancement', run_opts={"device":"cuda"})

est_sources = model.separate_file(path=audio_file)

torchaudio.save("enhanced_wham.wav", est_sources[:, :, 0].detach().cpu(), 8000)


问:
Gsap Toggle Class issue
```<code>`const pinLinks = gsap.utils.toArray('.pinScroll > div');
    pinLinks.forEach((pinLink, index) => {
        const lastpinLinks = document.querySelector('.pinScroll > div:last-child');
        ScrollTrigger.create({
            trigger: pinLink,
            start: 'top center',
            end: () => `+=${pinLink.clientHeight}`,
            toggleActions: 'play reverse none reverse',
            toggleClass: { targets: pinLink, className: "active"},
        });
});`
</code>```

The above code works fine for me to toggleClass based on scroll, but it removes the active class from the last child, which I don't want.

Can you please tell me how can is keep active class on last child?

Title: Gsap Toggle Class issue

Body:
`const pinLinks = gsap.utils.toArray('.pinScroll > div');
    pinLinks.forEach((pinLink, index) => {
        const lastpinLinks = document.querySelector('.pinScroll > div:last-child');
        ScrollTrigger.create({
            trigger: pinLink,
            start: 'top center',
            end: () => `+=${pinLink.clientHeight}`,
            toggleActions: 'play reverse none reverse',
            toggleClass: { targets: pinLink, className: "active"},
        });
});`

The above code works fine for me to toggleClass based on scroll, but it removes the active class from the last child, which I don't want.

Can you please tell me how can is keep active class on last child?


问:
merge or exception when val
i have code on oracle apex need to loop on a collection and then if the primary key is dublicated
then i must update if others then insert new one.

this is my code but give me errors.

```<code>BEGIN
    FOR r1
        IN (SELECT *
              FROM apex_application_temp_files f,
                   TABLE (
                       apex_data_parser.parse (
                           p_content           => f.blob_content,
                           p_add_headers_row   => 'Y',
                           p_file_name         => f.filename)) p
             WHERE f.name = :p24_upload AND line_number > 1)
    LOOP
        apex_collection.add_member (
            p_collection_name   => 'W',
            p_c001              => NVL (REPLACE (r1.col001, '-', ''), NULL),
            p_c002              => NVL (REPLACE (r1.col002, '-', ''), NULL),
            p_c003              => NVL (REPLACE (r1.col003, '-', ''), NULL),
            p_c004              => NVL (REPLACE (r1.col004, '-', ''), NULL),
            p_c005              => NVL (REPLACE (r1.col005, '-', ''), NULL),
            p_c006              => NVL (REPLACE (r1.col006, '-', ''), NULL),
            p_c007              => NVL (REPLACE (r1.col007, '-', ''), NULL),
            p_c008              => NVL (REPLACE (r1.col008, '-', ''), NULL),
            p_c009              => NVL (REPLACE (r1.col009, '-', ''), NULL),
            p_c010              => NVL (REPLACE (r1.col010, '-', ''), NULL),
            p_c011              => NVL (REPLACE (r1.col011, '-', ''), NULL),
            p_c012              => NVL (REPLACE (r1.col012, '-', ''), NULL),
            p_c013              => NVL (REPLACE (r1.col013, '-', ''), NULL),
            p_c014              => NVL (REPLACE (r1.col014, '-', ''), NULL),
            p_c015              => NVL (REPLACE (r1.col015, '-', ''), NULL),
            p_c016              => NVL (REPLACE (r1.col016, '-', ''), NULL),
            p_c017              => NVL (REPLACE (r1.col017, '-', ''), NULL),
            p_c018              => NVL (REPLACE (r1.col018, '-', ''), NULL),
            p_c019              => NVL (REPLACE (r1.col019, '-', ''), NULL),
            p_c020              => NVL (REPLACE (r1.col020, '-', ''), NULL),
            p_c021              => NVL (REPLACE (r1.col021, '-', ''), NULL),
            p_c022              => NVL (REPLACE (r1.col022, '-', ''), NULL),
            p_c023              => NVL (REPLACE (r1.col023, '-', ''), NULL),
            p_c024              => NVL (REPLACE (r1.col024, '-', ''), NULL),
            p_c025              => NVL (REPLACE (r1.col025, '-', ''), NULL));
    END LOOP;
END;                                                      1

DECLARE
    CURSOR c2
    IS
        (SELECT *
           FROM apex_collections
          WHERE collection_name = 'W');

BEGIN
FOR i IN c2
                LOOP
     MERGE INTO pos_cards_new NEWS
USING  (SELECT *
           FROM apex_collections
          WHERE collection_name = 'W') STC
  ON( NEWS.card_seq = I.C001 )
    WHEN MATCHED THEN
         UPDATE pos_cards_new
                       SET card_amt = I.C005,
                           iuser_id = :app_user,
                           itime_stamp = SYSDATE,
                           valid_from_date = I.C007,
                           vald_to_date = I.C008
                     WHERE card_seq = I.C001;
    WHEN NOT MATCHED THEN

            INSERT INTO pos_cards_new (comp_id,
                                       card_seq,
                                       curncy_code,
                                       curr_rate,
                                       card_amt,
                                       card_base_amt,
                                       valid_from_date,
                                       vald_to_date,
                                       card_points,
                                       card_balance,
                                       card_isvalid,
                                       iuser_id,
                                       itime_stamp,
                                       card_id,
                                       customer_code,
                                       employee_cridet_limit,
                                       employee_cridet_curr_balance,
                                       is_admin)
             VALUES (
                                        'IPOS',
                                        I.C001,
                                        (SELECT curncy_code
                                           FROM pos_stp_currencies
                                           WHERE curncy_desc_m = i.c003
                                           AND comp_id = :p0_comp_id),
                                        I.C004,
                                        I.C005,
                                        I.C006,
                                        TO_CHAR (TO_DATE (I.C007, 'YYYYMMDD'),'dd/mm/yyyy'),
                                        TO_CHAR (TO_DATE (I.C008, 'YYYYMMDD'),'dd/mm/yyyy'),
                                        I.C009,
                                        I.C010,
                                        I.C014,
                                        :app_user,
                                        SYSDATE,
                                        I.C002,
                                        I.C013,
                                        I.C015,
                                        I.C016,
                                        I.C017);
                      END LOOP;             -------------------3
               END;

</code>```

---- the primary key is card_seq with in collection is I.C001

EXPECTED TO CORRECT MY CODE

Title: merge or exception when val

Body:
i have code on oracle apex need to loop on a collection and then if the primary key is dublicated
then i must update if others then insert new one.

this is my code but give me errors.

BEGIN
    FOR r1
        IN (SELECT *
              FROM apex_application_temp_files f,
                   TABLE (
                       apex_data_parser.parse (
                           p_content           => f.blob_content,
                           p_add_headers_row   => 'Y',
                           p_file_name         => f.filename)) p
             WHERE f.name = :p24_upload AND line_number > 1)
    LOOP
        apex_collection.add_member (
            p_collection_name   => 'W',
            p_c001              => NVL (REPLACE (r1.col001, '-', ''), NULL),
            p_c002              => NVL (REPLACE (r1.col002, '-', ''), NULL),
            p_c003              => NVL (REPLACE (r1.col003, '-', ''), NULL),
            p_c004              => NVL (REPLACE (r1.col004, '-', ''), NULL),
            p_c005              => NVL (REPLACE (r1.col005, '-', ''), NULL),
            p_c006              => NVL (REPLACE (r1.col006, '-', ''), NULL),
            p_c007              => NVL (REPLACE (r1.col007, '-', ''), NULL),
            p_c008              => NVL (REPLACE (r1.col008, '-', ''), NULL),
            p_c009              => NVL (REPLACE (r1.col009, '-', ''), NULL),
            p_c010              => NVL (REPLACE (r1.col010, '-', ''), NULL),
            p_c011              => NVL (REPLACE (r1.col011, '-', ''), NULL),
            p_c012              => NVL (REPLACE (r1.col012, '-', ''), NULL),
            p_c013              => NVL (REPLACE (r1.col013, '-', ''), NULL),
            p_c014              => NVL (REPLACE (r1.col014, '-', ''), NULL),
            p_c015              => NVL (REPLACE (r1.col015, '-', ''), NULL),
            p_c016              => NVL (REPLACE (r1.col016, '-', ''), NULL),
            p_c017              => NVL (REPLACE (r1.col017, '-', ''), NULL),
            p_c018              => NVL (REPLACE (r1.col018, '-', ''), NULL),
            p_c019              => NVL (REPLACE (r1.col019, '-', ''), NULL),
            p_c020              => NVL (REPLACE (r1.col020, '-', ''), NULL),
            p_c021              => NVL (REPLACE (r1.col021, '-', ''), NULL),
            p_c022              => NVL (REPLACE (r1.col022, '-', ''), NULL),
            p_c023              => NVL (REPLACE (r1.col023, '-', ''), NULL),
            p_c024              => NVL (REPLACE (r1.col024, '-', ''), NULL),
            p_c025              => NVL (REPLACE (r1.col025, '-', ''), NULL));
    END LOOP;
END;                                                      1

DECLARE
    CURSOR c2
    IS
        (SELECT *
           FROM apex_collections
          WHERE collection_name = 'W');

BEGIN
FOR i IN c2
                LOOP
     MERGE INTO pos_cards_new NEWS
USING  (SELECT *
           FROM apex_collections
          WHERE collection_name = 'W') STC
  ON( NEWS.card_seq = I.C001 )
    WHEN MATCHED THEN
         UPDATE pos_cards_new
                       SET card_amt = I.C005,
                           iuser_id = :app_user,
                           itime_stamp = SYSDATE,
                           valid_from_date = I.C007,
                           vald_to_date = I.C008
                     WHERE card_seq = I.C001;
    WHEN NOT MATCHED THEN

            INSERT INTO pos_cards_new (comp_id,
                                       card_seq,
                                       curncy_code,
                                       curr_rate,
                                       card_amt,
                                       card_base_amt,
                                       valid_from_date,
                                       vald_to_date,
                                       card_points,
                                       card_balance,
                                       card_isvalid,
                                       iuser_id,
                                       itime_stamp,
                                       card_id,
                                       customer_code,
                                       employee_cridet_limit,
                                       employee_cridet_curr_balance,
                                       is_admin)
             VALUES (
                                        'IPOS',
                                        I.C001,
                                        (SELECT curncy_code
                                           FROM pos_stp_currencies
                                           WHERE curncy_desc_m = i.c003
                                           AND comp_id = :p0_comp_id),
                                        I.C004,
                                        I.C005,
                                        I.C006,
                                        TO_CHAR (TO_DATE (I.C007, 'YYYYMMDD'),'dd/mm/yyyy'),
                                        TO_CHAR (TO_DATE (I.C008, 'YYYYMMDD'),'dd/mm/yyyy'),
                                        I.C009,
                                        I.C010,
                                        I.C014,
                                        :app_user,
                                        SYSDATE,
                                        I.C002,
                                        I.C013,
                                        I.C015,
                                        I.C016,
                                        I.C017);
                      END LOOP;             -------------------3
               END;

---- the primary key is card_seq with in collection is I.C001

EXPECTED TO CORRECT MY CODE


问:
Python make a temp json file for AWS error
gives me the following error

part of the code giving me error:

```<code>        serviceAccount = 'googleKey.json'
        serviceAccount = '/tmp/' + serviceAccount
        data = {
            "type": TYPE,
            "project_id": PROJECT_ID,
            "private_key_id": PRIVATE_KEY_ID,
            "private_key": PRIVATE_KEY,
            "client_email": CLIENT_EMAIL,
            "client_id": CLIENT_ID,
            "auth_uri": AUTH_URI,
            "token_uri": TOKEN_URI,
            "auth_provider_x509_cert_url": AUTH_PROVIDER_X509_CERT_URL,
            "client_x509_cert_url": CLIENT_X509_CERT_URL
        }
        with open(serviceAccount, 'w') as f:
            json.dump(data, f, indent=2)
        timestamp.append("---#2 %s seconds ---" % (time.time() - start_time))
        with fileinput.FileInput(serviceAccount, inplace=True, backup='.bak') as file:
            for line in file:
                print(line.replace('\\\\', '\\'), end='')
</code>```

i added a /tmp to the file path

and now it gives me the following error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/googleKey.json'

Body:
gives me the following error

part of the code giving me error:

        serviceAccount = 'googleKey.json'
        serviceAccount = '/tmp/' + serviceAccount
        data = {
            "type": TYPE,
            "project_id": PROJECT_ID,
            "private_key_id": PRIVATE_KEY_ID,
            "private_key": PRIVATE_KEY,
            "client_email": CLIENT_EMAIL,
            "client_id": CLIENT_ID,
            "auth_uri": AUTH_URI,
            "token_uri": TOKEN_URI,
            "auth_provider_x509_cert_url": AUTH_PROVIDER_X509_CERT_URL,
            "client_x509_cert_url": CLIENT_X509_CERT_URL
        }
        with open(serviceAccount, 'w') as f:
            json.dump(data, f, indent=2)
        timestamp.append("---#2 %s seconds ---" % (time.time() - start_time))
        with fileinput.FileInput(serviceAccount, inplace=True, backup='.bak') as file:
            for line in file:
                print(line.replace('\\\\', '\\'), end='')

i added a /tmp to the file path

and now it gives me the following error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/googleKey.json'


问:
Web viewer in react not working , what to do
Compiled with problems:X

```<code>ERROR in ./node_modules/react-native-webview/lib/WebView.js
</code>```

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/pathparakh/Projects/react/new/new/node_modules/react-native-webview/lib/WebView.js: Support for the experimental syntax 'jsx' isn't currently enabled (5:37):

```<code>  3 | // This "dummy" WebView is to render something for unsupported platforms,
  4 | // like for example Expo SDK "web" platform.
> 5 | var WebView = function () { return (<View style={{ alignSelf: 'flex-start' }}>
    |                                     ^
  6 |       <Text style={{ color: 'red' }}>
  7 |           React Native WebView does not support this platform.
  8 |       </Text>
</code>```

this is error

and when i created app it is showing

i also run npm audit fix --force

this is showing error when i add

```<code>import { WebView } from "react-native-webview";
</code>```

in app.js

this is package.json

```<code>{
  "name": "new",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-native-webview": "^11.26.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6"
  }
}
</code>```

Body:
Compiled with problems:X

ERROR in ./node_modules/react-native-webview/lib/WebView.js

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/pathparakh/Projects/react/new/new/node_modules/react-native-webview/lib/WebView.js: Support for the experimental syntax 'jsx' isn't currently enabled (5:37):

  3 | // This "dummy" WebView is to render something for unsupported platforms,
  4 | // like for example Expo SDK "web" platform.
> 5 | var WebView = function () { return (<View style={{ alignSelf: 'flex-start' }}>
    |                                     ^
  6 |       <Text style={{ color: 'red' }}>
  7 |           React Native WebView does not support this platform.
  8 |       </Text>

this is error

and when i created app it is showing

i also run npm audit fix --force

this is showing error when i add

import { WebView } from "react-native-webview";

in app.js

this is package.json

{
  "name": "new",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-native-webview": "^11.26.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6"
  }
}


问:
Scala AmazonS3 unitest
I have a test that I have to change due to a change that I did in an S3Repository class
to use putObject method. I had to change the client from the type of AmazonS3Client that is deprecated to AmazonS3. That's how I did it:
The method is uploadCsvToS3:

```<code>val creds = DefaultAWSCredentialsProviderChain.getInstance()
val awsRegion: Regions = Regions.fromName(configuration.get[String]("aws.s3.region"))
val client: AmazonS3 = AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(creds).build()
val fileName = produceFileNameForVersion(params_to_this_method)
client.putObject(AWSS3Bucket, fileName, file.toFile)
</code>```

I know that the solution works, but there is a test that is not working:
I have a mock and override:

```<code>val client = mock[AmazonS3]
override def fakeApplication(): Application = new GuiceApplicationBuilder()
  .overrides(bind[AmazonS3].toInstance(client))
</code>```

and This is the test (positive case):

```<code>Mockito.when(client.putObject(MockitoMatchers.eq(s3Bucket), MockitoMatchers.anyString(), MockitoMatchers.eq(file))) thenReturn new PutObjectResult
val s3Repository : S3Repository = app.injector.instanceOf[S3Repository]
val s3Location = s3Repository.uploadCsvToS3(file.toPath).futureValue
assert(s3Location.fileName.nonEmpty)
</code>```

I get this error:

```<code>Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID:...
</code>```

I tried a lot of solutions like configuration of access and secret key, PowerMockito and others.

Thanks for any help.

EDIT - Solution:
I found that this method is not testable because there is an instantiation of a client, but the purpose is to mock the client in order to test this method.
The solution was to create a Provider - AmazonS3ClientProvider, and override the method get. There, the client will be instantiate the same way. Then:

```<code>bind(classOf[AmazonS3]).toProvider(classOf[AmazonS3ClientProvider])
</code>```

Title: Scala AmazonS3 unitest

Body:
I have a test that I have to change due to a change that I did in an S3Repository class
to use putObject method. I had to change the client from the type of AmazonS3Client that is deprecated to AmazonS3. That's how I did it:
The method is uploadCsvToS3:

val creds = DefaultAWSCredentialsProviderChain.getInstance()
val awsRegion: Regions = Regions.fromName(configuration.get[String]("aws.s3.region"))
val client: AmazonS3 = AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(creds).build()
val fileName = produceFileNameForVersion(params_to_this_method)
client.putObject(AWSS3Bucket, fileName, file.toFile)

I know that the solution works, but there is a test that is not working:
I have a mock and override:

val client = mock[AmazonS3]
override def fakeApplication(): Application = new GuiceApplicationBuilder()
  .overrides(bind[AmazonS3].toInstance(client))

and This is the test (positive case):

Mockito.when(client.putObject(MockitoMatchers.eq(s3Bucket), MockitoMatchers.anyString(), MockitoMatchers.eq(file))) thenReturn new PutObjectResult
val s3Repository : S3Repository = app.injector.instanceOf[S3Repository]
val s3Location = s3Repository.uploadCsvToS3(file.toPath).futureValue
assert(s3Location.fileName.nonEmpty)

I get this error:

Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID:...

I tried a lot of solutions like configuration of access and secret key, PowerMockito and others.

Thanks for any help.

EDIT - Solution:
I found that this method is not testable because there is an instantiation of a client, but the purpose is to mock the client in order to test this method.
The solution was to create a Provider - AmazonS3ClientProvider, and override the method get. There, the client will be instantiate the same way. Then:

bind(classOf[AmazonS3]).toProvider(classOf[AmazonS3ClientProvider])


问:
Spring 6 StrictHttpFirewall semicolon
After migration to the new Spring Boot 3 (which uses Spring 6), I am facing an issue with semicolons in URL. By default, this should not be allowed, which after debugging was proven to be correct. StrictHttpFirewall object throws the
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";"

as it should. But this exception ends up in some ObservationMarkingRequestRejectedHandler where it is somehow handled, but not re-thrown.

Before migration, semicolons (and other special characters) were returning status code 400, but now when the exception is lost somewhere in the process, the status code is 200, which is wrong.

Anybody else facing this issue?

Title: Spring 6 StrictHttpFirewall semicolon


问:
sass error on "@use '@material/feature-targeting/feature-targeting'" in "node_modues/@material/theme/_theme.scss";
I have never actively used sass, but Google's Material Design is written so that I need sass. But I stumbled upon this error and can't find out what is wrong.

```<code>Error: Can't find stylesheet to import.
   ╷
26 │ @use '@material/feature-targeting/feature-targeting';
   │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
  node_modules\@material\theme\_theme.scss 26:1  @forward
  node_modules\@material\theme\_index.scss 17:1  @use
</code>```

Line 26 in _theme.scss looks like this:

@use '@material/feature-targeting/feature-targeting';
```
<p>This target file is from <code>npm install @material/feature-targeting</code>. Is there something wrong with the file <code>_theme.scss</code> from Google or did I do something wrong? (There is a file <code>node_modules/@material/feature-target/_feature-target.scss</code>. Is perhaps the underscore missing in line 26 in <code>_theme.scss</code>?)</p>
<p>The file I give to sass is this one:</p>
<pre class="lang-scss prettyprint-override"><code>@use "../node_modules/@material/theme" with (
  $primary: #fcb8ab,
  $secondary: #feeae6,
  $on-primary: #442b2d,
  $on-secondary: #442b2d,
);
@use "@material/button/mdc-button";
</code>```

Body:
I have never actively used sass, but Google's Material Design is written so that I need sass. But I stumbled upon this error and can't find out what is wrong.

Error: Can't find stylesheet to import.
   ╷
26 │ @use '@material/feature-targeting/feature-targeting';
   │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
  node_modules\@material\theme\_theme.scss 26:1  @forward
  node_modules\@material\theme\_index.scss 17:1  @use

Line 26 in _theme.scss looks like this:

@use '@material/feature-targeting/feature-targeting';

This target file is from npm install @material/feature-targeting. Is there something wrong with the file _theme.scss from Google or did I do something wrong? (There is a file node_modules/@material/feature-target/_feature-target.scss. Is perhaps the underscore missing in line 26 in _theme.scss?)

The file I give to sass is this one:

@use "../node_modules/@material/theme" with (
  $primary: #fcb8ab,
  $secondary: #feeae6,
  $on-primary: #442b2d,
  $on-secondary: #442b2d,
);
@use "@material/button/mdc-button";


问:
Is there a way to set an expiry date on VBA module code or add-in code (.xlam)?
I have some code that I want to distribute for a 90 day trial period. I am able to set a dynamic expiry date based on the first instance that a user opens the Workbook. However, I am wanting to sell my code as an add-in and need a way to incorporate a similar function in my add-in Module code. I.e. if the user installs the add-in, is there a way that I can store the first date the code is run and terminate after 90 days no matter what workbook the add-in is run?

Here is the code for the Workbook:

```<code>Private Const NUM_DAYS_UNTIL_EXPIRATION = 90

Private Sub Workbook_Open()

Dim PassWord As String

PassWord = InputBox("Please input password. Trial expires in " & NUM_DAYS_UNTIL_EXPIRATION & " days.")

If PassWord = "123" Then

    Dim ExpDate As String

    On Error Resume Next

    ExpDate = Mid(ThisWorkbook.names("ExpDate").Value, 2)

If Err.Number <> 0 Then
    'Name doesn't exist
    'Calculate new expiration
    ExpDate = CStr(DateSerial(Year(Now), Month(Now), Day(Now) + NUM_DAYS_UNTIL_EXPIRATION))

    'Create a named range and store the date here
    ThisWorkbook.names.add name:="ExpDate", RefersTo:=Format(ExDate, "short date"), Visible:=False
    ThisWorkbook.Save
    End If

    If CDate(Now) > CDate(ExpDate) Then
        MsgBox "This workbook trial period has expired.", vbOKOnly
        ThisWorkbook.Close savechanges:=False 'this removes the entire vb code
    End If

    Else: MsgBox "Password is incorrect."
    Application.Quit

End If

End Sub
</code>```

Body:
I have some code that I want to distribute for a 90 day trial period. I am able to set a dynamic expiry date based on the first instance that a user opens the Workbook. However, I am wanting to sell my code as an add-in and need a way to incorporate a similar function in my add-in Module code. I.e. if the user installs the add-in, is there a way that I can store the first date the code is run and terminate after 90 days no matter what workbook the add-in is run?

Here is the code for the Workbook:

Private Const NUM_DAYS_UNTIL_EXPIRATION = 90

Private Sub Workbook_Open()

Dim PassWord As String

PassWord = InputBox("Please input password. Trial expires in " & NUM_DAYS_UNTIL_EXPIRATION & " days.")

If PassWord = "123" Then

    Dim ExpDate As String

    On Error Resume Next

    ExpDate = Mid(ThisWorkbook.names("ExpDate").Value, 2)

If Err.Number <> 0 Then
    'Name doesn't exist
    'Calculate new expiration
    ExpDate = CStr(DateSerial(Year(Now), Month(Now), Day(Now) + NUM_DAYS_UNTIL_EXPIRATION))

    'Create a named range and store the date here
    ThisWorkbook.names.add name:="ExpDate", RefersTo:=Format(ExDate, "short date"), Visible:=False
    ThisWorkbook.Save
    End If

    If CDate(Now) > CDate(ExpDate) Then
        MsgBox "This workbook trial period has expired.", vbOKOnly
        ThisWorkbook.Close savechanges:=False 'this removes the entire vb code
    End If

    Else: MsgBox "Password is incorrect."
    Application.Quit

End If

End Sub


问:
How to apply word-wrap to ANTD Select title and dropdown items so that it changes the height of the element?
I want my ANTD title/selected item to go to the next row and modify the height of the Select.

I have worked on this example: https://codesandbox.io/s/basic-usage-antd-4-24-7-forked-8jzp29?file=/demo.js

The styles that I am looking to target are:

.ant-select-item-option-content {
  white-space: break-spaces;
  word-break: break-word;
}

.ant-select-show-search.ant-select:not(.ant-select-customize-input)
  .ant-select-selector {
  height: auto;
}
.ant-select-single.ant-select-show-arrow .ant-select-selection-item {
  white-space: normal;
  word-break: break-all;
}

```

How can I target those when using CSS modules ?

I have added a class to the dropdown using the ANTD Select API popupClassName="_dropdown" which only accepts strings but this is ignored when using CSS modules.

Body:
I want my ANTD title/selected item to go to the next row and modify the height of the Select.

I have worked on this example: https://codesandbox.io/s/basic-usage-antd-4-24-7-forked-8jzp29?file=/demo.js

The styles that I am looking to target are:

.ant-select-item-option-content {
  white-space: break-spaces;
  word-break: break-word;
}

.ant-select-show-search.ant-select:not(.ant-select-customize-input)
  .ant-select-selector {
  height: auto;
}
.ant-select-single.ant-select-show-arrow .ant-select-selection-item {
  white-space: normal;
  word-break: break-all;
}

How can I target those when using CSS modules ?

I have added a class to the dropdown using the ANTD Select API popupClassName="_dropdown" which only accepts strings but this is ignored when using CSS modules.


问:
Difference between Ethernet Interface and layered Ethernet Interface in Omnet++
In Omnet++, TSN devices use layered Ethernet Interface and standardHosts use Ethernet Interface.

What is the difference between these two interfaces?


问:
Argument of type 'CardFormValues' is not assignable to parameter of type 'CardsPostDto'
error is name :  (parameter) cardFormValues: CardFormValues
Argument of type 'CardFormValues' is not assignable to parameter of type 'CardsPostDto'.
Type 'CardFormValues' is missing the following properties from type 'CardsPostDto': number, holderName, holderCPF, holderEmail, and 5 more.ts(2345)

```<code>type CardFormValues = {
  nameCard: string;
  cardNumber: string;
  cpfCard: string;
  creditCardDate: string;
  securityCode: string;
  phoneNumberCard: string;
};

const createCard = (cardFormValues: CardFormValues) => {
    paymentApi.createCard(cardFormValues); //erros is here "cardFormValues"
  };
</code>```

my error

Body:
error is name :  (parameter) cardFormValues: CardFormValues
Argument of type 'CardFormValues' is not assignable to parameter of type 'CardsPostDto'.
Type 'CardFormValues' is missing the following properties from type 'CardsPostDto': number, holderName, holderCPF, holderEmail, and 5 more.ts(2345)

type CardFormValues = {
  nameCard: string;
  cardNumber: string;
  cpfCard: string;
  creditCardDate: string;
  securityCode: string;
  phoneNumberCard: string;
};

const createCard = (cardFormValues: CardFormValues) => {
    paymentApi.createCard(cardFormValues); //erros is here "cardFormValues"
  };

my error


问:
How does a webapp like web.whatsapp posts an input without sending requests
In Web.Whatsapp you can chat with your mobile phone contacts using wifi, even when your phone is not online. However when I first looked in to how a webapp like whatsapp 'posts' your send message (or receive incoming) I did not notice any form of outgoing requests, posts / get requests etc on my chrome / firefox developer tool.

The developer in me would like to know how whatsapp sends my messages to the server without me seeing that in the network area. If whatsapp interacts to the server on a different way i would love to know whether that part is visible just like in 'network'.

other site where I can not see network interaction is for example:
youtube when posting an comment or giving a like


问:
pip3 installation issue using linux
I tried around 8 hours to install pip3- python in ubintu but its not working showing:

Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in
from pip import main
File "/usr/lib/python3/dist-packages/pip/init.py", line 29, in
from pip.utils import get_installed_distributions, get_prog
File "/usr/lib/python3/dist-packages/pip/utils/init.py", line 23, in
from pip.locations import (
File "/usr/lib/python3/dist-packages/pip/locations.py", line 9, in
from distutils import sysconfig
ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.9/distutils/init.py)

i did
sudo apt-get update
sudo apt-get -y install python3-pip
pip3 --version

after this step the error message in the above shown

Title: pip3 installation issue using linux


问:
Maven exported jar doesnt find maven dependency although I can run the main class with no problems
So I added these maven dependencies in my project which will allow me to encode my logs in JSON. After doing this I reloaded maven on IntelliJ and I was able to run the Main class and use these dependencies:

```<code><dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>7.2</version>
  </dependency>
  <dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>2.6.1</version>
  </dependency>
</code>```

When I do mvn clean install -DskipTests and run the exported jar then I get this error:

```<code>2023-01-11 13:07:54 13:07:54,863 |-ERROR in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Could not create component [encoder] of type [net.logstash.logback.encoder.LogstashEncoder] java.lang.ClassNotFoundException: net.logstash.logback.encoder.LogstashEncoder
</code>```

Would someone know why the exported jar complains about not finding this dependency although when running the main class the dependency seems to be in use? Thanks in advance for the help

Body:
So I added these maven dependencies in my project which will allow me to encode my logs in JSON. After doing this I reloaded maven on IntelliJ and I was able to run the Main class and use these dependencies:

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>7.2</version>
  </dependency>
  <dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>2.6.1</version>
  </dependency>

When I do mvn clean install -DskipTests and run the exported jar then I get this error:

2023-01-11 13:07:54 13:07:54,863 |-ERROR in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Could not create component [encoder] of type [net.logstash.logback.encoder.LogstashEncoder] java.lang.ClassNotFoundException: net.logstash.logback.encoder.LogstashEncoder

Would someone know why the exported jar complains about not finding this dependency although when running the main class the dependency seems to be in use? Thanks in advance for the help


问:
How to pass properties to icons with Storybook and React
How do I pass props (like colors and size) to an svg with storybook and react?.
My code is looking like this:

```<code>const ICONS = { icon: <Icon />, icon2: <Icon2 /> };
// This icons are simple svg files of an icon.
const noIcon = undefined;
export default {
  title: "Components/Button",
  component: Button,
  argTypes: {
    handleClick: { action: "handleClick" },
    icon: {
      control: {
        type: "select",
        options: [undefined, ...Object.keys(ICONS)],
      },
    },
  },
};

const Template = ({ iconName, ...rest }) => {
  const icon = ICONS[iconName];
  return <Button icon={icon} {...rest} />;
};
</code>```

Button.js is this code:

```<code><button
      onClick={handleClick}
      style={style}
      className={`button ${size === "m" ? "button-m" : "button-s"}`}
      disabled={disabled}
    >
      <div>{icon}</div>
      <span
        style={styleButton}
        className={size === "m" ? "button-content-m" : "button-content-s"}
      >
        {content}
      </span>
    </button>
</code>```

Currently, I can pass the object with icons, but I don't know how to change colors and sizes of the svg.

I'm expecting to find a way to change properties of the icons

Body:
How do I pass props (like colors and size) to an svg with storybook and react?.
My code is looking like this:

const ICONS = { icon: <Icon />, icon2: <Icon2 /> };
// This icons are simple svg files of an icon.
const noIcon = undefined;
export default {
  title: "Components/Button",
  component: Button,
  argTypes: {
    handleClick: { action: "handleClick" },
    icon: {
      control: {
        type: "select",
        options: [undefined, ...Object.keys(ICONS)],
      },
    },
  },
};

const Template = ({ iconName, ...rest }) => {
  const icon = ICONS[iconName];
  return <Button icon={icon} {...rest} />;
};

Button.js is this code:

<button
      onClick={handleClick}
      style={style}
      className={`button ${size === "m" ? "button-m" : "button-s"}`}
      disabled={disabled}
    >

{icon}

        {content}

    </button>

Currently, I can pass the object with icons, but I don't know how to change colors and sizes of the svg.

I'm expecting to find a way to change properties of the icons


问:
Balacing data set for a repeated measures ANOVA test
I have a data set where the columns are "class", "student", and "average". I have 7 different classes and around 100 total unique classes between all of the 7 classes, and each student has an average assigned to it that's unique to their class-student pairing. The only issue is that not every student appears in every class.

I want to do a repeated measures ANOVA test on my data, but because not every student is in every class I am getting the error that the data set is unbalanced. How can I only look at the students who appear in every class for the repeated ANOVA?

I am using Python library statsmodels.stats.anova and the function AnovaRM


问:
Separation of concern in React with event listeners that cause component rendering?
I have been reading about how it is a good idea to separate your "buiness logic" from your "view" when designing apps and it makes perfect sense. However, I was thinking about how you should handle event listeners that might cause a component to render as a result. The most obvious example would be that some kind of asynchronous request failed and you want an alert to appear with some information about what happened. How can you implement behviour like this while still keeping the view strictly separate from the logic?

For example, let's say you have a login button so you add some logic and a login request to the onClick handler. You write this handler in your logic file but it may throw an error. If you don't catch it you will have to catch it in the UI which means you are adding logic to the UI. If you do catch it and you want to render the alert then you are changing the view from the logic file. Is there any better way to handle this? If I had to choose one of the above I would proabably make the logic file render the alert in the handler function but this does not seem ideal.


问:
Enable service worker with playwright
I'm playing with telegram and playwright, and most of the time I'm getting a pop up that says that service worker is disabled. I have no idea how to turn it on. This is how I launch the browser:

browser = await playwright.chromium.launch(headless=False)
context = await browser.new_context(storage_state='state.json')
page = await context.new_page()
await page.goto(chat_url1)
```

Title: Enable service worker with playwright


问:
Feature extraction in pretrained model: different result from keras-gpu&tensorflow-gpu and keras&tensorflow base
I'm extracting features from a pretrained keras model (VGG16).The task is simple but I obtain different features (nx4096) when I run the code on GPU (tensorflow-gpu and keras-gpu installed) or CPU (tensorflow and keras installed).

The differences in the features are huge and when I use the different extracted features in a classifier, I obtain very much better results with those obtained on GPU.

Could someone explain me why?

I write the code in case it is useful:

```<code>from keras.preprocessing import image
from keras.applications.vgg16 import VGG16
import tensorflow.keras
from keras.applications.vgg16 import preprocess_input
import numpy as np
from sklearn.cluster import KMeans
# %matplotlib inline
import matplotlib.pyplot as plt
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import decode_predictions
from keras.models import Model
from pickle import dump

model = VGG16(weights='imagenet')#, include_top=False
# remove the output layer
model = Model(inputs=model.inputs, outputs=model.layers[-2].output)

model.summary()

trainstack=np.load('.../All_imgs.npy')
trainstack=np.transpose(trainstack,[2,0,1,3])
trainstack=preprocess_input(trainstack)
trainstacklabel=np.load('.../All_labels.npy')

img_data = preprocess_input(trainstack)
vgg16_feature_list=[]

for i in range(trainstack.shape[0]):

    v =img_data[i,:,:,:]
    v=v[np.newaxis,...]
    vgg16_feature = model.predict(v)
    print (vgg16_feature.shape)
    vgg16_feature_np = np.array(vgg16_feature)
    vgg16_feature_list.append(vgg16_feature_np.flatten())

np.save('.../features.npy',vgg16_feature_list)
</code>```

Thank you very much in advance!!

I try to extract features from a pretrained model for combining them with other variables in a binary classifier.

I obtain very different extracted features when I run my code on GPU and CPU.

Body:
I'm extracting features from a pretrained keras model (VGG16).The task is simple but I obtain different features (nx4096) when I run the code on GPU (tensorflow-gpu and keras-gpu installed) or CPU (tensorflow and keras installed).

The differences in the features are huge and when I use the different extracted features in a classifier, I obtain very much better results with those obtained on GPU.

Could someone explain me why?

I write the code in case it is useful:

from keras.preprocessing import image
from keras.applications.vgg16 import VGG16
import tensorflow.keras
from keras.applications.vgg16 import preprocess_input
import numpy as np
from sklearn.cluster import KMeans
# %matplotlib inline
import matplotlib.pyplot as plt
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import decode_predictions
from keras.models import Model
from pickle import dump

model = VGG16(weights='imagenet')#, include_top=False
# remove the output layer
model = Model(inputs=model.inputs, outputs=model.layers[-2].output)

model.summary()

trainstack=np.load('.../All_imgs.npy')
trainstack=np.transpose(trainstack,[2,0,1,3])
trainstack=preprocess_input(trainstack)
trainstacklabel=np.load('.../All_labels.npy')

img_data = preprocess_input(trainstack)
vgg16_feature_list=[]

for i in range(trainstack.shape[0]):

    v =img_data[i,:,:,:]
    v=v[np.newaxis,...]
    vgg16_feature = model.predict(v)
    print (vgg16_feature.shape)
    vgg16_feature_np = np.array(vgg16_feature)
    vgg16_feature_list.append(vgg16_feature_np.flatten())

np.save('.../features.npy',vgg16_feature_list)

Thank you very much in advance!!

I try to extract features from a pretrained model for combining them with other variables in a binary classifier.

I obtain very different extracted features when I run my code on GPU and CPU.


问:
handling errors with useSWR, reactjs, nextjs
The below works but the error checking feels really clunky. I don't really understand how SWR is working and what error contains.

What I want to do is make a request to my API; output the data; or if (anything) goes wrong - 404, timeout, no songs... then a generic error is output.

--

If I change my fetch URL to something that 404s, instead of getting the "error", I get Cannot read property 'splice' of undefined... which makes sense because my API is now returning

```<code>{"message": "Not Found", "url": "/invalid-link.json","code": 404}
</code>```

instead of {"songs":[{...jsondata}]}

I would as a layman expect the error variable to do something here - like intercept a non 200 code? Otherwise what is the point of it if I still need to then check the response.

My Hook adapted from next.js SWR:

```<code>import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())

export default function useGetSongs() {

    const { data, error, isLoading } = useSWR('https://myapi.com/songs.json', fetcher)

    return {
        data: data,
        isLoading,
        isError: error
    }
}
</code>```

My component:

```<code>import useGetSongs from '../hooks/useGetSongs';
export default function RecentlyPlayed() {
    const { data, isLoading, isError } = useGetSongs();

    if (isLoading) return <div>Loading...</div>

    if(data === undefined || isError || data.code === 404) {
        return <p>Sorry - there is a problem retrieving data.</p>
    }

    if(data.songs.length > 0) {
        return data.songs.map((song, songID) => {
              return <div key={songID}>{song.name}</div>
        })
    }
}
</code>```

Body:
The below works but the error checking feels really clunky. I don't really understand how SWR is working and what error contains.

What I want to do is make a request to my API; output the data; or if (anything) goes wrong - 404, timeout, no songs... then a generic error is output.

--

If I change my fetch URL to something that 404s, instead of getting the "error", I get Cannot read property 'splice' of undefined... which makes sense because my API is now returning

{"message": "Not Found", "url": "/invalid-link.json","code": 404}

instead of {"songs":[{...jsondata}]}

I would as a layman expect the error variable to do something here - like intercept a non 200 code? Otherwise what is the point of it if I still need to then check the response.

My Hook adapted from next.js SWR:

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())

export default function useGetSongs() {

    const { data, error, isLoading } = useSWR('https://myapi.com/songs.json', fetcher)

    return {
        data: data,
        isLoading,
        isError: error
    }
}

My component:

import useGetSongs from '../hooks/useGetSongs';
export default function RecentlyPlayed() {
    const { data, isLoading, isError } = useGetSongs();

    if (isLoading) return
Loading...

    if(data === undefined || isError || data.code === 404) {
        return
Sorry - there is a problem retrieving data.

    }

    if(data.songs.length > 0) {
        return data.songs.map((song, songID) => {
              return
{song.name}

        })
    }
}


问:
How to investigate network buffers from a gRPC stream in go
I am looking to poke at the network buffers on a gRPC stream. I gather I need to access the net.Conn to do this but I am having difficulty finding out to access this. I have access to a grpc.ServerStream, have tried poking in the stream context and in other gRPC libraries but can't find a way to get it. Anyone have any advice here?


问:
Is it possible to make a sip call over gprs with a SIM800 module?
I have an Asterisk server on cloud and I want ESP32 devices to register as SIP clients and make a VoIP call over GPRS via SIM800 module. AT commands of SIM800 module allows me to make a GPRS connection and I can send http request and send MQTT messages. However, I couldn't find a way to connect to VoIP server, if possible.

My current code establises MQTT connection over GPRS and make calls over GSM but cannot connect to Asterisk:

// ESP32 Configuration
#define TINY_GSM_MODEM_SIM800
#define SerialMon Serial
#define SerialAT Serial2
#define TINY_GSM_DEBUG SerialMon
#define GSM_AUTOBAUD_MIN 9600  /
#define GSM_AUTOBAUD_MAX 38400
#define TINY_GSM_USE_GPRS true

#define PhoneNumber "xxxxxxxxxxxxxxx"

#define rcSwitchInterruptPin 35
#define ENABLE_SIM800C 22
#define BUTTON_PIN 33
#define SOS_BUTTON_ID0 4236140
#define SOS_BUTTON_ID1 4236132
#define SOS_BUTTON_PIN 27

// GPRS internet settings, specific to your SIM card
const char apn[] = "internet";
const char gprsUser[] = "";
const char gprsPass[] = "";

// MQTT settings
const char *broker = "broker.emqx.io";
const int mqttPort = 1883;
const char * clientID = "esp32-client";
const char * mqttUser = "acido";
const char * mqttPassword = "12345678";

#include <TinyGsmClient.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <Wire.h>
#include <PubSubClient.h>
#include <elapsedMillis.h>
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

TinyGsm modem(SerialAT);
TinyGsmClient client(modem);
PubSubClient mqtt(client);

uint32_t lastReconnectAttempt = 0;
void mqttCallback(char *, byte *, unsigned int);
boolean mqttConnect();
void DRE_switch();
elapsedSeconds serialLogSeconds;
unsigned int serialLog_Interval = 3;
elapsedSeconds sinyalBekletme;
unsigned int sinyalBekletme_Interval = 3;
elapsedSeconds sosDelay;
unsigned int sosDelay_Interval = 3;
elapsedSeconds kapiacikDelay;
unsigned int kapiacikDelay_Interval = 3;
elapsedSeconds kapiKapaliDelay;
unsigned int kapiKapaliDelay_Interval = 3;
elapsedSeconds gazDelay;
unsigned int gazDelay_Interval = 3;
elapsedSeconds pirDelay;
unsigned int pirDelay_Interval = 3;
elapsedSeconds dumanDelay;
unsigned int dumanDelay_Interval = 3;

void setup()
{
    mqtt.setKeepAlive(60);

    // Set console baud rate
    SerialMon.begin(9600);
    while (!SerialMon)

    delay(10);

    // !!!!!!!!!!!
    mySwitch.enableReceive(35);
    pinMode(BUTTON_PIN, INPUT_PULLDOWN);
    pinMode(ENABLE_SIM800C, OUTPUT);

    digitalWrite(ENABLE_SIM800C, HIGH);
    delay(3000);
    digitalWrite(ENABLE_SIM800C, LOW);
    // !!!!!!!!!!!

    TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX);

    delay(6000);

    // Restart takes quite some time
    // To skip it, call init() instead of restart()

    // if (!modem.restart()) {
    if (!modem.init()) {
        DBG("Failed to restart modem, delaying 10s and retrying");
        // restart autobaud in case GSM just rebooted
        TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX);
        return;
    }

    String modemInfo = modem.getModemInfo();
    SerialMon.print("setup: Modem Info: ");
    SerialMon.println(modemInfo);

    SerialMon.print("setup: Waiting for network...");
    if (!modem.waitForNetwork())
    {
        SerialMon.println("setup:  fail, wait 5 seconds");
        delay(5000);
        return;
    }
    SerialMon.println("setup:  success");

    if (modem.isNetworkConnected())
        SerialMon.println("setup: Network connected");

#if TINY_GSM_USE_GPRS
    // GPRS connection parameters are usually set after network registration
    SerialMon.print(F("setup: Connecting to apn: "));
    SerialMon.print(apn);
    if (!modem.gprsConnect(apn, gprsUser, gprsPass))
    {
        SerialMon.println("setup:  GPRS Connecting fail, wait 5 seconds");
        delay(5000);
        return;
    }
    SerialMon.println("setup:  GPRS success");

    if (modem.isGprsConnected())
    {
        SerialMon.println("setup: GPRS connected");
    }
#endif

    // MQTT Broker setup
    mqtt.setServer(broker, mqttPort);
    mqtt.setCallback(mqttCallback);
}

void loop()
{
    bool result;

    // check if we're connected to network
    if (!modem.isNetworkConnected())
    {
        SerialMon.println("loop: modem disconnected");
        if (!modem.waitForNetwork(180000L, true))
        {
            SerialMon.println("loop: modem fail, wait 10 sec");
            delay(10000);
            return;
        }

        if (modem.isNetworkConnected())
        {
            SerialMon.println("loop: Modem re-connected");
        }

        // And make sure GPRS/EPS is still connected
        if (!modem.isGprsConnected())
        {
            SerialMon.println("loop: GPRS disconnected!");
            SerialMon.print(F("loop: Connecting to apn:"));
            SerialMon.print(apn);
            if (!modem.gprsConnect(apn, gprsUser, gprsPass))
            {
                SerialMon.println("loop:  GPRS fail, wait 10 sec");
                delay(10000);
                return;
            }
            if (modem.isGprsConnected())
            {
                SerialMon.println("loop: GPRS reconnected");
            }
        }
    }

    // check if we're connected to MQTT
    if (!mqtt.connected())
    {
        SerialMon.println("loop: === mqtt not connected ===");
        // Reconnect every 10 seconds
        uint32_t t = millis();
        if (t - lastReconnectAttempt > 10000L)
        {
            lastReconnectAttempt = t;
            if (mqttConnect())
            {
                lastReconnectAttempt = 0;
            }
        }
        return;
    }

    if (digitalRead(BUTTON_PIN) == HIGH)
    {
        Serial.println("BUTONA BASILDI");
        result = modem.callNumber(PhoneNumber);
        DBG("Call:", result ? "OK" : "fail");
    }

    // Check RF signals and publish to MQTT

    if (mySwitch.available())
    {
        int num = mySwitch.getReceivedValue();
        Serial.print("Num: ");
        Serial.print(num);
        Serial.print("  Protocol: ");
        Serial.println(mySwitch.getReceivedProtocol());

        if (sosDelay >= sosDelay_Interval)
        {
            if (num == 4236132) // SOS
            {
                Serial.println("SOS Butonuna Basıldı.");
                DRE_switch();
                mqtt.publish("CMR/ESP32s/SENSOR/SOS", "SOS"); // Publish message.
                result = modem.callNumber(PhoneNumber);
                DBG("Call:", result ? "OK" : "fail");
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/SOS", "0"); // Publish message.
            }
            sosDelay = 0;
        }

        if (pirDelay >= pirDelay_Interval)
        {
            if (num == 8330345)
            {
                DRE_switch();
                Serial.println("HAREKET ALGILANDI.");
                mqtt.publish("CMR/ESP32s/SENSOR/PIR", "HAREKET ALGILANDI"); // Publish message.
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/PIR", "0"); // Publish message
            }
            pirDelay = 0;
        }

        if (kapiacikDelay >= kapiacikDelay_Interval)
        {

            if (num == 5729285) // Kapi acilinca gelen sinyal
            {
                DRE_switch();
                Serial.println("KAPI AÇILDI.");
                mqtt.publish("CMR/ESP32s/SENSOR/KAPIACIK", "1"); // Publish message.
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/KAPIACIK", "0"); // Publish message
            }
            kapiacikDelay = 0;
        }

        if (kapiKapaliDelay >= kapiKapaliDelay_Interval)
        {

            if (num == 5729294) // Kapi kapaninca gelen sinyal
            {
                DRE_switch();
                Serial.println("KAPI KAPANDI.");
                mqtt.publish("CMR/ESP32s/SENSOR/KAPIKAPALI", "1"); // Publish message.
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/KAPIKAPALI", "0"); // Publish message
            }
            kapiKapaliDelay = 0;
        }

        if (gazDelay >= gazDelay_Interval)
        {
            if (num == 12607491)
            {
                DRE_switch();
                Serial.println("Gas Algılandı.");
                mqtt.publish("CMR/ESP32s/SENSOR/GAS", "GAS ALGILANDI"); // Publish message.
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/GAS", "0"); // Publish message
            }
            gazDelay = 0;
        }

        if (dumanDelay >= dumanDelay_Interval)
        {
            if (num == 79974)
            {
                DRE_switch();
                Serial.println("Duman Algılandı .");
                mqtt.publish("CMR/ESP32s/SENSOR/DUMAN", "DUMAN ALGILANDI"); // Publish message.
            }
            else
            {
                mqtt.publish("CMR/ESP32s/SENSOR/DUMAN", "0"); // Publish message
            }
            dumanDelay = 0;
        }
    } // end if mySwitch.available

    modem.maintain();
    mqtt.loop(); // Handling MQTT on the background.
} // end of loop

boolean mqttConnect()
{
    // Connect to MQTT Broker
    SerialMon.print("mqttConnect:  MQTT trying to connect: ");
    SerialMon.print(broker);

    // Connect to MQTT Broker with password protected
    boolean status = mqtt.connect(clientID, mqttUser, mqttPassword);

    // boolean status = mqtt.connect(clientID); // without password

    if (status == false)
    {
        SerialMon.println("mqttConnect:  MQTT Connection Fail");
        return false;
    }
    SerialMon.println("mqttConnect:  *** MQTT CONNECTED *** ");

    mqtt.publish("topic/akes", "Client connection started");
    mqtt.subscribe("topic/akes"); // subscribe to topic

    return mqtt.connected();
}

void mqttCallback(char *topic, byte *payload, unsigned int len)
{
    // Handle message arrived
    SerialMon.print("mqttCallback:  Message arrived [");
    SerialMon.print(topic);
    SerialMon.print("]: ");
    SerialMon.write(payload, len);
    SerialMon.println();
}

void DRE_switch()
{
    // Disable Reset Enable function for RF module
    mySwitch.disableReceive();
    mySwitch.resetAvailable();
    mySwitch.enableReceive(rcSwitchInterruptPin);
}
```


问:
How to attribute a vba code to all my combo boxes in MS access
I have several lines of code to add to around 80 combo boxes. What is the quickest way of doing this?

I have tried, copy and pasting individual combo boxes and manually changing the vba to reference the name of each new box. But it seems very tedious.


问:
VueJS apexchart not get populated with back end data properly
In my laravel vue application I'm trying to fetch some data from Shopify Admin REST API and display them on the vuejs front end.

Following is my laravel controller.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyStatsController extends Controller
{
    public function fetchStats(Request $request)
    {

        $startDate = $request->input('start_date');
        $endDate = Carbon::parse($request->input('end_date'))->addDay()->format('Y-m-d');
        if (!$startDate) {
            $startDate = Carbon::now()->format('Y-m-d');
        }
        if(!$endDate) {
           $endDate = Carbon::parse($startDate)->addDay()->format('Y-m-d');
        }

        // Set up cURL request
        $access_token = 'ACCESS_TOKEN';
        $apiKey = 'API_KEY';
        $storeName = 'STROE_NAME';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));

        $response = curl_exec($ch);

        curl_close($ch);

        $orders = json_decode($response);

        //dd($orders);die;

        $total_orders = ($orders->orders != null && !empty($orders->orders)) ? count($orders->orders) : 0;
        $total_sales = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $total_items = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $completed_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $to_be_fulfilled_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        foreach ($orders->orders as $order) {
            $total_sales += $order->total_price;
            $total_items += count($order->line_items);
            if ($order->financial_status == "paid") {
                $completed_orders++;
            }
            if ($order->fulfillment_status == null) {
                $to_be_fulfilled_orders++;
            }
        }

        $average_order_value = $total_orders > 0 ? $total_sales / $total_orders : 0;

        // Bar chart for the best selling days
        $start_date = date('Y-m-d', strtotime('-7 days'));
        $end_date = date('Y-m-d');
        $url = "https://API_KEY:ACCESS_TOKEN@STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=".date('Y-m-d', strtotime('-7 days'))."&created_at_max=".date('Y-m-d').""; // append the query to the URL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-Shopify-Access-Token:ACCESS_TOKEN', // access token
        ]);

        // Send the request
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);

        // Extract the data for each day from the response
        $day_totals = array();
        if (!empty($response['orders'])) {
            foreach ($response['orders'] as $order) {
                $order_date = date('Y-m-d', strtotime($order['created_at']));
                if (!isset($day_totals[$order_date])) {
                    $day_totals[$order_date] = 0;
                }
                $day_totals[$order_date]++;
            }
        }

        // Set 0 for days with no sales data
        for ($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date . ' +1 day'))) {
            if (!isset($day_totals[$date])) {
                $day_totals[$date] = 0;
            }
        }

        // Find the most selling day of the week
        $most_sales_day = max($day_totals);
        $most_selling_day = array_search($most_sales_day, $day_totals);

        // Return the total sales value
        return response()->json([
            'total_sales' => $total_sales,
            'total_orders' => $total_orders,
            'total_items' => $total_items,
            'completed_orders' => $completed_orders,
            'average_order_value' => $average_order_value,
            'day_totals' => $day_totals,
            'most_selling_day' => $most_selling_day,
            'most_sales_day' => $most_sales_day
        ]);
    }
}
</code>```

Here $day_totals will give me an array with day wise sales for a week, something like follows

```<code>array:8 [
  "2023-01-09" => 1
  "2023-01-04" => 0
  "2023-01-05" => 0
  "2023-01-06" => 0
  "2023-01-07" => 0
  "2023-01-08" => 0
  "2023-01-10" => 0
  "2023-01-11" => 0
]
</code>```

Now I have created a reusable vue component called, ShopifyDayWiseSales.vue and this needs to show day wise sales for the week in a bar chart.

Following is my ShopifyDayWiseSales.vue component.

```<code><template>
    <div>
      <apexchart type="bar" :options="chartOptions" :series="chartData"></apexchart>
    </div>
  </template>

  <script>
  import axios from 'axios';
  import moment from 'moment';

  export default {
    data() {
      return {
        chartOptions: {
          xaxis: {
            categories: [],
          },
          yaxis: {
            labels: {
              formatter: function(val) {
                return "$" + val;
              },
            },
          },
        },
        chartData: [
          {
            name: "Total Sales",
            data: [],
          },
        ],
      };
    },
    created() {
            axios.get(`/shopify-stats`).then(response => {
            console.log(response.data);
            let chartData = {};
            Object.entries(response.data.day_totals).forEach(([day, total]) => {
            chartData[day] = total;
            });
            this.chartOptions.xaxis.categories = Object.keys(chartData);
            this.chartData[0].data = Object.values(chartData);
            console.log(chartData);
        });
    },
  };
  </script>

</code>```

Here I'm using  module to draw the graph.

My console log gives me this out put

```<code>2023-01-04: 0
2023-01-05: 0
2023-01-06: 0
2023-01-07: 0
2023-01-08: 0
2023-01-09: 1
2023-01-10: 0
2023-01-11: 0
</code>```

Then I tried to use that component In my index.vue

```<code> <div >
                        <ShopifyDayWiseStats></ShopifyDayWiseStats>
                    </div>
</code>```

But when I run this, It gives me an empty chart with not populated x and y axis.

In short word, my chart has not been drawn, I'm just wondering what's I'm doing wrong...

This what I'm currently getting

Body:
In my laravel vue application I'm trying to fetch some data from Shopify Admin REST API and display them on the vuejs front end.

Following is my laravel controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyStatsController extends Controller
{
    public function fetchStats(Request $request)
    {

        $startDate = $request->input('start_date');
        $endDate = Carbon::parse($request->input('end_date'))->addDay()->format('Y-m-d');
        if (!$startDate) {
            $startDate = Carbon::now()->format('Y-m-d');
        }
        if(!$endDate) {
           $endDate = Carbon::parse($startDate)->addDay()->format('Y-m-d');
        }

        // Set up cURL request
        $access_token = 'ACCESS_TOKEN';
        $apiKey = 'API_KEY';
        $storeName = 'STROE_NAME';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));

        $response = curl_exec($ch);

        curl_close($ch);

        $orders = json_decode($response);

        //dd($orders);die;

        $total_orders = ($orders->orders != null && !empty($orders->orders)) ? count($orders->orders) : 0;
        $total_sales = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $total_items = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $completed_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $to_be_fulfilled_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        foreach ($orders->orders as $order) {
            $total_sales += $order->total_price;
            $total_items += count($order->line_items);
            if ($order->financial_status == "paid") {
                $completed_orders++;
            }
            if ($order->fulfillment_status == null) {
                $to_be_fulfilled_orders++;
            }
        }

        $average_order_value = $total_orders > 0 ? $total_sales / $total_orders : 0;

        // Bar chart for the best selling days
        $start_date = date('Y-m-d', strtotime('-7 days'));
        $end_date = date('Y-m-d');
        $url = "https://API_KEY:ACCESS_TOKEN@STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=".date('Y-m-d', strtotime('-7 days'))."&created_at_max=".date('Y-m-d').""; // append the query to the URL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-Shopify-Access-Token:ACCESS_TOKEN', // access token
        ]);

        // Send the request
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);

        // Extract the data for each day from the response
        $day_totals = array();
        if (!empty($response['orders'])) {
            foreach ($response['orders'] as $order) {
                $order_date = date('Y-m-d', strtotime($order['created_at']));
                if (!isset($day_totals[$order_date])) {
                    $day_totals[$order_date] = 0;
                }
                $day_totals[$order_date]++;
            }
        }

        // Set 0 for days with no sales data
        for ($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date . ' +1 day'))) {
            if (!isset($day_totals[$date])) {
                $day_totals[$date] = 0;
            }
        }

        // Find the most selling day of the week
        $most_sales_day = max($day_totals);
        $most_selling_day = array_search($most_sales_day, $day_totals);

        // Return the total sales value
        return response()->json([
            'total_sales' => $total_sales,
            'total_orders' => $total_orders,
            'total_items' => $total_items,
            'completed_orders' => $completed_orders,
            'average_order_value' => $average_order_value,
            'day_totals' => $day_totals,
            'most_selling_day' => $most_selling_day,
            'most_sales_day' => $most_sales_day
        ]);
    }
}

Here $day_totals will give me an array with day wise sales for a week, something like follows

array:8 [
  "2023-01-09" => 1
  "2023-01-04" => 0
  "2023-01-05" => 0
  "2023-01-06" => 0
  "2023-01-07" => 0
  "2023-01-08" => 0
  "2023-01-10" => 0
  "2023-01-11" => 0
]

Now I have created a reusable vue component called, ShopifyDayWiseSales.vue and this needs to show day wise sales for the week in a bar chart.

Following is my ShopifyDayWiseSales.vue component.

<template>

      <apexchart type="bar" :options="chartOptions" :series="chartData"></apexchart>

  </template>

Here I'm using  module to draw the graph.

My console log gives me this out put

2023-01-04: 0
2023-01-05: 0
2023-01-06: 0
2023-01-07: 0
2023-01-08: 0
2023-01-09: 1
2023-01-10: 0
2023-01-11: 0

Then I tried to use that component In my index.vue

                        <ShopifyDayWiseStats></ShopifyDayWiseStats>

But when I run this, It gives me an empty chart with not populated x and y axis.

In short word, my chart has not been drawn, I'm just wondering what's I'm doing wrong...

This what I'm currently getting


问:
Bigchaindb 2.2.2 error installing while building gevent
```<code>Error compiling Cython file:
      ------------------------------------------------------------
      ...
      cdef load_traceback
      cdef Waiter
      cdef wait
      cdef iwait
      cdef reraise
      cpdef GEVENT_CONFIG
            ^
      ------------------------------------------------------------

      src/gevent/_gevent_cgreenlet.pxd:181:6: Variables cannot be declared with 'cpdef'. Use 'cdef' instead.
      Compiling src/gevent/greenlet.py because it changed.
</code>```

I'm using ubuntu and getting this error while trying to install bigchaindb.

I'm following the tutorial at Bigchaindb docs and already using the latest version of pip

Body:
Error compiling Cython file:
      ------------------------------------------------------------
      ...
      cdef load_traceback
      cdef Waiter
      cdef wait
      cdef iwait
      cdef reraise
      cpdef GEVENT_CONFIG
            ^
      ------------------------------------------------------------

      src/gevent/_gevent_cgreenlet.pxd:181:6: Variables cannot be declared with 'cpdef'. Use 'cdef' instead.
      Compiling src/gevent/greenlet.py because it changed.

I'm using ubuntu and getting this error while trying to install bigchaindb.

I'm following the tutorial at Bigchaindb docs and already using the latest version of pip


问:
Automatic import of PDF files to the existing SharePoint List
The problem is the following. I have an empty SharePoint List (table) and I want to fulfill it with the particular data from the same to each other PDF files (consisting of tables). Then I want to show the fulfilled data from SharePoint List in PowerBI. I know, that SharePoint List can be connected to the PowerBI and PDF data can be imported there as well.

How to make this process automatic? Is there a possibility to make a macros, which will have an option to upload particular file and import the data, which I need, to the SharePoint List?

Thanks for your feedback in advance!

I tried to upload it directly to PowerBI, but only see the manual solution of fulfilling the table.


问:
Using variables for button names
I am trying to hide or make visible a large amount of buttons in an excel file. The button visibility is depending on the cell next to the button. If the cell is empty, the button is hidden. If the cell has content, the button is visible. The code for that is pretty straightforward, for instance:

```<code>If Range("B202").Value <> "" Then

Me.CommandButton2.Visible = True

Else

Me.CommandButton2.Visible = False

End If
</code>```

The sub is being triggered based on changing a cell on the worksheet:
Private Sub Worksheet_Change(ByVal Target As Range)

Instead of copying the code for the buttons tens of times and changing the range value as well as the button number, I'd like to have that done in a loop instead. Changing the range in a for/next loop has not created any issue, however, I was not successful in assigning the button name in a dynamic way. Note that my buttons are numbered in a sequential way, i.e. this would fit a loop approach.
Thanks for your thoughts!

Tried the following:

```<code>For i = 1 To 2

c = "B20" & i

j = i + 1

If Range(c).Value <> "" Then

me.Controls("CommandButton" & j).Visible = True

Else

me.Controls("CommandButton" & j).Visible = False

End If

Next
</code>```

Title: Using variables for button names

Body:
I am trying to hide or make visible a large amount of buttons in an excel file. The button visibility is depending on the cell next to the button. If the cell is empty, the button is hidden. If the cell has content, the button is visible. The code for that is pretty straightforward, for instance:

If Range("B202").Value <> "" Then

Me.CommandButton2.Visible = True

Else

Me.CommandButton2.Visible = False

End If

The sub is being triggered based on changing a cell on the worksheet:
Private Sub Worksheet_Change(ByVal Target As Range)

Instead of copying the code for the buttons tens of times and changing the range value as well as the button number, I'd like to have that done in a loop instead. Changing the range in a for/next loop has not created any issue, however, I was not successful in assigning the button name in a dynamic way. Note that my buttons are numbered in a sequential way, i.e. this would fit a loop approach.
Thanks for your thoughts!

Tried the following:

For i = 1 To 2

c = "B20" & i

j = i + 1

If Range(c).Value <> "" Then

me.Controls("CommandButton" & j).Visible = True

Else

me.Controls("CommandButton" & j).Visible = False

End If

Next


问:
SQL CONTAINSTABLE does not return all the expected results
I have a table with just 2 columns Id (identity) and lastname(nvarchar). I applied a fulltextIndex WITH ACCENT_SENSITIVITY = OFF for dutch --> 1043 on lastname with an empty stop words list and added 2 records:

insert into  [UserProfile] values  ('hoopman')
insert into  [UserProfile] values  ('koopmans')

when i do:

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)

I only get koopmans.

but if I do

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"hoopman*"',  LANGUAGE 1043)

I do get hoopman.

Here is the script to reproduce the scenario

```<code>USE [master]
GO
/****** Object:  Database [Tests]   Script Date: 11/01/2023 13:43:25 ******/
CREATE DATABASE [Tests]
 WITH CATALOG_COLLATION = DATABASE_DEFAULT
GO
ALTER DATABASE [Tests]SET COMPATIBILITY_LEVEL = 150
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Tests].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [Tests]SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Tests]SET ANSI_NULLS OFF
GO
ALTER DATABASE [Tests]SET ANSI_PADDING OFF
GO
ALTER DATABASE [Tests]SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Tests]SET ARITHABORT OFF
GO
ALTER DATABASE [Tests]SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Tests]SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Tests]SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Tests]SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Tests]SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [Tests]SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Tests]SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Tests]SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Tests]SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Tests]SET  DISABLE_BROKER
GO
ALTER DATABASE [Tests]SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Tests]SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Tests]SET TRUSTWORTHY OFF
GO
ALTER DATABASE [Tests]SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Tests]SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Tests]SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [Tests]SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [Tests]SET RECOVERY FULL
GO
ALTER DATABASE [Tests]SET  MULTI_USER
GO
ALTER DATABASE [Tests]SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Tests]SET DB_CHAINING OFF
GO
ALTER DATABASE [Tests]SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [Tests]SET TARGET_RECOVERY_TIME = 60 SECONDS
GO
ALTER DATABASE [Tests]SET DELAYED_DURABILITY = DISABLED
GO
ALTER DATABASE [Tests]SET ACCELERATED_DATABASE_RECOVERY = OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'Tests', N'ON'
GO
ALTER DATABASE [Tests] SET QUERY_STORE = OFF
GO
USE [Tests]
GO
/****** Object:  FullTextCatalog   Script Date: 11/01/2023 13:43:25 ******/
CREATE FULLTEXT CATALOG [MyCatalog] WITH ACCENT_SENSITIVITY = OFF
AS DEFAULT
GO
/****** Object:  Table [dbo].[UserProfile]    Script Date: 11/01/2023 13:43:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserProfile](
    [Id] [int] IDENTITY(1000000,1) NOT NULL,
    [Lastname] [nvarchar](255) NULL,
 CONSTRAINT [PK_UserProfile] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER DATABASE [Tests]SET  READ_WRITE
GO
CREATE FULLTEXT INDEX ON  dbo.UserProfile (
    lastname LANGUAGE 1043
) KEY INDEX [PK_UserProfile]
WITH
    CHANGE_TRACKING = AUTO,
    STOPLIST=OFF
;
GO
</code>```

then

```<code>
insert into  [UserProfile] values  ('hoopman')
insert into  [UserProfile] values  ('koopmans')

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)
</code>```

thx a lot!

expecting hoopman and koopmans and gettign only koopmans when doing

```<code>SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)
</code>```

Body:
I have a table with just 2 columns Id (identity) and lastname(nvarchar). I applied a fulltextIndex WITH ACCENT_SENSITIVITY = OFF for dutch --> 1043 on lastname with an empty stop words list and added 2 records:

insert into  [UserProfile] values  ('hoopman')
insert into  [UserProfile] values  ('koopmans')

when i do:

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)

I only get koopmans.

but if I do

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"hoopman*"',  LANGUAGE 1043)

I do get hoopman.

Here is the script to reproduce the scenario

USE [master]
GO
/****** Object:  Database [Tests]   Script Date: 11/01/2023 13:43:25 ******/
CREATE DATABASE [Tests]
 WITH CATALOG_COLLATION = DATABASE_DEFAULT
GO
ALTER DATABASE [Tests]SET COMPATIBILITY_LEVEL = 150
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Tests].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [Tests]SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Tests]SET ANSI_NULLS OFF
GO
ALTER DATABASE [Tests]SET ANSI_PADDING OFF
GO
ALTER DATABASE [Tests]SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Tests]SET ARITHABORT OFF
GO
ALTER DATABASE [Tests]SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Tests]SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Tests]SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Tests]SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Tests]SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [Tests]SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Tests]SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Tests]SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Tests]SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Tests]SET  DISABLE_BROKER
GO
ALTER DATABASE [Tests]SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Tests]SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Tests]SET TRUSTWORTHY OFF
GO
ALTER DATABASE [Tests]SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Tests]SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Tests]SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [Tests]SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [Tests]SET RECOVERY FULL
GO
ALTER DATABASE [Tests]SET  MULTI_USER
GO
ALTER DATABASE [Tests]SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Tests]SET DB_CHAINING OFF
GO
ALTER DATABASE [Tests]SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [Tests]SET TARGET_RECOVERY_TIME = 60 SECONDS
GO
ALTER DATABASE [Tests]SET DELAYED_DURABILITY = DISABLED
GO
ALTER DATABASE [Tests]SET ACCELERATED_DATABASE_RECOVERY = OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'Tests', N'ON'
GO
ALTER DATABASE [Tests] SET QUERY_STORE = OFF
GO
USE [Tests]
GO
/****** Object:  FullTextCatalog   Script Date: 11/01/2023 13:43:25 ******/
CREATE FULLTEXT CATALOG [MyCatalog] WITH ACCENT_SENSITIVITY = OFF
AS DEFAULT
GO
/****** Object:  Table [dbo].[UserProfile]    Script Date: 11/01/2023 13:43:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserProfile](
    [Id] [int] IDENTITY(1000000,1) NOT NULL,
    [Lastname] [nvarchar](255) NULL,
 CONSTRAINT [PK_UserProfile] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER DATABASE [Tests]SET  READ_WRITE
GO
CREATE FULLTEXT INDEX ON  dbo.UserProfile (
    lastname LANGUAGE 1043
) KEY INDEX [PK_UserProfile]
WITH
    CHANGE_TRACKING = AUTO,
    STOPLIST=OFF
;
GO

then

insert into  [UserProfile] values  ('hoopman')
insert into  [UserProfile] values  ('koopmans')

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)

thx a lot!

expecting hoopman and koopmans and gettign only koopmans when doing

SELECT *
from CONTAINSTABLE(UserProfile, Lastname, '"man*"',  LANGUAGE 1043)


问:
How do I get a FlatList to show correct items when I open the screen?
The idea is to have a toggle switch that switches from To Watch and Watched bookings. When I update a movie in the To Watch list, I want it to rerender the FlatList without that booking because it's now in the Watched list. And so when I press the toggle to see the Watched list I would now see the booking there. Same for reverse.

I have to press the toggle twice to see the change. Even when I open the screen for the first time it shows all the movies without the filter - this is the main thing I'm having trouble with. How can I get around this? This is the code I have:

```<code>const WatchList = () => {

  const uid = auth.currentUser.uid;
  const docRef = doc(db, 'users', uid);
  const [user, setUser] = useState({});
  const [watched, setWatched] = useState(true);
  const [text, setText] = useState('To watch');
  const [filteredBookings, setFilteredBookings] = useState(bookings);

  const bookingsRef = collection(db, "booking"); // imamo ref ka bazi

  const [bookings, setBookings] = useState({});
   useEffect(() => {
    getUser();
    getBookings();
  },[])

  const getUser = async () => {
    const snap = await getDoc(docRef)
    setUser({user, ...snap.data()})
  }

  const getBookings = async () =>{
    const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
      const unsubscribe = onSnapshot(q, (querySnapshot) => {
        const a = [];
        querySnapshot.forEach((doc) => {
        a.push(doc.data());
      });
      setBookings(querySnapshot.docs);
    });
  }

  const toggleSwitch = () =>{
    if(!watched){
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == true;
      }))
      setText('Watched');
    } else {
      setText('To watch');
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == false;
      }))
    }
    setWatched(previousState => !previousState);
  }

  const updateBooking = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: true
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const updateBooking1 = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: false
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const deleteBooking = async(id) => {
    try {
      await deleteDoc(doc(db, 'booking', id));
    }
    catch(e) {
      console.log(e)
    }
  }

  useEffect(() => {
    const resultOfFiltering = bookings
    setFilteredBookings(resultOfFiltering)
  }, [bookings])

  return (
    <View>
      <View>
        <Text>{text}</Text>
        <Switch
          value = {watched}
        />
      </View>

  <FlatList
    data = {filteredBookings}
    extraData = {watched}

    renderItem  = {({item}) => (
      <View>
      <View>
        <Text>{item.data().movie}</Text>
        <Text>{item.data().day} - {item.data().showtime}</Text>
      </View>
      <View>
        {item.data().watched == true ? (
            <TouchableOpacity style = {styles.delete} onPress = {() => {updateBookings(item.id); setFilteredBookings();}}>
            <Image source={require('../assets/watched.png')}/>
            </TouchableOpacity>
        ) : (
        <TouchableOpacity onPress = {() => {updateBookings1(item.id); setFilteredBookings();}}>
        <Image source={require('../assets/towatch.png')}/>
        </TouchableOpacity>)}

        <TouchableOpacity onPress = {() => {deleteBooking(item.id); setFilteredBookings();}}>
          <Image source={require('../assets/remove.png')}/>
        </TouchableOpacity>
      </View>
      </View>
    )}
  />
      </View>
  )
}

export default WatchList
</code>```

It's not really working properly at the moment and I'm not sure what I'm doing wrong so I'm kind of stuck. If I could get some help, I'd really appreciate it. Thank you!

Body:
The idea is to have a toggle switch that switches from To Watch and Watched bookings. When I update a movie in the To Watch list, I want it to rerender the FlatList without that booking because it's now in the Watched list. And so when I press the toggle to see the Watched list I would now see the booking there. Same for reverse.

I have to press the toggle twice to see the change. Even when I open the screen for the first time it shows all the movies without the filter - this is the main thing I'm having trouble with. How can I get around this? This is the code I have:

const WatchList = () => {

  const uid = auth.currentUser.uid;
  const docRef = doc(db, 'users', uid);
  const [user, setUser] = useState({});
  const [watched, setWatched] = useState(true);
  const [text, setText] = useState('To watch');
  const [filteredBookings, setFilteredBookings] = useState(bookings);

  const bookingsRef = collection(db, "booking"); // imamo ref ka bazi

  const [bookings, setBookings] = useState({});
   useEffect(() => {
    getUser();
    getBookings();
  },[])

  const getUser = async () => {
    const snap = await getDoc(docRef)
    setUser({user, ...snap.data()})
  }

  const getBookings = async () =>{
    const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
      const unsubscribe = onSnapshot(q, (querySnapshot) => {
        const a = [];
        querySnapshot.forEach((doc) => {
        a.push(doc.data());
      });
      setBookings(querySnapshot.docs);
    });
  }

  const toggleSwitch = () =>{
    if(!watched){
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == true;
      }))
      setText('Watched');
    } else {
      setText('To watch');
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == false;
      }))
    }
    setWatched(previousState => !previousState);
  }

  const updateBooking = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: true
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const updateBooking1 = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: false
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const deleteBooking = async(id) => {
    try {
      await deleteDoc(doc(db, 'booking', id));
    }
    catch(e) {
      console.log(e)
    }
  }

  useEffect(() => {
    const resultOfFiltering = bookings
    setFilteredBookings(resultOfFiltering)
  }, [bookings])

  return (
    <View>
      <View>
        <Text>{text}</Text>
        <Switch
          value = {watched}
        />
      </View>

  <FlatList
    data = {filteredBookings}
    extraData = {watched}

    renderItem  = {({item}) => (
      <View>
      <View>
        <Text>{item.data().movie}</Text>
        <Text>{item.data().day} - {item.data().showtime}</Text>
      </View>
      <View>
        {item.data().watched == true ? (
            <TouchableOpacity style = {styles.delete} onPress = {() => {updateBookings(item.id); setFilteredBookings();}}>
            <Image source={require('../assets/watched.png')}/>
            </TouchableOpacity>
        ) : (
        <TouchableOpacity onPress = {() => {updateBookings1(item.id); setFilteredBookings();}}>
        <Image source={require('../assets/towatch.png')}/>
        </TouchableOpacity>)}

        <TouchableOpacity onPress = {() => {deleteBooking(item.id); setFilteredBookings();}}>
          <Image source={require('../assets/remove.png')}/>
        </TouchableOpacity>
      </View>
      </View>
    )}
  />
      </View>
  )
}

export default WatchList

It's not really working properly at the moment and I'm not sure what I'm doing wrong so I'm kind of stuck. If I could get some help, I'd really appreciate it. Thank you!