问:
Why is signin in my body2.js file not working properly?
So, I'm able to create an account and to successfully get to the MyAccount page, see who's currently logged in to MyAccount page and log out of the MyAccount page (MyAccount.js).
However, when I try to log in using an email + password by pressing the Sign In button of the Body2.js, I can reach the MyAccount page but can't see who's logged in and I get the "User already Logged In!" error message.

Here's my firebase file:

```<code>// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signOut, signInWithEmailAndPassword } from "firebase/auth";
import { useEffect, useState } from "react";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  projectId: "XXXXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXX",
  messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const auth = getAuth(app);

export function signup(email, password) {
  return createUserWithEmailAndPassword(auth, email, password);
}

export function logout() {
  return signOut(auth);
}

export function login(email, password) {
  return signInWithEmailAndPassword(auth, email, password);
}

// Custom Hook

export function useAuth() {
  const [ currentUser, setCurrentUser ] = useState();
  useEffect(() => {
    const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
    return unsub;
  }, [])
  return currentUser;
}
</code>```

Here's my App.js file:

```<code>import React, { useState } from 'react';
import './App.css';
import Header from './Header';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Menu from './Menu';
import HeaderBlock from './HeaderBlock';

import Header2 from './Header2';
import Body2 from './Body2';
import Footer2 from './Footer2';

import SignUp from './SignUp';
import MyAccount from './MyAccount' ;

function App() {

  const [isMenuOpen, setIsMenuOpen] = useState(false);

  return (

    <Router>
      <div className="app">

        <Switch>

            <Route exact path='/'>

              <Header isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen}/>

              {isMenuOpen && <Menu/>}

              <HeaderBlock />

            </Route>

            <Route exact path='/Login2'>

              <Header2 />

              <Body2 />

              <Footer2 />

            </Route>

            <Route exact path='/signup'>

              <Header2 />

              <SignUp />

              <Footer2 />

            </Route>

            <Route exact path='/MyAccount'>

              <Header2 />

              <MyAccount />

              <Footer2 />

            </Route>

        </Switch>

      </div>
    </Router>

  );
}

export default App;
</code>```

Here's my signup file:

```<code>import './SignUp.css';
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { signup, useAuth } from './firebase';

function SignUp() {

  const history = useHistory();

  const emailRef = useRef();
  const passwordRef = useRef();

  const [ loading, setLoading ] = useState(false);

  const currentUser = useAuth();

  async function handleSignup() {

    setLoading(true);
    try {
        await signup(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("Account already created/Credentials already used");
    }
    setLoading(false);
};

  return (
    <div className='signup'>

        <div className='signup__info'>

                <h1> Account Creation </h1>

                <form className='signup__form'>

                    <label htmlFor='email'> Email Address </label>
                    <input
                        ref={emailRef}
                        placeholder=''
                    />

                    <label htmlFor='email'> Password </label>
                    <input
                        ref={passwordRef}
                        type="password"
                         placeholder=""
                    />

                    <div className='signupblock__actions'>
                        <button
                            className='signupblock__buttonPrimary'
                            disabled={ loading || currentUser }
                            onClick={() => {handleSignup(); history.push('/MyAccount');}}> Register </button>

                            <div className='signupblock__divider'>
                                <hr/> <span> OR </span> <hr/>
                            </div>

                        <button
                             className='signupblock__buttonSecondary'
                             onClick={() => {history.push('/');}}> Home </button>
                    </div>

                </form>

            </div>

    </div>
  );
};

export default SignUp;
</code>```

Here's my Body2.js file:

```<code>import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import './Body2.css';
import { useAuth, login } from './firebase';

function Body2() {

  const history = useHistory()

  const currentUser = useAuth();

  const [ loading, setLoading ] = useState(false);

  const emailRef = useRef();
  const passwordRef = useRef();

  async function handleLogin() {

    setLoading(true);
    try {
        await login(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("User already Logged In!");
    }
    setLoading(false);
};

  return (
    <div className='body2'>

        <div className='login2__info'>

                <h1> Sign In </h1>

                <form className='login2__form'>

                    <label htmlFor='email'> Email Address </label>
                    <input
                        type='email'
                         id='email'
                    />

                    <label htmlFor='email'> Password </label>
                    <input
                        type='password'
                         id='password'

                    />

                    <div className='headerBlock2__actions'>
                        <button
                            className='headerBlock2__buttonPrimary'
                            disabled={ loading || currentUser }
                            onClick={() => {handleLogin(); history.push('/MyAccount');}} > Sign In </button>

                            <div className='login2__divider'>
                                <hr/> <span> OR </span> <hr/>
                            </div>

                        <button
                             className='headerBlock2__buttonSecondary'
                             onClick={() => {history.push('/signup');}}> Create Account </button>
                    </div>

                </form>

            </div>

    </div>
  )
}

export default Body2;
</code>```

Here's my Account.js file:

```<code>import React, { useState } from 'react';
// import app from './firebase';
import './MyAccount.css';
import { logout, useAuth } from './firebase';
import { useHistory } from 'react-router-dom';

function Home() {

  const history = useHistory();

  const currentUser = useAuth();

  const [ loading, setLoading ] = useState(false);

  async function handleLogOut() {
    setLoading(true);
    try {
      await logout();
    }
    catch {
      alert("Couldn't Log Out Effectively");
    }
    setLoading(false);
  }

  return (
    <div>
        <h1> Home </h1>
        <p> What's Up Everyone! </p>

        <h2> Currently logged in as: { currentUser?.email } </h2>
        <button
          disabled={ loading }
          onClick={() => {handleLogOut(); history.push('/');}}> Log Out </button>
    </div>
  );
}

export default Home;
</code>```

I think I'm not resetting the current user value in Body2.js but I'm not sure or don't know how to.

Body:
So, I'm able to create an account and to successfully get to the MyAccount page, see who's currently logged in to MyAccount page and log out of the MyAccount page (MyAccount.js).
However, when I try to log in using an email + password by pressing the Sign In button of the Body2.js, I can reach the MyAccount page but can't see who's logged in and I get the "User already Logged In!" error message.

Here's my firebase file:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signOut, signInWithEmailAndPassword } from "firebase/auth";
import { useEffect, useState } from "react";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  projectId: "XXXXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXX",
  messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const auth = getAuth(app);

export function signup(email, password) {
  return createUserWithEmailAndPassword(auth, email, password);
}

export function logout() {
  return signOut(auth);
}

export function login(email, password) {
  return signInWithEmailAndPassword(auth, email, password);
}

// Custom Hook

export function useAuth() {
  const [ currentUser, setCurrentUser ] = useState();
  useEffect(() => {
    const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
    return unsub;
  }, [])
  return currentUser;
}

Here's my App.js file:

import React, { useState } from 'react';
import './App.css';
import Header from './Header';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Menu from './Menu';
import HeaderBlock from './HeaderBlock';

import Header2 from './Header2';
import Body2 from './Body2';
import Footer2 from './Footer2';

import SignUp from './SignUp';
import MyAccount from './MyAccount' ;

function App() {

  const [isMenuOpen, setIsMenuOpen] = useState(false);

  return (

    <Router>

        <Switch>

            <Route exact path='/'>

              {isMenuOpen && <Menu/>}

              <HeaderBlock />

            </Route>

            <Route exact path='/Login2'>

              <Header2 />

              <Body2 />

              <Footer2 />

            </Route>

            <Route exact path='/signup'>

              <Header2 />

              <SignUp />

              <Footer2 />

            </Route>

            <Route exact path='/MyAccount'>

              <Header2 />

              <MyAccount />

              <Footer2 />

            </Route>

        </Switch>

    </Router>

  );
}

export default App;

Here's my signup file:

import './SignUp.css';
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { signup, useAuth } from './firebase';

function SignUp() {

  const history = useHistory();

  const emailRef = useRef();
  const passwordRef = useRef();

  const [ loading, setLoading ] = useState(false);

  const currentUser = useAuth();

  async function handleSignup() {

    setLoading(true);
    try {
        await signup(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("Account already created/Credentials already used");
    }
    setLoading(false);
};

  return (

 Account Creation

                <form className='signup__form'>

                     Email Address
                    <input
                        ref={emailRef}
                        placeholder=''
                    />

                     Password
                    <input
                        ref={passwordRef}
                        type="password"
                         placeholder=""
                    />

                        <button
                            className='signupblock__buttonPrimary'
                            disabled={ loading || currentUser }
                            onClick={() => {handleSignup(); history.push('/MyAccount');}}> Register </button>

  OR

                        <button
                             className='signupblock__buttonSecondary'
                             onClick={() => {history.push('/');}}> Home </button>

                </form>

  );
};

export default SignUp;

Here's my Body2.js file:

import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import './Body2.css';
import { useAuth, login } from './firebase';

function Body2() {

  const history = useHistory()

  const currentUser = useAuth();

  const [ loading, setLoading ] = useState(false);

  const emailRef = useRef();
  const passwordRef = useRef();

  async function handleLogin() {

    setLoading(true);
    try {
        await login(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("User already Logged In!");
    }
    setLoading(false);
};

  return (

 Sign In

                <form className='login2__form'>

                     Email Address
                    <input
                        type='email'
                         id='email'
                    />

                     Password
                    <input
                        type='password'
                         id='password'

                    />

                        <button
                            className='headerBlock2__buttonPrimary'
                            disabled={ loading || currentUser }
                            onClick={() => {handleLogin(); history.push('/MyAccount');}} > Sign In </button>

  OR

                        <button
                             className='headerBlock2__buttonSecondary'
                             onClick={() => {history.push('/signup');}}> Create Account </button>

                </form>

  )
}

export default Body2;

Here's my Account.js file:

import React, { useState } from 'react';
// import app from './firebase';
import './MyAccount.css';
import { logout, useAuth } from './firebase';
import { useHistory } from 'react-router-dom';

function Home() {

  const history = useHistory();

  const currentUser = useAuth();

  const [ loading, setLoading ] = useState(false);

  async function handleLogOut() {
    setLoading(true);
    try {
      await logout();
    }
    catch {
      alert("Couldn't Log Out Effectively");
    }
    setLoading(false);
  }

  return (

 Home

 What's Up Everyone!

 Currently logged in as: { currentUser?.email }

        <button
          disabled={ loading }
          onClick={() => {handleLogOut(); history.push('/');}}> Log Out </button>

  );
}

export default Home;

I think I'm not resetting the current user value in Body2.js but I'm not sure or don't know how to.


来源: stackexchange

问:
can't connect django rest api with flutter and it always show connect refused
```<code>async{
     try {
           var url = Uri.parse("http://127.0.0.1:8000/todoget/");
           var response = await http.get(url,);
           print(response.statusCode.toString());
         }
      catch (e)
      {
        print(e.toString());
      }
</code>```

I want to connect Django API to flutter using the flutter dependency http.

ContentLicense: CC BY-SA 4.0

Body:
async{
     try {
           var url = Uri.parse("http://127.0.0.1:8000/todoget/");
           var response = await http.get(url,);
           print(response.statusCode.toString());
         }
      catch (e)
      {
        print(e.toString());
      }

I want to connect Django API to flutter using the flutter dependency http.


问:
Routing cannot map action parameters correctly
I have this in RouteConfig.cs file:

```<code>        routes.MapRoute(
            name: "PreSeleccion",
            url: "{controller}/{action}/{month}/{id}",
            defaults: new { controller = "Menu", action = "PreSeleccion" }
        );
</code>```

On the other hand, I have this in the Menu controller:

```<code>    // GET: Menu/PreSeleccion/{month}/{id}
    [HttpGet]
    [AllowAnonymous]
    public async Task<ActionResult> PreSeleccion(int month = 0, int id = 0)
    {

    }
</code>```

When calling that action with this URL: /Menu/PreSeleccion/202301/80 and debug, I can see that month parameter is 0 and the id parameter is 202301.

How can I fix this?

Body:
I have this in RouteConfig.cs file:

        routes.MapRoute(
            name: "PreSeleccion",
            url: "{controller}/{action}/{month}/{id}",
            defaults: new { controller = "Menu", action = "PreSeleccion" }
        );

On the other hand, I have this in the Menu controller:

    // GET: Menu/PreSeleccion/{month}/{id}
    [HttpGet]
    [AllowAnonymous]
    public async Task<ActionResult> PreSeleccion(int month = 0, int id = 0)
    {

    }

When calling that action with this URL: /Menu/PreSeleccion/202301/80 and debug, I can see that month parameter is 0 and the id parameter is 202301.

How can I fix this?


问:
How to include also folder in tsc output directory
Here is my project structure.

```<code> - routes
   - index.tsx
 - package.json
 - tsconfig.json

</code>```

I'm using tsc to build my project tsc is outputting files fine but it's not adding index.js in the routes folder.

here is my typescript config:-

```<code>{
  "compilerOptions": {
    /* Language and Environment */
    "target": "ES2022",                        /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "experimentalDecorators": true,            /* Enable experimental support for TC39 stage 2 draft decorators. */
    /* Modules */
    "module": "CommonJS",                      /* Specify what module code is generated. */
    "moduleResolution":"node",
    "outDir": ".randoms",                      /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                   /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,  /* Ensure that casing is correct in imports. */
    "strict": true,                            /* Enable all strict type-checking options. */
    "skipLibCheck": true                       /* Skip type checking all .d.ts files. */,
    "baseUrl": ".",                            /* base directory path */
    "paths": {  "@/*": ["./*"]  }              /* path alias */
  },
  "include": ["."],
  "exclude": ["node_modules", "**/*.spec.ts"]
  // "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  // "exclude": ["node_modules"],
}
</code>```

how can i make typescript compiler so it also add routes folder to output directory.

Body:
Here is my project structure.

 - routes
   - index.tsx
 - package.json
 - tsconfig.json

I'm using tsc to build my project tsc is outputting files fine but it's not adding index.js in the routes folder.

here is my typescript config:-

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "ES2022",                        /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "experimentalDecorators": true,            /* Enable experimental support for TC39 stage 2 draft decorators. */
    /* Modules */
    "module": "CommonJS",                      /* Specify what module code is generated. */
    "moduleResolution":"node",
    "outDir": ".randoms",                      /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                   /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,  /* Ensure that casing is correct in imports. */
    "strict": true,                            /* Enable all strict type-checking options. */
    "skipLibCheck": true                       /* Skip type checking all .d.ts files. */,
    "baseUrl": ".",                            /* base directory path */
    "paths": {  "@/*": ["./*"]  }              /* path alias */
  },
  "include": ["."],
  "exclude": ["node_modules", "**/*.spec.ts"]
  // "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  // "exclude": ["node_modules"],
}

how can i make typescript compiler so it also add routes folder to output directory.


问:
discord.js reaction check not working v14.7.1
i have this code, when i write the command !classes i get the embed and the 2 reactions but when i check a reaction nothing i happening i dont know whats wrong i tried lookin everywhere, my reaction isnt even getting cancled. im using replit and discord.js version 14.7.1 please help me.

```<code>const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.MessageContent,
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => {
  // Check if the message starts with the command prefix
  if (message.content.startsWith('!classes')) {
    // Create the embed
    const embed = new EmbedBuilder()
      .setTitle('Classes')
      .addFields(
        { name: 'Class 1', value: 'Description of Class 1' },
        { name: 'Class 2', value: 'Description of Class 2' }
      );

    // Send the embed to the same channel
    message.channel.send({ content: 'Here are the available classes:', embeds: [embed] }).then
      (async sentMessage => {
        // Add reactions to the message
        await sentMessage.react('');
        await sentMessage.react('');

        // Wait for a reaction to be added
        const filter = (reaction, user) => ['', ''].includes(reaction.emoji.name) && user.id === message.author.id;

        const collected = await sentMessage.awaitReactions(filter, { max: 1 });
        const reaction = collected.first();

        try {
          // Check which class was selected
          if (reaction.emoji.name === '') {
            // Class 1 was selected
            // Send a message asking for homework and due date
            message.channel.send('Please enter your homework for Class 1:');

            // Wait for a response
            const homeworkFilter = m => m.author.id === message.author.id;
            const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
            const homework = homeworkMessage.first().content;

            message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

            // Wait for a response
            const dateFilter = m => m.author.id === message.author.id;
            const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
            const dueDate = dateMessage.first().content;

            // Send the homework and due date to a different channel
            const homeworkChannel = client.channels.cache.get('CHANNEL ID');
            homeworkChannel.send(`Homework for Class 1: ${homework}\nDue date: ${dueDate}`);
          } else if (reaction.emoji.name === '') {
            // Class 2 was selected
            // Send a message asking for homework and due date
            message.channel.send('Please enter your homework for Class 2:');

            // Wait for a response
            const homeworkFilter = m => m.author.id === message.author.id;
            const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
            const homework = homeworkMessage.first().content;

            message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

            // Wait for a response
            const dateFilter = m => m.author.id === message.author.id;
            const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
            const dueDate = dateMessage.first().content;

            // Send the homework and due date to a different channel
            const homeworkChannel = client.channels.cache.get('CHANNEL ID');
            homeworkChannel.send(`Homework for Class 2: ${homework}\nDue date: ${dueDate}`);
          } else {
            // Invalid reaction was added
            message.channel.send('Invalid reaction added. Please try again.');
          }
        } catch (error) {
          console.error(error);
        }
      }
      )
  }
});

client.login('TOKEN');

</code>```

i tried looking for an answer but nothing helps

Body:
i have this code, when i write the command !classes i get the embed and the 2 reactions but when i check a reaction nothing i happening i dont know whats wrong i tried lookin everywhere, my reaction isnt even getting cancled. im using replit and discord.js version 14.7.1 please help me.

const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.MessageContent,
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => {
  // Check if the message starts with the command prefix
  if (message.content.startsWith('!classes')) {
    // Create the embed
    const embed = new EmbedBuilder()
      .setTitle('Classes')
      .addFields(
        { name: 'Class 1', value: 'Description of Class 1' },
        { name: 'Class 2', value: 'Description of Class 2' }
      );

    // Send the embed to the same channel
    message.channel.send({ content: 'Here are the available classes:', embeds: [embed] }).then
      (async sentMessage => {
        // Add reactions to the message
        await sentMessage.react('');
        await sentMessage.react('');

        // Wait for a reaction to be added
        const filter = (reaction, user) => ['', ''].includes(reaction.emoji.name) && user.id === message.author.id;

        const collected = await sentMessage.awaitReactions(filter, { max: 1 });
        const reaction = collected.first();

        try {
          // Check which class was selected
          if (reaction.emoji.name === '') {
            // Class 1 was selected
            // Send a message asking for homework and due date
            message.channel.send('Please enter your homework for Class 1:');

            // Wait for a response
            const homeworkFilter = m => m.author.id === message.author.id;
            const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
            const homework = homeworkMessage.first().content;

            message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

            // Wait for a response
            const dateFilter = m => m.author.id === message.author.id;
            const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
            const dueDate = dateMessage.first().content;

            // Send the homework and due date to a different channel
            const homeworkChannel = client.channels.cache.get('CHANNEL ID');
            homeworkChannel.send(`Homework for Class 1: ${homework}\nDue date: ${dueDate}`);
          } else if (reaction.emoji.name === '') {
            // Class 2 was selected
            // Send a message asking for homework and due date
            message.channel.send('Please enter your homework for Class 2:');

            // Wait for a response
            const homeworkFilter = m => m.author.id === message.author.id;
            const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
            const homework = homeworkMessage.first().content;

            message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

            // Wait for a response
            const dateFilter = m => m.author.id === message.author.id;
            const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
            const dueDate = dateMessage.first().content;

            // Send the homework and due date to a different channel
            const homeworkChannel = client.channels.cache.get('CHANNEL ID');
            homeworkChannel.send(`Homework for Class 2: ${homework}\nDue date: ${dueDate}`);
          } else {
            // Invalid reaction was added
            message.channel.send('Invalid reaction added. Please try again.');
          }
        } catch (error) {
          console.error(error);
        }
      }
      )
  }
});

client.login('TOKEN');

i tried looking for an answer but nothing helps


问:
How to Rename a column that is "Int64Index([0], dtype='int64')"?
Im trying to scrape this website for nfl standings: https://www.espn.com/nfl/standings

My end goal is to combine the red and the blue part in the picture.

for the red part: I'm trying to  make a list of tables for each of the afc's:

```<code>import pandas as pd
from bs4 import BeautifulSoup
import requests

url = 'https://www.espn.com/nfl/standings'
result = requests.get(url)
soup = BeautifulSoup(result.text, 'html.parser')
names_table = soup.find_all('table', {'class':'Table Table--align-right Table--fixed Table--fixed-left'})
names_database = pd.read_html(str(names_table[0]))[0]
database = pd.read_html(str(names_table[1]))[0]
names_database.index += 1

list_of_names = []
for i in range(5,len(names_database)+1,5):
    list_of_names.append(names_database.iloc[i-5:i])

for i in list_of_names:
    print(i)

print('\nColumns in table = ', list_of_names[0].columns)
</code>```

My output:

```<code>                        0
1                AFC East
2    x --BUFBuffalo Bills
3       MIAMiami Dolphins
4  NENew England Patriots
5        NYJNew York Jets
                            0
6                   AFC North
7   x --CINCincinnati Bengals
8         BALBaltimore Ravens
9         CLECleveland Browns
10     PITPittsburgh Steelers
                            0
11                  AFC South
12        TENTennessee Titans
13    JAXJacksonville Jaguars
14  e --INDIndianapolis Colts
15      e --HOUHouston Texans
                           0
16                  AFC West
17  z --KCKansas City Chiefs
18   LACLos Angeles Chargers
19       LVLas Vegas Raiders
20     e --DENDenver Broncos

Columns in table =  Int64Index([0], dtype='int64')
</code>```

I would like to remove the zero on top of each table and replace it with the first column. The afc columns.

I have tried the replace function. with the columns specified as 0 and '0' however it did not work

Body:
Im trying to scrape this website for nfl standings: https://www.espn.com/nfl/standings

My end goal is to combine the red and the blue part in the picture.

for the red part: I'm trying to  make a list of tables for each of the afc's:

import pandas as pd
from bs4 import BeautifulSoup
import requests

url = 'https://www.espn.com/nfl/standings'
result = requests.get(url)
soup = BeautifulSoup(result.text, 'html.parser')
names_table = soup.find_all('table', {'class':'Table Table--align-right Table--fixed Table--fixed-left'})
names_database = pd.read_html(str(names_table[0]))[0]
database = pd.read_html(str(names_table[1]))[0]
names_database.index += 1

list_of_names = []
for i in range(5,len(names_database)+1,5):
    list_of_names.append(names_database.iloc[i-5:i])

for i in list_of_names:
    print(i)

print('\nColumns in table = ', list_of_names[0].columns)

My output:

                        0
1                AFC East
2    x --BUFBuffalo Bills
3       MIAMiami Dolphins
4  NENew England Patriots
5        NYJNew York Jets
                            0
6                   AFC North
7   x --CINCincinnati Bengals
8         BALBaltimore Ravens
9         CLECleveland Browns
10     PITPittsburgh Steelers
                            0
11                  AFC South
12        TENTennessee Titans
13    JAXJacksonville Jaguars
14  e --INDIndianapolis Colts
15      e --HOUHouston Texans
                           0
16                  AFC West
17  z --KCKansas City Chiefs
18   LACLos Angeles Chargers
19       LVLas Vegas Raiders
20     e --DENDenver Broncos

Columns in table =  Int64Index([0], dtype='int64')

I would like to remove the zero on top of each table and replace it with the first column. The afc columns.

I have tried the replace function. with the columns specified as 0 and '0' however it did not work


问:
Is there any way to customize Google Play services Leaderboard on Android(Kotlin)?
I'm wondering if there is a way to customize the Default leaderboard UI of Google Play.

Can we for example get a list of users and all attributes (Score, ID, name, icon, etc...) and make our own UI with Google Play game service leaderboard?

Thank you!


问:
R markdown not returning anything from code chunk
Revisiting an issue that appears to have been asked before, but the answers aren't quite helping with the issue I'm experiencing.

I have the below in the YAML portion of my R Markdown document:

```<code>---
title: "Gambling"
output: html_document
date: "2022-12-22"
params:
  data: "spreadspoke_scores"
---
</code>```

I then add the code chunk below to try to display the column names of the dataframe identified above.

```<code>```{r params$data}
colnames(params$data)
```
</code>```

However, when I knit the file, I get the below result:

```<code>## NULL
</code>```

I'm not understanding what needs to be done to get the document to pull back results.  I can't find an answer anywhere on here, or on the internet in general, on what I'm missing.

Body:
Revisiting an issue that appears to have been asked before, but the answers aren't quite helping with the issue I'm experiencing.

I have the below in the YAML portion of my R Markdown document:

---
title: "Gambling"
output: html_document
date: "2022-12-22"
params:
  data: "spreadspoke_scores"
---

I then add the code chunk below to try to display the column names of the dataframe identified above.

```{r params$data}
colnames(params$data)
```

However, when I knit the file, I get the below result:

## NULL

I'm not understanding what needs to be done to get the document to pull back results.  I can't find an answer anywhere on here, or on the internet in general, on what I'm missing.


问:
How to make particle loop in python/pygame?
I am trying to do when a player tuches a wall particles are shown and then after around 1 second then stop appearing and they delete. For now when I tuch the wall they dissaper after 1 second but just visualy they dont delete because when I tuck the wall 2nd time they appear again on whole screen. I want them to explode for a sec and then after some seconds delete.

This is my code for particles:

```<code>class Particle:
    def __init__(self):
        self.particles = []
        self.surface = pygame.image.load('white_rect.png')
        self.width = self.surface.get_rect().width
        self.height = self.surface.get_rect().height
        self.particle_time = pygame.time.get_ticks()
        self.start = True
        self.draw = False

    def emit(self):

        if self.particles and self.start:
            self.delete_particles()
            self.draw = True
            self.start = False

        if self.draw:
            for particle in self.particles:
                particle[3] -= 0.2
                particle[0].x += particle[1]
                particle[0].y += particle[2]
                if player.banish:
                    screen.blit(self.surface, particle[0])

    def add_particles(self):
        pos_x = player.x
        pos_y = player.y - 5
        direction_x = random.randint(-1, 3)
        direction_y = random.randint(0, 3)
        if particle_draw_three:
            direction_x = random.randint(-1, 3)
            direction_y = random.randint(0, 3)
        life_time = random.randint(2, 5)
        particle_rect = pygame.Rect(pos_x, pos_y, self.width, self.height)
        self.particles.append([particle_rect, direction_x, direction_y, life_time])

    def delete_particles(self):
        particles_copy = [particle for particle in self.particles if particle[3] > 0]
        self.particles = particles_copy
</code>```

This is code that detects when player is touching the wall and run particles. I just don't know how to make this because its a loop and even if I turn it off it will go on because of loop

```<code>if player.y <= 255:
    if not did_it:
        particle1.draw = True

    particle_timer = pygame.time.get_ticks()

    if particle_timer - current_time_down > 1000:
        player.banish = False
        did_it = True

    particle_draw_three = True
    move_up = False
elif player.y > 255:
    player.banish = True
    particle_draw_three = False
    move_up = True
    did_it = False

player.update()
player.die()
player.death_particles()
particle1.emit()
fps.tick(60)
pygame.display.update()

</code>```

Body:
I am trying to do when a player tuches a wall particles are shown and then after around 1 second then stop appearing and they delete. For now when I tuch the wall they dissaper after 1 second but just visualy they dont delete because when I tuck the wall 2nd time they appear again on whole screen. I want them to explode for a sec and then after some seconds delete.

This is my code for particles:

class Particle:
    def __init__(self):
        self.particles = []
        self.surface = pygame.image.load('white_rect.png')
        self.width = self.surface.get_rect().width
        self.height = self.surface.get_rect().height
        self.particle_time = pygame.time.get_ticks()
        self.start = True
        self.draw = False

    def emit(self):

        if self.particles and self.start:
            self.delete_particles()
            self.draw = True
            self.start = False

        if self.draw:
            for particle in self.particles:
                particle[3] -= 0.2
                particle[0].x += particle[1]
                particle[0].y += particle[2]
                if player.banish:
                    screen.blit(self.surface, particle[0])

    def add_particles(self):
        pos_x = player.x
        pos_y = player.y - 5
        direction_x = random.randint(-1, 3)
        direction_y = random.randint(0, 3)
        if particle_draw_three:
            direction_x = random.randint(-1, 3)
            direction_y = random.randint(0, 3)
        life_time = random.randint(2, 5)
        particle_rect = pygame.Rect(pos_x, pos_y, self.width, self.height)
        self.particles.append([particle_rect, direction_x, direction_y, life_time])

    def delete_particles(self):
        particles_copy = [particle for particle in self.particles if particle[3] > 0]
        self.particles = particles_copy

This is code that detects when player is touching the wall and run particles. I just don't know how to make this because its a loop and even if I turn it off it will go on because of loop

if player.y <= 255:
    if not did_it:
        particle1.draw = True

    particle_timer = pygame.time.get_ticks()

    if particle_timer - current_time_down > 1000:
        player.banish = False
        did_it = True

    particle_draw_three = True
    move_up = False
elif player.y > 255:
    player.banish = True
    particle_draw_three = False
    move_up = True
    did_it = False

player.update()
player.die()
player.death_particles()
particle1.emit()
fps.tick(60)
pygame.display.update()


问:
Pushing Monday data to Google Sheets via Zapier

I have a CRM board in Monday.com which has contact details for my suppliers. I would like to create a Zapp that pushes the data of this CRM to a Google Sheets file. After the initial push, I want it to always be in sync so if any new items are created in the CRM or existing ones updated, Google Sheets rows update to reflect this.

How can I do this? In the below, I am not sure which accomplishes first A) the initial push of all the data in the board (given that the Google Sheet is empty now) and then B) the continual update + sync.

.

I can find lots of material online on pushing data from Gsheets to Monday but not as much for the vice versa.


问:
error 1292 on my website. I don't know where to correct it
I have deleted all the files from my site www.alquilaenpehuen.com to renew the page. Create a new database and import the content (tables) then I uploaded all the files through filezilla, but I can't access the website from any device, although I can access the backend. It is developed in Joomla 4.

On localhost the site works great.

The error it shows is "error 1292" and Hostinger tells me that it is a MySQL problem. But I don't know where to correct it. I will appreciate advice.

My server's version of MySQL on localhost is newer than my hosting provider's.

On localhost the site works fine, but the hosting provider versions cannot be changed.

I don't know where to make modifications so that the site works on the Internet.


问:
add subdomain for node.js application in DirectAdmin
On my VPS I host several laravel applications.
Subdomains are added using DirectAdmin and VirtualHost settings are done using the DirectAdmin Httpd.conf customization, like:

```<code>|*if SUB="cluego"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/cluego/public|
|*endif|

|*if SUB="ijsbrekerz"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/ijsbrekerz/public|
|*endif|
</code>```

Now I want to add the subdomain for qruzzle:

```<code>|*if SUB="qruzzle"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/qruzzle|
|*endif|
</code>```

But qruzzle is a node.js application, and in the qruzzle directory a server.js is running on port 3000.

Can anyone tell me how I can configure this in the easiest way? Do I need to set up a reverse proxy? Is that possible using DirectAdmin?

Body:
On my VPS I host several laravel applications.
Subdomains are added using DirectAdmin and VirtualHost settings are done using the DirectAdmin Httpd.conf customization, like:

|*if SUB="cluego"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/cluego/public|
|*endif|

|*if SUB="ijsbrekerz"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/ijsbrekerz/public|
|*endif|

Now I want to add the subdomain for qruzzle:

|*if SUB="qruzzle"|
|?DOCROOT=/home/admin/domains/netwerkspel.nl/public_html/qruzzle|
|*endif|

But qruzzle is a node.js application, and in the qruzzle directory a server.js is running on port 3000.

Can anyone tell me how I can configure this in the easiest way? Do I need to set up a reverse proxy? Is that possible using DirectAdmin?


问:
React native RN Camera crachs onTextRecognized
I am trying to get(read) text in image. Fot this I am using "react-native-camera": "^4.2.1",

Whenever I open camera it works fine. But when I add this line into code App craches without any log

```<code> onTextRecognized={({textBlocks})=>{console.log("textBlocks===", textBlocks)}}
</code>```

Body:
I am trying to get(read) text in image. Fot this I am using "react-native-camera": "^4.2.1",

Whenever I open camera it works fine. But when I add this line into code App craches without any log

 onTextRecognized={({textBlocks})=>{console.log("textBlocks===", textBlocks)}}


问:
Need to include .pdf files only while searching by partial file name in PowerShell
I have multiple PDF files example TK4156-10093411.pdf and I need to be able to search by only a part of the name like 4156 and inlcude .pdf files only.</p>
```<code># Set the path to the folder you want to search
$folderPath = "C:\temp"

# Search the folder for the PDF file
$pdfFile = Get-ChildItem -Path $folderPath -Filter $fileName -Include '*.pdf' -Recurse

# Check if the PDF file was found
if ($pdfFile)
{
    # PDF file was found, so open it in Adobe Reader
    Start-Process -FilePath "C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe" -ArgumentList $pdfFile.FullName
}
else
{
    # PDF file was not found
    Write-Output "PDF file not found"
}
</code>```

Body:
I have multiple PDF files example TK4156-10093411.pdf and I need to be able to search by only a part of the name like 4156 and inlcude .pdf files only.

# Set the path to the folder you want to search
$folderPath = "C:\temp"

# Search the folder for the PDF file
$pdfFile = Get-ChildItem -Path $folderPath -Filter $fileName -Include '*.pdf' -Recurse

# Check if the PDF file was found
if ($pdfFile)
{
    # PDF file was found, so open it in Adobe Reader
    Start-Process -FilePath "C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe" -ArgumentList $pdfFile.FullName
}
else
{
    # PDF file was not found
    Write-Output "PDF file not found"
}


问:
How to do cursor pagination for front-end?
I'm making a file manager and using the api provided by aws s3, but the response here is the cursor paging function, it's pretty bad that Fb clearly returns the next key and the back key here.  then only provide key next and I had to handle key back manually....

And the problem is that as far as I know large data pages like AMZ or Fb will use cursor pagination.  So is there any way for me to calculate the total number of pages to display the buttons 1 2 3... like this?

Hope I will get help from those who have had the same problem as me, thanks


问:
How can i get my args.field from my activity to my viewmodel
I want to use my args.breweryName from my reviewActivity in my reviewViewModel but i don't know what's the best way to do it. I have tried using savestatehandle but i'm not experienced with that. I'm new to programming with kotlin so i would appreciate the help!

My ReviewActivity

```<code>class ReviewActivity : AppCompatActivity() {
    val breweryText: TextView
    get() = findViewById(R.id.breweryName)
    private val args: ReviewActivityArgs by navArgs<ReviewActivityArgs>()
    private var shownFragment: Fragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_review)
        initView()

        if (savedInstanceState == null) {
            showFragment(ReviewFragment.newInstance())
        }
        breweryText.text = args.breweryName
    }

    fun test(): String {
        return args.breweryName
    }

    private fun initView() {
        val button : FloatingActionButton = findViewById(R.id.add)
        showFragment(ReviewFragment.newInstance())
        button.setOnClickListener { showSaveDialog() }
    }

    private fun showFragment(fragment: Fragment) {
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragmentHolder, fragment)
        fragmentTransaction.commitNow()
        shownFragment = fragment
    }

    private fun showSaveDialog() {
        val dialogFragment: DialogFragment
        val tag: String
        dialogFragment = ReviewDialog.newInstance(null, null, args.breweryName)
        tag = ReviewDialog.TAG_DIALOG_REVIEW_SAVE

        dialogFragment.show(supportFragmentManager, tag)
    }
</code>```

My ReviewViewModel

```<code>
class ReviewViewModel constructor(application: Application) : AndroidViewModel(application) {

    private val reviewDao: ReviewDao = ReviewsDatabase.getDatabase(application).reviewDao()
    private val userDao: UserDao = ReviewsDatabase.getDatabase(application).userDao()
    val data = MutableLiveData<String>()
    val reviewList: LiveData<List<Review>>
    val userList: LiveData<List<User>>
    fun data(item: String) {
        data.value = item
    }
    init {
        reviewList = reviewDao.allReviews
        userList = userDao.allUsers
    }

    fun insert(vararg reviews: Review) {
        reviewDao.insert(*reviews)
    }

    fun update(review: Review) {
        reviewDao.update(review)
    }

    fun deleteAll() {
        reviewDao.deleteAll()
    }
}
</code>```

Body:
I want to use my args.breweryName from my reviewActivity in my reviewViewModel but i don't know what's the best way to do it. I have tried using savestatehandle but i'm not experienced with that. I'm new to programming with kotlin so i would appreciate the help!

My ReviewActivity

class ReviewActivity : AppCompatActivity() {
    val breweryText: TextView
    get() = findViewById(R.id.breweryName)
    private val args: ReviewActivityArgs by navArgs<ReviewActivityArgs>()
    private var shownFragment: Fragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_review)
        initView()

        if (savedInstanceState == null) {
            showFragment(ReviewFragment.newInstance())
        }
        breweryText.text = args.breweryName
    }

    fun test(): String {
        return args.breweryName
    }

    private fun initView() {
        val button : FloatingActionButton = findViewById(R.id.add)
        showFragment(ReviewFragment.newInstance())
        button.setOnClickListener { showSaveDialog() }
    }

    private fun showFragment(fragment: Fragment) {
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragmentHolder, fragment)
        fragmentTransaction.commitNow()
        shownFragment = fragment
    }

    private fun showSaveDialog() {
        val dialogFragment: DialogFragment
        val tag: String
        dialogFragment = ReviewDialog.newInstance(null, null, args.breweryName)
        tag = ReviewDialog.TAG_DIALOG_REVIEW_SAVE

        dialogFragment.show(supportFragmentManager, tag)
    }

My ReviewViewModel

class ReviewViewModel constructor(application: Application) : AndroidViewModel(application) {

    private val reviewDao: ReviewDao = ReviewsDatabase.getDatabase(application).reviewDao()
    private val userDao: UserDao = ReviewsDatabase.getDatabase(application).userDao()
    val data = MutableLiveData<String>()
    val reviewList: LiveData<List<Review>>
    val userList: LiveData<List<User>>
    fun data(item: String) {
        data.value = item
    }
    init {
        reviewList = reviewDao.allReviews
        userList = userDao.allUsers
    }

    fun insert(vararg reviews: Review) {
        reviewDao.insert(*reviews)
    }

    fun update(review: Review) {
        reviewDao.update(review)
    }

    fun deleteAll() {
        reviewDao.deleteAll()
    }
}


问:
Grafana 9.3.1 version rollbacked my legacy alert rule configurations
I have recently upgraded my grafana image(helm chart) version 8.2.7 -> 9.3.1, After upgrade I noticed my existing alerts rules are missing

According to my analysis new version replaced the legacy alert configuration, So rollback the legacy alerting I tried following configuration in grafana.ini, but still my alert rules are missing

```<code>grafana.ini:
  alerting:
    enabled: true
  unified_alerting
    enabled: false
</code>```

Reference

https://grafana.com/docs/grafana-cloud/alerting/migrating-alerts/roll-back/
https://github.com/grafana/helm-charts/issues/1464

Could anyone please advise me on this

Body:
I have recently upgraded my grafana image(helm chart) version 8.2.7 -> 9.3.1, After upgrade I noticed my existing alerts rules are missing

According to my analysis new version replaced the legacy alert configuration, So rollback the legacy alerting I tried following configuration in grafana.ini, but still my alert rules are missing

grafana.ini:
  alerting:
    enabled: true
  unified_alerting
    enabled: false

Reference

https://grafana.com/docs/grafana-cloud/alerting/migrating-alerts/roll-back/
https://github.com/grafana/helm-charts/issues/1464

Could anyone please advise me on this