问:
Zod inferred union type does not work properly: 'hackerProfile' does not exist on type
My Zod inferred union type does not work properly; 'hackerProfile' does not exist on type...

Typescript is telling me that hackerProfile, partnerProfile, and mentorProfile don't exist on my UpdateUserInput, which I inferred from Zod.

Even though I can see hackerProfile, partnerProfile, and mentorProfile in the type when I hoer my cursor over it in VS code. It doesn't seem to have a problem with userUpdate.

What's going on here?

server/src/utils/validators.ts

```<code>import { z } from 'zod';

const userUpdateValidator = z.object({
  firstName: z.string().optional(),
  lastName: z.string().optional(),
  website: z.string().optional(),
  rules: z.boolean().optional(),
  linkedin: z.string().optional(),
});

const ethExpValidator = z.union([
  z.literal('beginner'),
  z.literal('intermediate'),
  z.literal('advanced'),
  z.literal(''),
]);

const motiavtionValidator = z.union([
  z.literal(''),
  z.array(
    z.union([
      z.literal('workshop'),
      z.literal('resume'),
      z.literal('improve'),
      z.literal('jobOps'),
      z.literal('meetPpl'),
      z.literal('launchProduct'),
      z.literal('winPrize'),
      z.literal('other'),
    ])
  ),
]);

const textAreaValidator = z.union([
  z.string().min(250).max(500),
  z.literal(''),
]);

const updateHackerValidator = z.object({
  userUpdate: userUpdateValidator,
  hackerProfile: z.object({
    github: z.string().optional(),
    yearsOfExp: z.number().min(0),
    ethExp: ethExpValidator,
    motivation: motiavtionValidator,
    builtBefore: textAreaValidator,
    lookingToBuild: textAreaValidator,
  }),
});

const updatePartnerValidator = z.object({
  userUpdate: userUpdateValidator,
  partnerProfile: z.object({
    organization: z.string().optional(),
    telegram: z.string().optional(),
    twitter: z.string().optional(),
    otherEvents: textAreaValidator,
    reasonForSupporting: textAreaValidator,
  }),
});

const updateMentorValidator = z.object({
  userUpdate: userUpdateValidator,
  mentorProfile: z.object({
    telegram: z.string().optional(),
    twitter: z.string().optional(),
    yearsOfExp: z.number(),
    ethExp: ethExpValidator,
    otherEvents: textAreaValidator,
    reasonForMentoring: textAreaValidator,
  }),
});

// tried this as well
// export const updateUserValidator = z.union([
export const updateUserValidator = z.discriminatedUnion('userUpdate', [
  updateHackerValidator,
  updatePartnerValidator,
  updateMentorValidator,
]);

export type UpdateUserInput = z.infer<typeof updateUserValidator>;

export type UpdateMentorInput = z.infer<typeof updateMentorValidator>;
export type UpdatePartnerInput = z.infer<typeof updatePartnerValidator>;
export type UpdateHackerInput = z.infer<typeof updateHackerValidator>;
</code>```

server/src/graphql/resolvers/mutations.ts

```<code>export const updateUser = async (
  _: undefined,
  // tried this as well
  // args: UpdateMentorInput | UpdatePartnerInput | UpdateHackerInput,
  args: UpdateUserInput,
  ctx: Context
) => {
  if (!updateUserValidator.parse(args)) {
    throw new Error('Invalid input');
  } else {
    console.log('valid input');
  }
  authRequest(ctx);
  console.log('args', args, Object.keys(args));
  const { userUpdate, hackerProfile, partnerProfile, mentorProfile } = args;
  // console.log('args', args);
  // console.log('here', userUpdate);

  const user = await ctx.prisma.user.update({
</code>```

https://github.com/currenthandle/next-apollo/blob/working-state/server/src/utils/validators.ts#L76
https://github.com/currenthandle/next-apollo/blob/working-state/server/src/graphql/resolvers/mutations.ts#L28

Body:
My Zod inferred union type does not work properly; 'hackerProfile' does not exist on type...

Typescript is telling me that hackerProfile, partnerProfile, and mentorProfile don't exist on my UpdateUserInput, which I inferred from Zod.

Even though I can see hackerProfile, partnerProfile, and mentorProfile in the type when I hoer my cursor over it in VS code. It doesn't seem to have a problem with userUpdate.

What's going on here?

server/src/utils/validators.ts

import { z } from 'zod';

const userUpdateValidator = z.object({
  firstName: z.string().optional(),
  lastName: z.string().optional(),
  website: z.string().optional(),
  rules: z.boolean().optional(),
  linkedin: z.string().optional(),
});

const ethExpValidator = z.union([
  z.literal('beginner'),
  z.literal('intermediate'),
  z.literal('advanced'),
  z.literal(''),
]);

const motiavtionValidator = z.union([
  z.literal(''),
  z.array(
    z.union([
      z.literal('workshop'),
      z.literal('resume'),
      z.literal('improve'),
      z.literal('jobOps'),
      z.literal('meetPpl'),
      z.literal('launchProduct'),
      z.literal('winPrize'),
      z.literal('other'),
    ])
  ),
]);

const textAreaValidator = z.union([
  z.string().min(250).max(500),
  z.literal(''),
]);

const updateHackerValidator = z.object({
  userUpdate: userUpdateValidator,
  hackerProfile: z.object({
    github: z.string().optional(),
    yearsOfExp: z.number().min(0),
    ethExp: ethExpValidator,
    motivation: motiavtionValidator,
    builtBefore: textAreaValidator,
    lookingToBuild: textAreaValidator,
  }),
});

const updatePartnerValidator = z.object({
  userUpdate: userUpdateValidator,
  partnerProfile: z.object({
    organization: z.string().optional(),
    telegram: z.string().optional(),
    twitter: z.string().optional(),
    otherEvents: textAreaValidator,
    reasonForSupporting: textAreaValidator,
  }),
});

const updateMentorValidator = z.object({
  userUpdate: userUpdateValidator,
  mentorProfile: z.object({
    telegram: z.string().optional(),
    twitter: z.string().optional(),
    yearsOfExp: z.number(),
    ethExp: ethExpValidator,
    otherEvents: textAreaValidator,
    reasonForMentoring: textAreaValidator,
  }),
});

// tried this as well
// export const updateUserValidator = z.union([
export const updateUserValidator = z.discriminatedUnion('userUpdate', [
  updateHackerValidator,
  updatePartnerValidator,
  updateMentorValidator,
]);

export type UpdateUserInput = z.infer<typeof updateUserValidator>;

export type UpdateMentorInput = z.infer<typeof updateMentorValidator>;
export type UpdatePartnerInput = z.infer<typeof updatePartnerValidator>;
export type UpdateHackerInput = z.infer<typeof updateHackerValidator>;

server/src/graphql/resolvers/mutations.ts

export const updateUser = async (
  _: undefined,
  // tried this as well
  // args: UpdateMentorInput | UpdatePartnerInput | UpdateHackerInput,
  args: UpdateUserInput,
  ctx: Context
) => {
  if (!updateUserValidator.parse(args)) {
    throw new Error('Invalid input');
  } else {
    console.log('valid input');
  }
  authRequest(ctx);
  console.log('args', args, Object.keys(args));
  const { userUpdate, hackerProfile, partnerProfile, mentorProfile } = args;
  // console.log('args', args);
  // console.log('here', userUpdate);

  const user = await ctx.prisma.user.update({

https://github.com/currenthandle/next-apollo/blob/working-state/server/src/utils/validators.ts#L76
https://github.com/currenthandle/next-apollo/blob/working-state/server/src/graphql/resolvers/mutations.ts#L28


来源: stackexchange

问:
C program that handles Xbox 360 game controller
I would like to create a C program that fetches data from an Xbox 360 game controller which is plugged into the USB port of my PC. To check whether buttons are pressed or not, positions of joysticks and how is pressure on the RT/LT buttons, and to print the data into the terminal.

Is there a library to do that?

Thanks

ContentLicense: CC BY-SA 4.0


问:
Keras, Graph Execution Error indices[0,0] = 123699 is not in some size of tokens+1
I'm currently engaging in classifying html text into two, benign and malicious.

I was successful in doing keras in jupyter notebook, but encountered another problem in the model fitting.

My problem consists of classifying 97027*12 feature matrix into 2. And here goes what I am done so far.. Imagine csv files are well defined.. though it has some sparcity.

```<code>url_benign = pd.read_csv("Making_Meta_Data_benign.csv")
url_malicious = pd.read_csv("Making_Meta_Data_malicious_div.csv")
url = url_benign.append(url_malicious)

lb_make = LabelEncoder()
url["type_code"] = lb_make.fit_transform(url["label"])
print(url["type_code"].value_counts())
X = url[["lines", "tags", "black", "tag_malicious", "white", "tag_benign", "words","js","xss", "dom", "defacing", "size"]]
y = url['type_code']

index = [i for i in range(len(url))]
random.shuffle(index)
data = np.array(X)[index]
labels = np.array(y)[index]

TRAIN_SPLIT = 0.8
TRAIN_SIZE = int(len(X) * TRAIN_SPLIT)

X_train, X_test = X[0:TRAIN_SIZE], X[TRAIN_SIZE:]
Y_train, Y_test = y[0:TRAIN_SIZE], y[TRAIN_SIZE:]
</code>```

And the Model Building..

```<code>texts = data
tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index
Vocab_size = 97027
max_length = 12

sequences = tokenizer.texts_to_sequences(data)
padded_reviews = pad_sequences(sequences, maxlen=max_length, padding='post')
embedding_layer = Embedding(input_dim=len(word_index)+1, output_dim=2, input_length=max_length)

model = Sequential()
model.add(embedding_layer)
model.add(Convolution1D(filters=1, kernel_size=1, padding='valid', activation='relu'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling1D(1))
model.add(Bidirectional(LSTM(64, return_sequences=True, dropout=0.3, recurrent_dropout=0.3)))
model.add(Convolution1D(filters=1, kernel_size=1, padding='valid', activation='relu'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling1D(1))
model.add(Flatten())

model.add(Dense(64))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dense(5))
model.add(BatchNormalization())
model.add(Activation("sigmoid"))

model.add(Flatten())
model.add(Dropout(0.3))
model.add(Dense(5))
model.add(Activation('softmax'))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['acc'])
model.summary()

print('Found %s unique tokens.' % len(word_index))
print('Shape of data tensor:', data.shape)
</code>```

And getting
Found 82416 unique tokens. Shape of data tensor: (97027, 12) as an answer.
However, I keep failing in the fitting procedure which is,

```<code>print(embedding_layer.get_weights()[0].shape)

model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=1, batch_size=64, shuffle=True)
</code>```

getting the InvalidArgumentError: Graph execution error:. I guess all problem comes from matrix dimensions.. but I have no clue to how to fix this..

Thank you very much in advance for your help.

Body:
I'm currently engaging in classifying html text into two, benign and malicious.

I was successful in doing keras in jupyter notebook, but encountered another problem in the model fitting.

My problem consists of classifying 97027*12 feature matrix into 2. And here goes what I am done so far.. Imagine csv files are well defined.. though it has some sparcity.

url_benign = pd.read_csv("Making_Meta_Data_benign.csv")
url_malicious = pd.read_csv("Making_Meta_Data_malicious_div.csv")
url = url_benign.append(url_malicious)

lb_make = LabelEncoder()
url["type_code"] = lb_make.fit_transform(url["label"])
print(url["type_code"].value_counts())
X = url[["lines", "tags", "black", "tag_malicious", "white", "tag_benign", "words","js","xss", "dom", "defacing", "size"]]
y = url['type_code']

index = [i for i in range(len(url))]
random.shuffle(index)
data = np.array(X)[index]
labels = np.array(y)[index]

TRAIN_SPLIT = 0.8
TRAIN_SIZE = int(len(X) * TRAIN_SPLIT)

X_train, X_test = X[0:TRAIN_SIZE], X[TRAIN_SIZE:]
Y_train, Y_test = y[0:TRAIN_SIZE], y[TRAIN_SIZE:]

And the Model Building..

texts = data
tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index
Vocab_size = 97027
max_length = 12

sequences = tokenizer.texts_to_sequences(data)
padded_reviews = pad_sequences(sequences, maxlen=max_length, padding='post')
embedding_layer = Embedding(input_dim=len(word_index)+1, output_dim=2, input_length=max_length)

model = Sequential()
model.add(embedding_layer)
model.add(Convolution1D(filters=1, kernel_size=1, padding='valid', activation='relu'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling1D(1))
model.add(Bidirectional(LSTM(64, return_sequences=True, dropout=0.3, recurrent_dropout=0.3)))
model.add(Convolution1D(filters=1, kernel_size=1, padding='valid', activation='relu'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling1D(1))
model.add(Flatten())

model.add(Dense(64))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dense(5))
model.add(BatchNormalization())
model.add(Activation("sigmoid"))

model.add(Flatten())
model.add(Dropout(0.3))
model.add(Dense(5))
model.add(Activation('softmax'))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['acc'])
model.summary()

print('Found %s unique tokens.' % len(word_index))
print('Shape of data tensor:', data.shape)

And getting
Found 82416 unique tokens. Shape of data tensor: (97027, 12) as an answer.
However, I keep failing in the fitting procedure which is,

print(embedding_layer.get_weights()[0].shape)

model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=1, batch_size=64, shuffle=True)

getting the InvalidArgumentError: Graph execution error:. I guess all problem comes from matrix dimensions.. but I have no clue to how to fix this..

Thank you very much in advance for your help.


问:
Undefined symbols for architecture x86_64: error in react native
I am using react native maps in the map application I developed with react native. I get the following error when I want to run the project on the ios simulator. I tried some of the solutions described in the forum. However, it didn't work.

```<code>Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_RCTBridge", referenced from:
      objc-class-ref in AppDelegate.o
  "_OBJC_CLASS_$_RCTBundleURLProvider", referenced from:
      objc-class-ref in AppDelegate.o
  "_RCTAppSetupDefaultRootView", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
  "_RCTAppSetupPrepareApp", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

The project runs normally in the ios simulator before loading react-native-maps. I added the react-native-maps package by following the steps mentioned. I also built with xcode. However, it gave an error.

Body:
I am using react native maps in the map application I developed with react native. I get the following error when I want to run the project on the ios simulator. I tried some of the solutions described in the forum. However, it didn't work.

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_RCTBridge", referenced from:
      objc-class-ref in AppDelegate.o
  "_OBJC_CLASS_$_RCTBundleURLProvider", referenced from:
      objc-class-ref in AppDelegate.o
  "_RCTAppSetupDefaultRootView", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
  "_RCTAppSetupPrepareApp", referenced from:
      -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The project runs normally in the ios simulator before loading react-native-maps. I added the react-native-maps package by following the steps mentioned. I also built with xcode. However, it gave an error.


问:
tranform tf.while_loop to python
i want to tranform tf.while loop to python while loop

i can understand if while loop is

```<code>def loop_body(x, y):
    x += 1
    return x, y
x, y = tf.while_loop(lambda x, y: x < y, loop_body, [0, 3])
print(x, y)
</code>```

can tranform to

```<code>x = 0
y = 3
while x < y:
    x += 1
print(x)
</code>```

but if i change tf_while loop loop_body to

```<code>def loop_body(x, y):
    x += 1
    return x+1, y
x, y = tf.while_loop(lambda x, y: x < y, loop_body, [0, 3])
print(x, y)
</code>```

where do i need to change

Title: tranform tf.while_loop to python

Body:
i want to tranform tf.while loop to python while loop

i can understand if while loop is

def loop_body(x, y):
    x += 1
    return x, y
x, y = tf.while_loop(lambda x, y: x < y, loop_body, [0, 3])
print(x, y)

can tranform to

x = 0
y = 3
while x < y:
    x += 1
print(x)

but if i change tf_while loop loop_body to

def loop_body(x, y):
    x += 1
    return x+1, y
x, y = tf.while_loop(lambda x, y: x < y, loop_body, [0, 3])
print(x, y)

where do i need to change


问:
Axios + Symfony : Retrieve image path in response after submit
trying to retrieve image path of uploaded media via Axios with Symfony backend.
So far the upload works fine : I can see the updated image after refreshing the page.
But in my JS response the object Qrcode_image is an empty array, and I can't find the path of the image to update my markup

JS

UpdateQrcodeImage(){

    $("#website-qrcode-image-form").on("submit", function(event, datas) {

        event.preventDefault();

        const file = $('#website-qrcode-image')[0].files[0];
        const website_id = $("#website-id").attr('data-value');

        let fDatas = new FormData();
        fDatas.append('website-qrcodeimage', file);
        fDatas.append('website-id', website_id);

        const sendPostRequest = async () => {
            try {
                const resp = await axios.post(`/api/website/${website_id}/qrcode_image`, fDatas, { headers: { 'Content-Type': 'multipart/form-data' } });
                console.log(resp.data);
            } catch (err) {
                console.error(err);
            }
        };
        sendPostRequest();

    });
}
```
<p>Controller: <em>/src/Controller/Api/ApiWebsiteController.php</em></p>
<pre class="lang-php prettyprint-override"><code>#[Route('/api/website/{id}/qrcode_image', name: 'api.website.qrcode_image', methods: ['POST', 'GET'])]
public function website_qrcode_image(?Website $website, Request $request): JsonResponse {

    $data = json_decode($request->getContent(), true);
    $file = $request->files->get('website-qrcodeimage');

    $media = new Media();
    $media->setMediaFile($file);
    $this->em->persist($media);
    $website->setQrcodeImage($media);
    $this->em->persist($website);
    $this->em->flush();

    return $this->json($website, 200, ['Content-Type' => "application/json"], ['groups' => ['qrcode']]);
}
</code>```

Entity: /src/Entity/Website.php

    #[Groups(['qrcode'])]
    #[ORM\OneToOne(cascade: ['persist', 'remove'])]
    private ?Media $Qrcode_image = null;

    [...]

    public function getQrcodeImage(): ?Media
    {
        return $this->Qrcode_image;
    }

    public function setQrcodeImage(?Media $Qrcode_image): self
    {
        $this->Qrcode_image = $Qrcode_image;

        return $this;
    }

```

Body:
trying to retrieve image path of uploaded media via Axios with Symfony backend.
So far the upload works fine : I can see the updated image after refreshing the page.
But in my JS response the object Qrcode_image is an empty array, and I can't find the path of the image to update my markup

JS

UpdateQrcodeImage(){

    $("#website-qrcode-image-form").on("submit", function(event, datas) {

        event.preventDefault();

        const file = $('#website-qrcode-image')[0].files[0];
        const website_id = $("#website-id").attr('data-value');

        let fDatas = new FormData();
        fDatas.append('website-qrcodeimage', file);
        fDatas.append('website-id', website_id);

        const sendPostRequest = async () => {
            try {
                const resp = await axios.post(`/api/website/${website_id}/qrcode_image`, fDatas, { headers: { 'Content-Type': 'multipart/form-data' } });
                console.log(resp.data);
            } catch (err) {
                console.error(err);
            }
        };
        sendPostRequest();

    });
}

Controller: /src/Controller/Api/ApiWebsiteController.php

#[Route('/api/website/{id}/qrcode_image', name: 'api.website.qrcode_image', methods: ['POST', 'GET'])]
public function website_qrcode_image(?Website $website, Request $request): JsonResponse {

    $data = json_decode($request->getContent(), true);
    $file = $request->files->get('website-qrcodeimage');

    $media = new Media();
    $media->setMediaFile($file);
    $this->em->persist($media);
    $website->setQrcodeImage($media);
    $this->em->persist($website);
    $this->em->flush();

    return $this->json($website, 200, ['Content-Type' => "application/json"], ['groups' => ['qrcode']]);
}

Entity: /src/Entity/Website.php

    #[Groups(['qrcode'])]
    #[ORM\OneToOne(cascade: ['persist', 'remove'])]
    private ?Media $Qrcode_image = null;

    [...]

    public function getQrcodeImage(): ?Media
    {
        return $this->Qrcode_image;
    }

    public function setQrcodeImage(?Media $Qrcode_image): self
    {
        $this->Qrcode_image = $Qrcode_image;

        return $this;
    }


问:
Test suite failed to run createRoot(...): Target container is not a DOM element
```<code>**FAIL  src/containers/pages/signIn/SignIn.test.js**
  ● Test suite failed to run

    createRoot(...): Target container is not a DOM element.

       5 | import { ConfigProvider } from "antd";
       6 |
    >  7 | const root = ReactDOM.createRoot(document.getElementById("root"));
         |                       ^
       8 | root.render(
       9 |   <React.StrictMode>
      10 |     <ConfigProvider theme={{ hashed: false }}>

      at createRoot (node_modules/react-dom/cjs/react-dom.development.js:29345:11)
      at Object.createRoot$1 [as createRoot] (node_modules/react-dom/cjs/react-dom.development.js:29800:10)
      at Object.createRoot (node_modules/react-dom/client.js:12:16)
      at Object.<anonymous> (src/index.js:7:23)
      at Object.<anonymous> (src/containers/pages/signIn/SignIn.js:3:1)
      at Object.<anonymous> (src/containers/pages/signIn/SignIn.test.js:3:1)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.995 s
Ran all test suites.

Watch Usage: Press w to show more.
</code>```

I am importing SignIn component in the below code. But the error is in index.js file. I don't have idea that whether it will automatically call index.js for all tests.

SignIn.test.js

```<code>import React from 'react';
import { shallow } from 'enzyme';
import SignIn from './SignIn';

describe('SignIn', () => {
  it('renders without crashing', () => {
    const { getByText } = shallow(<SignIn />);
    expect(getByText('Welcome to the App!')).toBeInTheDocument();
  });
});

</code>```

**
The import statement itself is the cause of this error. I don't know whether I am missing anything here.**

index.js

```<code>import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ConfigProvider } from "antd";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ConfigProvider theme={{ hashed: false }}>
      <App />
    </ConfigProvider>
  </React.StrictMode>
);
serviceWorker.unregister();

</code>```

SignIn.js Imports

```<code>import React from "react";
import { useNavigate } from "react-router-dom";
import { Form, Modal } from "antd";
import SignInStyleWrapper from "./SignIn.styles";
import applogo from "../../../image/applogo.png";
import { loginUser } from "../../../redux_Rtk/UserLogin/loginService";
import { useDispatch} from "react-redux";

</code>```

Dependencies installed

```<code>"react": "^18.2.0",
"react-custom-scrollbars": "^4.2.1",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-router": "^6.4.3",
"react-router-dom": "^6.4.3",
"react-saga": "^0.3.1",
"react-scripts": "5.0.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.4.3",
"enzyme": "^3.11.0",
"jest": "24.9.0",
"jest-html-reporters": "^3.0.11",
"enzyme-to-json": "^3.6.2",
</code>```

I tried "@testing-library/react" instead of enzyme. Its the same result. I could see the The import statement itself is the cause of this error.

I am writing unit testing for the first time. So don't know really what I am missing here.

Body:
**FAIL  src/containers/pages/signIn/SignIn.test.js**
  ● Test suite failed to run

    createRoot(...): Target container is not a DOM element.

       5 | import { ConfigProvider } from "antd";
       6 |
    >  7 | const root = ReactDOM.createRoot(document.getElementById("root"));
         |                       ^
       8 | root.render(
       9 |   <React.StrictMode>
      10 |     <ConfigProvider theme={{ hashed: false }}>

      at createRoot (node_modules/react-dom/cjs/react-dom.development.js:29345:11)
      at Object.createRoot$1 [as createRoot] (node_modules/react-dom/cjs/react-dom.development.js:29800:10)
      at Object.createRoot (node_modules/react-dom/client.js:12:16)
      at Object.<anonymous> (src/index.js:7:23)
      at Object.<anonymous> (src/containers/pages/signIn/SignIn.js:3:1)
      at Object.<anonymous> (src/containers/pages/signIn/SignIn.test.js:3:1)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.995 s
Ran all test suites.

Watch Usage: Press w to show more.

I am importing SignIn component in the below code. But the error is in index.js file. I don't have idea that whether it will automatically call index.js for all tests.

SignIn.test.js

import React from 'react';
import { shallow } from 'enzyme';
import SignIn from './SignIn';

describe('SignIn', () => {
  it('renders without crashing', () => {
    const { getByText } = shallow(<SignIn />);
    expect(getByText('Welcome to the App!')).toBeInTheDocument();
  });
});

**
The import statement itself is the cause of this error. I don't know whether I am missing anything here.**

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ConfigProvider } from "antd";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ConfigProvider theme={{ hashed: false }}>
      <App />
    </ConfigProvider>
  </React.StrictMode>
);
serviceWorker.unregister();

SignIn.js Imports

import React from "react";
import { useNavigate } from "react-router-dom";
import { Form, Modal } from "antd";
import SignInStyleWrapper from "./SignIn.styles";
import applogo from "../../../image/applogo.png";
import { loginUser } from "../../../redux_Rtk/UserLogin/loginService";
import { useDispatch} from "react-redux";

Dependencies installed

"react": "^18.2.0",
"react-custom-scrollbars": "^4.2.1",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-router": "^6.4.3",
"react-router-dom": "^6.4.3",
"react-saga": "^0.3.1",
"react-scripts": "5.0.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.4.3",
"enzyme": "^3.11.0",
"jest": "24.9.0",
"jest-html-reporters": "^3.0.11",
"enzyme-to-json": "^3.6.2",

I tried "@testing-library/react" instead of enzyme. Its the same result. I could see the The import statement itself is the cause of this error.

I am writing unit testing for the first time. So don't know really what I am missing here.


问:
why does my CRUD application show data not defined?
I'm trying to create a CRUD app where a certain user logs on and it takes them to a specific page with a table of data they can manipulate. For example, when an admin logs in, it takes them to a page only admins can see, when a student logs in, it takes them to a page only students can see etc.

I'm writing the code a user at a time so I've started with the admins. They can log in successfully as an admin and it redirects them to a page called admin user, however it displays this instead of the table from the SQL database i'm aiming for.

```<code>
    ReferenceError: /Users/Molly/Documents/Masters/Databases and information systems/Group work/enrolling/views/adminlist.ejs:65
        63|
        64|
     >> 65|                 <% if (data) { %>
        66|                     <% data.forEach(function(adminuser){ %>
        67|                         <tr>
        68|                             <td><%= adminuser.UserID %></td>

    data is not defined

</code>```

I've been able to display the table successfully before I implemented the login page. Before I could just run localhost****/user and it would be fine. But now that I've included a login page and it redirects to the page when logged in it's struggling to retrieve the data even though it is still connected to the database.

adminlist.ejs

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>User List</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<div class="container">>

    <div class="row mt-5">
        <div class="col-lg-12 col-md-12 text-center">
            <h2>Users within the college system</h2>
        </div>
    </div>

    <div class="row mt-3">
        <!-- heading -->
        <div class="col-lg-6 col-md-6 pt-3">
            <h3>User List</h3>
        </div>

        <div class="col-lg-6 col-md-6 text-end pt-3">
            <a href="/adminuser/adminadd" class="btn btn-primary btn-sm">+ Add New User</a>
        </div>
    </div>

    <div class="row">
        <!-- alert message -->
        <div class="col-lg-12 col-md-12 mt-2">
            <% if (messages.error) { %>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <%- messages.error %>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <% } %>

            <% if (messages.success) { %>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <strong>Success!</strong> <%- messages.success %>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <% } %>
        </div>

        <!-- print data -->
        <div class="col-lg-12 col-md-12 mt-3">
            <table class="table table-bordered table-hover table-striped">
                <thead class="table-dark">
                    <tr>
                        <th>UserID</th>
                        <th>Name</th>
                        <th>RoleID</th>
                        <th>password</th>
                        <th>username</th>
                        <th width="150" class="text-center">Action</th>
                    </tr>
                </thead>
                <!->

                <% if (data) { %>
                    <% data.forEach(function(adminuser){ %>
                        <tr>
                            <td><%= users.UserID %></td>
                            <td><%= users.Name %></td>
                            <td><%= users.RoleID %></td>
                            <td><%= users.password %></td>
                            <td><%= users.username %></td>
                            <td class="text-center">
                                <a href='/adminuser/adminedit/<%= users.UserID %>' class="btn btn-info text-white btn-sm inline-block">Edit</a>                            >
                                <form method="post" action="/adminuser/delete/<%= users.UserID %>" class="d-inline-block">
                                    <input type="submit" name="delete" value='Delete' class="btn btn-danger btn-sm" onClick="return confirm('Are you sure you want to delete?')" />
                                    <input type="hidden" name="_method" value="DELETE" />
                                </form>
                            </td>
                        </tr>
                    <% }) %>
                <% } %>
            </table>
        </div>
    </div>
</div>

</body>
</html>
</code>```

adminuser.js

```<code>var express = require('express')
var app = express()
var mysql = require('mysql');

//create connection database
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root123',
    database : 'mydb'
});

//create connection
connection.connect();

app.get('/', function(req, res, next) {

    selectQuery = "SELECT * FROM users";

    connection.query(selectQuery, function(error,data){

        //if(err) throw err
        if (error) {
            req.flash('error', error)
            res.render('adminuser/adminlist', {
                title: 'User List',
                data: ''
            })
        } else {
            res.render('adminuser/adminlist', {
                title: 'User List',
                data: data
            })
        }
    })
})

// Add User
app.get('/adminadd', function(req, res, next){

    res.render('adminuser/adminadd', {
        title: 'Add New User',
        UserID: '',
        Name: '',
        RoleID: '',
        password:'',
        username: ''
    })
})

// Add User Data
app.post('/adminadd', function(req, res, next){

    // add validation
    req.assert('UserID', 'UserID field is required').notEmpty()
    req.assert('Name', 'Name is required').notEmpty()
    req.assert('RoleID', 'RoleID field is required').notEmpty()
    req.assert('password', 'password field is required').notEmpty()
    req.assert('username', 'username field is required').notEmpty()

    var errors = req.validationErrors()

    if(errors){

        var error_msg = ''

        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })

        req.flash('error', error_msg)

        res.render('adminuser/adminadd', {
            title: 'Add New User',
            UserID: req.body.UserID,
            Name: req.body.Name,
            RoleID: req.body.RoleID,
            password: req.body.password,
            username: req.body.username
        })
    }else{
        //get data in form
        var UserID = req.body.UserID;
        var Name = req.body.Name;
        var RoleID = req.body.RoleID;
        var password = req.body.password;
        var username = req.body.username;

        // insert query get data user
        insertQuery = `INSERT INTO users (UserID,Name,RoleID,password,username) VALUES ("${UserID}", "${Name}", "${RoleID}", "${password}", "${username}")`;

        connection.query(insertQuery, function(error,result){

            req.flash('success', 'User add successfully!')
            // redirect to user list page
            res.redirect('/adminuser')

        });
    }
});

// Edit user
app.get('/adminedit/(:UserID)', function(req, res, next){

    // get id user
    var UserID = req.params.UserID;

    //select query select data edit form
    var selectQuery = `SELECT * FROM users WHERE UserID = "${UserID}"`;

    connection.query(selectQuery, function(error, data){

        res.render('adminuser/adminedit', {
            title: 'Edit User',
            //data: rows[0],
            UserID: data[0].UserID,
            Name: data[0].Name,
            RoleID: data[0].RoleID,
            password: data[0].password,
            username: data[0].username,
        })

    });

});

// Update user
app.post('/adminedit/(:UserID)', function(req, res, next){

    // get user product
    var UserID = req.params.UserID;

    // add validation
    req.assert('UserID', 'UserID field is required').notEmpty()      //Validate name
    req.assert('Name', 'Name is required').notEmpty()    //Validate price
    req.assert('RoleID', 'RoleID field is required').notEmpty()
    req.assert('password', 'password field is required').notEmpty()
    req.assert('username', 'Username field is required').notEmpty() //Validate detail

    var errors = req.validationErrors()

    if(errors){

        var error_msg = ''

        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })

        req.flash('error', error_msg)

        /**
         * Using req.body.name
         * because req.param('name') is deprecated
         */
        res.render('adminuser/adminedit', {
            title: 'Add New User',
            UserID: req.body.UserID,
            Name: req.body.Name,
            Role: req.body.RoleID,
            password: req.body.password,
            username: req.body.username
        })

    }else{

        // get data product
        var UserID = req.body.UserID;
        var Name = req.body.Name;
        var RoleID = req.body.RoleID;
        var password = req.body.password;
        var username = req.body.username;

        // update query product update
        var updateQuery = `UPDATE users SET Name = "${Name}", password = "${password}", username = "${username}", RoleID = "${RoleID}" WHERE UserID = "${UserID}"`;

        connection.query(updateQuery, function(error,result){

            req.flash('success', 'User update successfully!')
            // redirect to products list page
            res.redirect('/adminuser')
        });
    }

})

// Delete Product
app.delete('/delete/(:UserID)', function(req, res, next) {

    // get id product data
    var UserID = req.params.UserID;

    // delete query product delete
    deleteQuery = `DELETE FROM users WHERE UserID = "${UserID}"`;

    connection.query(deleteQuery, function(error,data){
        //if(err) throw err
        if (error) {
            req.flash('error', error)
            // redirect to products list page
            res.redirect('/adminuser')
        } else {
            req.flash('success', 'User deleted successfully!')
            // redirect to products list page
            res.redirect('/adminuser')
        }
    })
})

module.exports = app
</code>```

Body:
I'm trying to create a CRUD app where a certain user logs on and it takes them to a specific page with a table of data they can manipulate. For example, when an admin logs in, it takes them to a page only admins can see, when a student logs in, it takes them to a page only students can see etc.

I'm writing the code a user at a time so I've started with the admins. They can log in successfully as an admin and it redirects them to a page called admin user, however it displays this instead of the table from the SQL database i'm aiming for.

    ReferenceError: /Users/Molly/Documents/Masters/Databases and information systems/Group work/enrolling/views/adminlist.ejs:65
        63|
        64|
     >> 65|                 <% if (data) { %>
        66|                     <% data.forEach(function(adminuser){ %>
        67|

        68|                             <%= adminuser.UserID %>

    data is not defined

I've been able to display the table successfully before I implemented the login page. Before I could just run localhost****/user and it would be fine. But now that I've included a login page and it redirects to the page when logged in it's struggling to retrieve the data even though it is still connected to the database.

adminlist.ejs

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>User List</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">

>

Users within the college system

User List

            + Add New User

            <% if (messages.error) { %>

                    <%- messages.error %>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

            <% } %>

            <% if (messages.success) { %>

                    Success! <%- messages.success %>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

            <% } %>

                        UserID
                        Name
                        RoleID
                        password
                        username
                        Action

                <!->

                <% if (data) { %>
                    <% data.forEach(function(adminuser){ %>

                            <%= users.UserID %>
                            <%= users.Name %>
                            <%= users.RoleID %>
                            <%= users.password %>
                            <%= users.username %>

                                <a href='/adminuser/adminedit/<%= users.UserID %>' class="btn btn-info text-white btn-sm inline-block">Edit                            >
                                <form method="post" action="/adminuser/delete/<%= users.UserID %>" class="d-inline-block">
                                    <input type="submit" name="delete" value='Delete' class="btn btn-danger btn-sm" onClick="return confirm('Are you sure you want to delete?')" />
                                    <input type="hidden" name="_method" value="DELETE" />
                                </form>

                    <% }) %>
                <% } %>

adminuser.js

var express = require('express')
var app = express()
var mysql = require('mysql');

//create connection database
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root123',
    database : 'mydb'
});

//create connection
connection.connect();

app.get('/', function(req, res, next) {

    selectQuery = "SELECT * FROM users";

    connection.query(selectQuery, function(error,data){

        //if(err) throw err
        if (error) {
            req.flash('error', error)
            res.render('adminuser/adminlist', {
                title: 'User List',
                data: ''
            })
        } else {
            res.render('adminuser/adminlist', {
                title: 'User List',
                data: data
            })
        }
    })
})

// Add User
app.get('/adminadd', function(req, res, next){

    res.render('adminuser/adminadd', {
        title: 'Add New User',
        UserID: '',
        Name: '',
        RoleID: '',
        password:'',
        username: ''
    })
})

// Add User Data
app.post('/adminadd', function(req, res, next){

    // add validation
    req.assert('UserID', 'UserID field is required').notEmpty()
    req.assert('Name', 'Name is required').notEmpty()
    req.assert('RoleID', 'RoleID field is required').notEmpty()
    req.assert('password', 'password field is required').notEmpty()
    req.assert('username', 'username field is required').notEmpty()

    var errors = req.validationErrors()

    if(errors){

        var error_msg = ''

        errors.forEach(function(error) {
            error_msg += error.msg + '
'
        })

        req.flash('error', error_msg)

        res.render('adminuser/adminadd', {
            title: 'Add New User',
            UserID: req.body.UserID,
            Name: req.body.Name,
            RoleID: req.body.RoleID,
            password: req.body.password,
            username: req.body.username
        })
    }else{
        //get data in form
        var UserID = req.body.UserID;
        var Name = req.body.Name;
        var RoleID = req.body.RoleID;
        var password = req.body.password;
        var username = req.body.username;

        // insert query get data user
        insertQuery = `INSERT INTO users (UserID,Name,RoleID,password,username) VALUES ("${UserID}", "${Name}", "${RoleID}", "${password}", "${username}")`;

        connection.query(insertQuery, function(error,result){

            req.flash('success', 'User add successfully!')
            // redirect to user list page
            res.redirect('/adminuser')

        });
    }
});

// Edit user
app.get('/adminedit/(:UserID)', function(req, res, next){

    // get id user
    var UserID = req.params.UserID;

    //select query select data edit form
    var selectQuery = `SELECT * FROM users WHERE UserID = "${UserID}"`;

    connection.query(selectQuery, function(error, data){

        res.render('adminuser/adminedit', {
            title: 'Edit User',
            //data: rows[0],
            UserID: data[0].UserID,
            Name: data[0].Name,
            RoleID: data[0].RoleID,
            password: data[0].password,
            username: data[0].username,
        })

    });

});

// Update user
app.post('/adminedit/(:UserID)', function(req, res, next){

    // get user product
    var UserID = req.params.UserID;

    // add validation
    req.assert('UserID', 'UserID field is required').notEmpty()      //Validate name
    req.assert('Name', 'Name is required').notEmpty()    //Validate price
    req.assert('RoleID', 'RoleID field is required').notEmpty()
    req.assert('password', 'password field is required').notEmpty()
    req.assert('username', 'Username field is required').notEmpty() //Validate detail

    var errors = req.validationErrors()

    if(errors){

        var error_msg = ''

        errors.forEach(function(error) {
            error_msg += error.msg + '
'
        })

        req.flash('error', error_msg)

        /**
         * Using req.body.name
         * because req.param('name') is deprecated
         */
        res.render('adminuser/adminedit', {
            title: 'Add New User',
            UserID: req.body.UserID,
            Name: req.body.Name,
            Role: req.body.RoleID,
            password: req.body.password,
            username: req.body.username
        })

    }else{

        // get data product
        var UserID = req.body.UserID;
        var Name = req.body.Name;
        var RoleID = req.body.RoleID;
        var password = req.body.password;
        var username = req.body.username;

        // update query product update
        var updateQuery = `UPDATE users SET Name = "${Name}", password = "${password}", username = "${username}", RoleID = "${RoleID}" WHERE UserID = "${UserID}"`;

        connection.query(updateQuery, function(error,result){

            req.flash('success', 'User update successfully!')
            // redirect to products list page
            res.redirect('/adminuser')
        });
    }

})

// Delete Product
app.delete('/delete/(:UserID)', function(req, res, next) {

    // get id product data
    var UserID = req.params.UserID;

    // delete query product delete
    deleteQuery = `DELETE FROM users WHERE UserID = "${UserID}"`;

    connection.query(deleteQuery, function(error,data){
        //if(err) throw err
        if (error) {
            req.flash('error', error)
            // redirect to products list page
            res.redirect('/adminuser')
        } else {
            req.flash('success', 'User deleted successfully!')
            // redirect to products list page
            res.redirect('/adminuser')
        }
    })
})

module.exports = app


问:
How can I show image in flutter by file without path?
I want to show the image in flutter, but I have a file just in two shapes (file - base64).</p>


问:
Flutter facebook login issue with firebase
Hello i am trying to implement facebook login feature in my App i have issue in some devices login feature is working fine i tested it many devices it working but some devices its not working like Samsung s10 and xiaomi and Huawei devices  any one know this issue?here is my code below

```<code>  Future<UserCredential> signInWithFacebook() async {
    SharedPreferences prefs =await SharedPreferences.getInstance() ;
    // Trigger the sign-in flow
    final LoginResult loginResult = await FacebookAuth.instance.login(permissions: ['public_profile', 'email']);
    if(loginResult.status==LoginStatus.success){
    try{
      final userdata=await FacebookAuth.instance.getUserData();
      print(userdata);
      print(userdata['name']);
      print(userdata['email']);
      print(userdata['picture']['data']['url']);

      prefs.setString('name', userdata['name'].toString());
      prefs.setString('email', userdata['email'].toString());
      prefs.setString('profilepic', userdata['picture']['data']['url'].toString());
      prefs.setBool('islogin', true);
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => NavigationPage()),
      );
    }
    catch(e){
      print('error');
    }

    }else{
      print('ERROR');
    }
</code>```

this is my logcat which i recived from huawei device and in this device not working facebook login

```<code>I/zygote64( 6226): Do partial code cache collection, code=106KB, data=72KB
I/zygote64( 6226): After code cache collection, code=106KB, data=72KB
I/zygote64( 6226): Increasing code cache capacity to 512KB
D/HwCust  ( 6226): Create obj success use class android.app.HwCustActivityImpl
D/HwCust  ( 6226): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
V/ActivityThread( 6226): ActivityThread,callActivityOnCreate
D/HwRTBlurUtils( 6226): check blur style for HwPhoneWindow, themeResId : 0x7f0f0169, context : com.facebook.FacebookActivity@552496d, Nhwext : 0, get Blur : disable with , null
D/ActivityThread( 6226): add activity client record, r= ActivityRecord{7c17180 token=android.os.BinderProxy@baabd8 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@baabd8
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
I/PressGestureDetector( 6226): onAttached begin
I/PressGestureDetector( 6226): onAttached end
I/PressGestureDetector( 6226): HiTouch restricted: AboardArea.
D/mali_winsys( 6226): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
I/flutter ( 6226): ERROR
W/libEGL  ( 6226): EGLNativeWindowType 0x7757aa3010 disconnect failed
E/flutter ( 6226): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 6226): #0      _FacebookLoginState.signInWithFacebook (package:a_m_s/Pages/Login.dart:109:107)
E/flutter ( 6226): <asynchronous suspension>
E/flutter ( 6226):
D/ActivityThread( 6226): Remove activity client record, r= ActivityRecord{7c17180 token=android.os.BinderProxy@baabd8 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@baabd8
D/HwCust  ( 6226): Create obj success use class android.app.HwCustActivityImpl
D/HwCust  ( 6226): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
V/ActivityThread( 6226): ActivityThread,callActivityOnCreate
D/HwRTBlurUtils( 6226): check blur style for HwPhoneWindow, themeResId : 0x7f0f0169, context : com.facebook.FacebookActivity@a271a3, Nhwext : 0, get Blur : disable with , null
D/ActivityThread( 6226): add activity client record, r= ActivityRecord{6763c3d token=android.os.BinderProxy@38a1c07 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@38a1c07
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
I/PressGestureDetector( 6226): onAttached begin
I/PressGestureDetector( 6226): onAttached end
I/PressGestureDetector( 6226): HiTouch restricted: AboardArea.
D/mali_winsys( 6226): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
I/flutter ( 6226): ERROR
E/flutter ( 6226): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 6226): #0      _FacebookLoginState.signInWithFacebook (package:a_m_s/Pages/Login.dart:109:107)
E/flutter ( 6226): <asynchronous suspension>
E/flutter ( 6226):
W/libEGL  ( 6226): EGLNativeWindowType 0x7757abc010 disconnect failed
D/ActivityThread( 6226): Remove activity client record, r= ActivityRecord{6763c3d token=android.os.BinderProxy@38a1c07 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@38a1c07
W/InputMethodManager( 6226): startInputReason = 8
W/IInputConnectionWrapper( 6226): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper( 6226): getTextBeforeCursor on inactive InputConnection
V/ActivityThread( 6226): Finishing stop of ActivityRecord{59e045d token=android.os.BinderProxy@de5f29d {com.example.promotion_app/com.example.promotion_app.MainActivity}}
W/libEGL  ( 6226): EGLNativeWindowType 0x775c3cf010 disconnect failed
W/libEGL  ( 6226): EGLNativeWindowType 0x775cd0c010 disconnect failed
V/ActivityThread( 6226): Handle window ActivityRecord{59e045d token=android.os.BinderProxy@de5f29d {com.example.promotion_app/com.example.promotion_app.MainActivity}} visibility: false
I/zygote64( 6226): Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
Lost connection to device.
</code>```

Body:
Hello i am trying to implement facebook login feature in my App i have issue in some devices login feature is working fine i tested it many devices it working but some devices its not working like Samsung s10 and xiaomi and Huawei devices  any one know this issue?here is my code below

  Future<UserCredential> signInWithFacebook() async {
    SharedPreferences prefs =await SharedPreferences.getInstance() ;
    // Trigger the sign-in flow
    final LoginResult loginResult = await FacebookAuth.instance.login(permissions: ['public_profile', 'email']);
    if(loginResult.status==LoginStatus.success){
    try{
      final userdata=await FacebookAuth.instance.getUserData();
      print(userdata);
      print(userdata['name']);
      print(userdata['email']);
      print(userdata['picture']['data']['url']);

      prefs.setString('name', userdata['name'].toString());
      prefs.setString('email', userdata['email'].toString());
      prefs.setString('profilepic', userdata['picture']['data']['url'].toString());
      prefs.setBool('islogin', true);
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => NavigationPage()),
      );
    }
    catch(e){
      print('error');
    }

    }else{
      print('ERROR');
    }

this is my logcat which i recived from huawei device and in this device not working facebook login

I/zygote64( 6226): Do partial code cache collection, code=106KB, data=72KB
I/zygote64( 6226): After code cache collection, code=106KB, data=72KB
I/zygote64( 6226): Increasing code cache capacity to 512KB
D/HwCust  ( 6226): Create obj success use class android.app.HwCustActivityImpl
D/HwCust  ( 6226): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
V/ActivityThread( 6226): ActivityThread,callActivityOnCreate
D/HwRTBlurUtils( 6226): check blur style for HwPhoneWindow, themeResId : 0x7f0f0169, context : com.facebook.FacebookActivity@552496d, Nhwext : 0, get Blur : disable with , null
D/ActivityThread( 6226): add activity client record, r= ActivityRecord{7c17180 token=android.os.BinderProxy@baabd8 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@baabd8
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
I/PressGestureDetector( 6226): onAttached begin
I/PressGestureDetector( 6226): onAttached end
I/PressGestureDetector( 6226): HiTouch restricted: AboardArea.
D/mali_winsys( 6226): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
I/flutter ( 6226): ERROR
W/libEGL  ( 6226): EGLNativeWindowType 0x7757aa3010 disconnect failed
E/flutter ( 6226): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 6226): #0      _FacebookLoginState.signInWithFacebook (package:a_m_s/Pages/Login.dart:109:107)
E/flutter ( 6226): <asynchronous suspension>
E/flutter ( 6226):
D/ActivityThread( 6226): Remove activity client record, r= ActivityRecord{7c17180 token=android.os.BinderProxy@baabd8 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@baabd8
D/HwCust  ( 6226): Create obj success use class android.app.HwCustActivityImpl
D/HwCust  ( 6226): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
V/ActivityThread( 6226): ActivityThread,callActivityOnCreate
D/HwRTBlurUtils( 6226): check blur style for HwPhoneWindow, themeResId : 0x7f0f0169, context : com.facebook.FacebookActivity@a271a3, Nhwext : 0, get Blur : disable with , null
D/ActivityThread( 6226): add activity client record, r= ActivityRecord{6763c3d token=android.os.BinderProxy@38a1c07 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@38a1c07
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
D/OpenGLRenderer( 6226):   HWUI Binary is  enabled
I/PressGestureDetector( 6226): onAttached begin
I/PressGestureDetector( 6226): onAttached end
I/PressGestureDetector( 6226): HiTouch restricted: AboardArea.
D/mali_winsys( 6226): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
W/InputMethodManager( 6226): startInputReason = 1
I/flutter ( 6226): ERROR
E/flutter ( 6226): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 6226): #0      _FacebookLoginState.signInWithFacebook (package:a_m_s/Pages/Login.dart:109:107)
E/flutter ( 6226): <asynchronous suspension>
E/flutter ( 6226):
W/libEGL  ( 6226): EGLNativeWindowType 0x7757abc010 disconnect failed
D/ActivityThread( 6226): Remove activity client record, r= ActivityRecord{6763c3d token=android.os.BinderProxy@38a1c07 {com.example.promotion_app/com.facebook.FacebookActivity}} token= android.os.BinderProxy@38a1c07
W/InputMethodManager( 6226): startInputReason = 8
W/IInputConnectionWrapper( 6226): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper( 6226): getTextBeforeCursor on inactive InputConnection
V/ActivityThread( 6226): Finishing stop of ActivityRecord{59e045d token=android.os.BinderProxy@de5f29d {com.example.promotion_app/com.example.promotion_app.MainActivity}}
W/libEGL  ( 6226): EGLNativeWindowType 0x775c3cf010 disconnect failed
W/libEGL  ( 6226): EGLNativeWindowType 0x775cd0c010 disconnect failed
V/ActivityThread( 6226): Handle window ActivityRecord{59e045d token=android.os.BinderProxy@de5f29d {com.example.promotion_app/com.example.promotion_app.MainActivity}} visibility: false
I/zygote64( 6226): Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
Lost connection to device.


问:
Fetching parameters from activated link in WordPress ultimage member plugin
Am creating a Membership WordPress website using Ultimate Member Plugin. When a user registers, an activation link is sent to their email address. Once the link is clicked, I have set on ultimate member dashboard to redirect to a specific URL. The URL links to a page that has a modal where the user can finish setting up their account details.

The problem is once the user clicks on the Activation link on the email, the url opened on the activation page does not have any unique parameter e.g user_id that can be used to fetch user details from database .

Am expecting this URL: http://wplocaltheme.test/user_id=31  but I get this: http://wplocaltheme.test  , once the new page opens

I have tried using WordPress Hooks specifically um_registration_complete as seen in the documentation  but still a headache

Email Sent to me

Ultimate Member URL Configuration


问:
Is there a way to get the state of pressed keys at runtime? without using event
Is there a way to get the state of pressed keys at runtime?

without using events like: 'keyDown' or 'keyUp' or 'keyPress'.

Because this feature is supposed to be used in a basic class, I guess it will affect the performance.


问:
Firebase phone authentication not working after uploading my app to the play store
I'm working on flutter project and using firebase as a backend. I uploaded my app to the play store and the Firebase OTP message didn't send to my users at all but when I'm using my phone provider 'Test Number' the one i use it for testing is working, it also work fine on debug mode and when i build apk-release --split-per-api works fine
the problem is when i build 'appbundel' then google play repacking it for me the auth not working.

I've already add Google play sign in keys SHA1 and SHA256 to my firebase app settings and updated google-services.json for my app and upload it again and still not working.


问:
Using the sed command in tcsh script to replace a string with variable
I am having a file in directory structure which contains the date of creation within the directory name which may change.

File Path:

```<code>  /abc/xyz/mno_*/efg_*/file1.txt
</code>```

where, mno_* & efg_* directories is having a random numbers after _ which are nothing but system dates.

Now, I am having a file(file2.txt) in which I want to replace a string with these file path.

File:

```<code> .FILE_NAME: ???
</code>```

Required Output:

```<code>.FILE_NAME: /abc/xyz/mno_12172022/efg_12142022/file1.txt
</code>```

Here, The dates are just the assumptions, it may vary based on the directory creation date.

Code in tcsh script:

```<code> sed -i "s|.FILE_NAME: ???|.TOP_SPF: /abc/xyz/mno_*/efg_*/file1.txt|g" file2.txt
</code>```

Output:

```<code> .FILE_NAME: /abc/xyz/mno_*/efg_*/file1.txt
</code>```

How can I get the path along with the dates in the directory structure which are not fixed.
Can someone help me to do this?

Thanks & Regards,

Parth.

Body:
I am having a file in directory structure which contains the date of creation within the directory name which may change.

File Path:

  /abc/xyz/mno_*/efg_*/file1.txt

where, mno_* & efg_* directories is having a random numbers after _ which are nothing but system dates.

Now, I am having a file(file2.txt) in which I want to replace a string with these file path.

File:

 .FILE_NAME: ???

Required Output:

.FILE_NAME: /abc/xyz/mno_12172022/efg_12142022/file1.txt

Here, The dates are just the assumptions, it may vary based on the directory creation date.

Code in tcsh script:

 sed -i "s|.FILE_NAME: ???|.TOP_SPF: /abc/xyz/mno_*/efg_*/file1.txt|g" file2.txt

Output:

 .FILE_NAME: /abc/xyz/mno_*/efg_*/file1.txt

How can I get the path along with the dates in the directory structure which are not fixed.
Can someone help me to do this?

Thanks & Regards,

Parth.


问:
Adding tabular data to image classification model results in an Error tensorflow
I am not sure what I am doing wrong.

The data:

```<code>images_generator = ImageDataGenerator()
X_train_images = images_generator.flow_from_dataframe(
    dataframe=dataframe_train,
    directory=None,
    x_col='image_path',
    y_col='target',
    class_mode='raw'
)

dataframe_train.drop("image_path", axis=1, inplace=True)
X_train_tabular = dataframe_train.iloc[:, :-1].values
//scaling etc..
y_train = dataframe_train.iloc[:, -1].values
</code>```

The model:

```<code># Load the VGG16 model
vgg16 = keras.applications.VGG16(include_top=False, input_shape=(224, 224, 3))
for layer in vgg16.layers:
    layer.trainable = False

image_input = keras.Input(shape=(224, 224, 3), name='image')
tabular_input = keras.Input(shape=(NUM_TABULAR_COLS,), name='tabular')

vgg16_output = vgg16(image_input)
vgg16_output_flat = keras.layers.Flatten()(vgg16_output)

# Combine the flattened VGG16 output and tabular data
combined_inputs = tf.keras.layers.concatenate([vgg16_output_flat, tabular_input])

x = keras.layers.Dense(64, activation='relu')(combined_inputs)
output = keras.layers.Dense(2, activation='softmax')(x)

# Create a model using the inputs and outputs
model = keras.Model(inputs=[image_input, tabular_input], outputs=output)
model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(
    [X_train_images, X_train_tabular],
    y_test,
    epochs=2
)
</code>```

And when I try to fit it I get this exception:

```<code>ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'keras.preprocessing.image.DataFrameIterator'>", "<class 'numpy.ndarray'>"}), <class 'numpy.ndarray'>
</code>```

Not sure how to tackle it since I tried converting to tensors,np array etc. Nothing worked. So now I wonder If I`m doing something essentially wrong.

Body:
I am not sure what I am doing wrong.

The data:

images_generator = ImageDataGenerator()
X_train_images = images_generator.flow_from_dataframe(
    dataframe=dataframe_train,
    directory=None,
    x_col='image_path',
    y_col='target',
    class_mode='raw'
)

dataframe_train.drop("image_path", axis=1, inplace=True)
X_train_tabular = dataframe_train.iloc[:, :-1].values
//scaling etc..
y_train = dataframe_train.iloc[:, -1].values

The model:

# Load the VGG16 model
vgg16 = keras.applications.VGG16(include_top=False, input_shape=(224, 224, 3))
for layer in vgg16.layers:
    layer.trainable = False

image_input = keras.Input(shape=(224, 224, 3), name='image')
tabular_input = keras.Input(shape=(NUM_TABULAR_COLS,), name='tabular')

vgg16_output = vgg16(image_input)
vgg16_output_flat = keras.layers.Flatten()(vgg16_output)

# Combine the flattened VGG16 output and tabular data
combined_inputs = tf.keras.layers.concatenate([vgg16_output_flat, tabular_input])

x = keras.layers.Dense(64, activation='relu')(combined_inputs)
output = keras.layers.Dense(2, activation='softmax')(x)

# Create a model using the inputs and outputs
model = keras.Model(inputs=[image_input, tabular_input], outputs=output)
model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(
    [X_train_images, X_train_tabular],
    y_test,
    epochs=2
)

And when I try to fit it I get this exception:

ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'keras.preprocessing.image.DataFrameIterator'>", "<class 'numpy.ndarray'>"}), <class 'numpy.ndarray'>

Not sure how to tackle it since I tried converting to tensors,np array etc. Nothing worked. So now I wonder If I`m doing something essentially wrong.


问:
Can Entity Framework Core 7 include navigational properties that have the "internal" access modifier
I have a model that looks something like this

```<code>public sealed class Foo : EntityBase, IAggregateRoot
{
    internal ICollection<Bar> Bars  { get; init; } = new List<Bar>();

    public void AddBars(SomeDto someDto)
    {
        Bars.Add(new(){SomeProperty = someDto.SomeProperty}
    }
}

internal sealed class Bar : EntityBase
{
    internal required string SomeProperty { get; init; }
}
</code>```

Both these classes exist in my domain layer model project. I am trying to do domain-driven design here.

In my application services layer project, I want to reference the domain project but I only want to be able to new up a Foo and not a Bar.

In my infrastructure project I have wired up EF Core 7 using Fluent API.

Since Bar is internal, I am finding it hard to map this navigational property to a table.

I don't want to expose internals in the infrastructure project.

Should I just make Bar public but not add it to the DbSet. That way people can only new up a Bar but not go something like

```<code>dbset.Add<Bar>(new Bar())
</code>```

Ideally the Bar class is hidden from all other projects. And only my aggregate root Foo can modify this.

Didn't find much information in the docs https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

Body:
I have a model that looks something like this

public sealed class Foo : EntityBase, IAggregateRoot
{
    internal ICollection<Bar> Bars  { get; init; } = new List<Bar>();

    public void AddBars(SomeDto someDto)
    {
        Bars.Add(new(){SomeProperty = someDto.SomeProperty}
    }
}

internal sealed class Bar : EntityBase
{
    internal required string SomeProperty { get; init; }
}

Both these classes exist in my domain layer model project. I am trying to do domain-driven design here.

In my application services layer project, I want to reference the domain project but I only want to be able to new up a Foo and not a Bar.

In my infrastructure project I have wired up EF Core 7 using Fluent API.

Since Bar is internal, I am finding it hard to map this navigational property to a table.

I don't want to expose internals in the infrastructure project.

Should I just make Bar public but not add it to the DbSet. That way people can only new up a Bar but not go something like

dbset.Add<Bar>(new Bar())

Ideally the Bar class is hidden from all other projects. And only my aggregate root Foo can modify this.

Didn't find much information in the docs https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key


问:
Deployed react native app crashes when downloaded from google play store
I just deployed my first react native app to the google play store but the app crashes when i install it from the store.

I have tried multiple options to trace where the issues is coming from and i still don’t have an idea what could be causing it.

The app works fine when i run on a simulator or real device and when i build .apk from the expo server it also works fine without crash.

So i think maybe the issue is with the .aab version that was uploaded to the store. Please i really need your help. Thanks in advance.

Below is the crash report from google play console

```<code>Exception java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{bb9e4f0 u0a190 RCVR bg:+2m7s706ms idle change:uncached procs:4 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4035)
at android.app.ActivityThread.access$1400 (ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1924)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:223)
at android.app.ActivityThread.main (ActivityThread.java:7664)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{bb9e4f0 u0a190 RCVR bg:+2m7s706ms idle change:uncached procs:4 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1715)
at android.app.ContextImpl.startService (ContextImpl.java:1670)
at android.content.ContextWrapper.startService (ContextWrapper.java:720)
at alj.a (PG:2)
at alm.a (PG:3)
at wnv.a (PG:2)
at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive (PG:6)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4026)
</code>```

Body:
I just deployed my first react native app to the google play store but the app crashes when i install it from the store.

I have tried multiple options to trace where the issues is coming from and i still don’t have an idea what could be causing it.

The app works fine when i run on a simulator or real device and when i build .apk from the expo server it also works fine without crash.

So i think maybe the issue is with the .aab version that was uploaded to the store. Please i really need your help. Thanks in advance.

Below is the crash report from google play console

Exception java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{bb9e4f0 u0a190 RCVR bg:+2m7s706ms idle change:uncached procs:4 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4035)
at android.app.ActivityThread.access$1400 (ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1924)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:223)
at android.app.ActivityThread.main (ActivityThread.java:7664)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{bb9e4f0 u0a190 RCVR bg:+2m7s706ms idle change:uncached procs:4 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1715)
at android.app.ContextImpl.startService (ContextImpl.java:1670)
at android.content.ContextWrapper.startService (ContextWrapper.java:720)
at alj.a (PG:2)
at alm.a (PG:3)
at wnv.a (PG:2)
at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive (PG:6)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4026)


问:
Get data from another html page using curl but access denied error show?
a Another website i want to extract price so im using curl fetch the price from that website but error shown is
Access Denied
You don't have permission to access "http://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html" on this server.

Please Help me

Here the error.

```<code>
<br><br>============================================================ Website URL =================================================================<br><br>https://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html<br><br>============================================================ Header Details =====================================================================<br><br>Array
(
    [0] => HTTP/1.0 403 Forbidden
    [1] => Server: AkamaiGHost
    [2] => Mime-Version: 1.0
    [3] => Content-Type: text/html
    [4] => Content-Length: 331
    [5] => Cache-Control: max-age=0
    [6] => Expires: Sat, 17 Dec 2022 08:34:31 GMT
    [7] => Date: Sat, 17 Dec 2022 08:34:31 GMT
    [8] => Connection: close
    [9] => Cache-Control: no-transform
    [10] => Vary: User-Agent
)
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>

You don't have permission to access "http://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html" on this server.<P>
Reference #18.8ba02417.1671266071.612b49b2
</BODY>
</HTML>
<br><br>============================================================ Match the Content =======================================================================<br><br>
</code>```

And here my Curl Code

```<code> function file_url_contents($url){

            $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
            'Cookie: PHPSESSID=b01acff1177dc0a9608718b711e4297b'
            ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            echo $response;
            } //file_url_contents ENDS
</code>```

Body:
a Another website i want to extract price so im using curl fetch the price from that website but error shown is
Access Denied
You don't have permission to access "http://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html" on this server.

Please Help me

Here the error.

============================================================ Website URL =================================================================

https://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html

============================================================ Header Details =====================================================================

Array
(
    [0] => HTTP/1.0 403 Forbidden
    [1] => Server: AkamaiGHost
    [2] => Mime-Version: 1.0
    [3] => Content-Type: text/html
    [4] => Content-Length: 331
    [5] => Cache-Control: max-age=0
    [6] => Expires: Sat, 17 Dec 2022 08:34:31 GMT
    [7] => Date: Sat, 17 Dec 2022 08:34:31 GMT
    [8] => Connection: close
    [9] => Cache-Control: no-transform
    [10] => Vary: User-Agent
)

<TITLE>Access Denied</TITLE>

Access Denied

You don't have permission to access "http://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html" on this server.

Reference #18.8ba02417.1671266071.612b49b2

============================================================ Match the Content =======================================================================

And here my Curl Code

 function file_url_contents($url){

            $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://www.goodreturns.in/petrol-price-in-andaman-nicobar-s1.html',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
            'Cookie: PHPSESSID=b01acff1177dc0a9608718b711e4297b'
            ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            echo $response;
            } //file_url_contents ENDS


问:
How open new Chrome tab in already working browser by GOlang?
I understand that this needs to be done through the w32 parameter lib, but how to correctly open a tab in an already running Google Chrome?</p>


问:
Google wont give me the code for google authenticator app to secure my account
Here is the issue. When I go to my google account on my computer. I go to setup 2FA. Now for some reason, I'm already logged into my account on my computer. Now it's asking me to login onto my phone. I should be able to get a 2FA code from my computer to put into my google authenticator. I would have to log out of my computer account. What's the point of having to login into my google account from my computer. If it asks me to login into my phone. I'm confused.

I want to get my code to protect my google account. And then on my smart phone that I don't have it connected to the internet. I want to add that code to the authenticator so I can use 2FA to protect my account. Am I doing something wrong here? Or is google making this extra complicated? The google authenticator says to Scan a QR code or Enter a setup key. I know it seems I should be posting this issue some where else, but I'm not getting a support there. And I know you guys use phones a lot and have experience with phones. Do you have this issue with google authenticator? Because the google authenticator app itself doesn't say anything about signing in. In the first place. It just says Setup your first account. And if I'm logged into my computer on google. Why have that option if they don't want you to do it from there in the first place. And there google authenticator says nothing about logging in.

And I'm sorry for posting this here if it's a bad place to post. I have been searching for a while to fix this issue. I even posted on the google community. Reddit is also not working correctly were they don't let me post in the right community. They tell me to post else where. Where it's all a mess and not under the right topic. So I have been not getting and finding an answer to what is going on here.

```<code>When I researched the issue I found something about back up codes.

 I get to this part

    At the top, tap Security.

    Under "Signing in to Google," tap 2-Step Verification. You may need to sign in.

    Under "Backup codes," tap Continue .

There is no backup codes options. I even go to more option, and there is no back up codes option. I'm assuming I'm going to get a backup code on my desktop computer to enter into my google authenticator. But I'm not finding it? What is going on here? Is there a way to get that code?

</code>```

Body:
Here is the issue. When I go to my google account on my computer. I go to setup 2FA. Now for some reason, I'm already logged into my account on my computer. Now it's asking me to login onto my phone. I should be able to get a 2FA code from my computer to put into my google authenticator. I would have to log out of my computer account. What's the point of having to login into my google account from my computer. If it asks me to login into my phone. I'm confused.

I want to get my code to protect my google account. And then on my smart phone that I don't have it connected to the internet. I want to add that code to the authenticator so I can use 2FA to protect my account. Am I doing something wrong here? Or is google making this extra complicated? The google authenticator says to Scan a QR code or Enter a setup key. I know it seems I should be posting this issue some where else, but I'm not getting a support there. And I know you guys use phones a lot and have experience with phones. Do you have this issue with google authenticator? Because the google authenticator app itself doesn't say anything about signing in. In the first place. It just says Setup your first account. And if I'm logged into my computer on google. Why have that option if they don't want you to do it from there in the first place. And there google authenticator says nothing about logging in.

And I'm sorry for posting this here if it's a bad place to post. I have been searching for a while to fix this issue. I even posted on the google community. Reddit is also not working correctly were they don't let me post in the right community. They tell me to post else where. Where it's all a mess and not under the right topic. So I have been not getting and finding an answer to what is going on here.

When I researched the issue I found something about back up codes.

 I get to this part

    At the top, tap Security.

    Under "Signing in to Google," tap 2-Step Verification. You may need to sign in.

    Under "Backup codes," tap Continue .

There is no backup codes options. I even go to more option, and there is no back up codes option. I'm assuming I'm going to get a backup code on my desktop computer to enter into my google authenticator. But I'm not finding it? What is going on here? Is there a way to get that code?


问:
android studio unresolved reference
I try to run my app and get this errors

e: /Users/idanfadlon/Desktop/Law-Tech-App/app/src/main/java/com/example/law_tech_app/fragments/BaseFragment.kt: (11, 24): Unresolved reference: synthetic
2.e: /Users/idanfadlon/Desktop/Law-Tech-App/app/src/main/java/com/example/law_tech_app/fragments/BaseFragment.kt: (19, 25): Unresolved reference: tv_progress_text
3.e: /Users/idanfadlon/Desktop/Law-Tech-App/app/src/main/java/com/example/law_tech_app/fragments/BaseFragment.kt: (19, 42): Variable expected
the problem is in base activity file and I dont touch him

I try to pull project again from my repository

Title: android studio unresolved reference


问:
Can I do a python request using google vpn extension?
I just want to get my location using python.requests by retrieving the content of this website 'http://ipinfo.io/json'.

I planned to get the website content using google vpn extension (hola vpn) by using coockies. BUT I can't get the content of this website while using google vpn extension due to unknown reason

code:

```<code>import requests
import browser_cookie3

cookies = browser_cookie3.chrome(cookie_file="C:\\Users\\USERNAME\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1\\Network\\Cookies")
response = requests.get('http://ipinfo.io/json', cookies=cookies)
print(response.content)
</code>```

Note: I can do it by using selenium but I want another way to do it

Body:
I just want to get my location using python.requests by retrieving the content of this website 'http://ipinfo.io/json'.

I planned to get the website content using google vpn extension (hola vpn) by using coockies. BUT I can't get the content of this website while using google vpn extension due to unknown reason

code:

import requests
import browser_cookie3

cookies = browser_cookie3.chrome(cookie_file="C:\\Users\\USERNAME\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1\\Network\\Cookies")
response = requests.get('http://ipinfo.io/json', cookies=cookies)
print(response.content)

Note: I can do it by using selenium but I want another way to do it


问:
How to cause a delay with ReactiveUI.Validation in a ValidationRule
I am doing the following:

this.ValidationRule(vm => vm.UserEntry, this.WhenAnyValue(vm => vm.UserEntry, IsEntryValidOrEmpty).Delay(TimeSpan.FromSeconds(5)), "Invalid entry.")

Expecting this

but the Delay() acts almost like a Throttle() - causing each change in validation status (true/false) to be delayed 5 seconds.

I would expect that the observable sequence would only be shifted once at the start by 5 seconds as this is how Delay() is supposed to work as I understand it.

but getting this

What I'd really like to do in the end is actually to introduce a 5 second delay between the first and second element of the sequence, not before the the first, but that's the next step.

this is what I really want

I have tried various variations on the the theme, but they all behave as if the sequence is restarted between each change in validation status. There's definitely something I'm not getting here.


问:
Chainlink callback protection
How do i make sure the callback function of a call to a chainlink node isn't called by anyone else?

I understand I need to make it public so the node can call it back but I want to protect it from anyone else calling it?

I have tried making it private but then it can't be called by the node

Title: Chainlink callback protection


问:
How to implement cross-account RBAC using Cognito User groups and API Gateway?
I have 2 AWS accounts.The Front end along with cognito is hosted in Account 1 and the backend with the API GW is hosted in Account 2. I want to setup RBAC to prevent the users in the Cognito group  to 'DELETE' API's using cognito groups. I have created a permission policy as below and attached it to a Role and then attached the Role to the Cognito group. I have then created a Authoriser for the API GW in Account 2 using the Cognito user pool available in Account 1 and then attached the Authoriser to the API's Delete Method Request.

Deny Policy, where I have replaced the resource parameters with my account/API details:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "execute-api:Invoke"
            ],
            "Resource": [
               "arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path"
            ]
        }
    ]
}
</code>```

But when I try to delete the API, I am still able to successfully delete it. But I expect to get unauthorised as per the setup. I am able to see the Cognito user group details when I decode the token response, so my guess is the Cognito call is happening properly with API GW, but the Role/Deny Policy attached is not being enforced. Can someone please help me know what I am doing wrong, since this is cross account do I have to do something else with the IAM Role I have attached to the Cognito group or is there a issue with the Policy I am using?

Body:
I have 2 AWS accounts.The Front end along with cognito is hosted in Account 1 and the backend with the API GW is hosted in Account 2. I want to setup RBAC to prevent the users in the Cognito group  to 'DELETE' API's using cognito groups. I have created a permission policy as below and attached it to a Role and then attached the Role to the Cognito group. I have then created a Authoriser for the API GW in Account 2 using the Cognito user pool available in Account 1 and then attached the Authoriser to the API's Delete Method Request.

Deny Policy, where I have replaced the resource parameters with my account/API details:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "execute-api:Invoke"
            ],
            "Resource": [
               "arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path"
            ]
        }
    ]
}

But when I try to delete the API, I am still able to successfully delete it. But I expect to get unauthorised as per the setup. I am able to see the Cognito user group details when I decode the token response, so my guess is the Cognito call is happening properly with API GW, but the Role/Deny Policy attached is not being enforced. Can someone please help me know what I am doing wrong, since this is cross account do I have to do something else with the IAM Role I have attached to the Cognito group or is there a issue with the Policy I am using?


问:
I want to fetch data from firebase realtime database as i have a child with data and that child also have a child with data
This is the database I wants to get all users and check the value inside the enrolled child

as this is how my user's node looks and also I want to check inside all the users

this what I'm doing write now

Constants.databaseReference().child("users")
.addValueEventListener(new ValueEventListener(){
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                UserModel userModel = dataSnapshot.getValue(UserModel.class);
                Log.d("IDS Checl", userModel.isInstructor() + " " + userModel.getName() + " " + userModel.getEnrolled().getUserID());
                if (!userModel.isInstructor()){
                    CourseIDs ids = userModel.getEnrolled();
                    Log.d("IDS Checl", ids.getSellerID() + " " + Constants.auth().getCurrentUser().getUid() + " " + ids.getUserID());
                    if (ids.getSellerID().equals(Constants.auth().getCurrentUser().getUid())) {
                        IDS.add(ids.getUserID());
                        Toast.makeText(context, "IF", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            showTutorChat();
        }
    }
```
<p>the GetEnrolled is a model inside a user model I also try the getChild method but that didn't work.</p>
<p>also I was able to get with the auth ID but that work for single node</p>
<pre class="lang-java prettyprint-override"><code>Constants.databaseReference().child("users").child(Constants.auth().getCurrentUser().getUid())
    .child("enrolled").addValueEventListener(new ValueEventListener() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()){
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    CourseIDs ids = dataSnapshot.getValue(CourseIDs.class);
                    IDS.add(ids.getSellerID());
                }
                showUserChat();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
</code>```

Body:
This is the database I wants to get all users and check the value inside the enrolled child

as this is how my user's node looks and also I want to check inside all the users

this what I'm doing write now

Constants.databaseReference().child("users")
.addValueEventListener(new ValueEventListener(){
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                UserModel userModel = dataSnapshot.getValue(UserModel.class);
                Log.d("IDS Checl", userModel.isInstructor() + " " + userModel.getName() + " " + userModel.getEnrolled().getUserID());
                if (!userModel.isInstructor()){
                    CourseIDs ids = userModel.getEnrolled();
                    Log.d("IDS Checl", ids.getSellerID() + " " + Constants.auth().getCurrentUser().getUid() + " " + ids.getUserID());
                    if (ids.getSellerID().equals(Constants.auth().getCurrentUser().getUid())) {
                        IDS.add(ids.getUserID());
                        Toast.makeText(context, "IF", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            showTutorChat();
        }
    }

the GetEnrolled is a model inside a user model I also try the getChild method but that didn't work.

also I was able to get with the auth ID but that work for single node

Constants.databaseReference().child("users").child(Constants.auth().getCurrentUser().getUid())
    .child("enrolled").addValueEventListener(new ValueEventListener() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()){
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    CourseIDs ids = dataSnapshot.getValue(CourseIDs.class);
                    IDS.add(ids.getSellerID());
                }
                showUserChat();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });


问:
How to create animation splash screen in flutter for desktop application like discord destop?
I want to show a splash screen like discord splash screen  with animation  in flutter  desktop app.  i already used that package  flutter_native_splash  for android and ios app but that package   could not   work in   windows and   mac  application.  so  any  have  idea how too  craete  the  splash screen  for desktop appliction  like desktop discord application


问:
List the folders name inside s3 bucket using aws-sdk in React project
I am creating a ui in react to list folders inside s3 bucket and when I click on specific folder, I will see the list of objects present in that folder.

Currently, I am able to get the list of all objects inside s3 bucket using listsObjectsV2 method of aws-sdk. But first I want to get the list of folder in that bucket.

Below is the code:

import React, { useState, useEffect} from 'react'
import AWS from 'aws-sdk';

const Home = () => {
    AWS.config.update({
      accessKeyId: 'keyId',
      secretAccessKey: 'accessKey',
      s3Url: 'url'
    });

    const s3 = new AWS.S3();

    const params = {
      Bucket: 'bucket name',
      Delimiter: '',
      Prefix: ''`your text`
    };

  const [listFiles, setListFiles] = useState([]);

  useEffect(() => {
    s3.listObjectsV2(params, (err, data) => {
      if (err) {
        console.log(err, err.stack);
      } else {
        setListFiles(data.Contents);
        console.log(data.Contents);
      }
    });
  }, [])

  return (
    <>

        {listFiles &&
          listFiles.map((name, index) => (

              {name.Key}

          ))}

    </>
  )
}

export default Home
```


问:
Block networks ads in Google Adsence via a robot
How do I block networks ads in Google Adsence via a robot? I used this code below and it didn't work:

var toggl;

setInterval(function(){
    toggl=document.querySelector('.all-networks-table div.material-toggle[aria-pressed=false]');
    if (toggl==null){
        document.querySelector('.all-networks-table material-button.next').click()
    }else{
        toggl.click()
    }
}, 100);
```
<p>Screenshot of all add networks</p>
<p>I also tried this code because and it didn't work either:</p>
<pre class="lang-js prettyprint-override"><code>var toggl;

setInterval(function(){
    toggl=document.querySelector('.all-networks-table div.material-toggle[aria-pressed=false]');
    if (toggl==null){
        document.querySelector('.all-networks-table material-button.next').click()
    }else{
        toggl.click()
    }
}, 100);
</code>```

Body:
How do I block networks ads in Google Adsence via a robot? I used this code below and it didn't work:

var toggl;

setInterval(function(){
    toggl=document.querySelector('.all-networks-table div.material-toggle[aria-pressed=false]');
    if (toggl==null){
        document.querySelector('.all-networks-table material-button.next').click()
    }else{
        toggl.click()
    }
}, 100);

Screenshot of all add networks

I also tried this code because and it didn't work either:

var toggl;

setInterval(function(){
    toggl=document.querySelector('.all-networks-table div.material-toggle[aria-pressed=false]');
    if (toggl==null){
        document.querySelector('.all-networks-table material-button.next').click()
    }else{
        toggl.click()
    }
}, 100);