问:
How to plot text on plot for certain values
I started working on python and I am facing rough time because of the errors (for me) are not clear enough.

I am trying to plot stock market on matplotlib. The problem is that I either get the error TypeError: only size-1 arrays can be converted to Python scalars or the truth value of a series is ambiguous. With the current code, I am getting the first one.

```<code>#create figure
fig = plt.figure(figsize=(12,8),dpi=200)

axes1 = fig.add_axes([0, 0, 1, 1]) # Large figure

prices = data

#define width of candlestick elements
width = .4
width2 = .05

#define up and down prices
up = prices[prices["Direction"] == 1]
down = prices[prices["Direction"] == -1]

print(up.head())
print("-"*80)
print(down.head())

#define colors to use
green = 'green'
red = 'red'

print("-"*80)

print(up.info())

#plot up prices
for _, row in prices.iterrows():
    #here seems to be the error
    plt.text(x=prices.index, y=row["High"], s=row["KMeans_Labels"], rotation=90, color=green)
plt.bar(up.index, up["Close"]-up["Open"], width, bottom=up["Open"], color=green)
plt.bar(up.index, up["High"]-up["Close"],width2, bottom=up["Close"], color=green)
plt.bar(up.index, up["Low"]-up["Open"], width2, bottom=up["Open"], color=green)

#plot down prices
#for _, row in down.iterrows():
 #   plt.text(x=down.index, y=row["High"], s=row["KMeans_Labels"], rotation=90, color=green)
plt.bar(down.index, down["Close"]-down["Open"], width, bottom=down["Open"], color=red)
plt.bar(down.index, down["High"]-down["Open"], width2, bottom=down["Open"], color=red)
plt.bar(down.index, down["Low"]-down["Close"], width2, bottom=down["Close"], color=red)

#rotate x-axis tick labels
plt.xticks(rotation=90, ha='right')

#display candlestick chart
plt.show()
fig.savefig('figure.png', bbox_inches='tight')
</code>```

I think this might be because of, either the indexes or something similar. But I think that python errors are not clear enough.

Edit:

The error can be found on this public site.
Says the error is:

fig.savefig('figure.png', bbox_inches='tight')

Also, if you want to run it, I uploaded it into a public spot too.

Body:
I started working on python and I am facing rough time because of the errors (for me) are not clear enough.

I am trying to plot stock market on matplotlib. The problem is that I either get the error TypeError: only size-1 arrays can be converted to Python scalars or the truth value of a series is ambiguous. With the current code, I am getting the first one.

#create figure
fig = plt.figure(figsize=(12,8),dpi=200)

axes1 = fig.add_axes([0, 0, 1, 1]) # Large figure

prices = data

#define width of candlestick elements
width = .4
width2 = .05

#define up and down prices
up = prices[prices["Direction"] == 1]
down = prices[prices["Direction"] == -1]

print(up.head())
print("-"*80)
print(down.head())

#define colors to use
green = 'green'
red = 'red'

print("-"*80)

print(up.info())

#plot up prices
for _, row in prices.iterrows():
    #here seems to be the error
    plt.text(x=prices.index, y=row["High"], s=row["KMeans_Labels"], rotation=90, color=green)
plt.bar(up.index, up["Close"]-up["Open"], width, bottom=up["Open"], color=green)
plt.bar(up.index, up["High"]-up["Close"],width2, bottom=up["Close"], color=green)
plt.bar(up.index, up["Low"]-up["Open"], width2, bottom=up["Open"], color=green)

#plot down prices
#for _, row in down.iterrows():
 #   plt.text(x=down.index, y=row["High"], s=row["KMeans_Labels"], rotation=90, color=green)
plt.bar(down.index, down["Close"]-down["Open"], width, bottom=down["Open"], color=red)
plt.bar(down.index, down["High"]-down["Open"], width2, bottom=down["Open"], color=red)
plt.bar(down.index, down["Low"]-down["Close"], width2, bottom=down["Close"], color=red)

#rotate x-axis tick labels
plt.xticks(rotation=90, ha='right')

#display candlestick chart
plt.show()
fig.savefig('figure.png', bbox_inches='tight')

I think this might be because of, either the indexes or something similar. But I think that python errors are not clear enough.

Edit:

The error can be found on this public site.
Says the error is:

fig.savefig('figure.png', bbox_inches='tight')

Also, if you want to run it, I uploaded it into a public spot too.


来源: stackexchange

问:
NodeJs, ExpressJs socket io socket io client deployment
I am working project having main objective to share code in real time. Everything is working fine on local host but when I deployed it on netlify when a person into the room then suddenly it shows a alert that Socket connection failed try again later eventually joined person is getting out from  the room too.

I am attaching link of that application

https://sanitocodesharing.netlify.app/

Please find the repo of application below
https://github.com/A70810/Sanito--A-Real-Time-Code-Editor-

Application is performing as desired on local host but on deployment it is not working as it should.
Just throwing the users from out off the room and saying Socket connection failed try again later

ContentLicense: CC BY-SA 4.0


问:
Flutter Build error is resulting to a error , Could not load compiled classes for build
The whole code was working well last week, and now I try to open the same project and run the flutter build apk

It shows below error

FAILURE: Build failed with an exception.

```<code>* What went wrong:
  A problem occurred configuring project ':location'.

> Could not load compiled classes for build file 'D:\\flutter.pub-cache\\hosted\\pub.dartlang.org\\location-4.4.0\\android\\build.gradle' from cache.
> Failed to notify project evaluation listener.
> Could not get unknown property 'android' for the project ':location' of type org.gradle.api.Project.
> Could not get unknown property 'android' for the project ':location' of type org.gradle.api.Project.

* Try:
  ore log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
  BUILD FAILED in 16s
  Gradle task assembly release failed with exit code 1
</code>```

Running flutter doctor...

Doctor summary (to see all details, run flutter doctor -v):

US)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)

[√] Chrome - develop for the web

[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.3.6)

[√] Android Studio (version 2021.3)

[√] Connected device (3 available)

[√] HTTP Host Availability

• No issues found!

I tried cleaning the pub cache folder and also running pub get commands, but the build is not succeeding

Body:
The whole code was working well last week, and now I try to open the same project and run the flutter build apk

It shows below error

FAILURE: Build failed with an exception.

* What went wrong:
  A problem occurred configuring project ':location'.

> Could not load compiled classes for build file 'D:\\flutter.pub-cache\\hosted\\pub.dartlang.org\\location-4.4.0\\android\\build.gradle' from cache.
> Failed to notify project evaluation listener.
> Could not get unknown property 'android' for the project ':location' of type org.gradle.api.Project.
> Could not get unknown property 'android' for the project ':location' of type org.gradle.api.Project.

* Try:
  ore log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
  BUILD FAILED in 16s
  Gradle task assembly release failed with exit code 1

Running flutter doctor...

Doctor summary (to see all details, run flutter doctor -v):

US)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)

[√] Chrome - develop for the web

[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.3.6)

[√] Android Studio (version 2021.3)

[√] Connected device (3 available)

[√] HTTP Host Availability

• No issues found!

I tried cleaning the pub cache folder and also running pub get commands, but the build is not succeeding


问:
How to deal with foreign keys from another microservice?
I have 2 microservices: one for subjects and one for questions. Don't ask me why. It has to be like that.
So in questions I have this m2m-like model:

```<code>class QuestionsSubjects(models.Model):
    question = models.ForeignKey(Question, ...)
    subject_id = models.PositiveIntegerField()
</code>```

And question model has this property:

```<code>@property
def subjects(self) -> QuerySet[int]:
    return QuestionsSubjects.objects \
        .filter(question=self).values_list('subject_id', flat=True)
</code>```

I don't have Subject model I only have ids coming from frontend.
I need to store relations between questions and subjects.
But what I have now is not convenient because it's hard to create questions with subjects.

For example, I have this QuestionSerializer:

```<code>class QuestionSerializer(serializers.ModelSerializer):
    subjects = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = Question
        fields = [
            # some other question fields
            'subjects',
        ]

    def create(self, validated_data: dict[str, Any]) -> Question:
        subject_ids: list[int] = validated_data.pop('subjects', [])
        question = Question.objects.create(**validated_data)

        create_questions_subjects(question, subject_ids)

        return question

    def update(self, question: Question, validated_data: dict[str, Any]) -> Question:
        # delete all existing rows for specific question
        QuestionsSubjects.objects.filter(question=question).delete()

        # and recreate them with new subject ids
        subject_ids: list[int] = validated_data.pop('subjects', [])
        create_questions_subjects(question, subject_ids)

        return super().update(question, validated_data)
</code>```

The problem is I'm getting subject ids from client and everytime I need to go through each subject id and create row in QuestionsDirections for each subject with specific question. So I created function called create_questions_subjects:

```<code>def create_questions_subjects(
    question: Question,
    subject_ids: list[int]
) -> None:
    questions_subjects_list: list[QuestionsSubjects] = []

    for id in subject_ids:
        questions_subjects_list.append(
            QuestionsSubjects(question=question, subject_id=id)
        )

    QuestionsSubjects.objects.bulk_create(questions_subjects_list)
</code>```

But I don't where I have to put it. It's still in serializers.py. It works but looking so ugly to me. Is there a better way of dealing with such a task?

Body:
I have 2 microservices: one for subjects and one for questions. Don't ask me why. It has to be like that.
So in questions I have this m2m-like model:

class QuestionsSubjects(models.Model):
    question = models.ForeignKey(Question, ...)
    subject_id = models.PositiveIntegerField()

And question model has this property:

@property
def subjects(self) -> QuerySet[int]:
    return QuestionsSubjects.objects \
        .filter(question=self).values_list('subject_id', flat=True)

I don't have Subject model I only have ids coming from frontend.
I need to store relations between questions and subjects.
But what I have now is not convenient because it's hard to create questions with subjects.

For example, I have this QuestionSerializer:

class QuestionSerializer(serializers.ModelSerializer):
    subjects = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = Question
        fields = [
            # some other question fields
            'subjects',
        ]

    def create(self, validated_data: dict[str, Any]) -> Question:
        subject_ids: list[int] = validated_data.pop('subjects', [])
        question = Question.objects.create(**validated_data)

        create_questions_subjects(question, subject_ids)

        return question

    def update(self, question: Question, validated_data: dict[str, Any]) -> Question:
        # delete all existing rows for specific question
        QuestionsSubjects.objects.filter(question=question).delete()

        # and recreate them with new subject ids
        subject_ids: list[int] = validated_data.pop('subjects', [])
        create_questions_subjects(question, subject_ids)

        return super().update(question, validated_data)

The problem is I'm getting subject ids from client and everytime I need to go through each subject id and create row in QuestionsDirections for each subject with specific question. So I created function called create_questions_subjects:

def create_questions_subjects(
    question: Question,
    subject_ids: list[int]
) -> None:
    questions_subjects_list: list[QuestionsSubjects] = []

    for id in subject_ids:
        questions_subjects_list.append(
            QuestionsSubjects(question=question, subject_id=id)
        )

    QuestionsSubjects.objects.bulk_create(questions_subjects_list)

But I don't where I have to put it. It's still in serializers.py. It works but looking so ugly to me. Is there a better way of dealing with such a task?


问:
Why the while loop doesn't execute the statements in the 2nd iteration?
I've been facing a problem lately with my assignment. I was working on a part that would take input from a user and according to that input, it would print a certain thing. This should be an ongoing loop where the system keeps asking for input until the user would eventually type 99 which will end the loop. Although it works for the 1st time, when I re-input a value the system would no longer print what it is supposed to print corresponding to the value of the input, and for the value of input equal to 2, it wouldn't print anything at all.

```<code>import csv                       #importing the module
csv_file=open('ssc2.csv','r')
csv_reader=csv.reader(csv_file)
</code>```
```<code>while True:
    User_option=int(input('Your option is:'))
    if User_option== 99:
        break
    elif User_option== 1:
        Sum_books=0
        for i in csv_reader:
            Sum_books=Sum_books+1
        print('reading data was successful')
        print('current number of books in stock:',Sum_books-1)
   elif User_option == 2:
        for i in csv_reader:
            print(i)
</code>```

Output

Only works for the first time I Input

Where for the input value equal to 2, it should print a couple of lists which actually works the first time but then when the system re-asks for input and I re-input it doesn't work. And for an input value of 1, it should print a message and then a calculation of the no. of books in stock and again it works perfectly the first time but the second time it still prints the message but for the calculation its wrong.

I would be grateful if anyone would help me with this
Thank you!

Body:
I've been facing a problem lately with my assignment. I was working on a part that would take input from a user and according to that input, it would print a certain thing. This should be an ongoing loop where the system keeps asking for input until the user would eventually type 99 which will end the loop. Although it works for the 1st time, when I re-input a value the system would no longer print what it is supposed to print corresponding to the value of the input, and for the value of input equal to 2, it wouldn't print anything at all.

import csv                       #importing the module
csv_file=open('ssc2.csv','r')
csv_reader=csv.reader(csv_file)

while True:
    User_option=int(input('Your option is:'))
    if User_option== 99:
        break
    elif User_option== 1:
        Sum_books=0
        for i in csv_reader:
            Sum_books=Sum_books+1
        print('reading data was successful')
        print('current number of books in stock:',Sum_books-1)
   elif User_option == 2:
        for i in csv_reader:
            print(i)

Output

Only works for the first time I Input

Where for the input value equal to 2, it should print a couple of lists which actually works the first time but then when the system re-asks for input and I re-input it doesn't work. And for an input value of 1, it should print a message and then a calculation of the no. of books in stock and again it works perfectly the first time but the second time it still prints the message but for the calculation its wrong.

I would be grateful if anyone would help me with this
Thank you!


问:
Vercel deployment cannot resolve /api/products
I deployed a mern stack application to vercel.  The pages load but I get an error Request failed with status code 404.

I'm guessing it has to do with the server.js or that the server isn't running but I'm really not sure and I cannot find a solution.

I can navigate to the other pages like the sign in or sign up page but if I fill in the login info I get a 404 error.

I'm building it from a tutorial and it works locally but the course it deploying to heroku which doesn't have the free tier anymore so I'm trying vercel.

This is the HomeScreen that loads when I go to the site:

```<code>import { useEffect, useReducer } from 'react';
import axios from 'axios';
import logger from 'use-reducer-logger';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Product from '../components/Product';
import { Helmet } from 'react-helmet-async';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
// import data from '../data';

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_SUCCESS':
      return { ...state, products: action.payload, loading: false };
    case 'FETCH_FAIL':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};
const HomeScreen = () => {
  // const [products, setProducts] = useState([]);
  const [{ loading, error, products }, dispatch] = useReducer(logger(reducer), {
    products: [],
    loading: true,
    error: '',
  });
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get('/api/products/');
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (error) {
        dispatch({ type: 'FETCH_FAIL', payload: error.message });
      }
      // setProducts(result.data);
    };
    fetchData();
  }, []);

  return (
    <div>
      <Helmet>
        <title>Amazona</title>
      </Helmet>
      <h1>Featured Products</h1>
      <div className="products">
        {loading ? (
          <LoadingBox />
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <Row>
            {products.map((product) => (
              <Col key={product.slug} sm={6} md={4} lg={3} className="mb-3">
                <Product product={product} />
              </Col>
            ))}
          </Row>
        )}
      </div>
    </div>
  );
};

export default HomeScreen;
</code>```

Here is the server.js:

```<code>import { useEffect, useReducer } from 'react';
import axios from 'axios';
import logger from 'use-reducer-logger';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Product from '../components/Product';
import { Helmet } from 'react-helmet-async';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
// import data from '../data';

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_SUCCESS':
      return { ...state, products: action.payload, loading: false };
    case 'FETCH_FAIL':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};
const HomeScreen = () => {
  // const [products, setProducts] = useState([]);
  const [{ loading, error, products }, dispatch] = useReducer(logger(reducer), {
    products: [],
    loading: true,
    error: '',
  });
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get('/api/products/');
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (error) {
        dispatch({ type: 'FETCH_FAIL', payload: error.message });
      }
      // setProducts(result.data);
    };
    fetchData();
  }, []);

  return (
    <div>
      <Helmet>
        <title>Amazona</title>
      </Helmet>
      <h1>Featured Products</h1>
      <div className="products">
        {loading ? (
          <LoadingBox />
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <Row>
            {products.map((product) => (
              <Col key={product.slug} sm={6} md={4} lg={3} className="mb-3">
                <Product product={product} />
              </Col>
            ))}
          </Row>
        )}
      </div>
    </div>
  );
};

export default HomeScreen;
</code>```

This is the productRoutes.js

```<code>import express from 'express';
import Product from '../models/ProductModel.js';

const productRouter = express.Router();

productRouter.get('/', async (req, res) => {
  const products = await Product.find();
  res.send(products);
});

productRouter.get('/slug/:slug', async (req, res) => {
  const product = await Product.findOne({ slug: req.params.slug });
  if (product) {
    res.send(product);
  } else {
    res.status(404).send({ message: 'Product not found.' });
  }
});

productRouter.get('/:id', async (req, res) => {
  const product = await Product.findById(req.params.id);
  if (product) {
    res.send(product);
  } else {
    res.status(404).send({ message: 'Product not found.' });
  }
});

export default productRouter;
</code>```

Body:
I deployed a mern stack application to vercel.  The pages load but I get an error Request failed with status code 404.

I'm guessing it has to do with the server.js or that the server isn't running but I'm really not sure and I cannot find a solution.

I can navigate to the other pages like the sign in or sign up page but if I fill in the login info I get a 404 error.

I'm building it from a tutorial and it works locally but the course it deploying to heroku which doesn't have the free tier anymore so I'm trying vercel.

This is the HomeScreen that loads when I go to the site:

import { useEffect, useReducer } from 'react';
import axios from 'axios';
import logger from 'use-reducer-logger';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Product from '../components/Product';
import { Helmet } from 'react-helmet-async';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
// import data from '../data';

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_SUCCESS':
      return { ...state, products: action.payload, loading: false };
    case 'FETCH_FAIL':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};
const HomeScreen = () => {
  // const [products, setProducts] = useState([]);
  const [{ loading, error, products }, dispatch] = useReducer(logger(reducer), {
    products: [],
    loading: true,
    error: '',
  });
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get('/api/products/');
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (error) {
        dispatch({ type: 'FETCH_FAIL', payload: error.message });
      }
      // setProducts(result.data);
    };
    fetchData();
  }, []);

  return (

      <Helmet>
        <title>Amazona</title>
      </Helmet>

Featured Products

        {loading ? (
          <LoadingBox />
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <Row>
            {products.map((product) => (
              <Col key={product.slug} sm={6} md={4} lg={3} className="mb-3">
                <Product product={product} />
              </Col>
            ))}
          </Row>
        )}

  );
};

export default HomeScreen;

Here is the server.js:

import { useEffect, useReducer } from 'react';
import axios from 'axios';
import logger from 'use-reducer-logger';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Product from '../components/Product';
import { Helmet } from 'react-helmet-async';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
// import data from '../data';

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_SUCCESS':
      return { ...state, products: action.payload, loading: false };
    case 'FETCH_FAIL':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};
const HomeScreen = () => {
  // const [products, setProducts] = useState([]);
  const [{ loading, error, products }, dispatch] = useReducer(logger(reducer), {
    products: [],
    loading: true,
    error: '',
  });
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get('/api/products/');
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (error) {
        dispatch({ type: 'FETCH_FAIL', payload: error.message });
      }
      // setProducts(result.data);
    };
    fetchData();
  }, []);

  return (

      <Helmet>
        <title>Amazona</title>
      </Helmet>

Featured Products

        {loading ? (
          <LoadingBox />
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <Row>
            {products.map((product) => (
              <Col key={product.slug} sm={6} md={4} lg={3} className="mb-3">
                <Product product={product} />
              </Col>
            ))}
          </Row>
        )}

  );
};

export default HomeScreen;

This is the productRoutes.js

import express from 'express';
import Product from '../models/ProductModel.js';

const productRouter = express.Router();

productRouter.get('/', async (req, res) => {
  const products = await Product.find();
  res.send(products);
});

productRouter.get('/slug/:slug', async (req, res) => {
  const product = await Product.findOne({ slug: req.params.slug });
  if (product) {
    res.send(product);
  } else {
    res.status(404).send({ message: 'Product not found.' });
  }
});

productRouter.get('/:id', async (req, res) => {
  const product = await Product.findById(req.params.id);
  if (product) {
    res.send(product);
  } else {
    res.status(404).send({ message: 'Product not found.' });
  }
});

export default productRouter;


问:
Mysql Database where I am creating a procedure to figure out if it is able to determine whether the input is correct or not
I was creating a procedure which can determine if the input (parameter) is correct or not. But I think it is not working.</p>
```<code>DELIMITER //
CREATE PROCEDURE akatsuki_TailedBeast()
BEGIN
    SELECT * from Shinobi_Every_Nation WHERE Caught_TailedBeastName != "NA";
END;
//
DELIMITER ;
</code>```

Body:
I was creating a procedure which can determine if the input (parameter) is correct or not. But I think it is not working.

DELIMITER //
CREATE PROCEDURE akatsuki_TailedBeast()
BEGIN
    SELECT * from Shinobi_Every_Nation WHERE Caught_TailedBeastName != "NA";
END;
//
DELIMITER ;


问:
Failed Error : Failed loading libpng16.dll: The specified module could not be found. when using sld2-image with c++
I am trying to use sdl2-image, but I get the following error:

```<code>Failed Error: Failed loading libpng16.dll: The specified module could not be found.
</code>```

Using:

#include <iostream>
#include "SDL2/SDL_image.h"

int main(int argc, char* args[]) {
    if (!(IMG_Init(IMG_INIT_PNG))) std::cout << "Failed Error : " << SDL_GetError() << std::endl;
    return 0;
}
```

I am using Visual Studio compiler with ninja build system and vcpkg in clion.

There should be no error when using IMG_Init but I keep geting the error.

Body:
I am trying to use sdl2-image, but I get the following error:

Failed Error: Failed loading libpng16.dll: The specified module could not be found.

Using:

#include <iostream>
#include "SDL2/SDL_image.h"

int main(int argc, char* args[]) {
    if (!(IMG_Init(IMG_INIT_PNG))) std::cout << "Failed Error : " << SDL_GetError() << std::endl;
    return 0;
}

I am using Visual Studio compiler with ninja build system and vcpkg in clion.

There should be no error when using IMG_Init but I keep geting the error.


问:
Error when installing Node-SSH with Typescript
I tried installing Node-SSH on my webserver, but I kept gettign errors. After a lot of tries I managed to duplicate the issue on a fresh environment as follows:

Install a new react typescript website using npx create-react-app my-app --template typescript

Install dependencies: npm install --save typescript @types/node @types/react @types/react-dom @types/jest

Install the node-ssh and its typescript dependencies starting with npm install --save-dev @types/ssh2 then npm i node-ssh

Add this code to 'App.tsx' file:

const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()```
</div>
</div>
</p>
<ul>
<li>I got about ~20 errors, a part of them:</li>
</ul>
```ERROR in ./node_modules/asn1/lib/ber/writer.js 3:13-30
Module not found: Error: Can't resolve 'assert' in 'E:\ProjectsAI\devicewisevi\node_modules\asn1\lib\ber'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'
        - install 'assert'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "assert": false }

ERROR in ./node_modules/make-dir/index.js 3:11-24
Module not found: Error: Can't resolve 'fs' in 'E:\ProjectsAI\devicewisevi\node_modules\make-dir'

ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'E:\ProjectsAI\devicewisevi\node_modules\safer-buffer'
```
<p>I tried installing the missing packages but it's definetley not the correct way to fix it.. I figured it something to do with the way <code>node_modules/@types</code> is being compiled.  I tried adding:</p>
```"typeRoots": [
      "./node_modules/@types",
      "./@types"
    ],
    "types": ["node"],
```

to tsconfig.json file but it didn't help.
I would appreciate any help regarding the matter.

Body:
I tried installing Node-SSH on my webserver, but I kept gettign errors. After a lot of tries I managed to duplicate the issue on a fresh environment as follows:

Install a new react typescript website using npx create-react-app my-app --template typescript

Install dependencies: npm install --save typescript @types/node @types/react @types/react-dom @types/jest

Install the node-ssh and its typescript dependencies starting with npm install --save-dev @types/ssh2 then npm i node-ssh

Add this code to 'App.tsx' file:

const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()

I got about ~20 errors, a part of them:

ERROR in ./node_modules/asn1/lib/ber/writer.js 3:13-30
Module not found: Error: Can't resolve 'assert' in 'E:\ProjectsAI\devicewisevi\node_modules\asn1\lib\ber'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'
        - install 'assert'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "assert": false }

ERROR in ./node_modules/make-dir/index.js 3:11-24
Module not found: Error: Can't resolve 'fs' in 'E:\ProjectsAI\devicewisevi\node_modules\make-dir'

ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'E:\ProjectsAI\devicewisevi\node_modules\safer-buffer'

I tried installing the missing packages but it's definetley not the correct way to fix it.. I figured it something to do with the way node_modules/@types is being compiled.  I tried adding:

"typeRoots": [
      "./node_modules/@types",
      "./@types"
    ],
    "types": ["node"],

to tsconfig.json file but it didn't help.
I would appreciate any help regarding the matter.


问:
Calling a method in the main activity from class adapter
Here is my code in my AddClassAdapter recylerview using firebase below on "onBindViewHolder":

```<code>holder.editBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        UserClasses userClasses = new UserClasses();
        userClasses.openEditClassDialog();
    }
});
</code>```

And here is the "openEdiClassDialog" method in my main activity:

```<code>public void openEditClassDialog(){
    UserClassEditDialog userClassEditDialog = new UserClassEditDialog();
    userClassEditDialog.show(getSupportFragmentManager(),"user class dialog");
}
</code>```

My problem is, If I clicked the edit button of an item in the recylerview adapter, this error shows in my logcat:

```<code>java.lang.IllegalStateException: FragmentManager has not been attached to a host. at androidx.fragment.app.FragmentManager.enqueueAction
</code>```

At this moment, I am finding a solution to try, but I am expecting that if I clicked the edit button, a dialog will pop up.

Body:
Here is my code in my AddClassAdapter recylerview using firebase below on "onBindViewHolder":

holder.editBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        UserClasses userClasses = new UserClasses();
        userClasses.openEditClassDialog();
    }
});

And here is the "openEdiClassDialog" method in my main activity:

public void openEditClassDialog(){
    UserClassEditDialog userClassEditDialog = new UserClassEditDialog();
    userClassEditDialog.show(getSupportFragmentManager(),"user class dialog");
}

My problem is, If I clicked the edit button of an item in the recylerview adapter, this error shows in my logcat:

java.lang.IllegalStateException: FragmentManager has not been attached to a host. at androidx.fragment.app.FragmentManager.enqueueAction

At this moment, I am finding a solution to try, but I am expecting that if I clicked the edit button, a dialog will pop up.


问:
How to fit entire webpage in one sheet while printing
I have a website and i print the website after finishing some work. Sometimes based on the length of the text field, the webpage overflows to next page while printing. We need to scale it down before printing to fit in one page. Sometimes it may happen that the contents are so small that we need to scale up to fit in one page. How do I automate this scaling (up scaling or down scaling) process to fit the entire webpage in one page only while printing?

I've tried this:

```<code>body{
   height:620px;
   width:1023px;
   position:absolute;
   box-sizing:border-box;
   transform-origin: 0 0;
   -moz-transform-origin:0 0;
   -o-transform-origin: 0 0;
   -webkit-transform-origin: 0 0;
}
@page {size:210mm 297mm;}
</code>```

but this doesn't scale the webpage to fit in one page while printing.

I just want the webpage to fit in an entire page either by up scaling or down scaling the size while printing.

Body:
I have a website and i print the website after finishing some work. Sometimes based on the length of the text field, the webpage overflows to next page while printing. We need to scale it down before printing to fit in one page. Sometimes it may happen that the contents are so small that we need to scale up to fit in one page. How do I automate this scaling (up scaling or down scaling) process to fit the entire webpage in one page only while printing?

I've tried this:

body{
   height:620px;
   width:1023px;
   position:absolute;
   box-sizing:border-box;
   transform-origin: 0 0;
   -moz-transform-origin:0 0;
   -o-transform-origin: 0 0;
   -webkit-transform-origin: 0 0;
}
@page {size:210mm 297mm;}

but this doesn't scale the webpage to fit in one page while printing.

I just want the webpage to fit in an entire page either by up scaling or down scaling the size while printing.


问:
Error When Executing mongod Command in Window 10
In this problem, when I tried to execute mongod command to establish connection to db server. However, the error has been displayed as bellow.

[here is the error when I executed mongod command](https://i.stack.imgur.com/gAfoW.jpg)

here is the rest of error message

I have already installed mongo successfully, created data/db folder, tried to search some references that suggested removing lock file and restarting MongoDB service. But, they do not work.

Here is the full error message:

```<code>    {"t":{"$date":"2022-12-18T12:32:39.606+07:00"},"s":"I",  "c":"CONTROL",  "id":23
285,   "ctx":"thread1","msg":"Automatically disabling TLS 1.0, to force-enable T
LS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-12-18T12:32:39.608+07:00"},"s":"I",  "c":"NETWORK",  "id":49
15701, "ctx":"thread1","msg":"Initialized wire specification","attr":{"spec":{"i
ncomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInterna
lClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0
,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2022-12-18T12:32:39.612+07:00"},"s":"W",  "c":"ASIO",     "id":22
601,   "ctx":"thread1","msg":"No TransportLayer configured during NetworkInterfa
ce startup"}
{"t":{"$date":"2022-12-18T12:32:39.612+07:00"},"s":"I",  "c":"NETWORK",  "id":46
48602, "ctx":"thread1","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"W",  "c":"ASIO",     "id":22
601,   "ctx":"thread1","msg":"No TransportLayer configured during NetworkInterfa
ce startup"}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"I",  "c":"REPL",     "id":51
23008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr"
:{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"I",  "c":"REPL",     "id":51
23008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr"
:{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipi
ents"}}
{"t":{"$date":"2022-12-18T12:32:39.615+07:00"},"s":"I",  "c":"CONTROL",  "id":59
45603, "ctx":"thread1","msg":"Multi threading initialized"}
{"t":{"$date":"2022-12-18T12:32:39.616+07:00"},"s":"I",  "c":"CONTROL",  "id":46
15611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":4280,"port":
27017,"dbPath":"C:/data/db/","architecture":"64-bit","host":"DESKTOP-KMNS09Q"}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":23
398,   "ctx":"initandlisten","msg":"Target operating system minimum version","at
tr":{"targetMinOS":"Windows 7/Windows Server 2008 R2"}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":23
403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"
5.0.14","gitVersion":"1b3b0073a0b436a8a502b612f24fb2bd572772e5","modules":[],"al
locator":"tcmalloc","environment":{"distmod":"windows","distarch":"x86_64","targ
et_arch":"x86_64"}}}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":51
765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Micr
osoft Windows 10","version":"10.0 (build 19043)"}}}
{"t":{"$date":"2022-12-18T12:32:39.618+07:00"},"s":"I",  "c":"CONTROL",  "id":21
951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"option
s":{}}}
{"t":{"$date":"2022-12-18T12:32:39.620+07:00"},"s":"E",  "c":"CONTROL",  "id":20
557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","
attr":{"error":"IllegalOperation: Attempted to create a lock file on a read-only
 directory: C:\\data\\db\\"}}
{"t":{"$date":"2022-12-18T12:32:39.620+07:00"},"s":"I",  "c":"REPL",     "id":47
84900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for
 shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"COMMAND",  "id":47
84901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"SHARDING", "id":47
84902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"NETWORK",  "id":20
562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}

{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"NETWORK",  "id":47
84905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"-",        "id":20
520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisi
tions."}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"NETWORK",  "id":47
84918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"SHARDING", "id":47
84921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"ASIO",     "id":22
582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress
activity."}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"COMMAND",  "id":47
84923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"-",        "id":47
84931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"FTDC",     "id":47
84926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"CONTROL",  "id":20
565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2022-12-18T12:32:39.625+07:00"},"s":"I",  "c":"CONTROL",  "id":23
138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}
</code>```

What can be the reason here? Thanks a lot for your help.

Body:
In this problem, when I tried to execute mongod command to establish connection to db server. However, the error has been displayed as bellow.

[here is the error when I executed mongod command](https://i.stack.imgur.com/gAfoW.jpg)

here is the rest of error message

I have already installed mongo successfully, created data/db folder, tried to search some references that suggested removing lock file and restarting MongoDB service. But, they do not work.

Here is the full error message:

    {"t":{"$date":"2022-12-18T12:32:39.606+07:00"},"s":"I",  "c":"CONTROL",  "id":23
285,   "ctx":"thread1","msg":"Automatically disabling TLS 1.0, to force-enable T
LS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-12-18T12:32:39.608+07:00"},"s":"I",  "c":"NETWORK",  "id":49
15701, "ctx":"thread1","msg":"Initialized wire specification","attr":{"spec":{"i
ncomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInterna
lClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0
,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2022-12-18T12:32:39.612+07:00"},"s":"W",  "c":"ASIO",     "id":22
601,   "ctx":"thread1","msg":"No TransportLayer configured during NetworkInterfa
ce startup"}
{"t":{"$date":"2022-12-18T12:32:39.612+07:00"},"s":"I",  "c":"NETWORK",  "id":46
48602, "ctx":"thread1","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"W",  "c":"ASIO",     "id":22
601,   "ctx":"thread1","msg":"No TransportLayer configured during NetworkInterfa
ce startup"}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"I",  "c":"REPL",     "id":51
23008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr"
:{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-12-18T12:32:39.614+07:00"},"s":"I",  "c":"REPL",     "id":51
23008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr"
:{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipi
ents"}}
{"t":{"$date":"2022-12-18T12:32:39.615+07:00"},"s":"I",  "c":"CONTROL",  "id":59
45603, "ctx":"thread1","msg":"Multi threading initialized"}
{"t":{"$date":"2022-12-18T12:32:39.616+07:00"},"s":"I",  "c":"CONTROL",  "id":46
15611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":4280,"port":
27017,"dbPath":"C:/data/db/","architecture":"64-bit","host":"DESKTOP-KMNS09Q"}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":23
398,   "ctx":"initandlisten","msg":"Target operating system minimum version","at
tr":{"targetMinOS":"Windows 7/Windows Server 2008 R2"}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":23
403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"
5.0.14","gitVersion":"1b3b0073a0b436a8a502b612f24fb2bd572772e5","modules":[],"al
locator":"tcmalloc","environment":{"distmod":"windows","distarch":"x86_64","targ
et_arch":"x86_64"}}}}
{"t":{"$date":"2022-12-18T12:32:39.617+07:00"},"s":"I",  "c":"CONTROL",  "id":51
765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Micr
osoft Windows 10","version":"10.0 (build 19043)"}}}
{"t":{"$date":"2022-12-18T12:32:39.618+07:00"},"s":"I",  "c":"CONTROL",  "id":21
951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"option
s":{}}}
{"t":{"$date":"2022-12-18T12:32:39.620+07:00"},"s":"E",  "c":"CONTROL",  "id":20
557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","
attr":{"error":"IllegalOperation: Attempted to create a lock file on a read-only
 directory: C:\\data\\db\\"}}
{"t":{"$date":"2022-12-18T12:32:39.620+07:00"},"s":"I",  "c":"REPL",     "id":47
84900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for
 shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"COMMAND",  "id":47
84901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"SHARDING", "id":47
84902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"NETWORK",  "id":20
562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}

{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"NETWORK",  "id":47
84905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2022-12-18T12:32:39.621+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"-",        "id":20
520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisi
tions."}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"NETWORK",  "id":47
84918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"SHARDING", "id":47
84921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2022-12-18T12:32:39.622+07:00"},"s":"I",  "c":"ASIO",     "id":22
582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress
activity."}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"COMMAND",  "id":47
84923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2022-12-18T12:32:39.623+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"CONTROL",  "id":47
84929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"-",        "id":47
84931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"FTDC",     "id":47
84926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2022-12-18T12:32:39.624+07:00"},"s":"I",  "c":"CONTROL",  "id":20
565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2022-12-18T12:32:39.625+07:00"},"s":"I",  "c":"CONTROL",  "id":23
138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}

What can be the reason here? Thanks a lot for your help.


问:
Crypto JS and Java Security Library for replicate both Encryption and Decryption
Here is my AES Library in Java:

```<code>public class AESUtil {

  private SecretKeySpec secretKey;

  public static void main(String[] args) {
    String str = args[1];
    String salt = args[2];

    AESUtil aesUtil = new AESUtil();

    if (args[0].equals("D")) {
      //Going to Decrypt
      System.out.println(aesUtil.decrypt(str, salt));
    } else {
      //Going to Encrypt
      System.out.println(aesUtil.encrypt(str, salt));
    }
  }

  public String encrypt(final String strToEncrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      return Base64.getEncoder()
          .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
      System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
  }

  public String decrypt(final String strToDecrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      return new String(cipher.doFinal(Base64.getDecoder()
          .decode(strToDecrypt)));
    } catch (Exception e) {
      System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
  }

  private void setKey(final String myKey) {
    MessageDigest sha = null;
    try {
      byte[] key = myKey.getBytes(StandardCharsets.UTF_8);
      sha = MessageDigest.getInstance("SHA-1");
      key = sha.digest(key);

      key = Arrays.copyOf(key, 16);

      secretKey = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }
}
</code>```

Here is my Decryption Logic in Javascript using CryptoJS lib:

```<code>function decrypt() {
    var hashedKey = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse(document.getElementById("pass").value));
    console.log(hashedKey)

    var encryptedCipherText = document.getElementById("text").value;
    console.log(encryptedCipherText)

    var decryptedData = CryptoJS.AES.decrypt(encryptedCipherText, hashedKey,
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
    console.log(decryptedData)

    var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
    console.log(decryptedText)

    document.getElementById("decrypted").innerHTML = decryptedText;
    document.getElementById("result").innerHTML = '';
  }
</code>```

In Java:

For:

Plain Text: This Value is to Encrypt

Secret: shh!

Encrypted Value: i8DHmeHuoQWv3rwZ+cybgSdSkyUX7MAcU54NUf2iyxU=

However when putting the same value in Javascript:

I have a high suspect on SHA1 logic i have in Java, that might be causing the issue. But not sure on how to validate that.

Body:
Here is my AES Library in Java:

public class AESUtil {

  private SecretKeySpec secretKey;

  public static void main(String[] args) {
    String str = args[1];
    String salt = args[2];

    AESUtil aesUtil = new AESUtil();

    if (args[0].equals("D")) {
      //Going to Decrypt
      System.out.println(aesUtil.decrypt(str, salt));
    } else {
      //Going to Encrypt
      System.out.println(aesUtil.encrypt(str, salt));
    }
  }

  public String encrypt(final String strToEncrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      return Base64.getEncoder()
          .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
      System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
  }

  public String decrypt(final String strToDecrypt, final String secret) {
    try {
      setKey(secret);
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      return new String(cipher.doFinal(Base64.getDecoder()
          .decode(strToDecrypt)));
    } catch (Exception e) {
      System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
  }

  private void setKey(final String myKey) {
    MessageDigest sha = null;
    try {
      byte[] key = myKey.getBytes(StandardCharsets.UTF_8);
      sha = MessageDigest.getInstance("SHA-1");
      key = sha.digest(key);

      key = Arrays.copyOf(key, 16);

      secretKey = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }
}

Here is my Decryption Logic in Javascript using CryptoJS lib:

function decrypt() {
    var hashedKey = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse(document.getElementById("pass").value));
    console.log(hashedKey)

    var encryptedCipherText = document.getElementById("text").value;
    console.log(encryptedCipherText)

    var decryptedData = CryptoJS.AES.decrypt(encryptedCipherText, hashedKey,
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
    console.log(decryptedData)

    var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
    console.log(decryptedText)

    document.getElementById("decrypted").innerHTML = decryptedText;
    document.getElementById("result").innerHTML = '';
  }

In Java:

For:

Plain Text: This Value is to Encrypt

Secret: shh!

Encrypted Value: i8DHmeHuoQWv3rwZ+cybgSdSkyUX7MAcU54NUf2iyxU=

However when putting the same value in Javascript:

I have a high suspect on SHA1 logic i have in Java, that might be causing the issue. But not sure on how to validate that.


问:
discord.gateway: Shard ID None has successfully RESUMED session
While executing the function in the while loop, no error occurred, but "discord.gateway: Shard ID None has successfully RESUMED session " is displayed, and the loop execution stops. Does anyone know a solution?</p>
```<code>    while True:
        response = requests.get(account_creation_date_url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        titles = soup.select_one('#serverPage > div > div > div > div > div > div > span')

                #print(titles.get_text())

        await asyncio.sleep(3.0)
</code>```

Body:
While executing the function in the while loop, no error occurred, but "discord.gateway: Shard ID None has successfully RESUMED session " is displayed, and the loop execution stops. Does anyone know a solution?

    while True:
        response = requests.get(account_creation_date_url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        titles = soup.select_one('#serverPage > div > div > div > div > div > div > span')

                #print(titles.get_text())

        await asyncio.sleep(3.0)


问:
Python nested init in inheritance
What is the disadvantage of doing this way in python

I want to reduce variable that unique to each class but same line for every class.
For example a logging

import abc
import logging

def get_logger(name: str) -> logging.Logger:
    return logging.getLogger("myapp.{}".format(name))

class AbstractService(abc.ABC):
    def __init__(self, *args, **kwargs):
        self._logger = get_logger(self.__class__.__name__)
        self._init(*args, **kwargs)

    def _init(self, *args, **kwargs):
        pass
```
<p>Then we have the actual class which is extending AbstractService<br />
But here the <strong>_init</strong> will be call by AbstractService.</p>
<pre class="lang-py prettyprint-override"><code>class UserService(AbstractService):
    def _init(self, user_repository):
        self._user_repository = user_repository
</code>```

self._logger.info("") in UserService will print the correct class as "myapp.UserService" when logging something

This is help me a lot, like sharing db, queue, etc.

This way the _init argument can be focus on what dependency is actually need for the service.

I use dependency-injector https://python-dependency-injector.ets-labs.org/ for the class initiation.

But what is the disadvantage, I haven't tested it if it was deep nested class or a diamond inheritance

Is there a better way to call nested init without writing this

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
```

on every class ?

Title: Python nested init in inheritance

Body:
What is the disadvantage of doing this way in python

I want to reduce variable that unique to each class but same line for every class.
For example a logging

import abc
import logging

def get_logger(name: str) -> logging.Logger:
    return logging.getLogger("myapp.{}".format(name))

class AbstractService(abc.ABC):
    def __init__(self, *args, **kwargs):
        self._logger = get_logger(self.__class__.__name__)
        self._init(*args, **kwargs)

    def _init(self, *args, **kwargs):
        pass

Then we have the actual class which is extending AbstractService

But here the _init will be call by AbstractService.

class UserService(AbstractService):
    def _init(self, user_repository):
        self._user_repository = user_repository

self._logger.info("") in UserService will print the correct class as "myapp.UserService" when logging something

This is help me a lot, like sharing db, queue, etc.

This way the _init argument can be focus on what dependency is actually need for the service.

I use dependency-injector https://python-dependency-injector.ets-labs.org/ for the class initiation.

But what is the disadvantage, I haven't tested it if it was deep nested class or a diamond inheritance

Is there a better way to call nested init without writing this

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

on every class ?


问:
Is there any alternative to bubble_overlay in Flutter?
I'd like to create a bubble overlay for my Flutter app...

Through Google, I found the package bubble_overlay and it is discontinued now... So is there any alternative or any other way to implement bubble overlay for Android devices in Flutter???


问:
Accessing all imported features in shape file in Google Earth Engine
I've imported the district shape files of a state 'Karnataka'. I'm able to view only 10 districts' property in the table. It says *Limited to the first 10 features. I am, however, able to see all 31 districts on the map. How do I view the properties of the other districts as I would like to access just one of those?

I don't see any option to view the rest of the details. What do I do?


问:
how do i open the developer menu of react-native
I am trying to open it using

npm run web
but it doesn't work instead it gives this error

```<code>some-random-app@1.0.0 web
> expo start --web

Starting project at C:\Users\surya\OneDrive\Desktop\react-native\some-random-app
Starting Metro Bundler
Starting Webpack on port 19006 in development mode.
‼ ｢wds｣: transportMode is an experimental option, meaning its usage could potentially change without warning
node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:140:10)
    at module.exports (C:\Users\surya\node_modules\webpack\lib\util\createHash.js:135:53)
    at NormalModule._initBuildHash (C:\Users\surya\node_modules\webpack\lib\NormalModule.js:417:16)
    at handleParseError (C:\Users\surya\node_modules\webpack\lib\NormalModule.js:471:10)
    at C:\Users\surya\node_modules\webpack\lib\NormalModule.js:503:5
    at C:\Users\surya\node_modules\webpack\lib\NormalModule.js:358:12
    at C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
    at Array.<anonymous> (C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (C:\Users\surya\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)
    at C:\Users\surya\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9
    at C:\Users\surya\node_modules\graceful-fs\graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v19.3.0
</code>```

how do i overcome this

i just want to open the developer menu of react

Body:
I am trying to open it using

npm run web
but it doesn't work instead it gives this error

some-random-app@1.0.0 web
> expo start --web

Starting project at C:\Users\surya\OneDrive\Desktop\react-native\some-random-app
Starting Metro Bundler
Starting Webpack on port 19006 in development mode.
‼ ｢wds｣: transportMode is an experimental option, meaning its usage could potentially change without warning
node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:140:10)
    at module.exports (C:\Users\surya\node_modules\webpack\lib\util\createHash.js:135:53)
    at NormalModule._initBuildHash (C:\Users\surya\node_modules\webpack\lib\NormalModule.js:417:16)
    at handleParseError (C:\Users\surya\node_modules\webpack\lib\NormalModule.js:471:10)
    at C:\Users\surya\node_modules\webpack\lib\NormalModule.js:503:5
    at C:\Users\surya\node_modules\webpack\lib\NormalModule.js:358:12
    at C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
    at Array.<anonymous> (C:\Users\surya\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (C:\Users\surya\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)
    at C:\Users\surya\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9
    at C:\Users\surya\node_modules\graceful-fs\graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v19.3.0

how do i overcome this

i just want to open the developer menu of react


问:
httpx.RemoteProtocolError: <ConnectionTerminated error_code:ErrorCodes.NO_ERROR, last_stream_id:0, additional_data:7b22726561736f6e223a22426164436572>
I am trying to create a webservice to update a wallet pass using apns push notifications. I am using httpx for this as it can use http/2. I have the following test code for this:

```<code>import httpx
import ssl
import asyncio

async def send_push():
    context = ssl.create_default_context()
    context.load_verify_locations(cafile = "/Users/valley/Desktop/External_Finder/Learning_Centers_Development/Arcade-Pass/certs/passcertificate.pem")

    payload = {
        "aps" : ""
    }

    async with httpx.AsyncClient(http2 = True, cert = "/Users/valley/Desktop/External_Finder/Learning_Centers_Development/Arcade-Pass/certs/ArcadePassCertKey.pem") as client:
        r = await client.post("https://api.sandbox.push.apple.com:2197/3/device/4c526af3e9cd29cc0c6f8954de5f68fd1d00348696fe4a984581e35f19fe1ddf", data = payload)
        print(r.http_version)
        print(r.text)

asyncio.run(send_push())
</code>```

When I try to run this, I am getting the following traceback and error:

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 60, in map_httpcore_exceptions
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 353, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection_pool.py", line 253, in handle_async_request
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection_pool.py", line 237, in handle_async_request
    response = await connection.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection.py", line 90, in handle_async_request
    return await self._connection.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 146, in handle_async_request
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 114, in handle_async_request
    status, headers = await self._receive_response(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 231, in _receive_response
    event = await self._receive_stream_event(request, stream_id)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 262, in _receive_stream_event
    await self._receive_events(request, stream_id)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 291, in _receive_events
    raise RemoteProtocolError(event)
httpcore.RemoteProtocolError: <ConnectionTerminated error_code:ErrorCodes.NO_ERROR, last_stream_id:0, additional_data:7b22726561736f6e223a22426164436572746966>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test_push_notifications.py", line 24, in <module>
    asyncio.run(send_push())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "test_push_notifications.py", line 19, in send_push
    r = await client.post("https://api.sandbox.push.apple.com:2197/3/device/4c526af3e9cd29cc0c6f8954de5f68fd1d00348696fe4a984581e35f19fe1ddf", data = payload)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1848, in post
    return await self.request(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1533, in request
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1620, in send
    response = await self._send_handling_auth(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1648, in _send_handling_auth
    response = await self._send_handling_redirects(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1685, in _send_handling_redirects
    response = await self._send_single_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1722, in _send_single_request
    response = await transport.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 353, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
    raise mapped_exc(message) from exc
httpx.RemoteProtocolError: <ConnectionTerminated error_code:ErrorCodes.NO_ERROR, last_stream_id:0, additional_data:7b22726561736f6e223a22426164436572746966>
</code>```

Can someone please help me navigate this error and send a successful request to APNS?

Body:
I am trying to create a webservice to update a wallet pass using apns push notifications. I am using httpx for this as it can use http/2. I have the following test code for this:

import httpx
import ssl
import asyncio

async def send_push():
    context = ssl.create_default_context()
    context.load_verify_locations(cafile = "/Users/valley/Desktop/External_Finder/Learning_Centers_Development/Arcade-Pass/certs/passcertificate.pem")

    payload = {
        "aps" : ""
    }

    async with httpx.AsyncClient(http2 = True, cert = "/Users/valley/Desktop/External_Finder/Learning_Centers_Development/Arcade-Pass/certs/ArcadePassCertKey.pem") as client:
        r = await client.post("https://api.sandbox.push.apple.com:2197/3/device/4c526af3e9cd29cc0c6f8954de5f68fd1d00348696fe4a984581e35f19fe1ddf", data = payload)
        print(r.http_version)
        print(r.text)

asyncio.run(send_push())

When I try to run this, I am getting the following traceback and error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 60, in map_httpcore_exceptions
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 353, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection_pool.py", line 253, in handle_async_request
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection_pool.py", line 237, in handle_async_request
    response = await connection.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/connection.py", line 90, in handle_async_request
    return await self._connection.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 146, in handle_async_request
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 114, in handle_async_request
    status, headers = await self._receive_response(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 231, in _receive_response
    event = await self._receive_stream_event(request, stream_id)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 262, in _receive_stream_event
    await self._receive_events(request, stream_id)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpcore/_async/http2.py", line 291, in _receive_events
    raise RemoteProtocolError(event)
httpcore.RemoteProtocolError: <ConnectionTerminated error_code:ErrorCodes.NO_ERROR, last_stream_id:0, additional_data:7b22726561736f6e223a22426164436572746966>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test_push_notifications.py", line 24, in <module>
    asyncio.run(send_push())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "test_push_notifications.py", line 19, in send_push
    r = await client.post("https://api.sandbox.push.apple.com:2197/3/device/4c526af3e9cd29cc0c6f8954de5f68fd1d00348696fe4a984581e35f19fe1ddf", data = payload)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1848, in post
    return await self.request(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1533, in request
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1620, in send
    response = await self._send_handling_auth(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1648, in _send_handling_auth
    response = await self._send_handling_redirects(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1685, in _send_handling_redirects
    response = await self._send_single_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_client.py", line 1722, in _send_single_request
    response = await transport.handle_async_request(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 353, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
    raise mapped_exc(message) from exc
httpx.RemoteProtocolError: <ConnectionTerminated error_code:ErrorCodes.NO_ERROR, last_stream_id:0, additional_data:7b22726561736f6e223a22426164436572746966>

Can someone please help me navigate this error and send a successful request to APNS?


问:
what is Bytes32 defaultValue = 'address'; in Merkle tree
So Im new to this merkle tree stuff, i was looking for a code that implement a merkle tree inside their smartcontract, and then i found code which implement merkle tree, the code basically store voter data using merkle tree.

in the smartcontract and javascript file, he put a 'bytes32 default value and declare an address', what it is and how do i get the address ?

below is the smart contract

```<code> mapping(uint => bytes32) public votingToRoot;
    mapping(uint => bytes32[]) public votingToLeaves;
    mapping(address => History[]) public voterHistory;

    function addLeaf(uint _votingId, bytes32 _leaf, bytes32 _newRoot) external {
        bytes32 defaultValue = 0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728;
        bool result = checkLeaf(_votingId, _leaf);
        require(result, "The same leaf already added to the tree");
        votingToLeaves[_votingId].push(_leaf);
        votingToLeaves[_votingId].push(defaultValue);
        setRoot(_votingId, _newRoot);
    }

    function setRoot(uint _votingId, bytes32 _root) public {
        votingToRoot[_votingId] = _root;
    }
</code>```

this is the javascript file

```<code>async function checkRoom(result) {
    const root = await voterContract.votingToRoot(result);
    if (result > 0 && root.slice(3, 8) === "00000") {
      const leaf = [identifier, name, secret];
      const leafHashed = keccak256(leaf);
      const toHex = (voter) => "0x" + voter.toString("hex");
      const leafBytes = toHex(leafHashed);
      const leaves = [
        leafBytes,
        "0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728",
      ];
      const tree = new MerkleTree(leaves, keccak256, { sortPairs: true });
      const treeHex = toHex(tree.getRoot());

else if (result > 0 && root.slice(3, 8) !== "00000") {
      const leaf = [identifier, name, secret];
      const leafHashed = keccak256(leaf);
      const toHex = (voter) => "0x" + voter.toString("hex");
      const leafBytes = toHex(leafHashed);
      const leavesData = await voterContract.getLeaves(result);
      const tree = new MerkleTree(leavesData, keccak256, { sortPairs: true });
      tree.addLeaf(leafBytes);
      tree.addLeaf(
        "0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728"
      );

</code>```

Body:
So Im new to this merkle tree stuff, i was looking for a code that implement a merkle tree inside their smartcontract, and then i found code which implement merkle tree, the code basically store voter data using merkle tree.

in the smartcontract and javascript file, he put a 'bytes32 default value and declare an address', what it is and how do i get the address ?

below is the smart contract

 mapping(uint => bytes32) public votingToRoot;
    mapping(uint => bytes32[]) public votingToLeaves;
    mapping(address => History[]) public voterHistory;

    function addLeaf(uint _votingId, bytes32 _leaf, bytes32 _newRoot) external {
        bytes32 defaultValue = 0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728;
        bool result = checkLeaf(_votingId, _leaf);
        require(result, "The same leaf already added to the tree");
        votingToLeaves[_votingId].push(_leaf);
        votingToLeaves[_votingId].push(defaultValue);
        setRoot(_votingId, _newRoot);
    }

    function setRoot(uint _votingId, bytes32 _root) public {
        votingToRoot[_votingId] = _root;
    }

this is the javascript file

async function checkRoom(result) {
    const root = await voterContract.votingToRoot(result);
    if (result > 0 && root.slice(3, 8) === "00000") {
      const leaf = [identifier, name, secret];
      const leafHashed = keccak256(leaf);
      const toHex = (voter) => "0x" + voter.toString("hex");
      const leafBytes = toHex(leafHashed);
      const leaves = [
        leafBytes,
        "0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728",
      ];
      const tree = new MerkleTree(leaves, keccak256, { sortPairs: true });
      const treeHex = toHex(tree.getRoot());

else if (result > 0 && root.slice(3, 8) !== "00000") {
      const leaf = [identifier, name, secret];
      const leafHashed = keccak256(leaf);
      const toHex = (voter) => "0x" + voter.toString("hex");
      const leafBytes = toHex(leafHashed);
      const leavesData = await voterContract.getLeaves(result);
      const tree = new MerkleTree(leavesData, keccak256, { sortPairs: true });
      tree.addLeaf(leafBytes);
      tree.addLeaf(
        "0xcfee7c08a98f4b565d124c7e4e28acc52e1bc780e3887db0a02a7d2d5bc66728"
      );


问:
NAudio hanging and crashing when default device is changed
I've been stuck on this all day, so I'm going to post everything I've been able to find today that might be useful to helping me, it will be a long post. I'm having 2 issues that I believe are related to the same problem. First, let me explain what I am doing. I have 3 Winforms combo boxes that are bound to lists of all of the devices found by MMDeviceEnumerator. Two output device boxes, one input device. I am using the MMDeviceEnumerator to register a callback for whenever the devices are changed, removed, or a default device is set. The callback fires an event that then invokes a delegate to the form thread to re-enumerate the devices into combo boxes. It looks like this:

```<code>public void OnDefaultDeviceChanged(DataFlow dataFlow, Role deviceRole, string defaultDeviceId)
{
    Devices.OnDevicesUpdated();
}

//The handler called by this event:

private void UpdateDeviceSelectors(object? sender = null, EventArgs? e = null)
{

    Invoke(delegate ()
    {

        int primaryIndex = Devices.PrimaryOutput + 1, secondaryIndex = Devices.SecondaryOutput + 2, microphoneIndex = Devices.Microphone + 1;
        Devices.Refresh();

        try
        {
            SecondaryOutputComboBox.SelectedIndex = secondaryIndex;
            PrimaryOutputComboBox.SelectedIndex = primaryIndex;
            MicrophoneSelectComboBox.SelectedIndex = microphoneIndex;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    });
}
</code>```

Now for the two issues I have. The first one involves a semi-random crash that leads back to NAudio.Wasapi.dll, where a System.ExecutionEngineException is thrown. It is kind of easy to reproduce. All I do is change the values of the combo boxes, switch the default devices around, and it will randomly crash.

The second issue occurs when another part of my code is involved. I have a microphone injector, which redirects a WaveInEvent that records a selected input device to a WaveOutEvent, like a loopback. Here is the relevant code for this:

```<code>public void Start()
{

    if (Soundboard.Devices.SecondaryOutput == -2) return;

    micStream = new WaveInEvent();

    micStream.BufferMilliseconds = 50;
    micStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(Soundboard.Devices.Microphone).Channels);

    micStream.DeviceNumber = Soundboard.Devices.Microphone;

    WaveInProvider waveIn = new(micStream);

    var volumeSampleProvider = new VolumeSampleProvider(waveIn.ToSampleProvider());
    volumeSampleProvider.Volume = 1 + Settings.Default.MicrophoneGain;

    virtualCable = new WaveOutEvent();
    virtualCable.DesiredLatency = 150;
    virtualCable.DeviceNumber = Soundboard.Devices.SecondaryOutput;
    virtualCable.Init(volumeSampleProvider);

    micStream.StartRecording();
    virtualCable.Play();

}

public void Stop()
{
    try
    {
        if (micStream != null && virtualCable != null)
        {

            micStream.Dispose();
            micStream = null;

            virtualCable.Dispose();
            virtualCable = null;

        }
    }
    catch
    {
        micStream = null;

        virtualCable = null;
    }
}
</code>```

In the delegate mentioned earlier, I am calling the Stop method of the Mic Injector and then the Start method to refresh the WaveIn and WaveOut devices to use the current device numbers so users do not see a device selected when a different device is being used. When this happens, the program, rather than crashing instantly and inconsistently, always hangs and has to be killed from the task manager. I am certain these 2 problems are related to the same root cause, but I have no idea what that root cause may be. Switching to Wasapi, DirectSound, or ASIO won't work because they lack certain functionalities I need, so I would really like to get this working still using Wave streams.

I've tried to find different ways to detect the device changes, assuming it is an issue deep inside NAudio, but I just can't find anything else. For the second problem specifically, I have moved the calls to the Mic Injector around thinking it may be a threading issue or something, but it didn't work or change the behavior.

Body:
I've been stuck on this all day, so I'm going to post everything I've been able to find today that might be useful to helping me, it will be a long post. I'm having 2 issues that I believe are related to the same problem. First, let me explain what I am doing. I have 3 Winforms combo boxes that are bound to lists of all of the devices found by MMDeviceEnumerator. Two output device boxes, one input device. I am using the MMDeviceEnumerator to register a callback for whenever the devices are changed, removed, or a default device is set. The callback fires an event that then invokes a delegate to the form thread to re-enumerate the devices into combo boxes. It looks like this:

public void OnDefaultDeviceChanged(DataFlow dataFlow, Role deviceRole, string defaultDeviceId)
{
    Devices.OnDevicesUpdated();
}

//The handler called by this event:

private void UpdateDeviceSelectors(object? sender = null, EventArgs? e = null)
{

    Invoke(delegate ()
    {

        int primaryIndex = Devices.PrimaryOutput + 1, secondaryIndex = Devices.SecondaryOutput + 2, microphoneIndex = Devices.Microphone + 1;
        Devices.Refresh();

        try
        {
            SecondaryOutputComboBox.SelectedIndex = secondaryIndex;
            PrimaryOutputComboBox.SelectedIndex = primaryIndex;
            MicrophoneSelectComboBox.SelectedIndex = microphoneIndex;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    });
}

Now for the two issues I have. The first one involves a semi-random crash that leads back to NAudio.Wasapi.dll, where a System.ExecutionEngineException is thrown. It is kind of easy to reproduce. All I do is change the values of the combo boxes, switch the default devices around, and it will randomly crash.

The second issue occurs when another part of my code is involved. I have a microphone injector, which redirects a WaveInEvent that records a selected input device to a WaveOutEvent, like a loopback. Here is the relevant code for this:

public void Start()
{

    if (Soundboard.Devices.SecondaryOutput == -2) return;

    micStream = new WaveInEvent();

    micStream.BufferMilliseconds = 50;
    micStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(Soundboard.Devices.Microphone).Channels);

    micStream.DeviceNumber = Soundboard.Devices.Microphone;

    WaveInProvider waveIn = new(micStream);

    var volumeSampleProvider = new VolumeSampleProvider(waveIn.ToSampleProvider());
    volumeSampleProvider.Volume = 1 + Settings.Default.MicrophoneGain;

    virtualCable = new WaveOutEvent();
    virtualCable.DesiredLatency = 150;
    virtualCable.DeviceNumber = Soundboard.Devices.SecondaryOutput;
    virtualCable.Init(volumeSampleProvider);

    micStream.StartRecording();
    virtualCable.Play();

}

public void Stop()
{
    try
    {
        if (micStream != null && virtualCable != null)
        {

            micStream.Dispose();
            micStream = null;

            virtualCable.Dispose();
            virtualCable = null;

        }
    }
    catch
    {
        micStream = null;

        virtualCable = null;
    }
}

In the delegate mentioned earlier, I am calling the Stop method of the Mic Injector and then the Start method to refresh the WaveIn and WaveOut devices to use the current device numbers so users do not see a device selected when a different device is being used. When this happens, the program, rather than crashing instantly and inconsistently, always hangs and has to be killed from the task manager. I am certain these 2 problems are related to the same root cause, but I have no idea what that root cause may be. Switching to Wasapi, DirectSound, or ASIO won't work because they lack certain functionalities I need, so I would really like to get this working still using Wave streams.

I've tried to find different ways to detect the device changes, assuming it is an issue deep inside NAudio, but I just can't find anything else. For the second problem specifically, I have moved the calls to the Mic Injector around thinking it may be a threading issue or something, but it didn't work or change the behavior.


问:
how can i generate C/G chord in chordictionaryjs?
I'm trying to generate C/G chord in https://github.com/greird/chordictionaryjs . but it doesn't seems to recognize that chord. anyone have idea? is there any other way or is there another dictionary?</p>
```<code>var guitar = new chordictionary.Instrument('EADGBE', 24, 5, 4);
var chords = getGuitarChord(guitar, "C/G");
</code>```

Body:
I'm trying to generate C/G chord in https://github.com/greird/chordictionaryjs . but it doesn't seems to recognize that chord. anyone have idea? is there any other way or is there another dictionary?

var guitar = new chordictionary.Instrument('EADGBE', 24, 5, 4);
var chords = getGuitarChord(guitar, "C/G");


问:
System.InvalidOperationException ASP.NET C#
Solved Solved Solved
Error;
System.InvalidOperationException: 'An exception was thrown while attempting to evaluate a LINQ query parameter expression. See the inner exception for more information. To show additional information call 'DbContextOptionsBuilder.EnableSensitiveDataLogging'.'

When Is It Happening;
When I try to use register method with those properties, Its poping up on return claims.ToList();:

```<code>    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string? MiddleName { get; set; }
    public string LastName { get; set; }
</code>```

My Controller Method

```<code>[HttpPost("register")]
public IActionResult Register(RegisterDTO registerDTO)
{
var result = _authService.Register(registerDTO, registerDTO.Password);
if (!result.Success) return BadRequest(result);
var createAccessTokenResult = _authService.CreateAccessToken(result.Data);
if (!result.Success) return BadRequest(result);

var createdAccessTokenDataWithSuccessResult = new SuccessDataResult<AccessToken>(createAccessTokenResult.Data, result.Message);

return Ok(createdAccessTokenDataWithSuccessResult);
}
</code>```

DataAccess Layer

```<code>public List<OperationClaim> GetClaims(User user)
        {
            var claims = from uoc in Context.UserOperationClaims
                         join oc in Context.OperationClaims
                         on uoc.OperationClaimId equals oc.Id
                         where uoc.UserId == user.Id
                         select new OperationClaim
                         { Id = oc.Id, Name = oc.Name };

            return claims.ToList();
        }
</code>```

Entity User;

```<code>public int Id { get; set; }
    public string FirstName { get; set; }
    public string? MiddleName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public byte[] PasswordSalt { get; set; }
    public byte[] PasswordHash { get; set; }
    public bool Status { get; set; }
</code>```

I solved it
The problem is, Im was not sending parameter user when It is success on Business Layer

```<code>public IDataResult<User> Register(RegisterDTO registerDTO, string password)
        {
            BusinessRules.Run(CheckTheEmailIsAlreadyRegistered(registerDTO));

            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordPash(password, out passwordHash, out passwordSalt);

            var user = new User()
            {
                Email = registerDTO.Email,
                FirstName = registerDTO.FirstName,
                MiddleName = registerDTO.MiddleName,
                LastName = registerDTO.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Status = true
            };

            var result = _userService.Add(user);

            if (!result.Success) return new ErrorDataResult<User>();

            return new SuccessDataResult<User>(**user**);
        }
</code>```

Body:
Solved Solved Solved
Error;
System.InvalidOperationException: 'An exception was thrown while attempting to evaluate a LINQ query parameter expression. See the inner exception for more information. To show additional information call 'DbContextOptionsBuilder.EnableSensitiveDataLogging'.'

When Is It Happening;
When I try to use register method with those properties, Its poping up on return claims.ToList();:

    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string? MiddleName { get; set; }
    public string LastName { get; set; }

My Controller Method

[HttpPost("register")]
public IActionResult Register(RegisterDTO registerDTO)
{
var result = _authService.Register(registerDTO, registerDTO.Password);
if (!result.Success) return BadRequest(result);
var createAccessTokenResult = _authService.CreateAccessToken(result.Data);
if (!result.Success) return BadRequest(result);

var createdAccessTokenDataWithSuccessResult = new SuccessDataResult<AccessToken>(createAccessTokenResult.Data, result.Message);

return Ok(createdAccessTokenDataWithSuccessResult);
}

DataAccess Layer

public List<OperationClaim> GetClaims(User user)
        {
            var claims = from uoc in Context.UserOperationClaims
                         join oc in Context.OperationClaims
                         on uoc.OperationClaimId equals oc.Id
                         where uoc.UserId == user.Id
                         select new OperationClaim
                         { Id = oc.Id, Name = oc.Name };

            return claims.ToList();
        }

Entity User;

public int Id { get; set; }
    public string FirstName { get; set; }
    public string? MiddleName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public byte[] PasswordSalt { get; set; }
    public byte[] PasswordHash { get; set; }
    public bool Status { get; set; }

I solved it
The problem is, Im was not sending parameter user when It is success on Business Layer

public IDataResult<User> Register(RegisterDTO registerDTO, string password)
        {
            BusinessRules.Run(CheckTheEmailIsAlreadyRegistered(registerDTO));

            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordPash(password, out passwordHash, out passwordSalt);

            var user = new User()
            {
                Email = registerDTO.Email,
                FirstName = registerDTO.FirstName,
                MiddleName = registerDTO.MiddleName,
                LastName = registerDTO.LastName,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Status = true
            };

            var result = _userService.Add(user);

            if (!result.Success) return new ErrorDataResult<User>();

            return new SuccessDataResult<User>(**user**);
        }