问:
cin in a while loop not working as expected
I am a new cpp learner and currently trying the std iostream library. I am working on a program that takes number as input and output the number, and exit when enter 0. Also I want the program can ignore the invalid input, output an error message when encounter an invalid input and continue reading the number until I enter 0 to exit. Below is the code I wrote:

```<code>while (true) {
        cout << "Please input value" << endl;
        cin >> value;
        if (cin.fail()) {
            cerr << "Invalid input" << endl;
        } else if (value == 0) {
            cout << "Exit with 0";
            break;
        } else {
            cout << "You have entered " << value << endl;
        }
    }
</code>```

The code does not work as I expected. When I input normal number and it worked well, output each number until I entered 0:

```<code>Please input value
1
You have entered 1
Please input value
2
You have entered 2
Please input value
0
Exit with 0
</code>```

However when I entered something not a number, then the cin won't work in the next while loop and repeatedly output the error message:

```<code>Please input value
a
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
more lines
</code>```

I assume that when a cin fail, it will not read another number in the next loop. I was wondering how can I "reactivate" the cin to make it read number even it failed previously.

Any help is appreciated.

Body:
I am a new cpp learner and currently trying the std iostream library. I am working on a program that takes number as input and output the number, and exit when enter 0. Also I want the program can ignore the invalid input, output an error message when encounter an invalid input and continue reading the number until I enter 0 to exit. Below is the code I wrote:

while (true) {
        cout << "Please input value" << endl;
        cin >> value;
        if (cin.fail()) {
            cerr << "Invalid input" << endl;
        } else if (value == 0) {
            cout << "Exit with 0";
            break;
        } else {
            cout << "You have entered " << value << endl;
        }
    }

The code does not work as I expected. When I input normal number and it worked well, output each number until I entered 0:

Please input value
1
You have entered 1
Please input value
2
You have entered 2
Please input value
0
Exit with 0

However when I entered something not a number, then the cin won't work in the next while loop and repeatedly output the error message:

Please input value
a
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
Invalid input
Please input value
more lines

I assume that when a cin fail, it will not read another number in the next loop. I was wondering how can I "reactivate" the cin to make it read number even it failed previously.

Any help is appreciated.


来源: stackexchange

问:
Storybook installation Error : Cannot find module 'core-js/modules/es.array.concat.js'
I ran the command :

npx storybook init

```<code>node:internal/modules/cjs/loader:998
     throw err;
      ^

Error: Cannot find module 'core-js/modules/es.array.concat.js'
    Require stack:
</code>```

My node version:
v18.12.1

I tried with https://github.com/nodejs/help/issues/1846, but still doesn't work

ContentLicense: CC BY-SA 4.0

Body:
I ran the command :

npx storybook init

node:internal/modules/cjs/loader:998
     throw err;
      ^

Error: Cannot find module 'core-js/modules/es.array.concat.js'
    Require stack:

My node version:
v18.12.1

I tried with https://github.com/nodejs/help/issues/1846, but still doesn't work


问:
How can I identify a video resolution with javascript
Once a video is uploaded to a html file input field, how could I identify the video resolution with javascript? 360p, 720p, 1080p, or 4K.</p>


问:
How do I render a second window in Electron / Angular after building it with Electron Forge?
I'm trying to build my Electron / Angular project using Electron Forge or Electron Builder (tried both).  The app uses two BrowserWindows both being rendered from the Angular Routing components.
After doing a build the second window no longer renders.

I have two windows running in DEV mode by using the code:

```<code>    mainWindow.loadURL('http://localhost:4200');
    secondWindow.loadURL('http://localhost:4200/window2');
</code>```

which works as expected.   Using the Angular server that is running, the app-routing would open index.html and route the mainWindow to the home component.   Window2 would open index.html and be routed to the window2Component.  Works great.

But after using Electron Forge and/or Electron Builder.. window2 no longer renders the window2Component.

The code for initializing the BrowserWindows without the Angular Server is this:

```<code>mainWindow.loadFile('dist/index.html');
const secondWindowPath = path.join(__dirname, 'src/window2.html');
secondWindow.loadURL(secondWindowPath);
</code>```

Electron is able to find the index.html and render the home component.  But the secondWindow cannot find either the router path or the window2.html path.

What is the best way to render an Angular component to a second window in Electron and Electron-Forge?

Body:
I'm trying to build my Electron / Angular project using Electron Forge or Electron Builder (tried both).  The app uses two BrowserWindows both being rendered from the Angular Routing components.
After doing a build the second window no longer renders.

I have two windows running in DEV mode by using the code:

    mainWindow.loadURL('http://localhost:4200');
    secondWindow.loadURL('http://localhost:4200/window2');

which works as expected.   Using the Angular server that is running, the app-routing would open index.html and route the mainWindow to the home component.   Window2 would open index.html and be routed to the window2Component.  Works great.

But after using Electron Forge and/or Electron Builder.. window2 no longer renders the window2Component.

The code for initializing the BrowserWindows without the Angular Server is this:

mainWindow.loadFile('dist/index.html');
const secondWindowPath = path.join(__dirname, 'src/window2.html');
secondWindow.loadURL(secondWindowPath);

Electron is able to find the index.html and render the home component.  But the secondWindow cannot find either the router path or the window2.html path.

What is the best way to render an Angular component to a second window in Electron and Electron-Forge?


问:
there is no message or log in console when executing the command discord.py
I come with a problem that I can't solve despite several attempts, and when I enter the .balance or .work command, there is no message and error log in the console.

main.py:

```<code>import discord
from discord.ext import commands
from webserver import keep_alive
import json
import os

os.chdir("/home/runner/exidexi")

intents = discord.Intents.all()

client = commands.Bot(command_prefix=".", intents=intents, case_insensitive=True)
client.remove_command('help')

@client.event
async def on_ready():
  await client.change_presence(activity=discord.Game('.pomoc'))
  print("Bot is currently online!")

@client.event
async def setup_hook():
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
      await client.load_extension(f'cogs.{filename[:-3]}')
      print(f"Loaded Cog: {filename[:-3]}")
    else:
      print("Unable to load pycache folder.")

keep_alive()
token = os.environ.get("discord_bot_secret")
client.run(token)
</code>```

economy.py:

```<code>import discord
from discord.ext import commands
import datetime
import random
import json
import os

class balance(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.Cog.listener()
  async def on_ready(self):
      print("economy.py is ready!")

  @commands.command()
  async def balance(self, ctx):
      await open_account(ctx.author)

      users = await get_bank_data()
      user = ctx.author

      wallet_amt = users[str(user.id)]["wallet"]
      bank_amt = users[str(user.id)]["bank"]

      embed = discord.Embed(title = f"{ctx.author.name}'s balance",color = discord.Color.red())
      embed.add_field(name = "Wallet balance",value = wallet_amt)
      embed.add_field(name = "Bank balance",value = bank_amt)
      await ctx.reply(embed = embed)

  @commands.command()
  async def work(self, ctx):
      await open_account(ctx.author)

      users = await get_bank_data()
      user = ctx.author

      earnings = random.randrange(101)
      await ctx.reply(f"Someone gave you {earnings} coins!!")

      users[str(user.id)]["wallet"] += earnings

      with open("mainbank.json","w") as f:
          json.dump(users,f)

  async def open_account(user):

      users = await get_bank_data()
      user = ctx.author

      if str(user.id) in users:
          return False
      else:
          users[str(user.id)] = {}
          users[str(user.id)]["wallet"] = 0
          users[str(user.id)]["bank"] = 0

      with open("mainbank.json","w") as f:
          json.dump(users,f)
      return True

  async def get_bank_data():
      with open("mainbank.json","r") as f:
          users = json.load(f)

      return users

async def setup(client):
  await client.add_cog(economy(client))
</code>```

in mainbank.json:

```<code>{

}
</code>```

I saw similar questions, but there was at least one error, but i dont have at least one. However, I tried to do as written, but nothing helped. I also tried removing await and async with open_account and get_bank_data but it didnt help.

Body:
I come with a problem that I can't solve despite several attempts, and when I enter the .balance or .work command, there is no message and error log in the console.

main.py:

import discord
from discord.ext import commands
from webserver import keep_alive
import json
import os

os.chdir("/home/runner/exidexi")

intents = discord.Intents.all()

client = commands.Bot(command_prefix=".", intents=intents, case_insensitive=True)
client.remove_command('help')

@client.event
async def on_ready():
  await client.change_presence(activity=discord.Game('.pomoc'))
  print("Bot is currently online!")

@client.event
async def setup_hook():
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
      await client.load_extension(f'cogs.{filename[:-3]}')
      print(f"Loaded Cog: {filename[:-3]}")
    else:
      print("Unable to load pycache folder.")

keep_alive()
token = os.environ.get("discord_bot_secret")
client.run(token)

economy.py:

import discord
from discord.ext import commands
import datetime
import random
import json
import os

class balance(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.Cog.listener()
  async def on_ready(self):
      print("economy.py is ready!")

  @commands.command()
  async def balance(self, ctx):
      await open_account(ctx.author)

      users = await get_bank_data()
      user = ctx.author

      wallet_amt = users[str(user.id)]["wallet"]
      bank_amt = users[str(user.id)]["bank"]

      embed = discord.Embed(title = f"{ctx.author.name}'s balance",color = discord.Color.red())
      embed.add_field(name = "Wallet balance",value = wallet_amt)
      embed.add_field(name = "Bank balance",value = bank_amt)
      await ctx.reply(embed = embed)

  @commands.command()
  async def work(self, ctx):
      await open_account(ctx.author)

      users = await get_bank_data()
      user = ctx.author

      earnings = random.randrange(101)
      await ctx.reply(f"Someone gave you {earnings} coins!!")

      users[str(user.id)]["wallet"] += earnings

      with open("mainbank.json","w") as f:
          json.dump(users,f)

  async def open_account(user):

      users = await get_bank_data()
      user = ctx.author

      if str(user.id) in users:
          return False
      else:
          users[str(user.id)] = {}
          users[str(user.id)]["wallet"] = 0
          users[str(user.id)]["bank"] = 0

      with open("mainbank.json","w") as f:
          json.dump(users,f)
      return True

  async def get_bank_data():
      with open("mainbank.json","r") as f:
          users = json.load(f)

      return users

async def setup(client):
  await client.add_cog(economy(client))

in mainbank.json:

{

}

I saw similar questions, but there was at least one error, but i dont have at least one. However, I tried to do as written, but nothing helped. I also tried removing await and async with open_account and get_bank_data but it didnt help.


问:
Manipulate the DOM with function argument
My goal is for this code to convert the ".textContent" argument to a method. instead its a string.

`const displayMessage = function (selector, method, message) {
document.querySelector(selector) + method + '=' + message;
};

displayMessage('p', '.textContent', 'Hello World');`


问:
New to React testing!! Getting an error in a simple React testing while using Redux
I'm just trying to learn/get a simple test to pass, so I can move onto some more advance testing.
I am trying to test if the heading in AddTodo matches the screen.getByText test.
It keeps throwing an error at line 7 the dispatch variable.

This is my AddTodo component

```<code>import { useState } from "react";
import { useDispatch } from "react-redux";
import { addTodoAsync } from "../redux/todoSlice";

const AddTodo = () => {
const [value, setValue] = useState("");
const dispatch = useDispatch();

const onSubmit = (event) => {
event.preventDefault();
dispatch(
  addTodoAsync({
  title: value,
 })
 );
  setValue("");
};

 return (
    <>
<heading>Add Todo</heading>
<div className="task-container">
  <input
  type="text"
  placeholder="Add Todo"
  value={value}
  onChange={(event) => setValue(event.target.value)}
  />
  <button onClick={onSubmit}>Add Todo</button>
</div>
</>
)
</code>```

}

This is my testing code

```<code>import{ render, screen } from '@testing-library/react';
import AddTodo from './AddTodo';

test('if heading should render Add Todo', () => {
  render(<AddTodo />);
  const headingElement = screen.getByText('Add Todo');
  expect(headingElement).toBeInTheDocument();
});

This is the error I'm getting.

 ● if heading should render Add Todo

   could not find react-redux context value; please ensure the component is wrapped in a <Provider>

     5 | const AddTodo = () => {
     6 |   const [value, setValue] = useState("");
  >  7 |   const dispatch = useDispatch();
       |                    ^
     8 |
     9 |   const onSubmit = (event) => {
    10 |     event.preventDefault();
</code>```

Body:
I'm just trying to learn/get a simple test to pass, so I can move onto some more advance testing.
I am trying to test if the heading in AddTodo matches the screen.getByText test.
It keeps throwing an error at line 7 the dispatch variable.

This is my AddTodo component

import { useState } from "react";
import { useDispatch } from "react-redux";
import { addTodoAsync } from "../redux/todoSlice";

const AddTodo = () => {
const [value, setValue] = useState("");
const dispatch = useDispatch();

const onSubmit = (event) => {
event.preventDefault();
dispatch(
  addTodoAsync({
  title: value,
 })
 );
  setValue("");
};

 return (
    <>
<heading>Add Todo</heading>

  <input
  type="text"
  placeholder="Add Todo"
  value={value}
  onChange={(event) => setValue(event.target.value)}
  />
  <button onClick={onSubmit}>Add Todo</button>

</>
)

}

This is my testing code

import{ render, screen } from '@testing-library/react';
import AddTodo from './AddTodo';

test('if heading should render Add Todo', () => {
  render(<AddTodo />);
  const headingElement = screen.getByText('Add Todo');
  expect(headingElement).toBeInTheDocument();
});

This is the error I'm getting.

 ● if heading should render Add Todo

   could not find react-redux context value; please ensure the component is wrapped in a <Provider>

     5 | const AddTodo = () => {
     6 |   const [value, setValue] = useState("");
  >  7 |   const dispatch = useDispatch();
       |                    ^
     8 |
     9 |   const onSubmit = (event) => {
    10 |     event.preventDefault();


问:
React Zustand confirm dialog return value
Just got started with Zustand. Trying to implement a confirm dialog. It is working but i can't get the last bit. I am trying to get a return value if the user declined the dialog, however i am lacking the understanding.

This is what i got so far.
Calling the confirm Dialog:

```<code>confirmDialog("Are you sure?", (userAccepted) => {
              replace(userAccepted)
            })
// I am not able to run code if a user declines the dialog. confirmDialog yields void
function replace(userAccepted: boolean) {
 ...
 }
</code>```

I am struggeling with running code when a user declines the dialog.

This is my store:

```<code>import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, IconButton, Alert } from "@pankod/refine-mui"

import create from "zustand"

type ConfirmDialogStore = {
   message: string
   onSubmit?: (userAccepted: boolean) => void
   close: () => void
}

const useConfirmDialogStore = create<ConfirmDialogStore>((set) => ({
   //states and their default values
   message: "",
   onSubmit: undefined,
   // Updating state via close property (which is a function)
   close: () => set({ onSubmit: undefined }),
}))

export const confirmDialog = (message: string, onSubmit: (userAccepted: boolean) => void) => {
   // Schreibt in den Store
   useConfirmDialogStore.setState({
      message,
      onSubmit,
   })
}

const ConfirmDialog = () => {
   // Liest aus dem Store
   const { message, onSubmit, close } = useConfirmDialogStore()

   // This will be rendered if Boolean(onSubmit) is true / if onSubmit is provided
   return (
      <Dialog
         open={Boolean(onSubmit)}
         onClose={close}
         maxWidth="sm"
         fullWidth
      >
         <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
         >
            <DialogTitle>Bist du Sicher?</DialogTitle>
            <IconButton onClick={close}>{/* <Close /> */}</IconButton>
         </Box>
         <DialogContent>
            <Alert severity="error">{message}</Alert>
         </DialogContent>
         <DialogActions sx={{ padding: (theme) => theme.spacing(2) }}>
            <Button
               color="primary"
               variant="contained"
               onClick={close}
            >
               Cancel
            </Button>
            <Button
               color="secondary"
               variant="contained"
               onClick={() => {
                  if (onSubmit) {
                     onSubmit(true)
                  }
                  close()
               }}
            >
               Confirm
            </Button>
         </DialogActions>
      </Dialog>
   )
}

export default ConfirmDialog
</code>```

Body:
Just got started with Zustand. Trying to implement a confirm dialog. It is working but i can't get the last bit. I am trying to get a return value if the user declined the dialog, however i am lacking the understanding.

This is what i got so far.
Calling the confirm Dialog:

confirmDialog("Are you sure?", (userAccepted) => {
              replace(userAccepted)
            })
// I am not able to run code if a user declines the dialog. confirmDialog yields void
function replace(userAccepted: boolean) {
 ...
 }

I am struggeling with running code when a user declines the dialog.

This is my store:

import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, IconButton, Alert } from "@pankod/refine-mui"

import create from "zustand"

type ConfirmDialogStore = {
   message: string
   onSubmit?: (userAccepted: boolean) => void
   close: () => void
}

const useConfirmDialogStore = create<ConfirmDialogStore>((set) => ({
   //states and their default values
   message: "",
   onSubmit: undefined,
   // Updating state via close property (which is a function)
   close: () => set({ onSubmit: undefined }),
}))

export const confirmDialog = (message: string, onSubmit: (userAccepted: boolean) => void) => {
   // Schreibt in den Store
   useConfirmDialogStore.setState({
      message,
      onSubmit,
   })
}

const ConfirmDialog = () => {
   // Liest aus dem Store
   const { message, onSubmit, close } = useConfirmDialogStore()

   // This will be rendered if Boolean(onSubmit) is true / if onSubmit is provided
   return (
      <Dialog
         open={Boolean(onSubmit)}
         onClose={close}
         maxWidth="sm"
         fullWidth
      >
         <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
         >
            <DialogTitle>Bist du Sicher?</DialogTitle>
            <IconButton onClick={close}>{/* <Close /> */}</IconButton>
         </Box>
         <DialogContent>
            <Alert severity="error">{message}</Alert>
         </DialogContent>
         <DialogActions sx={{ padding: (theme) => theme.spacing(2) }}>
            <Button
               color="primary"
               variant="contained"
               onClick={close}
            >
               Cancel
            </Button>
            <Button
               color="secondary"
               variant="contained"
               onClick={() => {
                  if (onSubmit) {
                     onSubmit(true)
                  }
                  close()
               }}
            >
               Confirm
            </Button>
         </DialogActions>
      </Dialog>
   )
}

export default ConfirmDialog


问:
How to create range variable in DoCPLEX the way I prefer?
Suppose we have two variable x and y, and I want x-y between 0 and 1. So I did this

```<code>x = mdl.continuous_var(0, 1, 'x')
y = mdl.continuous_var(0, 1, 'y')
mdl.add_range(0.0, x - y, 1.0, f'_range_experiment')
</code>```

In the LP file, I can see that this is translated into

```<code>_range_experiment: x - y- Rg_range_experiment = 1
 -1 <= Rg_range_experiment <= 0
</code>```

This seems very strange to me. Totally not what I expected. It is correct, but very unpleasant to read. The desired output should be:

```<code>_range_experiment: x - y- Rg_range_experiment = 0
 0 <= Rg_range_experiment <= 1
</code>```

I am wondering whether I can have some control over the LP file generated? Thanks!

Body:
Suppose we have two variable x and y, and I want x-y between 0 and 1. So I did this

x = mdl.continuous_var(0, 1, 'x')
y = mdl.continuous_var(0, 1, 'y')
mdl.add_range(0.0, x - y, 1.0, f'_range_experiment')

In the LP file, I can see that this is translated into

_range_experiment: x - y- Rg_range_experiment = 1
 -1 <= Rg_range_experiment <= 0

This seems very strange to me. Totally not what I expected. It is correct, but very unpleasant to read. The desired output should be:

_range_experiment: x - y- Rg_range_experiment = 0
 0 <= Rg_range_experiment <= 1

I am wondering whether I can have some control over the LP file generated? Thanks!


问:
Connecting API data array to chartjs in django
I am trying to create a chart using chartjs and this chart is displaying API data(Stock Data). I have made the API successfully and make the data wanted in the form of an array inorder to put it in the chart. When I define the API data array as a variable and use the variable in the chart data it doesn't display anything:

```<code><script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <script>
     const ctx = document.getElementById('myChart');
     let y=new Array();
    let theapi = fetch('api_src')
    .then(response => response.json())
    .then(data => {
        const thewanted = Object.values(data)[1]
        for (const [key, value] of Object.entries(thewanted)) {
  y.push(key);
}
 console.log(y)
    })
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: y,
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
         }]
       }
    ,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }}}});

  </script>
</code>```

if you look at the labels in the chart you will find that I have used the variable as the value of the labels but it doesn't work and whan I console.log the variable I find that it contains the values that I want.

Note: When I closed the pc and opened it again after time I found that it worked but when I refreshed the page or restarted the server it doesn't work

update: the chart data is shown only when I zoom the page in or out and other than that it shows a blank chart.

Body:
I am trying to create a chart using chartjs and this chart is displaying API data(Stock Data). I have made the API successfully and make the data wanted in the form of an array inorder to put it in the chart. When I define the API data array as a variable and use the variable in the chart data it doesn't display anything:

if you look at the labels in the chart you will find that I have used the variable as the value of the labels but it doesn't work and whan I console.log the variable I find that it contains the values that I want.

Note: When I closed the pc and opened it again after time I found that it worked but when I refreshed the page or restarted the server it doesn't work

update: the chart data is shown only when I zoom the page in or out and other than that it shows a blank chart.


问:
sqlalchemy composite key error when cell run twice
My configuration cell contains the following:

```<code>from sqlalchemy import create_engine
import io

def df_to_postgres(dataframe, table_name):

    engine = create_engine('postgresql://postgres:pass@localhost:5432/postgres')
    df=dataframe

    df.head(0).to_sql(table_name.lower(), engine, if_exists='replace', index=False)

    conn = engine.raw_connection()
    cur = conn.cursor()
    output = io.StringIO()
    df.to_csv(output, sep='\t', header=False, index=False)
    output.seek(0)
    contents = output.getvalue()
    cur.copy_expert('COPY ' + table_name + ' FROM STDIN', output)
    conn.commit()
</code>```

and the cell uploading the dataframe has:

```<code>
df_to_postgres(product_table,'final.product')

</code>```

The product_table has a composite key which has been created in postgres. When I run it the 1st time everything is good, when I try the 2nd time I get:

```<code>
UniqueViolation                           Traceback (most recent call last)
<timed eval> in <module>

~\AppData\Local\Temp/ipykernel_8004/2936867318.py in df_to_postgres(dataframe, table_name)
     15     output.seek(0)
     16     contents = output.getvalue()
---> 17     cur.copy_expert('COPY ' + table_name + ' FROM STDIN', output)
     18     conn.commit()

UniqueViolation: duplicate key value violates unique constraint "product_pkey"
DETAIL:  Key (sku, unit)=(000002, kg) already exists.
CONTEXT:  COPY product, line 1

</code>```

I thought that if_exists='replace' would have solved this problem. Any solution?

Body:
My configuration cell contains the following:

from sqlalchemy import create_engine
import io

def df_to_postgres(dataframe, table_name):

    engine = create_engine('postgresql://postgres:pass@localhost:5432/postgres')
    df=dataframe

    df.head(0).to_sql(table_name.lower(), engine, if_exists='replace', index=False)

    conn = engine.raw_connection()
    cur = conn.cursor()
    output = io.StringIO()
    df.to_csv(output, sep='\t', header=False, index=False)
    output.seek(0)
    contents = output.getvalue()
    cur.copy_expert('COPY ' + table_name + ' FROM STDIN', output)
    conn.commit()

and the cell uploading the dataframe has:

df_to_postgres(product_table,'final.product')

The product_table has a composite key which has been created in postgres. When I run it the 1st time everything is good, when I try the 2nd time I get:

UniqueViolation                           Traceback (most recent call last)
<timed eval> in <module>

~\AppData\Local\Temp/ipykernel_8004/2936867318.py in df_to_postgres(dataframe, table_name)
     15     output.seek(0)
     16     contents = output.getvalue()
---> 17     cur.copy_expert('COPY ' + table_name + ' FROM STDIN', output)
     18     conn.commit()

UniqueViolation: duplicate key value violates unique constraint "product_pkey"
DETAIL:  Key (sku, unit)=(000002, kg) already exists.
CONTEXT:  COPY product, line 1

I thought that if_exists='replace' would have solved this problem. Any solution?


问:
Did I overwrite my old version of Jenkins?
My Jenkins is running on CentOS 7 and I was looking to upgrade my Jenkins version 2.277.4 to 2.375.1. I tried using sudo yum update jenkins to update jenkins. I received this message: “Public key for jenkins-2.375.1-1.1.noarch.rpm is not installed”. I read an article telling me to pull the key from online, so I performed these commands:

sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo --no-check-certificate
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum update jenkins

Afterwards, I haven’t been able to correctly start Jenkins. Obviously, I should have just uploaded the new war file instead of using yum update.

Any time I try Sudo systemctl start jenkins I get this warning.
Warning: jenkins.service changed on disk. Run ‘systemctl daemon-reload’ to reload units.

Any suggestions on fixing this issue? Any way to revert back to the old version?

Thank you ahead of time!

**Edit: I tried reloading the daemon and restarting the service. However, my Jenkins start/restart is timing out even though I’ve set the timer to 10 mins.

Additionally, I installed java-11-openjdk during the upgrade, would that cause issues?


问:
What is the correct way in Node.js, running on Linux, to kill a Firefox browser tab spawned with child_process.spawn?
I am spawning a browser like so:

```<code>async function launchBrowser(): Promise<child_process.ChildProcessWithoutNullStreams> {
  let cmd = process.platform === 'darwin' ? 'open' : (process.platform === 'win32' ? 'start' : 'xdg-open');
  return child_process.spawn(
    cmd, [`${process.env.PROTOCOL}://${process.env.HOST}:${process.env.PORT}`]);
}
</code>```

Then using it like this:

```<code>const browser = await launchBrowser();
process.on('SIGINT', () => {
  if (!browser.kill('SIGKILL')) {
    console.log(`Failed to kill browser. Exiting...`);
    process.exit(2);
  } else {
    console.log(`Browser shut down. Exiting...`);
    process.exit(0);
  }
});
</code>```

Output:

```<code>Failed to kill browser. Exiting...
</code>```

I have also tried adding {detached: true} to the spawn command options, and then using:

```<code>process.kill(-browser.id)
</code>```

as suggested in answers to similar questions. But this produces the following:

```<code>Error: kill ESRCH
</code>```

and does not kill the process. How can I kill this browser tab?

Body:
I am spawning a browser like so:

async function launchBrowser(): Promise<child_process.ChildProcessWithoutNullStreams> {
  let cmd = process.platform === 'darwin' ? 'open' : (process.platform === 'win32' ? 'start' : 'xdg-open');
  return child_process.spawn(
    cmd, [`${process.env.PROTOCOL}://${process.env.HOST}:${process.env.PORT}`]);
}

Then using it like this:

const browser = await launchBrowser();
process.on('SIGINT', () => {
  if (!browser.kill('SIGKILL')) {
    console.log(`Failed to kill browser. Exiting...`);
    process.exit(2);
  } else {
    console.log(`Browser shut down. Exiting...`);
    process.exit(0);
  }
});

Output:

Failed to kill browser. Exiting...

I have also tried adding {detached: true} to the spawn command options, and then using:

process.kill(-browser.id)

as suggested in answers to similar questions. But this produces the following:

Error: kill ESRCH

and does not kill the process. How can I kill this browser tab?


问:
How to properly reference my font asset from my npm package?
I have two packages called "library and "nextjs". "library" is a dependency of "nextjs" and is exporting an MUI ThemeProvider component that exports a global @font-face in the CssBaseline component. My @font-face is using a custom .woff font I have included in the package and is being built with parcel.

This custom ThemeProvider wraps everything in the nextjs app.

When I look at the console to see if there are any errors, I see this.

Not allowed to load local resource: file:///project/exporting-assets-example/packages/nextjs/.next/server/pages/raleway-bold.e83afe7e.woff

How do I properly reference my font so I don't get this error?

Here is my codesandbox example.


问:
I can't seem to animate an asteroid impact
I have a project due in a couple days. I have to do a simulation of what would happen during an asteroid impact on earth. I found this short video on youtube:

text

and it shows exactly what I want to do.

I tried doing it myself because the author did not do any tutorial or explain how they did it except for the fact that they used 'flip fluid addon' which I have. I watched countless tutorials but nothing seems to work because no one did it. Tutorials are all on how to do ocean/sea and how to make an object go through a liquid. I need to make it so an object falls into the liquid and the recreates the slap from the Youtube video. Could someone point me to the right direction? It's really important.
Thank you.


问:
Talkback Input date in Android Chrome Jumps to Top After Selecting Date?

Create a simple <input type="date" /> on a page.

Open your web app on an Android device with a Chrome browser (I'm using P7).

Turn on Talkback.

Open date input.

Select a date, and set.

Watch as the focus is now on the top left home button of the browser. It will say "Chrome Home Button Double-tap To Activate ...".

Anyone else experiencing this?

I wanted to just add setTimeout into onChange callback so that it just focuses back to the input itself, but it won't work if user decided to use keyboard input for the date.


问:
Db2 LUW Java SP issue
I am trying to run a Stored Procedure which has registered as an external Java Program to Db2. Whenever I call it, I keep getting the error:

SQL4304N  Java stored procedure or user-defined function
"RSARKAR.CREATE_USER", specific name "CREATE_USER" could not load Java class
"/home/rsarkar/sqllib/function/jar/RSARKAR", reason code "".  SQLSTATE=42724

The db2diag.log is showing the following messages ( with DIAGLEVEL 4 )

2023-01-03-22.10.02.119785+000 I27596E440            LEVEL: Info
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:90
DATA #1 : String, 47 bytes
Exception thrown during class loader loadClass:

2023-01-03-22.10.02.119949+000 I28037E448            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : Class loader loadClass failed. Possible out of memory in JAVA_HEAP_SZ

I've tried with JAVA_HEAP_SZ set to 1,000,000 but still get the same error.

Java Virtual Machine heap size (4KB)     (JAVA_HEAP_SZ) = 1000000

2023-01-03-22.10.02.120041+000 I28486E636            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : PATH to jar is in the form of sqllib/function/jar/.
jar_id:
DATA #1 : Hexdump, 17 bytes
0x00007F372B039C22 : 2252 4453 4442 2020 2022 2E44 4232 4A41    "RSARKAR ".DB2JA
0x00007F372B039C32 : 52                                         R

2023-01-03-22.10.02.120139+000 I29123E871            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : If not using JAR, then common paths are sqllib/function and
sqllib/function/unfenced. Check that you have file .class or this
jar:
DATA #1 : Hexdump, 52 bytes
0x00007F372B03ADA0 : 2F68 6F6D 652F 7264 7364 622F 7371 6C6C    /home/rsarkar/sqll
0x00007F372B03ADB0 : 6962 2F66 756E 6374 696F 6E2F 6A61 722F    ib/function/jar/
0x00007F372B03ADC0 : 5244 5344 422F 4442 324A 4152 2E6A 6172    RSARKAR/DB2JAR.jar
0x00007F372B03ADD0 : 3A44 6232                                  :Db2

2023-01-03-22.10.02.120232+000 I29995E766            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rdsdb                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rdsdb.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:41
MESSAGE : Method missing from the class above:
DATA #1 : Hexdump, 63 bytes
0x00007F372B03ADD5 : 6372 6561 7465 284C 6A61 7661 2F6C 616E    create(Ljava/lan
0x00007F372B03ADE5 : 672F 5374 7269 6E67 3B4C 6A61 7661 2F6C    g/String;Ljava/l
0x00007F372B03ADF5 : 616E 672F 5374 7269 6E67 3B4C 6A61 7661    ang/String;Ljava
0x00007F372B03AE05 : 2F6C 616E 672F 5374 7269 6E67 3B29 56      /lang/String;)V

2023-01-03-22.10.02.122131+000 I32501E843            LEVEL: Info
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, oper system services, sqlofica, probe:10
DATA #1 : SQLCA, PD_DB2_TYPE_SQLCA, 136 bytes
sqlcaid : SQLCA     sqlcabc: 136   sqlcode: -4304   sqlerrml: 70
sqlerrmc: RSARKAR.CREATE_USER CREATE_USER /home/rsarkar/sqllib/function/jar/RSARKAR
sqlerrp : SQLEJEXT
sqlerrd : (1) 0x00000000      (2) 0x00000000      (3) 0x00000000
(4) 0x00000000      (5) 0x00000000      (6) 0x00000000
sqlwarn : (1)      (2)      (3)      (4)        (5)       (6)
(7)      (8)      (9)      (10)        (11)
sqlstate: 42724

The definition of the SP is as follows:

call sqlj.install_jar( 'file:/home/rsarkar/plugins/DB2.jar', 'DB2JAR');
call sqlj.refresh_classes();

CREATE OR REPLACE PROCEDURE RSARKAR.CREATE_USER
(
USERID VARCHAR(128),
PASS   VARCHAR(128) DEFAULT NULL,
GROUPS VARCHAR(256) DEFAULT NULL
)
LANGUAGE JAVA
SPECIFIC RDSADMIN.CREATE_USER
PARAMETER STYLE JAVA
DETERMINISTIC
NO EXTERNAL ACTION
NO SQL
FENCED THREADSAFE
EXTERNAL NAME 'DB2JAR:Db2.create';

I was expecting it to run but it keeps giving me error that it cannot find the method in the class.

I tried with a smaller test with a simple Java program and registered it as follows:

create or replace procedure MYJAVASP (in input char(6))
specific myjavasp
dynamic result sets 0
deterministic
language java
parameter style java
no dbinfo
fenced
threadsafe
modifies sql data
program type sub
external name 'MYJAVASPJAR:MYJAVASP.my_JAVASP';

This one works fine without any issues. Any pointers or ideas are welcome.

```<code>
The definition in Db2.java:

package db2.registry.sql.storedprocedure;

import db2.registry.User;
import db2.registry.UserRegistry;
import org.apache.commons.lang3.StringUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;

import static db2.registry.utils.LineBasedFileUtils.DEFAULT_LOCALUSERS_FILE;

public class Db2 {
    public static void create(String username, String password, String groups) {
        UserRegistry.createUser(username, password, unpackGroups(groups), DEFAULT_LOCALUSERS_FILE);
    }

    public static void delete(String username) {
        UserRegistry.deleteUser(username, DEFAULT_LOCALUSERS_FILE);
    }

    public java.sql.ResultSet list() {
        Collection<User> users = UserRegistry.listUsers(DEFAULT_LOCALUSERS_FILE).values();
        return convertToListCallResultSet(users);
    }

    public static void modify(String username, String password, String groups) {
        UserRegistry.modifyUser(username, password, unpackGroups(groups), DEFAULT_LOCALUSERS_FILE);
    }
}

The create procedure statement:

call sqlj.remove_jar( 'DB2JAR');
call sqlj.install_jar( 'file:/home/rsarkar/plugins/DB2.jar', 'DB2JAR');
call sqlj.refresh_classes();

CREATE OR REPLACE PROCEDURE RSARKAR.CREATE_USER
(
  USERID VARCHAR(128),
  PASS   VARCHAR(128) DEFAULT NULL,
  GROUPS VARCHAR(256) DEFAULT NULL
)
LANGUAGE JAVA
SPECIFIC RSARKAR.CREATE_USER
PARAMETER STYLE JAVA
DETERMINISTIC
NO EXTERNAL ACTION
NO SQL
FENCED THREADSAFE
EXTERNAL NAME 'DB2JAR:Db2.create';

Calling the Stored Procedure:

db2 "call rsarkar.create_user('testuser','xx','DBA')"
</code>```

Title: Db2 LUW Java SP issue

Body:
I am trying to run a Stored Procedure which has registered as an external Java Program to Db2. Whenever I call it, I keep getting the error:

SQL4304N  Java stored procedure or user-defined function
"RSARKAR.CREATE_USER", specific name "CREATE_USER" could not load Java class
"/home/rsarkar/sqllib/function/jar/RSARKAR", reason code "".  SQLSTATE=42724

The db2diag.log is showing the following messages ( with DIAGLEVEL 4 )

2023-01-03-22.10.02.119785+000 I27596E440            LEVEL: Info
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:90
DATA #1 : String, 47 bytes
Exception thrown during class loader loadClass:

2023-01-03-22.10.02.119949+000 I28037E448            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : Class loader loadClass failed. Possible out of memory in JAVA_HEAP_SZ

I've tried with JAVA_HEAP_SZ set to 1,000,000 but still get the same error.

Java Virtual Machine heap size (4KB)     (JAVA_HEAP_SZ) = 1000000

2023-01-03-22.10.02.120041+000 I28486E636            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : PATH to jar is in the form of sqllib/function/jar/.
jar_id:
DATA #1 : Hexdump, 17 bytes
0x00007F372B039C22 : 2252 4453 4442 2020 2022 2E44 4232 4A41    "RSARKAR ".DB2JA
0x00007F372B039C32 : 52                                         R

2023-01-03-22.10.02.120139+000 I29123E871            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:40
MESSAGE : If not using JAR, then common paths are sqllib/function and
sqllib/function/unfenced. Check that you have file .class or this
jar:
DATA #1 : Hexdump, 52 bytes
0x00007F372B03ADA0 : 2F68 6F6D 652F 7264 7364 622F 7371 6C6C    /home/rsarkar/sqll
0x00007F372B03ADB0 : 6962 2F66 756E 6374 696F 6E2F 6A61 722F    ib/function/jar/
0x00007F372B03ADC0 : 5244 5344 422F 4442 324A 4152 2E6A 6172    RSARKAR/DB2JAR.jar
0x00007F372B03ADD0 : 3A44 6232                                  :Db2

2023-01-03-22.10.02.120232+000 I29995E766            LEVEL: Warning
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rdsdb                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rdsdb.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, BSU Java support, sqlejCallJavaRoutine_dll, probe:41
MESSAGE : Method missing from the class above:
DATA #1 : Hexdump, 63 bytes
0x00007F372B03ADD5 : 6372 6561 7465 284C 6A61 7661 2F6C 616E    create(Ljava/lan
0x00007F372B03ADE5 : 672F 5374 7269 6E67 3B4C 6A61 7661 2F6C    g/String;Ljava/l
0x00007F372B03ADF5 : 616E 672F 5374 7269 6E67 3B4C 6A61 7661    ang/String;Ljava
0x00007F372B03AE05 : 2F6C 616E 672F 5374 7269 6E67 3B29 56      /lang/String;)V

2023-01-03-22.10.02.122131+000 I32501E843            LEVEL: Info
PID     : 5363                 TID : 139874111354624 PROC : db2fmp (
INSTANCE: rsarkar                NODE : 000            DB   : SAMPLE
APPID   : *LOCAL.rsarkar.230103220934
HOSTNAME: ip-172-31-20-141.us-west-1.compute.internal
FUNCTION: DB2 UDB, oper system services, sqlofica, probe:10
DATA #1 : SQLCA, PD_DB2_TYPE_SQLCA, 136 bytes
sqlcaid : SQLCA     sqlcabc: 136   sqlcode: -4304   sqlerrml: 70
sqlerrmc: RSARKAR.CREATE_USER CREATE_USER /home/rsarkar/sqllib/function/jar/RSARKAR
sqlerrp : SQLEJEXT
sqlerrd : (1) 0x00000000      (2) 0x00000000      (3) 0x00000000
(4) 0x00000000      (5) 0x00000000      (6) 0x00000000
sqlwarn : (1)      (2)      (3)      (4)        (5)       (6)
(7)      (8)      (9)      (10)        (11)
sqlstate: 42724

The definition of the SP is as follows:

call sqlj.install_jar( 'file:/home/rsarkar/plugins/DB2.jar', 'DB2JAR');
call sqlj.refresh_classes();

CREATE OR REPLACE PROCEDURE RSARKAR.CREATE_USER
(
USERID VARCHAR(128),
PASS   VARCHAR(128) DEFAULT NULL,
GROUPS VARCHAR(256) DEFAULT NULL
)
LANGUAGE JAVA
SPECIFIC RDSADMIN.CREATE_USER
PARAMETER STYLE JAVA
DETERMINISTIC
NO EXTERNAL ACTION
NO SQL
FENCED THREADSAFE
EXTERNAL NAME 'DB2JAR:Db2.create';

I was expecting it to run but it keeps giving me error that it cannot find the method in the class.

I tried with a smaller test with a simple Java program and registered it as follows:

create or replace procedure MYJAVASP (in input char(6))
specific myjavasp
dynamic result sets 0
deterministic
language java
parameter style java
no dbinfo
fenced
threadsafe
modifies sql data
program type sub
external name 'MYJAVASPJAR:MYJAVASP.my_JAVASP';

This one works fine without any issues. Any pointers or ideas are welcome.

The definition in Db2.java:

package db2.registry.sql.storedprocedure;

import db2.registry.User;
import db2.registry.UserRegistry;
import org.apache.commons.lang3.StringUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;

import static db2.registry.utils.LineBasedFileUtils.DEFAULT_LOCALUSERS_FILE;

public class Db2 {
    public static void create(String username, String password, String groups) {
        UserRegistry.createUser(username, password, unpackGroups(groups), DEFAULT_LOCALUSERS_FILE);
    }

    public static void delete(String username) {
        UserRegistry.deleteUser(username, DEFAULT_LOCALUSERS_FILE);
    }

    public java.sql.ResultSet list() {
        Collection<User> users = UserRegistry.listUsers(DEFAULT_LOCALUSERS_FILE).values();
        return convertToListCallResultSet(users);
    }

    public static void modify(String username, String password, String groups) {
        UserRegistry.modifyUser(username, password, unpackGroups(groups), DEFAULT_LOCALUSERS_FILE);
    }
}

The create procedure statement:

call sqlj.remove_jar( 'DB2JAR');
call sqlj.install_jar( 'file:/home/rsarkar/plugins/DB2.jar', 'DB2JAR');
call sqlj.refresh_classes();

CREATE OR REPLACE PROCEDURE RSARKAR.CREATE_USER
(
  USERID VARCHAR(128),
  PASS   VARCHAR(128) DEFAULT NULL,
  GROUPS VARCHAR(256) DEFAULT NULL
)
LANGUAGE JAVA
SPECIFIC RSARKAR.CREATE_USER
PARAMETER STYLE JAVA
DETERMINISTIC
NO EXTERNAL ACTION
NO SQL
FENCED THREADSAFE
EXTERNAL NAME 'DB2JAR:Db2.create';

Calling the Stored Procedure:

db2 "call rsarkar.create_user('testuser','xx','DBA')"


问:
Mirror TextMeshPro text doesn't synchronize on client
I'm trying to get users to see each other's nicknames, but it doesn't work on client.

On server it works fine? but on client texts don't sync. TextMehPro is child of PlayerPrefab

On Client
enter image description here
On Server
enter image description here

This is my network manager

```<code>using Mirror;
using TMPro;

public class NetManager : NetworkManager
{
    private UserController controller;
    public TextMeshPro nickname;

    public override void Start()
    {
        base.Start();
        controller = UserController.Shared;
    }

    private void OnCreateCharacter(NetworkConnectionToClient conn, UserMessage message)
    {
        var go = Instantiate(playerPrefab);
        var user = new User(message);
        var tank = go.GetComponent<TankController>();
        tank.thisNick.text = user.UserName;
        NetworkServer.AddPlayerForConnection(conn, go);
        tank.SetUser(user);
    }

    public override void OnStartServer()
    {
        base.OnStartServer();
        NetworkServer.RegisterHandler<UserMessage>(OnCreateCharacter);
    }

    public override void OnClientConnect()
    {
        base.OnClientConnect();
        ActivatePLayerSpawn();
    }

    private void ActivatePLayerSpawn()
    {
        var user = controller.User;
        var message = new UserMessage(user);
        NetworkClient.Send(message);
    }
}

public struct UserMessage: NetworkMessage
{
    public string Name;
    public int Coins;
    public int Id;
    public UserMessage(User u)
    {
        Name = u.UserName;
        Coins = u.Coins;
        Id = u.Id;
    }
}

</code>```

Body:
I'm trying to get users to see each other's nicknames, but it doesn't work on client.

On server it works fine? but on client texts don't sync. TextMehPro is child of PlayerPrefab

On Client
enter image description here
On Server
enter image description here

This is my network manager

using Mirror;
using TMPro;

public class NetManager : NetworkManager
{
    private UserController controller;
    public TextMeshPro nickname;

    public override void Start()
    {
        base.Start();
        controller = UserController.Shared;
    }

    private void OnCreateCharacter(NetworkConnectionToClient conn, UserMessage message)
    {
        var go = Instantiate(playerPrefab);
        var user = new User(message);
        var tank = go.GetComponent<TankController>();
        tank.thisNick.text = user.UserName;
        NetworkServer.AddPlayerForConnection(conn, go);
        tank.SetUser(user);
    }

    public override void OnStartServer()
    {
        base.OnStartServer();
        NetworkServer.RegisterHandler<UserMessage>(OnCreateCharacter);
    }

    public override void OnClientConnect()
    {
        base.OnClientConnect();
        ActivatePLayerSpawn();
    }

    private void ActivatePLayerSpawn()
    {
        var user = controller.User;
        var message = new UserMessage(user);
        NetworkClient.Send(message);
    }
}

public struct UserMessage: NetworkMessage
{
    public string Name;
    public int Coins;
    public int Id;
    public UserMessage(User u)
    {
        Name = u.UserName;
        Coins = u.Coins;
        Id = u.Id;
    }
}


问:
Python Selenium - No such elemeny: unable to locate element. Don't think it's iframe issue
I was trying to do test on a website and I need to click this button:
click xpath

But when I run the code, it shows No such elemeny: unable to locate element.

I have checked the code, there is no iframe. But interestingly, I can find "Publish to All" through inspect, but cannot find it through "View Page SourceView Page Source"

Here is the context from windows powershell

```<code>
Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[2]/div[2]/div[2]/div[1]/div/form/div/div[8]/div/table/tbody/tr/td[2]/table/tbody/tr[1]/td/div/div[3]/div[2]/div[1]/a"}
  (Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
        (No symbol) [0x00D6F243]
        (No symbol) [0x00CF7FD1]
        (No symbol) [0x00BED04D]
        (No symbol) [0x00C1C0B0]
        (No symbol) [0x00C1C22B]
        (No symbol) [0x00C4E612]
        (No symbol) [0x00C385D4]
        (No symbol) [0x00C4C9EB]
        (No symbol) [0x00C38386]
        (No symbol) [0x00C1163C]
        (No symbol) [0x00C1269D]
GetHandleVerifier [0x01009A22+2655074]
GetHandleVerifier [0x00FFCA24+2601828]
GetHandleVerifier [0x00E18C0A+619850]
GetHandleVerifier [0x00E17830+614768]
        (No symbol) [0x00D005FC]
        (No symbol) [0x00D05968]
        (No symbol) [0x00D05A55]
        (No symbol) [0x00D1051B]
BaseThreadInitThunk [0x774400F9+25]
RtlGetAppContainerNamedObjectPath [0x77C17BBE+286]
RtlGetAppContainerNamedObjectPath [0x77C17B8E+238]
</code>```

And my codes are here:

try:
publish_button = browser.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]/div[2]/div[1]/div/form/div/div[8]/div/table/tbody/tr/td[2]/table/tbody/tr[1]/td/div/div[3]/div[2]/div[1]/a")
publish_button.click()
except Exception as e:
print(e)
print(9999)

browser.quit()

Body:
I was trying to do test on a website and I need to click this button:
click xpath

But when I run the code, it shows No such elemeny: unable to locate element.

I have checked the code, there is no iframe. But interestingly, I can find "Publish to All" through inspect, but cannot find it through "View Page SourceView Page Source"

Here is the context from windows powershell

Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[2]/div[2]/div[2]/div[1]/div/form/div/div[8]/div/table/tbody/tr/td[2]/table/tbody/tr[1]/td/div/div[3]/div[2]/div[1]/a"}
  (Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
        (No symbol) [0x00D6F243]
        (No symbol) [0x00CF7FD1]
        (No symbol) [0x00BED04D]
        (No symbol) [0x00C1C0B0]
        (No symbol) [0x00C1C22B]
        (No symbol) [0x00C4E612]
        (No symbol) [0x00C385D4]
        (No symbol) [0x00C4C9EB]
        (No symbol) [0x00C38386]
        (No symbol) [0x00C1163C]
        (No symbol) [0x00C1269D]
GetHandleVerifier [0x01009A22+2655074]
GetHandleVerifier [0x00FFCA24+2601828]
GetHandleVerifier [0x00E18C0A+619850]
GetHandleVerifier [0x00E17830+614768]
        (No symbol) [0x00D005FC]
        (No symbol) [0x00D05968]
        (No symbol) [0x00D05A55]
        (No symbol) [0x00D1051B]
BaseThreadInitThunk [0x774400F9+25]
RtlGetAppContainerNamedObjectPath [0x77C17BBE+286]
RtlGetAppContainerNamedObjectPath [0x77C17B8E+238]

And my codes are here:

try:
publish_button = browser.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]/div[2]/div[1]/div/form/div/div[8]/div/table/tbody/tr/td[2]/table/tbody/tr[1]/td/div/div[3]/div[2]/div[1]/a")
publish_button.click()
except Exception as e:
print(e)
print(9999)

browser.quit()


问:
DatabaseError: Execution failed on SQL Select
I'm trying to connect my SQL database with Python. I used:

```<code>import pyodbc
import pandas as pd

cnxn_str = ("Driver={SQL Server};"
            "Server=server_name;"
            "Database=database_name;"
            "Trusted_Connection=yes;"
            )
cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()
data = pd.read_sql("select * from dbo.table", cnxn)
</code>```

But I get this error:

DatabaseError: Execution failed on sql Select ... : ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]

Body:
I'm trying to connect my SQL database with Python. I used:

import pyodbc
import pandas as pd

cnxn_str = ("Driver={SQL Server};"
            "Server=server_name;"
            "Database=database_name;"
            "Trusted_Connection=yes;"
            )
cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()
data = pd.read_sql("select * from dbo.table", cnxn)

But I get this error:

DatabaseError: Execution failed on sql Select ... : ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]


问:
Creating an AWS lambda that calls a rest endpoint
I want to create a simple AWS lambda that makes a url request to a rest endpoint. The thing I’m not sure about is I know for lambdas the response size limit is 6mb, and the response that comes back from the rest endpoint I intend to have it call fluctuates and sometimes can go beyond that limit.

I don’t necessarily need to return the response from the rest endpoint that the lambda will make a call to, but rather I feel like I can have the lambda write the contents of the response into a database instead of returning it, and then just return a response code at the end. I was wondering if this workaround will work or will I still have issues with the 6mb size limit on some manner?

Still in the prototyping phase, just a general question that I can elaborate more on if necessary


问:
Use PyWin32 to execute VBA Macro from Python
I have two Excel Files and I can execute Macro ReadBM_AP_Data, but not PythonScript. For this function I used PyWin32 with the Function RunApplication

Here is the Python Code:

```<code>    xl = win32com.client.Dispatch("Excel.Application", pythoncom.CoInitialize())
    #C:\Users\dx5entir\PycharmProjects\pythonProject
    xl.Workbooks.Open("C:/Users/dx5entir/PycharmProjects/pythonProject/FapsXML.xlsm")
    xl.RunApplication("FapsXML.xlsm!Modul1.PythonScript()")
    #xl.Application.Run('ReadEC_DC_Data.xlsm!Modul2.ReadBM_AP_Data()')
    xl.Application.Quit()
</code>```

If I open the Excel File and start PythonScript it works.

This is the Error Messages:

Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\dx5entir\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 205, in run
self.dispatch_events(self.event_queue)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 381, in dispatch_events
handler.dispatch(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\events.py", line 271, in dispatch
self.on_any_event(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 54, in on_any_event
start_xl()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 68, in start_xl
xl.Application.Run("FapsXML.xlsm!Modul1.PythonScript()")
File "<COMObject >", line 8, in Run
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\win32com\client\dynamic.py", line 368, in ApplyTypes
result = self.oleobj.InvokeTypes(
^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_Serror: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft Excel', "Das Makro 'FapsXML.xlsm!Modul1.PythonScript()' kann nicht ausgeführt werden. Das Makro ist möglicherweise in dieser Arbeitsmappe nicht verfügbar, oder alle Makros wurden deaktiviert.", 'xlmain11.chm', 0, -2146827284), None)

I implement a watchdog to trigger this Event, but it still works with the other macro, so I see no problem with that.

Name Excel Sheets:

Name of Module and Sub:

At the beginning my Excel Sheets had spaces. So I fixed that.

I tried other macros and they worked. This macro PythonScript is working when I start it manually in the Excel file.

I called the function per Button and not trigger it with a watchdog event. Same error.

I updated my PythonInterpreter to Python 3.11.1 and updated every Python Packages in my Enviroment

Im confused why this function doesn't work with this macro, when this macro works when i start it manually and other macros works when I use PyWin32. I have no clue to fix that problem. Any advices? :)

Body:
I have two Excel Files and I can execute Macro ReadBM_AP_Data, but not PythonScript. For this function I used PyWin32 with the Function RunApplication

Here is the Python Code:

    xl = win32com.client.Dispatch("Excel.Application", pythoncom.CoInitialize())
    #C:\Users\dx5entir\PycharmProjects\pythonProject
    xl.Workbooks.Open("C:/Users/dx5entir/PycharmProjects/pythonProject/FapsXML.xlsm")
    xl.RunApplication("FapsXML.xlsm!Modul1.PythonScript()")
    #xl.Application.Run('ReadEC_DC_Data.xlsm!Modul2.ReadBM_AP_Data()')
    xl.Application.Quit()

If I open the Excel File and start PythonScript it works.

This is the Error Messages:

Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\dx5entir\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 205, in run
self.dispatch_events(self.event_queue)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 381, in dispatch_events
handler.dispatch(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\events.py", line 271, in dispatch
self.on_any_event(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 54, in on_any_event
start_xl()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 68, in start_xl
xl.Application.Run("FapsXML.xlsm!Modul1.PythonScript()")
File "<COMObject >", line 8, in Run
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\win32com\client\dynamic.py", line 368, in ApplyTypes
result = self.oleobj.InvokeTypes(
^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_Serror: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft Excel', "Das Makro 'FapsXML.xlsm!Modul1.PythonScript()' kann nicht ausgeführt werden. Das Makro ist möglicherweise in dieser Arbeitsmappe nicht verfügbar, oder alle Makros wurden deaktiviert.", 'xlmain11.chm', 0, -2146827284), None)

I implement a watchdog to trigger this Event, but it still works with the other macro, so I see no problem with that.

Name Excel Sheets:

Name of Module and Sub:

At the beginning my Excel Sheets had spaces. So I fixed that.

I tried other macros and they worked. This macro PythonScript is working when I start it manually in the Excel file.

I called the function per Button and not trigger it with a watchdog event. Same error.

I updated my PythonInterpreter to Python 3.11.1 and updated every Python Packages in my Enviroment

Im confused why this function doesn't work with this macro, when this macro works when i start it manually and other macros works when I use PyWin32. I have no clue to fix that problem. Any advices? :)


问:
Object of which I have a working method for is somehow undefined? Javascript app.patch request
Here is the request section of code that is causing the error, I'm making a patch request via Postman and it successfully updates the array of objects that I want

```<code>app.patch('/comments/:id', (req, res) => {

    const { id } = req.params;

    const foundComment = comments.find(c => c.id === id)

    const newCommentText = req.body.comment;

    foundComment.comment = newCommentText;      //THIS LINE IS THE ONE FLARING THE TYPE ERROR
                                                //CANNOT SET PROPERTIES OF UNDEFINED (setting 'comment')
    res.redirect('comments')
})
</code>```

My thought process for how the above code works or I think it should?

app.patch('/comments/:id', (req, res) => { //Defines logic for what should happen when a patch request is
// made @/comments/:id

// Then the ID is taken out of the request object that the user inputs and is stored in a variable id
// Then I created a foundComment variable to store an object taken from an array using the array.find
// method to identify the correct object.

The foundComment.comment = newCommentText is where the type error TypeError: Cannot set properties of undefined (setting 'comment&#39 appears.

Or

TypeError: Cannot set properties of undefined (setting 'comment')

// but as far as I'm aware this should take the comment from form data parsed in (I have done app.use(express.urlencoded({extended: true}) ) and modify this data

the res.redirect was intentional only for when I made an EJS template to fulfil this task on, I understand its use is moot at the moment, I Just cannot fathom how I'm getting the error

This is the array for reference:

```<code>> const comments = [
>     {name: 'Boris',
> comment: 'Hahaha Nice One Dude',
> id: uuidv4()
>     },
>     {name: 'Dan',
> comment: 'That triangle was nuts',
> id: uuidv4()
>     },
>     {name: 'James',
> comment: 'Sorry I broke your knee',
> id: uuidv4()
>     }
> ]
</code>```

I haven't produced a form for it yet as this part of the online course I'm doing doesn't do so

I've narrowed the problem down to being that while the code actually succeeds in making the post request, I seem to be getting the error due to the foundComment.comment line as it states that the method cannot be used as foundComment is undefined, which confuses me as I've defined it prior to be equal to,

```<code>const foundComment = comments.find(c => c.id === id)
</code>```

I thought it might be an issue with comments.find but after using it standalone I can confirm it returns the correct object and stores it in foundComment.

I also console.logged all ids, because my ids are generated using UUID, I print them out everytime I run the code on node so I can confirm that when i'm making a patch request the id for which I'm trying to update does indeed exist!

When I hover over found comment the following shows, I'm not sure why there is | undefined is there but this is as far as I've gotten.

```<code>const foundComment: {
    name: string;
    comment: string;
    id: string;
} | undefined

</code>```

Body:
Here is the request section of code that is causing the error, I'm making a patch request via Postman and it successfully updates the array of objects that I want

app.patch('/comments/:id', (req, res) => {

    const { id } = req.params;

    const foundComment = comments.find(c => c.id === id)

    const newCommentText = req.body.comment;

    foundComment.comment = newCommentText;      //THIS LINE IS THE ONE FLARING THE TYPE ERROR
                                                //CANNOT SET PROPERTIES OF UNDEFINED (setting 'comment')
    res.redirect('comments')
})

My thought process for how the above code works or I think it should?

app.patch('/comments/:id', (req, res) => { //Defines logic for what should happen when a patch request is
// made @/comments/:id

// Then the ID is taken out of the request object that the user inputs and is stored in a variable id
// Then I created a foundComment variable to store an object taken from an array using the array.find
// method to identify the correct object.

The foundComment.comment = newCommentText is where the type error TypeError: Cannot set properties of undefined (setting 'comment&#39 appears.

Or

TypeError: Cannot set properties of undefined (setting 'comment')

// but as far as I'm aware this should take the comment from form data parsed in (I have done app.use(express.urlencoded({extended: true}) ) and modify this data

the res.redirect was intentional only for when I made an EJS template to fulfil this task on, I understand its use is moot at the moment, I Just cannot fathom how I'm getting the error

This is the array for reference:

> const comments = [
>     {name: 'Boris',
> comment: 'Hahaha Nice One Dude',
> id: uuidv4()
>     },
>     {name: 'Dan',
> comment: 'That triangle was nuts',
> id: uuidv4()
>     },
>     {name: 'James',
> comment: 'Sorry I broke your knee',
> id: uuidv4()
>     }
> ]

I haven't produced a form for it yet as this part of the online course I'm doing doesn't do so

I've narrowed the problem down to being that while the code actually succeeds in making the post request, I seem to be getting the error due to the foundComment.comment line as it states that the method cannot be used as foundComment is undefined, which confuses me as I've defined it prior to be equal to,

const foundComment = comments.find(c => c.id === id)

I thought it might be an issue with comments.find but after using it standalone I can confirm it returns the correct object and stores it in foundComment.

I also console.logged all ids, because my ids are generated using UUID, I print them out everytime I run the code on node so I can confirm that when i'm making a patch request the id for which I'm trying to update does indeed exist!

When I hover over found comment the following shows, I'm not sure why there is | undefined is there but this is as far as I've gotten.

const foundComment: {
    name: string;
    comment: string;
    id: string;
} | undefined


问:
Hibernate formula SQL Server: Generated invalid SQL
My XML mapping file is as follows

```<code><property name="lineNo" type="java.lang.Float"
                  update="false" insert="false"
                  formula="(select l.[LineNo] from DLVLPoint l where l.StationID=StationID)"/>
</code>```

The expected SQL statement is：

```<code>SELECT (
  SELECT l.[LineNo] FROM DLVLPoint l WHERE l.StationID=v.StationID)
FROM view_DLVLImage v WHERE v.ProjectID=181
</code>```

However, the SQL automatically generated by hibernate is：

```<code>SELECT (
  SELECT l.v.[LineNo] FROM DLVLPoint l WHERE l.StationID=v.StationID)
FROM view_DLVLImage v WHERE v.ProjectID=181
</code>```

Added alias v before LineNo, Causes invalid SQL statements.
In SQL server database '[]' is required

I tried to wrap l.[LineNo] with upper(), as follows

```<code><property name="lineNo" type="java.lang.Float"
                  update="false" insert="false"
                  formula="(select upper(l.[LineNo]) from DLVLPoint l where l.StationID=StationID)"/>
</code>```

but, it still didn't solve the problem.

Body:
My XML mapping file is as follows

<property name="lineNo" type="java.lang.Float"
                  update="false" insert="false"
                  formula="(select l.[LineNo] from DLVLPoint l where l.StationID=StationID)"/>

The expected SQL statement is：

SELECT (
  SELECT l.[LineNo] FROM DLVLPoint l WHERE l.StationID=v.StationID)
FROM view_DLVLImage v WHERE v.ProjectID=181

However, the SQL automatically generated by hibernate is：

SELECT (
  SELECT l.v.[LineNo] FROM DLVLPoint l WHERE l.StationID=v.StationID)
FROM view_DLVLImage v WHERE v.ProjectID=181

Added alias v before LineNo, Causes invalid SQL statements.
In SQL server database '[]' is required

I tried to wrap l.[LineNo] with upper(), as follows

<property name="lineNo" type="java.lang.Float"
                  update="false" insert="false"
                  formula="(select upper(l.[LineNo]) from DLVLPoint l where l.StationID=StationID)"/>

but, it still didn't solve the problem.


问:
TypeError [ColorConvert]: Unable to convert color to a number
```<code>  client.on('messageCreate', (message) => {
  // Check if the message content starts with '!commandname'.
  if (message.content.startsWith('!dadada')) {
    const Discord = require('discord.js');
    const convert = require('color-convert');

    const [color, ...messageArgs] = message.content.split(' ');
    const messageContent = messageArgs.join(' ');

    // Check if the color variable is a valid HSL color value.
    if (!color || color.split(',').length !== 3) {
      return message.channel.send("Invalid color value. Please provide a valid HSL color in the format 'hue,saturation,lightness'.");
    }

    // Convert the hue value from degrees to a percentage.
    const [hue, saturation, lightness] = color.split(',').map((string, i) => {
      if (i === 0) {
        return parseInt(string, 10) / 360;
      }
      return string;
    });

    const rgbColor = convert.hsl.rgb([hue, saturation, lightness]);

    // Create an embed with the specified color and message.
    const embed = new Discord.EmbedBuilder()
      .setColor(rgbColor)
      .setDescription(messageContent);

    // Send the embed to the channel.
    message.channel.send({ embeds: [embed] });
  }
});

</code>```

I've been struggling for 5 hours and I can't make it :(
I didn't find any solution, do you have any idea?
Command format

!dadada 50,100%,50% text

Body:
  client.on('messageCreate', (message) => {
  // Check if the message content starts with '!commandname'.
  if (message.content.startsWith('!dadada')) {
    const Discord = require('discord.js');
    const convert = require('color-convert');

    const [color, ...messageArgs] = message.content.split(' ');
    const messageContent = messageArgs.join(' ');

    // Check if the color variable is a valid HSL color value.
    if (!color || color.split(',').length !== 3) {
      return message.channel.send("Invalid color value. Please provide a valid HSL color in the format 'hue,saturation,lightness'.");
    }

    // Convert the hue value from degrees to a percentage.
    const [hue, saturation, lightness] = color.split(',').map((string, i) => {
      if (i === 0) {
        return parseInt(string, 10) / 360;
      }
      return string;
    });

    const rgbColor = convert.hsl.rgb([hue, saturation, lightness]);

    // Create an embed with the specified color and message.
    const embed = new Discord.EmbedBuilder()
      .setColor(rgbColor)
      .setDescription(messageContent);

    // Send the embed to the channel.
    message.channel.send({ embeds: [embed] });
  }
});

I've been struggling for 5 hours and I can't make it :(
I didn't find any solution, do you have any idea?
Command format

!dadada 50,100%,50% text


问:
Finding AIC and BIC for GEV using R
How to find the AIC and BIC for GEV after finding its parameter using L-moments?

```<code>#Load data
library(quantmod)
getSymbols(c("BTC-USD","ETH-USD"), from="2020-05-01", to="2022-05-31", src="yahoo", periodicity="daily")

`BTC-USD`$BTC.r<-diff(log(`BTC-USD`$`BTC-USD.Adjusted`))
`BTC-USD`$BTC.r[1]=0

#Converting the xts object to a dataframe and processing dates
`BTC-USD`$Date1<-rownames(`BTC-USD`)
BTC<-data.frame(date=index(`BTC-USD`),coredata(`BTC-USD`))
BTC$date<-as.POSIXct(BTC$date)
BTC$mo<-strftime(BTC$date,"%m")
BTC$yr<-strftime(BTC$date,"%Y")

#Block Maxima - Generalized Extreme Value distribution
library(extRemes)
extrema1<- setDT(BTC)[,.(BTC_down = -min(BTC.r)),by=.(yr,mo)]

# fitting of GEV distribution based on L-moments estimation
fit_lmom_1 <- fevd(as.vector(extrema1$BTC_down), method = "Lmoments", type="GEV")
</code>```

I have find the parameters, but I'm not sure on how to find the AIC and BIC.

Title: Finding AIC and BIC for GEV using R

Body:
How to find the AIC and BIC for GEV after finding its parameter using L-moments?

#Load data
library(quantmod)
getSymbols(c("BTC-USD","ETH-USD"), from="2020-05-01", to="2022-05-31", src="yahoo", periodicity="daily")

`BTC-USD`$BTC.r<-diff(log(`BTC-USD`$`BTC-USD.Adjusted`))
`BTC-USD`$BTC.r[1]=0

#Converting the xts object to a dataframe and processing dates
`BTC-USD`$Date1<-rownames(`BTC-USD`)
BTC<-data.frame(date=index(`BTC-USD`),coredata(`BTC-USD`))
BTC$date<-as.POSIXct(BTC$date)
BTC$mo<-strftime(BTC$date,"%m")
BTC$yr<-strftime(BTC$date,"%Y")

#Block Maxima - Generalized Extreme Value distribution
library(extRemes)
extrema1<- setDT(BTC)[,.(BTC_down = -min(BTC.r)),by=.(yr,mo)]

# fitting of GEV distribution based on L-moments estimation
fit_lmom_1 <- fevd(as.vector(extrema1$BTC_down), method = "Lmoments", type="GEV")

I have find the parameters, but I'm not sure on how to find the AIC and BIC.


问:
Can HTTPS Nodejs read .crt?
I am trying to create https server like this

```<code>https
.createServer(
    {
      key: fs.readFileSync(key),
      cert: fs.readFileSync(cert),
      ca: fs.readFileSync(ca)
    },
    webServer
  )
  .listen(webServerPort, function () {
    console.log("Server Monitor Web Service Running on port: " + webServerPort);
  });
</code>```

However at cert: I'm receiving an error saying

```<code>node:internal/tls/secure-context:65
context.setCert(cert);
Error: error:0909006C:PEM routines:get_name:no start line
</code>```

The cert is referencing to a .crt file

Can HTTPS create servers from .crt?

Is this error thrown because the cert itself is invalid or because of the file extension type?

Thanks

Title: Can HTTPS Nodejs read .crt?

Body:
I am trying to create https server like this

https
.createServer(
    {
      key: fs.readFileSync(key),
      cert: fs.readFileSync(cert),
      ca: fs.readFileSync(ca)
    },
    webServer
  )
  .listen(webServerPort, function () {
    console.log("Server Monitor Web Service Running on port: " + webServerPort);
  });

However at cert: I'm receiving an error saying

node:internal/tls/secure-context:65
context.setCert(cert);
Error: error:0909006C:PEM routines:get_name:no start line

The cert is referencing to a .crt file

Can HTTPS create servers from .crt?

Is this error thrown because the cert itself is invalid or because of the file extension type?

Thanks


问:
Dynamic class names are not allowed in compile-time ::class fetch
```<code>class Model extends Database
{
  function __construct()
  {
    if(property_exists($this, 'table'))
    {
      $this->table = strtolower($this::class) . "s";
    }
  }
</code>```

whats have problem

Body:
class Model extends Database
{
  function __construct()
  {
    if(property_exists($this, 'table'))
    {
      $this->table = strtolower($this::class) . "s";
    }
  }

whats have problem


问:
What are the differences between the console.log extension in Chrome for desktop and for iOS?
I've written a Javascript app and used console.log with format strings to help debug. It works fine on Chrome on Mac desktop. On Chrome for iOS, it logs the format strings instead of the corresponding positional parameters.

What I tried was...
I hunted around the Chrome Developers website on the Formatting console.log messages page here: https://developer.chrome.com/docs/devtools/console/format-style/, and tried out the new YOu.com search engine, but couldn't find the docs that say that console.log works differently on iOS Chrome.

Do I need to re-write my console log messages into the style of "msg1" + "msg2" + ... ?


问:
How do I initialize the "settingscontroller" for the languageSwitch in this Statefulwidget
```<code>Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (kDebugMode) {
    print("Handling a background message: ${message.messageId}");
  }
}

class App extends StatefulWidget {
  const App({Key? key, required this.settingsController})
      : super(key: key);

  final SettingsController settingsController;

  @override
  AppState createState() => AppState();
}

class AppState extends State<App> {
  // Notification
  late final FirebaseMessaging _messaging;
  late int _totalNotifications;
  PushNotification? _notificationInfo;
  // BottomNavigationBar
  int currentPageIndex = 0;

  Widget _appBar() {
    return Stack(
      children: <Widget>[
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:[
                  15.width,
                  Text(l(context).appName,
                      style: Theme.of(context).textTheme.titleLarge),
                ]),
            Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children:[
                  LanguageSwitch(settingsController: settingsController),
                  5.width,
                  InkWell(
                    onTap: () {
                      bottomSheetMenu(context);
                    },
                    child:
                    NotificationBadge(totalNotifications: _totalNotifications),
                  ),
                ]),
          ],
        ),],
    );
  }
</code>```

I can't seem to find the correct way to initialize the settingscontroller on the "LanguageSwitch"
I have been trying different options but noting seems to work.
With this app i'm adding Firebase Messaging and Locale "l10n"
I can't get Locale working on a Statefulwidget.

Who knows how?

Body:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (kDebugMode) {
    print("Handling a background message: ${message.messageId}");
  }
}

class App extends StatefulWidget {
  const App({Key? key, required this.settingsController})
      : super(key: key);

  final SettingsController settingsController;

  @override
  AppState createState() => AppState();
}

class AppState extends State<App> {
  // Notification
  late final FirebaseMessaging _messaging;
  late int _totalNotifications;
  PushNotification? _notificationInfo;
  // BottomNavigationBar
  int currentPageIndex = 0;

  Widget _appBar() {
    return Stack(
      children: <Widget>[
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:[
                  15.width,
                  Text(l(context).appName,
                      style: Theme.of(context).textTheme.titleLarge),
                ]),
            Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children:[
                  LanguageSwitch(settingsController: settingsController),
                  5.width,
                  InkWell(
                    onTap: () {
                      bottomSheetMenu(context);
                    },
                    child:
                    NotificationBadge(totalNotifications: _totalNotifications),
                  ),
                ]),
          ],
        ),],
    );
  }

I can't seem to find the correct way to initialize the settingscontroller on the "LanguageSwitch"
I have been trying different options but noting seems to work.
With this app i'm adding Firebase Messaging and Locale "l10n"
I can't get Locale working on a Statefulwidget.

Who knows how?


问:
How to troubleshoot field errors when using Zapier to transfer donations made via to Salesforce
I am currently using Zapier to transfer donation records from Raisely to Salesforce. I have recently added PayPal as a payment gateway on Raisely. When a donor donates via PayPal, their donation is appearing as a recurring donation on Salesforce rather than a single/one-time donation

Does anyone know how to fix this issue so our PayPal donation details are transferred into Salesforce as single rather than recurring?

Thank you for your help!


问:
How to access Nothing Phone Glyphs
I have just recently purchased the Nothing Phone (1) and was wondering if it were possible to control the glyphs lights on the nothing phone in my own app.
I am aware of the Activity Launcher app with which you can control the lights individually and so I was wondering if it could be done similarly to that.

I couldn't find anything online and have no idea where to start. Any help is much appreciated!

Title: How to access Nothing Phone Glyphs


问:
AttributeError: module 'sklearn.metrics._dist_metrics' has no attribute 'DistanceMetric32'
I'm new to scikit-learn, and currently I just want to use its train_test_split function.  Below is what I typed:

```<code>from sklearn.model_selection import train_test_split
</code>```

And this is the error message:

```<code>Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[18], line 1
----> 1 from sklearn.model_selection import train_test_split

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/model_selection/__init__.py:23
     20 from ._split import train_test_split
     21 from ._split import check_cv
---> 23 from ._validation import cross_val_score
     24 from ._validation import cross_val_predict
     25 from ._validation import cross_validate

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/model_selection/_validation.py:32
     30 from ..utils.fixes import delayed
     31 from ..utils.metaestimators import _safe_split
---> 32 from ..metrics import check_scoring
     33 from ..metrics._scorer import _check_multimetric_scoring, _MultimetricScorer
     34 from ..exceptions import FitFailedWarning

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/metrics/__init__.py:41
     37 from ._classification import multilabel_confusion_matrix
     39 from ._dist_metrics import DistanceMetric
---> 41 from . import cluster
     42 from .cluster import adjusted_mutual_info_score
     43 from .cluster import adjusted_rand_score
...
     19 )

File sklearn/metrics/_pairwise_distances_reduction/_base.pyx:1, in init sklearn.metrics._pairwise_distances_reduction._base()

AttributeError: module 'sklearn.metrics._dist_metrics' has no attribute 'DistanceMetric32'
</code>```

I've tried to search for similar errors, and most of them are version issues.  My Python is 3.10.8 and scikit-learn is 1.2.0.  I tried to upgrading (1.2.0 is already the latest) and downgrading, but the error remains.  In addition, the other errors I found are lack of some other attributes rather than 'DistanceMetric32'.  Could anyone provides some ideas?

Body:
I'm new to scikit-learn, and currently I just want to use its train_test_split function.  Below is what I typed:

from sklearn.model_selection import train_test_split

And this is the error message:

Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[18], line 1
----> 1 from sklearn.model_selection import train_test_split

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/model_selection/__init__.py:23
     20 from ._split import train_test_split
     21 from ._split import check_cv
---> 23 from ._validation import cross_val_score
     24 from ._validation import cross_val_predict
     25 from ._validation import cross_validate

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/model_selection/_validation.py:32
     30 from ..utils.fixes import delayed
     31 from ..utils.metaestimators import _safe_split
---> 32 from ..metrics import check_scoring
     33 from ..metrics._scorer import _check_multimetric_scoring, _MultimetricScorer
     34 from ..exceptions import FitFailedWarning

File ~/.conda/envs/tf/lib/python3.10/site-packages/sklearn/metrics/__init__.py:41
     37 from ._classification import multilabel_confusion_matrix
     39 from ._dist_metrics import DistanceMetric
---> 41 from . import cluster
     42 from .cluster import adjusted_mutual_info_score
     43 from .cluster import adjusted_rand_score
...
     19 )

File sklearn/metrics/_pairwise_distances_reduction/_base.pyx:1, in init sklearn.metrics._pairwise_distances_reduction._base()

AttributeError: module 'sklearn.metrics._dist_metrics' has no attribute 'DistanceMetric32'

I've tried to search for similar errors, and most of them are version issues.  My Python is 3.10.8 and scikit-learn is 1.2.0.  I tried to upgrading (1.2.0 is already the latest) and downgrading, but the error remains.  In addition, the other errors I found are lack of some other attributes rather than 'DistanceMetric32'.  Could anyone provides some ideas?


问:
error in given code but no solutions available for beautifulsoup
```<code>from splinter import Browser
from bs4 import BeautifulSoup as soup
from webdriver_manager.chrome import ChromeDriverManager

# Set up Splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
</code>```

When I tried the code above I would get the following error:

TypeError: 'NoneType' object is not callable
at this line:

----> 3 browser = Browser('chrome', **executable_path, headless=False)

can someone please help me figure out why this is not working?

Thanks a bunch!!

Body:
from splinter import Browser
from bs4 import BeautifulSoup as soup
from webdriver_manager.chrome import ChromeDriverManager

# Set up Splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)

When I tried the code above I would get the following error:

TypeError: 'NoneType' object is not callable
at this line:

----> 3 browser = Browser('chrome', **executable_path, headless=False)

can someone please help me figure out why this is not working?

Thanks a bunch!!


问:
How to get the questions for the answers on Google Forms API in C#?
I'm trying to get the question for each answers from a Google Form using their API.

Here is the method that I'm trying to use:

void Responses()
{
    ListFormResponsesResponse responses = service.Forms.Responses.List(formId).Execute();

    for (int i = 0; i < responses.Responses.Count; i++)
    {
        FormResponse response = responses.Responses[i];
        string email = response.RespondentEmail;    //I've got the Email of the respondent

        IDictionary<string, Answer> answers = response.Answers;

        foreach (KeyValuePair<string, Answer> answerPair in answers)
        {
            foreach (TextAnswer textAnswer in answerPair.Value.TextAnswers.Answers)
            {
                string answer = textAnswer.Value;  //I've got the answers
                string question = "????";          //But what's the question that he answered to??? The keys are only ID's.
            }
        }

    }
}
```

I want to make a Class that stores each person's Email, and answers for each question.

That's why it's important to have the question too, so I can make some other stuff with those

Anyhelp would be greatly appreciated!

Body:
I'm trying to get the question for each answers from a Google Form using their API.

Here is the method that I'm trying to use:

void Responses()
{
    ListFormResponsesResponse responses = service.Forms.Responses.List(formId).Execute();

    for (int i = 0; i < responses.Responses.Count; i++)
    {
        FormResponse response = responses.Responses[i];
        string email = response.RespondentEmail;    //I've got the Email of the respondent

        IDictionary<string, Answer> answers = response.Answers;

        foreach (KeyValuePair<string, Answer> answerPair in answers)
        {
            foreach (TextAnswer textAnswer in answerPair.Value.TextAnswers.Answers)
            {
                string answer = textAnswer.Value;  //I've got the answers
                string question = "????";          //But what's the question that he answered to??? The keys are only ID's.
            }
        }

    }
}

I want to make a Class that stores each person's Email, and answers for each question.

That's why it's important to have the question too, so I can make some other stuff with those

Anyhelp would be greatly appreciated!


问:
Responsive card grid with full image height on hover
I'm hoping to get some advice on creating a responsive card that will display the full height of an image on hover. I've been working on it for the past hour and have come up with a solution, which you can see in my jsfiddle file. However, it's not quite as responsive as I'd like it to be. I'd really appreciate any tips or recommendations you might have.

Here is my take: jsfiddle

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  gap: 2rem;
}

.card {
  position: relative;
  background: #eee;
  display: flex;
  flex-direction: column;
  height: 420px;
}

.card .thumbnail {
  position: relative;
  width: 100%;
  height: 275px;
}

.card:hover {
  z-index: 999;
}

.card:hover .thumbnail {
  height: auto;
}

.card:hover .details {
  top: 100%;
}

.card .thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: height 0.3s ease-in-out;
}

.card .details {
  display: flex;
  flex-direction: column;
  position: absolute;
  width: 100%;
  background: blue;
  bottom: 0;
  height: 170px;
}

.card .details h1 {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-grid">
  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>

  <div class="card">
    <div class="thumbnail">
      <img src="#" alt="Card Thumbnail">
    </div>
    <div class="details">
      <h1>Card Title</h1>
      <p>Card description goes here</p>
    </div>
  </div>
</div></code>```

I am using position: absolute in order to prevent the card height from changing and disrupting the grid layout.

Thank you!

Body:
I'm hoping to get some advice on creating a responsive card that will display the full height of an image on hover. I've been working on it for the past hour and have come up with a solution, which you can see in my jsfiddle file. However, it's not quite as responsive as I'd like it to be. I'd really appreciate any tips or recommendations you might have.

Here is my take: jsfiddle

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  gap: 2rem;
}

.card {
  position: relative;
  background: #eee;
  display: flex;
  flex-direction: column;
  height: 420px;
}

.card .thumbnail {
  position: relative;
  width: 100%;
  height: 275px;
}

.card:hover {
  z-index: 999;
}

.card:hover .thumbnail {
  height: auto;
}

.card:hover .details {
  top: 100%;
}

.card .thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: height 0.3s ease-in-out;
}

.card .details {
  display: flex;
  flex-direction: column;
  position: absolute;
  width: 100%;
  background: blue;
  bottom: 0;
  height: 170px;
}

.card .details h1 {}

Card Title

Card description goes here

Card Title

Card description goes here

Card Title

Card description goes here

Card Title

Card description goes here

Card Title

Card description goes here

Card Title

Card description goes here

Card Title

Card description goes here

I am using position: absolute in order to prevent the card height from changing and disrupting the grid layout.

Thank you!


问:
How to add React routing to mapped list items?
I'm studying React and trying to make a Todo app. I made a first section and a menu which should switch the app between two sections. I'm mapping buttons in order to add them class because they should have different styling after they are clicked. Now I need to add routing to these buttons but I can't make it work.

This is my code:

```<code>import React, { useState } from "react";
import Todo from "../Todo/Todo";
import About from "../About/About";
import { BrowserRouter as Router, Route, Link, Routes } from "react-router-dom";
import classnames from "classnames";
import styles from "./App.module.css";

const App = () => {
  const [clicked, setClicked] = useState("");
  const buttons = ["About me", 'Todos'];

  return (
    <Router>
      <div>
        <nav className={styles.menu}>
          <ul className={styles.nav}>
            {buttons.map((item, index) => {
              return (
                <li
                  key={index}
                  onClick={() => {
                    if (clicked === index) {
                      setClicked();
                    } else {
                      setClicked(index);
                    }
                  }}
                >
                  <Link to={`/buttons/${index}`}>
                    {
                      <button
                        className={classnames({ [styles.button]: true,       [styles.selected]: clicked === index
                        })}
                      >
                        {item}
                      </button>
                    }
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>
        <Routes>
          <Route path="/" exact element={<About />} />
          <Route path="/todo" element={<Todo />} />
        </Routes>
      </div>
    </Router>
  );`

export default App;
</code>```

The error message I get in console is 'No routes matched location "/buttons/0"'. And the same for "/buttons/1".
Probably I indicated paths wrong somehow but I don't know how to fix it.

Body:
I'm studying React and trying to make a Todo app. I made a first section and a menu which should switch the app between two sections. I'm mapping buttons in order to add them class because they should have different styling after they are clicked. Now I need to add routing to these buttons but I can't make it work.

This is my code:

import React, { useState } from "react";
import Todo from "../Todo/Todo";
import About from "../About/About";
import { BrowserRouter as Router, Route, Link, Routes } from "react-router-dom";
import classnames from "classnames";
import styles from "./App.module.css";

const App = () => {
  const [clicked, setClicked] = useState("");
  const buttons = ["About me", 'Todos'];

  return (
    <Router>

            {buttons.map((item, index) => {
              return (

 {
                    if (clicked === index) {
                      setClicked();
                    } else {
                      setClicked(index);
                    }
                  }}
                >
                  <Link to={`/buttons/${index}`}>
                    {
                      <button
                        className={classnames({ [styles.button]: true,       [styles.selected]: clicked === index
                        })}
                      >
                        {item}
                      </button>
                    }
                  </Link>

              );
            })}

        <Routes>
          <Route path="/" exact element={<About />} />
          <Route path="/todo" element={<Todo />} />
        </Routes>

    </Router>
  );`

export default App;

The error message I get in console is 'No routes matched location "/buttons/0"'. And the same for "/buttons/1".
Probably I indicated paths wrong somehow but I don't know how to fix it.