问:
How do I use Content-Security-Policy in the options page of a Chrome extension?
I'm trying to add a widget to my Chrome extension's options page, but can't seem to get past the error it gives.

TL;DR:
CSP (Content-Security-Policy) isn't allowing an external script to load on my options.html page of my Chrome extension. I've tried following MDN documentation and Chrome Extension documentation but can't get it to work unless I copy-paste the external JavaScript file and host it locally, but I'm not sure if this is an acceptable method when it comes to security or when it comes time to publish the extension to Chrome Web Store.

Here's what I've tried doing...

I've added this to the head of my options.html:

```<code><meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval' https://js.example.com;"
    />
</code>```

But I'm still receiving these 2 errors in my console when running the page:

Refused to load the script 'https://js.example.com/1.0.0/widget.prod.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Refused to load the script 'https://js.example.com/1.0.0/widget.prod.min.js' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I've tried including the entire external JavaScript source URL in the meta tag like this, but I still get the same 2 error messages.

```<code><meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval' https://js.example.com/1.0.0/widget.prod.min.js;"
    />
</code>```

I've also tried adding a second content-security-policy like this, but then it fails to load the 'self' JavaScript:

```<code><meta
      http-equiv="Content-Security-Policy"
      content="script-src-elem https://js.example.com;"
    />
</code>```

And I've tried adding to the initial Content-Security-Policy meta tag like this, but it also fails to load the 'self' JavaScript:

```<code><meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval'; script-src-elem https://js.example.com;"
    />
</code>```

I've been reading every MDN documentation related to CSP: script-src but can't figure out what I'm doing wrong. I've even started watching YouTube videos and reading random blog articles related to CSP (Content-Security-Policy) but nothing I've tried based on my research has worked.

*I've also reviewed some similar questions asked here on StackOverflow but can't seem to find a solid answer.

One of the recommendations was to add your CSP to the manifest.json, which I did, but the CSP section says you can only use 'self', 'none', 'wasm-unsafe-eval' and local sources. (seems like you can't use external sources unless you're using sandbox?)

So I tried doing this, but received the same errors again (I'm not sure if I coded this correctly though, I couldn't find how to add the "script-src 'self' ..." for "extension_pages", only for "sandbox").

```<code> "content_security_policy": {
    "extension_pages": "options.html",
    "extension_pages": "allow-scripts; script-src 'self' 'wasm-unsafe-eval'"
  }
</code>```

One alternative I tried was grabbing the external JavaScript file and copy-pasting it into a local file. This method got the widget loading and functioning as expected, but I'm not sure if this would be a good practice.

Some questions I have with using this method:

Are there security risks when doing this?

Will my extension be allowed to be published to Chrome Web Store if I leave it like this?

Body:
I'm trying to add a widget to my Chrome extension's options page, but can't seem to get past the error it gives.

TL;DR:
CSP (Content-Security-Policy) isn't allowing an external script to load on my options.html page of my Chrome extension. I've tried following MDN documentation and Chrome Extension documentation but can't get it to work unless I copy-paste the external JavaScript file and host it locally, but I'm not sure if this is an acceptable method when it comes to security or when it comes time to publish the extension to Chrome Web Store.

Here's what I've tried doing...

I've added this to the head of my options.html:

<meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval' https://js.example.com;"
    />

But I'm still receiving these 2 errors in my console when running the page:

Refused to load the script 'https://js.example.com/1.0.0/widget.prod.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Refused to load the script 'https://js.example.com/1.0.0/widget.prod.min.js' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I've tried including the entire external JavaScript source URL in the meta tag like this, but I still get the same 2 error messages.

<meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval' https://js.example.com/1.0.0/widget.prod.min.js;"
    />

I've also tried adding a second content-security-policy like this, but then it fails to load the 'self' JavaScript:

<meta
      http-equiv="Content-Security-Policy"
      content="script-src-elem https://js.example.com;"
    />

And I've tried adding to the initial Content-Security-Policy meta tag like this, but it also fails to load the 'self' JavaScript:

<meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'wasm-unsafe-eval'; script-src-elem https://js.example.com;"
    />

I've been reading every MDN documentation related to CSP: script-src but can't figure out what I'm doing wrong. I've even started watching YouTube videos and reading random blog articles related to CSP (Content-Security-Policy) but nothing I've tried based on my research has worked.

*I've also reviewed some similar questions asked here on StackOverflow but can't seem to find a solid answer.

One of the recommendations was to add your CSP to the manifest.json, which I did, but the CSP section says you can only use 'self', 'none', 'wasm-unsafe-eval' and local sources. (seems like you can't use external sources unless you're using sandbox?)

So I tried doing this, but received the same errors again (I'm not sure if I coded this correctly though, I couldn't find how to add the "script-src 'self' ..." for "extension_pages", only for "sandbox").

 "content_security_policy": {
    "extension_pages": "options.html",
    "extension_pages": "allow-scripts; script-src 'self' 'wasm-unsafe-eval'"
  }

One alternative I tried was grabbing the external JavaScript file and copy-pasting it into a local file. This method got the widget loading and functioning as expected, but I'm not sure if this would be a good practice.

Some questions I have with using this method:

Are there security risks when doing this?

Will my extension be allowed to be published to Chrome Web Store if I leave it like this?


来源: stackexchange

问:
Outgoing messages are being dropped for client x
I have a client (ESP32) running umqtt.simple, and a broker (Pi) running Paho.MQTT. The Broker sends messages to the client. The client simply subscribes - and calls some functions as part of client.call_back().

I am am using client.ping() to keep the client connection alive.

The client works, but I notice that after some time the client stops receiving messages. Looking at /var/log/mosquitto/mosquitto.log on the broker I see the message 'Outgoing messages are being dropped for client [CLIENT NAME]`.

There is no disconnect shown.

I am trying to work out why outgoing messages are being dropped. The only question I can see describing this is here: Mosquitto: Outgoing messages are being dropped. They suggest the solution is to set max_queued_messages 0 in mosquitto.conf. The explanation for this is that this parameter controls the 'maximum number of QoS 1 or 2 messages to hold in the queue (per client)'.

The issue is I am publishing my messages from the broker with the default qos = 0, which is 'fire and forget'. Nothing should be being held.

Here is a simplified account of my code on the broker - which is dropping messages for the client.

```<code>import paho.mqtt.client as paho
BROKER = [broker_ip]
uname = [uname]
pwd = [password]

def on_pub(client, userdata, result):
    print('Published', result)
    pass

client = paho.Client('Pi')
client.on_publish = on_pub
client.username_pw_set(password = pwd, username = uname)
while True:
    [when some condition True]: #This condition isn't met very repeatedly very fast. Its a motion sensor that only sends a message if there hasn't been motion for a while, or if the motion reset counter has expired
        client.publish(topic = [topic], payload = [payload])
</code>```

A simplified account of the micropython code on the ESP is as follows:

```<code>from umqtt.simple import MQTTClient
import time
[Call function to connect to the WiFi function]

BROKER_IP = [broker_IP]
CLIENT_NAME = [client_name]
USER = [user]
PASSWORD = [password]
TOPIC = [topic]

x = [some_list]
def sub_cb(topic, msg):
    global x
    [clean the message string so its a list]
    [pass the cleaned list and x to a function]
    [reassign some variables so that the cleaned list becomes x for the time the message is recieved]

def connect_and_subscribe():
    global CLIENT_NAME, BROKER_IP, USER, PASSWORD, TOPIC
    client = MQTTClient(client_id=CLIENT_NAME,
                    server=BROKER_IP,
                    user=USER,
                    password=PASSWORD,
                    keepalive=60)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(TOPIC)
    print('Connected to MQTT broker at: %s, subscribed to topic: %s' % (BROKER_IP, TOPIC))
    return(client)

client = connect_and_subscribe()

now = time.time()
while True:
    try: #In case broker has had to reboot, and check_masg fails, wait 60 secs and try again
        client.check_msg()
    except:
        time.sleep(60)
        client = connect_and_subscribe()
    time.sleep(0.1)
    if time.time() - now > 80: #Ping every 80 secs to keep client alive (will drop client after 90secs (1.5 * keepalive value)
        client.ping()
        now = time.time()
</code>```

The other thing i should note is that the function called in sub_cb can take 5 secs to run. I saw on the golang MQTT page that if the callback function invokes a long run-time, a separate go routine should be written for it. I saw nothing of the sort for the python documentation.

Why am I getting this error and what can I do to get rid of it? I don't want to just set max_queued_messages 0 as I assume this will just store whatever is being stored until the system runs out memory and fails silently - but perhaps I have this wrong.

ContentLicense: CC BY-SA 4.0

Body:
I have a client (ESP32) running umqtt.simple, and a broker (Pi) running Paho.MQTT. The Broker sends messages to the client. The client simply subscribes - and calls some functions as part of client.call_back().

I am am using client.ping() to keep the client connection alive.

The client works, but I notice that after some time the client stops receiving messages. Looking at /var/log/mosquitto/mosquitto.log on the broker I see the message 'Outgoing messages are being dropped for client [CLIENT NAME]`.

There is no disconnect shown.

I am trying to work out why outgoing messages are being dropped. The only question I can see describing this is here: Mosquitto: Outgoing messages are being dropped. They suggest the solution is to set max_queued_messages 0 in mosquitto.conf. The explanation for this is that this parameter controls the 'maximum number of QoS 1 or 2 messages to hold in the queue (per client)'.

The issue is I am publishing my messages from the broker with the default qos = 0, which is 'fire and forget'. Nothing should be being held.

Here is a simplified account of my code on the broker - which is dropping messages for the client.

import paho.mqtt.client as paho
BROKER = [broker_ip]
uname = [uname]
pwd = [password]

def on_pub(client, userdata, result):
    print('Published', result)
    pass

client = paho.Client('Pi')
client.on_publish = on_pub
client.username_pw_set(password = pwd, username = uname)
while True:
    [when some condition True]: #This condition isn't met very repeatedly very fast. Its a motion sensor that only sends a message if there hasn't been motion for a while, or if the motion reset counter has expired
        client.publish(topic = [topic], payload = [payload])

A simplified account of the micropython code on the ESP is as follows:

from umqtt.simple import MQTTClient
import time
[Call function to connect to the WiFi function]

BROKER_IP = [broker_IP]
CLIENT_NAME = [client_name]
USER = [user]
PASSWORD = [password]
TOPIC = [topic]

x = [some_list]
def sub_cb(topic, msg):
    global x
    [clean the message string so its a list]
    [pass the cleaned list and x to a function]
    [reassign some variables so that the cleaned list becomes x for the time the message is recieved]

def connect_and_subscribe():
    global CLIENT_NAME, BROKER_IP, USER, PASSWORD, TOPIC
    client = MQTTClient(client_id=CLIENT_NAME,
                    server=BROKER_IP,
                    user=USER,
                    password=PASSWORD,
                    keepalive=60)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(TOPIC)
    print('Connected to MQTT broker at: %s, subscribed to topic: %s' % (BROKER_IP, TOPIC))
    return(client)

client = connect_and_subscribe()

now = time.time()
while True:
    try: #In case broker has had to reboot, and check_masg fails, wait 60 secs and try again
        client.check_msg()
    except:
        time.sleep(60)
        client = connect_and_subscribe()
    time.sleep(0.1)
    if time.time() - now > 80: #Ping every 80 secs to keep client alive (will drop client after 90secs (1.5 * keepalive value)
        client.ping()
        now = time.time()

The other thing i should note is that the function called in sub_cb can take 5 secs to run. I saw on the golang MQTT page that if the callback function invokes a long run-time, a separate go routine should be written for it. I saw nothing of the sort for the python documentation.

Why am I getting this error and what can I do to get rid of it? I don't want to just set max_queued_messages 0 as I assume this will just store whatever is being stored until the system runs out memory and fails silently - but perhaps I have this wrong.


问:
comparing results from groupby query in neo4j
I had a query which resulted in the table below.

```<code>╒═══════════════════════════════════════════════════╤═════════════════════╤═════════╕
│"title"                                            │"count(theme)"       │"x.name" │
╞═══════════════════════════════════════════════════╪═════════════════════╪═════════╡
│"Game of thrones"                                  │8                    │"X1"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of thrones"                                  │4                    │"X2"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of empire"                                   │4                    │"X1"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of empire"                                   │4                    │"X2"     │

</code>```

However, I will like to return the result below because the count(theme) is not equal for the group.

```<code>╒═══════════════════════════════════════════════════
│"title"                                            │
╞═══════════════════════════════════════════════════
│"Game of thrones"                                  │
├───────────────────────────────────────────────────┼
</code>```

I have tried using a match and with but i am not getting it right as i am new to neo4j.

Body:
I had a query which resulted in the table below.

╒═══════════════════════════════════════════════════╤═════════════════════╤═════════╕
│"title"                                            │"count(theme)"       │"x.name" │
╞═══════════════════════════════════════════════════╪═════════════════════╪═════════╡
│"Game of thrones"                                  │8                    │"X1"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of thrones"                                  │4                    │"X2"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of empire"                                   │4                    │"X1"     │
├───────────────────────────────────────────────────┼─────────────────────┼─────────┤
│"Game of empire"                                   │4                    │"X2"     │

However, I will like to return the result below because the count(theme) is not equal for the group.

╒═══════════════════════════════════════════════════
│"title"                                            │
╞═══════════════════════════════════════════════════
│"Game of thrones"                                  │
├───────────────────────────────────────────────────┼

I have tried using a match and with but i am not getting it right as i am new to neo4j.


问:
How to loop through a list of documents using Dart to find one where the other reference parameter is in the record using Dart?
This is my code.

There are two input parameters: userCounterParty which is a reference to the User collection; chatsDocsListAuthUser which is a list of records from the Chats Collection.

I want to return the Chat doc where userCounterParty is in the field (which is a List) userList.

userList is one of the fields for every Chat doc.

```<code>    ChatsRecord? returnChatDocFromAuthUser(List<ChatsRecord>? chatDocList, DocumentReference? chatCounterParty,)  {
  /// MODIFY CODE ONLY BELOW THIS LINE

  if (chatDocList != null && chatCounterParty != null)

    for (ChatsRecord chatDoc in chatDocList) {
      chatDoc ?? " ";

      if (chatDoc.userList.contains(chatCounterParty)) {
        return chatDoc;
        break;
      } else {
        return null;
      }
    }
  }

  return null;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}
</code>```

Body:
This is my code.

There are two input parameters: userCounterParty which is a reference to the User collection; chatsDocsListAuthUser which is a list of records from the Chats Collection.

I want to return the Chat doc where userCounterParty is in the field (which is a List) userList.

userList is one of the fields for every Chat doc.

    ChatsRecord? returnChatDocFromAuthUser(List<ChatsRecord>? chatDocList, DocumentReference? chatCounterParty,)  {
  /// MODIFY CODE ONLY BELOW THIS LINE

  if (chatDocList != null && chatCounterParty != null)

    for (ChatsRecord chatDoc in chatDocList) {
      chatDoc ?? " ";

      if (chatDoc.userList.contains(chatCounterParty)) {
        return chatDoc;
        break;
      } else {
        return null;
      }
    }
  }

  return null;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}


问:
Typegoose generic manager error with compiler
I'm having some issues with the creation of a generic manager with typegoose and mongoose

export class Manager<T extends types.AnyParamConstructor<any>> {
  model: ReturnModelType<T>;

  constructor(cls: T) {
    this.model = getModelForClass(cls);
  }

  async findOneOr404(
    filter?: FilterQuery<T>,
    projection?: ProjectionType<T> | null,
    options?: QueryOptions<T> | null,
    callback?: Callback<HydratedDocument<DocumentType<InstanceType<T>, types.BeAnObject>, {}, {}> | null> | undefined,
  ): Promise<DocumentType<T>> {
    const object = await this.model.findOne(filter, projection, options, callback);
    if (!object) {
      throw new NotFoundException(`${this.model.modelName} not found`);
    }
    return object;
  }
}
```
<p>This is my actual generic manager, the main goal here is to have functions like <code>findOneOr404</code> to use in the most common cases.</p>
<p>After this, I thought it would be easy, I create a User model like this one></p>
<pre class="lang-js prettyprint-override"><code>import { prop } from '@typegoose/typegoose';

// Export the User class to be used as TypeScript type
export class User {
  @prop()
  name: string;

  @prop({ unique: true, required: true })
  email: string;

  @prop({ required: true, minlength: 8, maxLength: 32 })
  password: string;

  @prop({ required: true, minlength: 8, maxLength: 32 })
  salt: string;

  @prop({ default: 'user' })
  role: string;
}
</code>```

Up to here nothing fancy, just easy code

But now, when I'm going to the controller the thing starts going crazy

export class AuthController {
  path = '/auth';
  userManager;
  public router = Router();
  private jwtService: JwtService;

  constructor() {
    this.jwtService = new JwtService();
    this.userManager = new Manager(User);
    this.initializePaths();
  }
  login = async (req: Request, res: Response, next: NextFunction): Promise<any> => {
    try {
      const { body } = req;
      const user = await this.userManager.findOneOr404({ email: body.email });
      this.validateUser(user, body.password);
      const token = await this.signToken(user);
      res.json({
        error: null,
        data: { token },
      });
    } catch (e) {
      throw e;
    }
  };
  private validateUser = (user: DocumentType<User, BeAnObject>, password: string): void => {
    if (!user) throw new Error('Not found');
    if (!verifyPassword(user.password, user.salt, password)) throw new ForbiddenException('Wrong email or password');
  };
```
<p>In this very first case Im having the following issue</p>
```TS2345: Argument of type 'DocumentType<typeof User, BeAnObject>' is not assignable to parameter of type 'DocumentType<User, BeAnObject>'.   Type 'DocumentType<typeof User, BeAnObject>' is not assignable to type 'User'.
```
<p>I don't know why is referring to typeof user</p>
<p>then if I change for something like</p>
<pre class="lang-js prettyprint-override"><code>export class AuthController {
  path = '/auth';
  userManager: Manager<User>;
....
</code>```
```<code>TS2344: Type 'User' does not satisfy the constraint 'AnyParamConstructor<any>'.   Type 'User' provides no match for the signature 'new (...args: any): any'.
</code>```

Does anyone knows what could be happening here?
I've been looking for days

Body:
I'm having some issues with the creation of a generic manager with typegoose and mongoose

export class Manager<T extends types.AnyParamConstructor<any>> {
  model: ReturnModelType<T>;

  constructor(cls: T) {
    this.model = getModelForClass(cls);
  }

  async findOneOr404(
    filter?: FilterQuery<T>,
    projection?: ProjectionType<T> | null,
    options?: QueryOptions<T> | null,
    callback?: Callback<HydratedDocument<DocumentType<InstanceType<T>, types.BeAnObject>, {}, {}> | null> | undefined,
  ): Promise<DocumentType<T>> {
    const object = await this.model.findOne(filter, projection, options, callback);
    if (!object) {
      throw new NotFoundException(`${this.model.modelName} not found`);
    }
    return object;
  }
}

This is my actual generic manager, the main goal here is to have functions like findOneOr404 to use in the most common cases.

After this, I thought it would be easy, I create a User model like this one>

import { prop } from '@typegoose/typegoose';

// Export the User class to be used as TypeScript type
export class User {
  @prop()
  name: string;

  @prop({ unique: true, required: true })
  email: string;

  @prop({ required: true, minlength: 8, maxLength: 32 })
  password: string;

  @prop({ required: true, minlength: 8, maxLength: 32 })
  salt: string;

  @prop({ default: 'user' })
  role: string;
}

Up to here nothing fancy, just easy code

But now, when I'm going to the controller the thing starts going crazy

export class AuthController {
  path = '/auth';
  userManager;
  public router = Router();
  private jwtService: JwtService;

  constructor() {
    this.jwtService = new JwtService();
    this.userManager = new Manager(User);
    this.initializePaths();
  }
  login = async (req: Request, res: Response, next: NextFunction): Promise<any> => {
    try {
      const { body } = req;
      const user = await this.userManager.findOneOr404({ email: body.email });
      this.validateUser(user, body.password);
      const token = await this.signToken(user);
      res.json({
        error: null,
        data: { token },
      });
    } catch (e) {
      throw e;
    }
  };
  private validateUser = (user: DocumentType<User, BeAnObject>, password: string): void => {
    if (!user) throw new Error('Not found');
    if (!verifyPassword(user.password, user.salt, password)) throw new ForbiddenException('Wrong email or password');
  };

In this very first case Im having the following issue

TS2345: Argument of type 'DocumentType<typeof User, BeAnObject>' is not assignable to parameter of type 'DocumentType<User, BeAnObject>'.   Type 'DocumentType<typeof User, BeAnObject>' is not assignable to type 'User'.

I don't know why is referring to typeof user

then if I change for something like

export class AuthController {
  path = '/auth';
  userManager: Manager<User>;
....

TS2344: Type 'User' does not satisfy the constraint 'AnyParamConstructor<any>'.   Type 'User' provides no match for the signature 'new (...args: any): any'.

Does anyone knows what could be happening here?
I've been looking for days


问:
Python Desktop Pop-Up Notification doesn't work with .pyw file
I wrote this python script that sends me a Desktop Notification of the current temperature, but when I save the .py file as a .pyw file, to start the script in the background, the pop up isn't working and the message only appears in the info center. Otherwise the code works just fine when I run it in the terminal or in vscode. Even when I run it with the pythonw command in the terminal it works fine. The only problem is that when I try opening it by hand, the pop up doesn't appear. I want to put the file in startup to execute it when I log in.

```<code>from plyer import notification
import requests
import time

temperature = None
lat = None
lon = None         #didn't want to show these variables so i cut them out temporarly
apikey = None

try:
    response = requests.get("https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid= {}&units=metric".format(lat, lon, apikey))
    data = response.json()
except:
    print("Please! Check your internet connection")

notification.notify(
    title = "Today's temperature",
    message = "{}\u00B0C".format(data['main']['temp']),
    app_icon = "C:/Users/myUsername/Desktop/DailyWeather/weather.ico",
    timeout = 10,
)
</code>```

This is my code.

Body:
I wrote this python script that sends me a Desktop Notification of the current temperature, but when I save the .py file as a .pyw file, to start the script in the background, the pop up isn't working and the message only appears in the info center. Otherwise the code works just fine when I run it in the terminal or in vscode. Even when I run it with the pythonw command in the terminal it works fine. The only problem is that when I try opening it by hand, the pop up doesn't appear. I want to put the file in startup to execute it when I log in.

from plyer import notification
import requests
import time

temperature = None
lat = None
lon = None         #didn't want to show these variables so i cut them out temporarly
apikey = None

try:
    response = requests.get("https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid= {}&units=metric".format(lat, lon, apikey))
    data = response.json()
except:
    print("Please! Check your internet connection")

notification.notify(
    title = "Today's temperature",
    message = "{}\u00B0C".format(data['main']['temp']),
    app_icon = "C:/Users/myUsername/Desktop/DailyWeather/weather.ico",
    timeout = 10,
)

This is my code.


问:
Since symfony/http-foundation 6.2: The "Symfony\Component\HttpFoundation\Request::getContentType()" method is deprecated, use "getContentTypeFormat()"
In my new project using Symfony 6.2 & Api Platform, I have a deprecation that I would like to correct. Can you help me to corret it please ?

I have the following error after running tests with PhpUnit :

Remaining indirect deprecation notices (1)

1x: Since symfony/http-foundation 6.2: The "Symfony\Component\HttpFoundation\Request::getContentType()" method is deprecated, use "getContentTypeFormat()" instead.

1x in UserTest::testPost from App\Tests\Func

The method testPost contain the following code :

public function testPost(): void
{
    $response = static::createClient()->request('POST', '/api/users', [
        'headers' => ['Accept' => 'application/json'],
        'json' => [
            'email' => 'new-user@example.com',
            'password' => 'password',
        ],
    ]);
    $this->assertResponseStatusCodeSame(201);
}
```
<p>I have try :</p>
<pre class="lang-bash prettyprint-override"><code>composer update
</code>```

But it dosent fix it. Thanks for your help.

Edit :

composer.json :

```<code>{
"type": "project",
"license": "proprietary",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
    "php": ">=8.1",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "api-platform/core": "^3.0",
    "doctrine/annotations": "^1.0",
    "doctrine/doctrine-bundle": "^2.7",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "^2.14",
    "lexik/jwt-authentication-bundle": "^2.16",
    "nelmio/cors-bundle": "^2.2",
    "phpdocumentor/reflection-docblock": "^5.3",
    "phpstan/phpdoc-parser": "^1.15",
    "symfony/asset": "6.2.*",
    "symfony/console": "6.2.*",
    "symfony/dotenv": "6.2.*",
    "symfony/expression-language": "6.2.*",
    "symfony/flex": "^2",
    "symfony/framework-bundle": "6.2.*",
    "symfony/property-access": "6.2.*",
    "symfony/property-info": "6.2.*",
    "symfony/runtime": "6.2.*",
    "symfony/security-bundle": "6.2.*",
    "symfony/serializer": "6.2.*",
    "symfony/twig-bundle": "6.2.*",
    "symfony/validator": "6.2.*",
    "symfony/yaml": "6.2.*"
},
"require-dev": {
    "doctrine/doctrine-fixtures-bundle": "^3.4",
    "fakerphp/faker": "^1.21",
    "phpunit/phpunit": "^9.5",
    "symfony/browser-kit": "6.2.*",
    "symfony/css-selector": "6.2.*",
    "symfony/http-client": "6.2.*",
    "symfony/maker-bundle": "^1.48",
    "symfony/phpunit-bridge": "^6.2"
},
"config": {
    "allow-plugins": {
        "symfony/flex": true,
        "symfony/runtime": true
    },
    "sort-packages": true
},
"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "App\\Tests\\": "tests/"
    }
},
"replace": {
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php72": "*",
    "symfony/polyfill-php73": "*",
    "symfony/polyfill-php74": "*",
    "symfony/polyfill-php80": "*",
    "symfony/polyfill-php81": "*"
},
"scripts": {
    "auto-scripts": {
        "cache:clear": "symfony-cmd",
        "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
        "@auto-scripts"
    ],
    "post-update-cmd": [
        "@auto-scripts"
    ]
},
"conflict": {
    "symfony/symfony": "*"
},
"extra": {
    "symfony": {
        "allow-contrib": false,
        "require": "6.2.*"
    }
}
}
</code>```

Body:
In my new project using Symfony 6.2 & Api Platform, I have a deprecation that I would like to correct. Can you help me to corret it please ?

I have the following error after running tests with PhpUnit :

Remaining indirect deprecation notices (1)

1x: Since symfony/http-foundation 6.2: The "Symfony\Component\HttpFoundation\Request::getContentType()" method is deprecated, use "getContentTypeFormat()" instead.

1x in UserTest::testPost from App\Tests\Func

The method testPost contain the following code :

public function testPost(): void
{
    $response = static::createClient()->request('POST', '/api/users', [
        'headers' => ['Accept' => 'application/json'],
        'json' => [
            'email' => 'new-user@example.com',
            'password' => 'password',
        ],
    ]);
    $this->assertResponseStatusCodeSame(201);
}

I have try :

composer update

But it dosent fix it. Thanks for your help.

Edit :

composer.json :

{
"type": "project",
"license": "proprietary",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
    "php": ">=8.1",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "api-platform/core": "^3.0",
    "doctrine/annotations": "^1.0",
    "doctrine/doctrine-bundle": "^2.7",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "^2.14",
    "lexik/jwt-authentication-bundle": "^2.16",
    "nelmio/cors-bundle": "^2.2",
    "phpdocumentor/reflection-docblock": "^5.3",
    "phpstan/phpdoc-parser": "^1.15",
    "symfony/asset": "6.2.*",
    "symfony/console": "6.2.*",
    "symfony/dotenv": "6.2.*",
    "symfony/expression-language": "6.2.*",
    "symfony/flex": "^2",
    "symfony/framework-bundle": "6.2.*",
    "symfony/property-access": "6.2.*",
    "symfony/property-info": "6.2.*",
    "symfony/runtime": "6.2.*",
    "symfony/security-bundle": "6.2.*",
    "symfony/serializer": "6.2.*",
    "symfony/twig-bundle": "6.2.*",
    "symfony/validator": "6.2.*",
    "symfony/yaml": "6.2.*"
},
"require-dev": {
    "doctrine/doctrine-fixtures-bundle": "^3.4",
    "fakerphp/faker": "^1.21",
    "phpunit/phpunit": "^9.5",
    "symfony/browser-kit": "6.2.*",
    "symfony/css-selector": "6.2.*",
    "symfony/http-client": "6.2.*",
    "symfony/maker-bundle": "^1.48",
    "symfony/phpunit-bridge": "^6.2"
},
"config": {
    "allow-plugins": {
        "symfony/flex": true,
        "symfony/runtime": true
    },
    "sort-packages": true
},
"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "App\\Tests\\": "tests/"
    }
},
"replace": {
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php72": "*",
    "symfony/polyfill-php73": "*",
    "symfony/polyfill-php74": "*",
    "symfony/polyfill-php80": "*",
    "symfony/polyfill-php81": "*"
},
"scripts": {
    "auto-scripts": {
        "cache:clear": "symfony-cmd",
        "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
        "@auto-scripts"
    ],
    "post-update-cmd": [
        "@auto-scripts"
    ]
},
"conflict": {
    "symfony/symfony": "*"
},
"extra": {
    "symfony": {
        "allow-contrib": false,
        "require": "6.2.*"
    }
}
}


问:
(python) How do I write code to accept input from two different (emulated) COM ports at the same time?
I'm writing a program to accept input from multiple barcode scanners, and differentiate between individual scanners. I'm using pyserial, and I can differentiate between scanners, and get input from each, but the problem is that it's way too unreliable. It seems like when my code is waiting for input from one scanner, the input from the other is lost.

In the following code, assume ports is a list of the ports the scanners occupy:

```<code>import serial

while True:
    for port in ports:
        scanner = serial.Serial(port=port, baudrate=9600, bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE)
        string = scanner.readline()
        scanner.close()
        if not string.decode() == '': print(string.decode())
</code>```

The problem here is that when scanner.readline() executes, it pauses my code for how ever long I specified in the timeout portion of the serial.Serial() line. So what I think is happening is that my code is only looking at one scanner at a time, and misses any imputs from the other during that period. I've also tried timeout=.01, but that only seems to make things worse. I also tried serial.Serial(port=ports, ...) which throws up an error, and I'm unaware of any other method to create an object which contains every scanner, and manipulate them all as a group.

I was also thinking I might be able to tell a scanner to wait, or buffer any inputs from it while I'm reading one, but I don't know where I'd even begin to do that. I'm using scanners from Netum, if that's important. They're pretty opaque when it comes to customer support, so I'm not even certain they can accept input from anything outside of the barcodes they scan. But I do know they have a buffer in case they get disconnected from the computer temporarily, so I might be able to finagle that into what I need.

Any advice? I'm more than willing to switch to a different approach or library. I just need my code to talk to multiple scanners simultaneously (or close to it), as well as differentiate between each of them.

I also saw this post, which should solve my problem on paper, but I didn't even know the subprocess module existed until just now. No matter how much I fiddle with it, I can't get it to work. Even if I swap in my program name in the Popen() line, and add a timeout value, it can't see my scanner no matter what I do. All I get out of p1.stdout.readline() is a 'bytes' object which reads b'' If this is the solution, that's okay, but I'm hoping for something simpler. I'm already pushing the limit of my abilities to the max, so the idea of needing to learn yet another library is pretty daunting.

Body:
I'm writing a program to accept input from multiple barcode scanners, and differentiate between individual scanners. I'm using pyserial, and I can differentiate between scanners, and get input from each, but the problem is that it's way too unreliable. It seems like when my code is waiting for input from one scanner, the input from the other is lost.

In the following code, assume ports is a list of the ports the scanners occupy:

import serial

while True:
    for port in ports:
        scanner = serial.Serial(port=port, baudrate=9600, bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE)
        string = scanner.readline()
        scanner.close()
        if not string.decode() == '': print(string.decode())

The problem here is that when scanner.readline() executes, it pauses my code for how ever long I specified in the timeout portion of the serial.Serial() line. So what I think is happening is that my code is only looking at one scanner at a time, and misses any imputs from the other during that period. I've also tried timeout=.01, but that only seems to make things worse. I also tried serial.Serial(port=ports, ...) which throws up an error, and I'm unaware of any other method to create an object which contains every scanner, and manipulate them all as a group.

I was also thinking I might be able to tell a scanner to wait, or buffer any inputs from it while I'm reading one, but I don't know where I'd even begin to do that. I'm using scanners from Netum, if that's important. They're pretty opaque when it comes to customer support, so I'm not even certain they can accept input from anything outside of the barcodes they scan. But I do know they have a buffer in case they get disconnected from the computer temporarily, so I might be able to finagle that into what I need.

Any advice? I'm more than willing to switch to a different approach or library. I just need my code to talk to multiple scanners simultaneously (or close to it), as well as differentiate between each of them.

I also saw this post, which should solve my problem on paper, but I didn't even know the subprocess module existed until just now. No matter how much I fiddle with it, I can't get it to work. Even if I swap in my program name in the Popen() line, and add a timeout value, it can't see my scanner no matter what I do. All I get out of p1.stdout.readline() is a 'bytes' object which reads b'' If this is the solution, that's okay, but I'm hoping for something simpler. I'm already pushing the limit of my abilities to the max, so the idea of needing to learn yet another library is pretty daunting.


问:
Navigate from one Component to another with React, WHILE Passing Props
I have a React App with several Components, in separate Files.

Each Component is nested under the Root, of course.

I have BrowserRouter at the Root-level

```<code>function App() {

  return (
    <div className="app">
      <BrowserRouter>
        <Routes>
          <Route path="/product" element={<Home />} />

          <Route path="/program" element={<Program subject={SubjectSelector.TEST_SUBJECT} program={ProgramSelector.TEST_PROGRAM} />} />

          <Route path="/purchase" element={<Purchase />} />
        </Routes>
      </BrowserRouter>
    </div>
  );
}
</code>```

As you can see, the /program Route Renders the <Program> Component with some Props.

I want to Route to this <Program> Component after clicking a button in my Apps' Header Navigation.

Here's my Question:

How do I Navigate to this Component when a Button is pressed AND pass in Props?

I'm hoping to avoid something like Context that I'd need to wrap around the Root Component, since that would be a lot of unnecessary data available throughout all my Components. But I need the ability to set Props and Navigate to a Component from another upon a Button Click.

I have looked around the internet for a solution, but haven't seen anything beyond the below.

I'm aware of the history.push() and history.location options.
BUT, none of these allow me to pass Props.

I believe location has a state Field, but I don't believe this will populate my Props (correct me if I'm mistaken).

I effectively want to do something like:

```<code>...
  const goToProgram = (programName: string) => {
    // ... Something that allows me to Render a Component like the below
    <Program subject={SubjectSelector.FITNESS} program={programName} />
  }

 return (
   <h2 onClick={() => goToProgram(ProgramSelector.SOME_PROGRAM)} >Go To Program</h2>
 );
...
</code>```

\

NOTE:

I see this Post, but it doesn't allow Props on a Component. I am asking to pass data WITH Props

For example:

```<code><Program subject={SubjectSelector.TEST_SUBJECT} program={ProgramSelector.TEST_PROGRAM} />
</code>```

I wish to handle this explicitly, with Props defined on the Component.

Then, I want to Navigate to this Component, populating these explicit Properties.

useNavigate and useLocation works, as mentioned in the above linked Post with answer section of "Pass Route State".

BUT, when I defined my BrowserRouter Routes, I give some value to the Props (e.g. <Program subject={....}.../>, so the Props exist. And if I use useLocation to extract the passed State (which is NOT via Props), I'll need to name it something different than the Props, leading to some ugly code (and never actually doing what I wanted in the first place, populating the Props themselves).

For example:

```<code>function Program( {subject, program}: {subject: SubjectSelector, program: ProgramSelector} ) {

  const { state: { sub, prog } = {} } = useLocation();
  if( sub != null ) subject = sub;
  if( prog != null ) program = prog;

  ...
}
</code>```

Body:
I have a React App with several Components, in separate Files.

Each Component is nested under the Root, of course.

I have BrowserRouter at the Root-level

function App() {

  return (

      <BrowserRouter>
        <Routes>
          <Route path="/product" element={<Home />} />

          <Route path="/program" element={<Program subject={SubjectSelector.TEST_SUBJECT} program={ProgramSelector.TEST_PROGRAM} />} />

          <Route path="/purchase" element={<Purchase />} />
        </Routes>
      </BrowserRouter>

  );
}

As you can see, the /program Route Renders the <Program> Component with some Props.

I want to Route to this <Program> Component after clicking a button in my Apps' Header Navigation.

Here's my Question:

How do I Navigate to this Component when a Button is pressed AND pass in Props?

I'm hoping to avoid something like Context that I'd need to wrap around the Root Component, since that would be a lot of unnecessary data available throughout all my Components. But I need the ability to set Props and Navigate to a Component from another upon a Button Click.

I have looked around the internet for a solution, but haven't seen anything beyond the below.

I'm aware of the history.push() and history.location options.
BUT, none of these allow me to pass Props.

I believe location has a state Field, but I don't believe this will populate my Props (correct me if I'm mistaken).

I effectively want to do something like:

...
  const goToProgram = (programName: string) => {
    // ... Something that allows me to Render a Component like the below
    <Program subject={SubjectSelector.FITNESS} program={programName} />
  }

 return (

 goToProgram(ProgramSelector.SOME_PROGRAM)} >Go To Program

 );
...

\

NOTE:

I see this Post, but it doesn't allow Props on a Component. I am asking to pass data WITH Props

For example:

<Program subject={SubjectSelector.TEST_SUBJECT} program={ProgramSelector.TEST_PROGRAM} />

I wish to handle this explicitly, with Props defined on the Component.

Then, I want to Navigate to this Component, populating these explicit Properties.

useNavigate and useLocation works, as mentioned in the above linked Post with answer section of "Pass Route State".

BUT, when I defined my BrowserRouter Routes, I give some value to the Props (e.g. <Program subject={....}.../>, so the Props exist. And if I use useLocation to extract the passed State (which is NOT via Props), I'll need to name it something different than the Props, leading to some ugly code (and never actually doing what I wanted in the first place, populating the Props themselves).

For example:

function Program( {subject, program}: {subject: SubjectSelector, program: ProgramSelector} ) {

  const { state: { sub, prog } = {} } = useLocation();
  if( sub != null ) subject = sub;
  if( prog != null ) program = prog;

  ...
}


问:
Pinescript - different results on backtesting vs live alert
I have created a basic script with the following buy and sell conditions and  calc_on_order_fills = true.

```<code>strategy("Current strategy code", overlay=true,use_bar_magnifier = true, pyramiding = 0, calc_on_order_fills = true)

length = input.int(14, minval=1)
smoothK = 3
smoothD = 3
k = ta.sma(ta.stoch(close, high, low, length), smoothK)
d = ta.sma(k, smoothD)
sma= ta.sma(close, 200)

buycondition = ta.crossover(k,d)
sellcondition = ta.crossunder(k,d)

if (buycondition)
    strategy.entry("Long", strategy.long, comment="Long")

if (sellcondition)
    strategy.entry("Short", strategy.short, comment="Short")
</code>```

When I compare the results on tradingview backtest vs the alert I've set up they're different.

Would this be because the backtest is recalculating once the order is filled? Or only has the data for the open, high and low of the candle?
Is there something I can add so that the alert does exactly the same trades as the backtest?

I tried changing the code to only enter trades based off the close of the candle but this had a bad effect on the results, so would ideally like to replicate the backtest process for my alerts.

Any help appreciated!

Body:
I have created a basic script with the following buy and sell conditions and  calc_on_order_fills = true.

strategy("Current strategy code", overlay=true,use_bar_magnifier = true, pyramiding = 0, calc_on_order_fills = true)

length = input.int(14, minval=1)
smoothK = 3
smoothD = 3
k = ta.sma(ta.stoch(close, high, low, length), smoothK)
d = ta.sma(k, smoothD)
sma= ta.sma(close, 200)

buycondition = ta.crossover(k,d)
sellcondition = ta.crossunder(k,d)

if (buycondition)
    strategy.entry("Long", strategy.long, comment="Long")

if (sellcondition)
    strategy.entry("Short", strategy.short, comment="Short")

When I compare the results on tradingview backtest vs the alert I've set up they're different.

Would this be because the backtest is recalculating once the order is filled? Or only has the data for the open, high and low of the candle?
Is there something I can add so that the alert does exactly the same trades as the backtest?

I tried changing the code to only enter trades based off the close of the candle but this had a bad effect on the results, so would ideally like to replicate the backtest process for my alerts.

Any help appreciated!


问:
How to call a function out of list by its index in R?
So I have a list of functions and need to call specific function in this list without using it's name. So just using a position in the list.

Adding simplificated example for the general idea.

```<code>d <- function(){print("d")}
e <- function(){print("e")}
r <- list(d, e)
</code>```

Now if I wanted to call function "d" while using r[], how do I do that?

I've tried using

```<code>r[1]()
</code>```

but it just brings the "Attempt to apply non function" Error.

Body:
So I have a list of functions and need to call specific function in this list without using it's name. So just using a position in the list.

Adding simplificated example for the general idea.

d <- function(){print("d")}
e <- function(){print("e")}
r <- list(d, e)

Now if I wanted to call function "d" while using r[], how do I do that?

I've tried using

r[1]()

but it just brings the "Attempt to apply non function" Error.


问:
Proper way to to show chords and lyrics in Android app using a textview
I have made a simple Kotlin app which is used to see lyrics and chords together.

I made a textview and set it as per requirements, but the problem is that  I could not show chords in the lyrics properly.

This is the current status of my app, while this is an example of what I'm trying to achieve.

In the first image, I can edit the content but the ending result is not good.
In the second image, which is taken from another app, the ending result is nice, and every chord is clickable too.

How can I achieve the same in Kotlin or in Java? How can I make it clickable for a single letter within a textview?

How to put chords in proper way?

Please help me.


问:
Why isn't silence placed in the output audio file with AudioSegment.silent?
The output of the file is unchanged from the source.

I expect the following to mute the audio for a length of one second at two seconds into the audio file.

Python version: 3.7

```<code>from pydub import AudioSegment

audio_file = "input_audio.mp3"

# Load audio file into pydub
audio = AudioSegment.from_mp3(audio_file)

# place one second of silence two seconds in to mute that portion
audio = audio.overlay(AudioSegment.silent(duration=1000, frame_rate=audio.frame_rate), position=2000)

# Save audio with word muted to new file
audio.export("output audio.mp3", format="mp3")```
```

Body:
The output of the file is unchanged from the source.

I expect the following to mute the audio for a length of one second at two seconds into the audio file.

Python version: 3.7

from pydub import AudioSegment

audio_file = "input_audio.mp3"

# Load audio file into pydub
audio = AudioSegment.from_mp3(audio_file)

# place one second of silence two seconds in to mute that portion
audio = audio.overlay(AudioSegment.silent(duration=1000, frame_rate=audio.frame_rate), position=2000)

# Save audio with word muted to new file
audio.export("output audio.mp3", format="mp3")```


问:
How to make a Random Vec3 in Three.js and Open GL
I am Currently using Vec3's in my code to produce a gradient. However when i create the Material in THREE.js I want to make the two colors I blend together random. `

```<code>   shader.vertexShader = `
      uniform float time;
      attribute float sizes;
      attribute vec4 shift;
      vec3 randColor1;
      varying vec3 vColor;

      ${shader.vertexShader}
    `.replace(
      `gl_PointSize = size;`,
      `gl_PointSize = size * sizes;`
    ).replace(
      `#include <color_vertex>`,
      `#include <color_vertex>

        randColor1 = vec3(10, 520., 80.);
        float d = length(abs(position) / vec3(40., 10., 40));
        d = clamp(d, 0., 1.);
        vColor = mix(randColor1, vec3(10., 20., 200.), d) / 255.;
      `
    )
</code>```

`
I want randColor1 to be three random floating point  values

I used the rand() % method my object doesn't generate. I also tried to use `

```<code>#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // Initialization, should only be called once.
int r = rand();
</code>```

`
however the imports mess up my object creation

Body:
I am Currently using Vec3's in my code to produce a gradient. However when i create the Material in THREE.js I want to make the two colors I blend together random. `

   shader.vertexShader = `
      uniform float time;
      attribute float sizes;
      attribute vec4 shift;
      vec3 randColor1;
      varying vec3 vColor;

      ${shader.vertexShader}
    `.replace(
      `gl_PointSize = size;`,
      `gl_PointSize = size * sizes;`
    ).replace(
      `#include <color_vertex>`,
      `#include <color_vertex>

        randColor1 = vec3(10, 520., 80.);
        float d = length(abs(position) / vec3(40., 10., 40));
        d = clamp(d, 0., 1.);
        vColor = mix(randColor1, vec3(10., 20., 200.), d) / 255.;
      `
    )

`
I want randColor1 to be three random floating point  values

I used the rand() % method my object doesn't generate. I also tried to use `

#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // Initialization, should only be called once.
int r = rand();

`
however the imports mess up my object creation


问:
EF Distinct In One Column
How to get values from several columns based on distinct values from one column?

I have a table with 3 columns (ID, Name ,Date).
I need to retrieve all distinct names with respective Date using Entity Framework, how can I do it?

I have this

```<code>TabLogVisits = await _context.TabLogVisits
               .Select( x =>  new { x.Name, x.Date })
               .Distinct()
               .ToListAsync();
</code>```

but it retrieves all the names, not distinct.

If I use this

```<code>TabLogVisits = await _context.TabLogVisits
               .Select( x =>  x.Name)
               .Distinct()
               .ToListAsync();
</code>```

I can get only the distinct name, but, of course, I will not get the respective Date.
I already tried everything I found in google, but I can't figure it out.
What am I doing wrong here?

Title: EF Distinct In One Column

Body:
How to get values from several columns based on distinct values from one column?

I have a table with 3 columns (ID, Name ,Date).
I need to retrieve all distinct names with respective Date using Entity Framework, how can I do it?

I have this

TabLogVisits = await _context.TabLogVisits
               .Select( x =>  new { x.Name, x.Date })
               .Distinct()
               .ToListAsync();

but it retrieves all the names, not distinct.

If I use this

TabLogVisits = await _context.TabLogVisits
               .Select( x =>  x.Name)
               .Distinct()
               .ToListAsync();

I can get only the distinct name, but, of course, I will not get the respective Date.
I already tried everything I found in google, but I can't figure it out.
What am I doing wrong here?


问:
How do I crop a dart:ui Image in Flutter
How can I crop a dart:ui Image in Flutter.

I am aware of the copyCrop() function in the image package (https://pub.dev/packages/image), however that would then require converting Image types...

The following question:
How do I Crop Images in Flutter?
Requires the use of the image package, but I want to keep the image in ui image format...

What I am using this for requires high speeds, and using the image package to crop my image, would then require me to convert back and forth and back again to ui image.

Is there a way to crop an Image and keep it as a ui Image?


问:
Lost connect to MySQL server during query
I have an Innodb database which have a big table with many rows. Once I'm trying to access the data or run any query(like "check table_name") against this specific table mysql crashes(restarts) and I'm getting the error:
ERROR 2013 (HY000): Lost connection to MySQL server during query

I have already tried to increase max_packetsize and the net_timeouts flags.

Any help will be appreciated, Thanks!

Edit:

Crash log:

```<code>2022-12-30T16:25:56.676880Z 208 [ERROR] InnoDB: In pages [page id: space=372, pa                                                                         ge number=11135] and [page id: space=372, page number=11136] of index `GEN_CLUST                                                                         _INDEX` of table `SHAS_2015_NEW`.`b_media_21_646_0000_11925`
InnoDB: broken FIL_PAGE_NEXT or FIL_PAGE_PREV links
2022-12-30T16:25:56.676925Z 208 [ERROR] InnoDB: In pages [page id: space=372, pa                                                                         ge number=11135] and [page id: space=372, page number=11136] of index `GEN_CLUST                                                                         _INDEX` of table `SHAS_2015_NEW`.`b_media_21_646_0000_11925`
InnoDB: 'compact' flag mismatch
2022-12-30T16:25:56.676936Z 208 [ERROR] InnoDB: Page index id 0 != data dictiona                                                                         ry index id 577
2022-12-30 18:25:56 0x7fa1384e9700  InnoDB: Assertion failure in thread 14033041                                                                         1136768 in file btr0btr.cc line 4710
InnoDB: Failing assertion: !page_is_empty(page) || (level == 0 && page_get_page_                                                                         no(page) == dict_index_get_page(index))
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
16:25:56 UTC - mysqld got signal 6 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
Attempting to collect some information that could help diagnose the problem.
As this is a crash and something is definitely wrong, the information
collection process might fail.

key_buffer_size=16777216
read_buffer_size=131072
max_used_connections=1
max_threads=151
thread_count=1
connection_count=1
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 76388 K  b                                                                         ytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x7fa0f81dd110
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 7fa1384e8e70 thread_stack 0x30000
/usr/sbin/mysqld(my_print_stacktrace+0x3b)[0xe8e68b]
/usr/sbin/mysqld(handle_fatal_signal+0x36f)[0x77524f]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fa67f45d390]
/lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fa67e816438]
/lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fa67e81803a]
/usr/sbin/mysqld[0x74a77c]
/usr/sbin/mysqld[0x10dd73d]
/usr/sbin/mysqld(_Z18btr_validate_indexP12dict_index_tPK5trx_tb+0x264)[0x10dec34                                                                         ]
/usr/sbin/mysqld(_ZN11ha_innobase5checkEP3THDP15st_ha_check_opt+0x278)[0xf2a378]
/usr/sbin/mysqld(_ZN7handler8ha_checkEP3THDP15st_ha_check_opt+0x7b)[0x7cd71b]
/usr/sbin/mysqld[0xdb48f4]
/usr/sbin/mysqld(_ZN19Sql_cmd_check_table7executeEP3THD+0x97)[0xdb5497]
/usr/sbin/mysqld(_Z21mysql_execute_commandP3THDb+0x2160)[0xc42570]
/usr/sbin/mysqld(_Z11mysql_parseP3THDP12Parser_state+0x3dd)[0xc473ad]
/usr/sbin/mysqld(_Z16dispatch_commandP3THDPK8COM_DATA19enum_server_command+0x11a                                                                         0)[0xc48610]
/usr/sbin/mysqld(_Z10do_commandP3THD+0x1c7)[0xc49ae7]
/usr/sbin/mysqld(handle_connection+0x290)[0xd0e140]
/usr/sbin/mysqld(pfs_spawn_thread+0x1b4)[0xeb03e4]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7fa67f4536ba]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7fa67e8e851d]

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (7fa0f8072240): check table b_media_21_646_0000_11925
Connection ID (thread ID): 208
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
2022-12-30T16:25:56.970335Z 0 [Warning] Changed limits: max_open_files: 1024 (re                                                                         quested 5000)
2022-12-30T16:25:56.970397Z 0 [Warning] Changed limits: table_open_cache: 431 (r                                                                         equested 2000)
2022-12-30T16:25:57.145883Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is                                                                          deprecated. Please use --explicit_defaults_for_timestamp server option (see doc                                                                         umentation for more details).
2022-12-30T16:25:57.148901Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.33-0ubuntu0.16                                                                         .04.1-log) starting as process 9454 ...
2022-12-30T16:25:57.153242Z 0 [Note] InnoDB: PUNCH HOLE support available
2022-12-30T16:25:57.153267Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic                                                                          builtins
2022-12-30T16:25:57.153272Z 0 [Note] InnoDB: Uses event mutexes
2022-12-30T16:25:57.153276Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence()                                                                          is used for memory barrier
2022-12-30T16:25:57.153283Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
2022-12-30T16:25:57.153286Z 0 [Note] InnoDB: Using Linux native AIO
2022-12-30T16:25:57.153526Z 0 [Note] InnoDB: Number of pools: 1
2022-12-30T16:25:57.153643Z 0 [Note] InnoDB: Using CPU crc32 instructions
2022-12-30T16:25:57.155093Z 0 [Note] InnoDB: Initializing buffer pool, total siz                                                                         e = 20G, instances = 8, chunk size = 128M
2022-12-30T16:25:58.482523Z 0 [Note] InnoDB: Completed initialization of buffer                                                                          pool
2022-12-30T16:25:58.719968Z 0 [Note] InnoDB: If the mysqld execution user is aut                                                                         horized, page cleaner thread priority can be changed. See the man page of setpri                                                                         ority().
2022-12-30T16:25:58.744995Z 0 [Note] InnoDB: Highest supported file format is Ba                                                                         rracuda.
2022-12-30T16:25:58.915826Z 0 [Note] InnoDB: Log scan progressed past the checkp                                                                         oint lsn 10408206134578
2022-12-30T16:25:58.915857Z 0 [Note] InnoDB: Doing recovery: scanned up to log s                                                                         equence number 10408206134587
2022-12-30T16:25:58.915862Z 0 [Note] InnoDB: Database was not shutdown normally!
2022-12-30T16:25:58.915872Z 0 [Note] InnoDB: Starting crash recovery.
2022-12-30T16:25:59.270028Z 0 [Note] InnoDB: Last MySQL binlog file position 0 1                                                                         862900, file name mysql-bin.000001
2022-12-30T16:26:00.014203Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2022-12-30T16:26:00.014242Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2022-12-30T16:26:00.014281Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2022-12-30T16:26:00.075009Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2022-12-30T16:26:00.076863Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2022-12-30T16:26:00.076904Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2022-12-30T16:26:00.077640Z 0 [Note] InnoDB: Waiting for purge to start
2022-12-30T16:26:00.127880Z 0 [Note] InnoDB: 5.7.33 started; log sequence number 10408206134587
2022-12-30T16:26:00.128095Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2022-12-30T16:26:00.128605Z 0 [Note] Plugin 'FEDERATED' is disabled.
2022-12-30T16:26:00.138272Z 0 [Note] Recovering after a crash using /var/log/mysql/mysql-bin
2022-12-30T16:26:00.138325Z 0 [Note] Starting crash recovery...
2022-12-30T16:26:00.138384Z 0 [Note] Crash recovery finished.
</code>```

If I'm Using select with Limit statement then I can select up to 681,000 rows

Body:
I have an Innodb database which have a big table with many rows. Once I'm trying to access the data or run any query(like "check table_name") against this specific table mysql crashes(restarts) and I'm getting the error:
ERROR 2013 (HY000): Lost connection to MySQL server during query

I have already tried to increase max_packetsize and the net_timeouts flags.

Any help will be appreciated, Thanks!

Edit:

Crash log:

2022-12-30T16:25:56.676880Z 208 [ERROR] InnoDB: In pages [page id: space=372, pa                                                                         ge number=11135] and [page id: space=372, page number=11136] of index `GEN_CLUST                                                                         _INDEX` of table `SHAS_2015_NEW`.`b_media_21_646_0000_11925`
InnoDB: broken FIL_PAGE_NEXT or FIL_PAGE_PREV links
2022-12-30T16:25:56.676925Z 208 [ERROR] InnoDB: In pages [page id: space=372, pa                                                                         ge number=11135] and [page id: space=372, page number=11136] of index `GEN_CLUST                                                                         _INDEX` of table `SHAS_2015_NEW`.`b_media_21_646_0000_11925`
InnoDB: 'compact' flag mismatch
2022-12-30T16:25:56.676936Z 208 [ERROR] InnoDB: Page index id 0 != data dictiona                                                                         ry index id 577
2022-12-30 18:25:56 0x7fa1384e9700  InnoDB: Assertion failure in thread 14033041                                                                         1136768 in file btr0btr.cc line 4710
InnoDB: Failing assertion: !page_is_empty(page) || (level == 0 && page_get_page_                                                                         no(page) == dict_index_get_page(index))
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
16:25:56 UTC - mysqld got signal 6 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
Attempting to collect some information that could help diagnose the problem.
As this is a crash and something is definitely wrong, the information
collection process might fail.

key_buffer_size=16777216
read_buffer_size=131072
max_used_connections=1
max_threads=151
thread_count=1
connection_count=1
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 76388 K  b                                                                         ytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x7fa0f81dd110
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 7fa1384e8e70 thread_stack 0x30000
/usr/sbin/mysqld(my_print_stacktrace+0x3b)[0xe8e68b]
/usr/sbin/mysqld(handle_fatal_signal+0x36f)[0x77524f]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fa67f45d390]
/lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fa67e816438]
/lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fa67e81803a]
/usr/sbin/mysqld[0x74a77c]
/usr/sbin/mysqld[0x10dd73d]
/usr/sbin/mysqld(_Z18btr_validate_indexP12dict_index_tPK5trx_tb+0x264)[0x10dec34                                                                         ]
/usr/sbin/mysqld(_ZN11ha_innobase5checkEP3THDP15st_ha_check_opt+0x278)[0xf2a378]
/usr/sbin/mysqld(_ZN7handler8ha_checkEP3THDP15st_ha_check_opt+0x7b)[0x7cd71b]
/usr/sbin/mysqld[0xdb48f4]
/usr/sbin/mysqld(_ZN19Sql_cmd_check_table7executeEP3THD+0x97)[0xdb5497]
/usr/sbin/mysqld(_Z21mysql_execute_commandP3THDb+0x2160)[0xc42570]
/usr/sbin/mysqld(_Z11mysql_parseP3THDP12Parser_state+0x3dd)[0xc473ad]
/usr/sbin/mysqld(_Z16dispatch_commandP3THDPK8COM_DATA19enum_server_command+0x11a                                                                         0)[0xc48610]
/usr/sbin/mysqld(_Z10do_commandP3THD+0x1c7)[0xc49ae7]
/usr/sbin/mysqld(handle_connection+0x290)[0xd0e140]
/usr/sbin/mysqld(pfs_spawn_thread+0x1b4)[0xeb03e4]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7fa67f4536ba]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7fa67e8e851d]

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (7fa0f8072240): check table b_media_21_646_0000_11925
Connection ID (thread ID): 208
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
2022-12-30T16:25:56.970335Z 0 [Warning] Changed limits: max_open_files: 1024 (re                                                                         quested 5000)
2022-12-30T16:25:56.970397Z 0 [Warning] Changed limits: table_open_cache: 431 (r                                                                         equested 2000)
2022-12-30T16:25:57.145883Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is                                                                          deprecated. Please use --explicit_defaults_for_timestamp server option (see doc                                                                         umentation for more details).
2022-12-30T16:25:57.148901Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.33-0ubuntu0.16                                                                         .04.1-log) starting as process 9454 ...
2022-12-30T16:25:57.153242Z 0 [Note] InnoDB: PUNCH HOLE support available
2022-12-30T16:25:57.153267Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic                                                                          builtins
2022-12-30T16:25:57.153272Z 0 [Note] InnoDB: Uses event mutexes
2022-12-30T16:25:57.153276Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence()                                                                          is used for memory barrier
2022-12-30T16:25:57.153283Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
2022-12-30T16:25:57.153286Z 0 [Note] InnoDB: Using Linux native AIO
2022-12-30T16:25:57.153526Z 0 [Note] InnoDB: Number of pools: 1
2022-12-30T16:25:57.153643Z 0 [Note] InnoDB: Using CPU crc32 instructions
2022-12-30T16:25:57.155093Z 0 [Note] InnoDB: Initializing buffer pool, total siz                                                                         e = 20G, instances = 8, chunk size = 128M
2022-12-30T16:25:58.482523Z 0 [Note] InnoDB: Completed initialization of buffer                                                                          pool
2022-12-30T16:25:58.719968Z 0 [Note] InnoDB: If the mysqld execution user is aut                                                                         horized, page cleaner thread priority can be changed. See the man page of setpri                                                                         ority().
2022-12-30T16:25:58.744995Z 0 [Note] InnoDB: Highest supported file format is Ba                                                                         rracuda.
2022-12-30T16:25:58.915826Z 0 [Note] InnoDB: Log scan progressed past the checkp                                                                         oint lsn 10408206134578
2022-12-30T16:25:58.915857Z 0 [Note] InnoDB: Doing recovery: scanned up to log s                                                                         equence number 10408206134587
2022-12-30T16:25:58.915862Z 0 [Note] InnoDB: Database was not shutdown normally!
2022-12-30T16:25:58.915872Z 0 [Note] InnoDB: Starting crash recovery.
2022-12-30T16:25:59.270028Z 0 [Note] InnoDB: Last MySQL binlog file position 0 1                                                                         862900, file name mysql-bin.000001
2022-12-30T16:26:00.014203Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2022-12-30T16:26:00.014242Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2022-12-30T16:26:00.014281Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2022-12-30T16:26:00.075009Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2022-12-30T16:26:00.076863Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2022-12-30T16:26:00.076904Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2022-12-30T16:26:00.077640Z 0 [Note] InnoDB: Waiting for purge to start
2022-12-30T16:26:00.127880Z 0 [Note] InnoDB: 5.7.33 started; log sequence number 10408206134587
2022-12-30T16:26:00.128095Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2022-12-30T16:26:00.128605Z 0 [Note] Plugin 'FEDERATED' is disabled.
2022-12-30T16:26:00.138272Z 0 [Note] Recovering after a crash using /var/log/mysql/mysql-bin
2022-12-30T16:26:00.138325Z 0 [Note] Starting crash recovery...
2022-12-30T16:26:00.138384Z 0 [Note] Crash recovery finished.

If I'm Using select with Limit statement then I can select up to 681,000 rows


问:
storybook v7 beta, viewports and other options disappear on startup
I'm trying to setup my storybook environment and while it mostly works fine, the viewport tab, and other options, disappear on build/start. I'm not sure what's going on here, I haven't seen any information regarding it and I've been removing features from my SB environment to fix it ... so far to no avail. Any guidance would be appreciated.

storybook/preview.js -- emptied it of all content

storybook/main.js (below)

```<code>module.exports = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions'
  ],
  framework: {
    name: '@storybook/nextjs',
    options: {}
  },
  docs: {
    docsPage: true
  }
};
</code>```

step for video below:

run npm run storybook

open new browser tab

while building:

after building:

Body:
I'm trying to setup my storybook environment and while it mostly works fine, the viewport tab, and other options, disappear on build/start. I'm not sure what's going on here, I haven't seen any information regarding it and I've been removing features from my SB environment to fix it ... so far to no avail. Any guidance would be appreciated.

storybook/preview.js -- emptied it of all content

storybook/main.js (below)

module.exports = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions'
  ],
  framework: {
    name: '@storybook/nextjs',
    options: {}
  },
  docs: {
    docsPage: true
  }
};

step for video below:

run npm run storybook

open new browser tab

while building:

after building:


问:
Tabbed pane does not appear when running Java swing app. nested classes approach
I am using nested private classes to build a Java Swing application.
The tabbedPane does not appear when running the application.
When run, the application shows a blank frame. The app exits on close.

The main question is, what are the options to get the tabbedPane to appear? A second question is if nested classes are a good approach/ am I using them correctly?

The following are the relevant classes.

Constructor

```<code>package personalApp;

//imports

public class SwingApp {
//Attributes
//----- CONSTRUCTOR ------
SwingApp() throws IOException{
f1 = new Jframe();
 JTabbedPane z = new tabbedPane();
        f1.add(z);
        f1.setVisible(true);
        f1.setSize(400,400);
        f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
</code>```

tabbedPane

```<code>   private class tabbedPane extends JTabbedPane {
        @Override
        public void setVisible(boolean aFlag) {
            super.setVisible(true);
        }

        @Override
        public Component add(String title, Component component) {
            super.add("Contacts", new panel2());
            return new panel2();
        }

    }
</code>```

panel2

```<code>private class panel2 extends JPanel{

        @Override
        public void setLayout(LayoutManager mgr) {super.setLayout(new GridBagLayout());}

        @Override
        public void setBackground(Color bg) {super.setBackground(mainColor);}

        @Override
        public void setVisible(boolean aFlag) {super.setVisible(true);}

 public void add(Component comp, Object constraints) {
  //There is a JTable, JScrollPane(JTable),JToolbar and JButton added within this method. They all follow the same structure.
            openButtonPhonebook = new JButton("Open");
         //multiple lines of GridBagConstriants. c = GridBagconstraints.
            super.add(openButtonNotebook,c);
    }
}
</code>```

Main

```<code>public static void main(String[] args) throws IOException {new SwingApp();}
</code>```

I have tried adding the components in multiple add methods. This gives an error for overwriting the same method.

I have tried and was successful with adding components within the constructor method. This is causing the code to become hard to navigate. I want to use more abstraction to improve the readability of the code.

Ultimately, I am building a swing app with too much code to put in a constructor method. If there are alternatives to nested classes which improve readability, I am open to them.

Body:
I am using nested private classes to build a Java Swing application.
The tabbedPane does not appear when running the application.
When run, the application shows a blank frame. The app exits on close.

The main question is, what are the options to get the tabbedPane to appear? A second question is if nested classes are a good approach/ am I using them correctly?

The following are the relevant classes.

Constructor

package personalApp;

//imports

public class SwingApp {
//Attributes
//----- CONSTRUCTOR ------
SwingApp() throws IOException{
f1 = new Jframe();
 JTabbedPane z = new tabbedPane();
        f1.add(z);
        f1.setVisible(true);
        f1.setSize(400,400);
        f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

tabbedPane

   private class tabbedPane extends JTabbedPane {
        @Override
        public void setVisible(boolean aFlag) {
            super.setVisible(true);
        }

        @Override
        public Component add(String title, Component component) {
            super.add("Contacts", new panel2());
            return new panel2();
        }

    }

panel2

private class panel2 extends JPanel{

        @Override
        public void setLayout(LayoutManager mgr) {super.setLayout(new GridBagLayout());}

        @Override
        public void setBackground(Color bg) {super.setBackground(mainColor);}

        @Override
        public void setVisible(boolean aFlag) {super.setVisible(true);}

 public void add(Component comp, Object constraints) {
  //There is a JTable, JScrollPane(JTable),JToolbar and JButton added within this method. They all follow the same structure.
            openButtonPhonebook = new JButton("Open");
         //multiple lines of GridBagConstriants. c = GridBagconstraints.
            super.add(openButtonNotebook,c);
    }
}

Main

public static void main(String[] args) throws IOException {new SwingApp();}

I have tried adding the components in multiple add methods. This gives an error for overwriting the same method.

I have tried and was successful with adding components within the constructor method. This is causing the code to become hard to navigate. I want to use more abstraction to improve the readability of the code.

Ultimately, I am building a swing app with too much code to put in a constructor method. If there are alternatives to nested classes which improve readability, I am open to them.


问:
AWS CodeDeploy No space left on device With PNPM Project
Recently, I start NestJS project with PNPM.

every steps are very okay but when I deploy project to EC2 I got this AWS CodeDeploy Error

as you can see my EC2 storage got full.

this problem happened every CodeDeploy install event hook...

this is a CI/CD strategy.

CI with GitAction -> build -> compress tar.gz -> upload S3 -> call CodeDeploy -> PM2 Deploy

this image is CodeDeployAgent auto decompression tar file form deployment-root

when code deploy execute install event hook the node_modules file size are way bigger than before like this..

inside of node_modules every dependency reinstall they are dependencies.

```<code>ex) node_modules 1.5G
    - .pnpm 1.5G
        - lib 1
           - node_modules 500M ..
        - lib 2
           - node_modules 500M ..
        - lib 3
           - node_modules 500M ..
          ...
</code>```

this is part of GitAction workflow

```<code>...
build:
  name:  Build & S3 Upload
  needs: dependency_install
  runs-on: ubuntu-latest
  strategy:
    matrix:
      pnpm-version: [ 7.x ]
      node-version: [ 18.12.x ]

  steps:
    - uses: actions/checkout@v3
    - name: Setup Environments
      uses: ./.github/actions/setup

    - name: Use pnpm ${{ matrix.pnpm-version }}
      uses: pnpm/action-setup@v2
      with:
        version: ${{ matrix.pnpm-version }}

    - name: Use Node ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: pnpm

    - name: Check dependency cache
      uses: actions/cache@v3
      with:
        path: |
          ${{ github.workspace }}/node_modules
          ${{ github.workspace }}/common/*/node_modules
          ${{ github.workspace }}/apps/${{env.SERVICE}}/node_modules
        key: ${{ needs.dependency_install.outputs.dependency_cache_key }}

    - name: Build
      run: pnpm build:${{ env.SERVICE }}

    - name: Remove DevDependencies
      run: pnpm install --production

    - name: AWS access registration
      uses: aws-actions/configure-aws-credentials@v1-node16
      with:
        aws-access-key-id: ${{ secrets.AWS_IAM_MANAGE_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_IAM_MANAGE_SECRET_ACCESS_KEY }}
        aws-region: ap-northeast-2

    - name: add .env
      run: aws s3 cp s3://${{env.BUCKET}}/env/.env.${{ env.TARGET_ENVIRONMENT }} ./

    - name: tar compress
      run: tar -cpzf ./build.tgz --files-from='tar_include.txt' apps/${{ env.SERVICE }}/ecosystem.config.js apps/${{ env.SERVICE }}/dist apps/${{ env.SERVICE }}/node_modules apps/${{ env.SERVICE }}/package.json .env.*
      shell: bash

    - name: S3 Upload
      run: aws s3 cp --region ap-northeast-2 ./build.tgz s3://${{env.BUCKET}}/${{env.TARGET_ENVIRONMENT}}/build.tgz
</code>```
```<code>deploy:
  name:  Deploy
  needs: [test, build]
  runs-on: ubuntu-latest

  steps:
    - uses: actions/checkout@v3
    - name: Setup Environments
      uses: ./.github/actions/setup

    - name: AWS access registration
      uses: aws-actions/configure-aws-credentials@v1-node16
      with:
        aws-access-key-id: ${{ secrets.AWS_IAM_MANAGE_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_IAM_MANAGE_SECRET_ACCESS_KEY }}
        aws-region: ap-northeast-2
    - name: Code Deploy
      run: aws deploy create-deployment --application-name $CODE_DEPLOY_APP_NAME --file-exists-behavior OVERWRITE --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name ${{env.BUCKET}}-${{env.TARGET_ENVIRONMENT}} --s3-location bucket=$BUCKET,bundleType=tgz,key=${{env.TARGET_ENVIRONMENT}}/build.tgz

...
</code>```

appspec.yml

```<code>version: 0.0
os: linux

files:
  - source: /
    destination: /home/ubuntu/app/my-project
    overwrite: yes

permissions:
  - object: /home/ubuntu/app/my-project
    owner: ubuntu
    group: ubuntu
    mode: 755

hooks:
  BeforeInstall:
    - location: scripts/beforeInstall.sh
      timeout: 120
      runas: ubuntu
  AfterInstall:
    - location: scripts/deploy.sh
      timeout: 180
      runas: ubuntu

</code>```

beforeInstall.sh

```<code>#!/bin/bash

REPOSITORY=/home/ubuntu/app/my-project

if [ -d $REPOSITORY ]; then
    rm -rf $REPOSITORY
fi
mkdir -vp $REPOSITORY

</code>```

how come node_modules storage size bigger and is there any solution to deploy project?

thank you!

Body:
Recently, I start NestJS project with PNPM.

every steps are very okay but when I deploy project to EC2 I got this AWS CodeDeploy Error

as you can see my EC2 storage got full.

this problem happened every CodeDeploy install event hook...

this is a CI/CD strategy.

CI with GitAction -> build -> compress tar.gz -> upload S3 -> call CodeDeploy -> PM2 Deploy

this image is CodeDeployAgent auto decompression tar file form deployment-root

when code deploy execute install event hook the node_modules file size are way bigger than before like this..

inside of node_modules every dependency reinstall they are dependencies.

ex) node_modules 1.5G
    - .pnpm 1.5G
        - lib 1
           - node_modules 500M ..
        - lib 2
           - node_modules 500M ..
        - lib 3
           - node_modules 500M ..
          ...

this is part of GitAction workflow

...
build:
  name:  Build & S3 Upload
  needs: dependency_install
  runs-on: ubuntu-latest
  strategy:
    matrix:
      pnpm-version: [ 7.x ]
      node-version: [ 18.12.x ]

  steps:
    - uses: actions/checkout@v3
    - name: Setup Environments
      uses: ./.github/actions/setup

    - name: Use pnpm ${{ matrix.pnpm-version }}
      uses: pnpm/action-setup@v2
      with:
        version: ${{ matrix.pnpm-version }}

    - name: Use Node ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: pnpm

    - name: Check dependency cache
      uses: actions/cache@v3
      with:
        path: |
          ${{ github.workspace }}/node_modules
          ${{ github.workspace }}/common/*/node_modules
          ${{ github.workspace }}/apps/${{env.SERVICE}}/node_modules
        key: ${{ needs.dependency_install.outputs.dependency_cache_key }}

    - name: Build
      run: pnpm build:${{ env.SERVICE }}

    - name: Remove DevDependencies
      run: pnpm install --production

    - name: AWS access registration
      uses: aws-actions/configure-aws-credentials@v1-node16
      with:
        aws-access-key-id: ${{ secrets.AWS_IAM_MANAGE_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_IAM_MANAGE_SECRET_ACCESS_KEY }}
        aws-region: ap-northeast-2

    - name: add .env
      run: aws s3 cp s3://${{env.BUCKET}}/env/.env.${{ env.TARGET_ENVIRONMENT }} ./

    - name: tar compress
      run: tar -cpzf ./build.tgz --files-from='tar_include.txt' apps/${{ env.SERVICE }}/ecosystem.config.js apps/${{ env.SERVICE }}/dist apps/${{ env.SERVICE }}/node_modules apps/${{ env.SERVICE }}/package.json .env.*
      shell: bash

    - name: S3 Upload
      run: aws s3 cp --region ap-northeast-2 ./build.tgz s3://${{env.BUCKET}}/${{env.TARGET_ENVIRONMENT}}/build.tgz

deploy:
  name:  Deploy
  needs: [test, build]
  runs-on: ubuntu-latest

  steps:
    - uses: actions/checkout@v3
    - name: Setup Environments
      uses: ./.github/actions/setup

    - name: AWS access registration
      uses: aws-actions/configure-aws-credentials@v1-node16
      with:
        aws-access-key-id: ${{ secrets.AWS_IAM_MANAGE_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_IAM_MANAGE_SECRET_ACCESS_KEY }}
        aws-region: ap-northeast-2
    - name: Code Deploy
      run: aws deploy create-deployment --application-name $CODE_DEPLOY_APP_NAME --file-exists-behavior OVERWRITE --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name ${{env.BUCKET}}-${{env.TARGET_ENVIRONMENT}} --s3-location bucket=$BUCKET,bundleType=tgz,key=${{env.TARGET_ENVIRONMENT}}/build.tgz

...

appspec.yml

version: 0.0
os: linux

files:
  - source: /
    destination: /home/ubuntu/app/my-project
    overwrite: yes

permissions:
  - object: /home/ubuntu/app/my-project
    owner: ubuntu
    group: ubuntu
    mode: 755

hooks:
  BeforeInstall:
    - location: scripts/beforeInstall.sh
      timeout: 120
      runas: ubuntu
  AfterInstall:
    - location: scripts/deploy.sh
      timeout: 180
      runas: ubuntu

beforeInstall.sh

#!/bin/bash

REPOSITORY=/home/ubuntu/app/my-project

if [ -d $REPOSITORY ]; then
    rm -rf $REPOSITORY
fi
mkdir -vp $REPOSITORY

how come node_modules storage size bigger and is there any solution to deploy project?

thank you!


问:
ARIMA prediction always give zero values in python
I'm t**rying to predict stock market using ARIMA but the predicted values are always zero if the differencing value is greater than zero how should i solve this problem.
another question when using forecast funtion instead of predict function it gives me another result. **
this is my code

```<code>from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_absolute_error
import pandas as pd
df = pd.read_csv('D:\SBIN.csv',  names = ['Date','Price'], header = 0, index_col = 0)
#series=pd.DataFrame(df)
print(len(df))
X = df.values
size = int(len(X) * 0.955)
print(size)
train = df[:size]
print(len(train))
test = df[size:]
history = [x for x in train.Price]
print(history)
predictions = list()
for t in range(len(test)):
    history_df = pd.DataFrame(history)
    model = ARIMA(history_df.astype(float), order=(1,1,1))

    model_fit = model.fit()
    print(model_fit.summary())
    predicted = model_fit.predict(start=0,end=0)
    yhat = predicted
    predictions.append(yhat)
    history.append(yhat)
predict=pd.DataFrame(predictions,index = test.index)
print(predict)
</code>```

in other websites and papers they use history.append(test[i]) instead of history.append(yhat) but i think they should use the second as we should fit the model based on the predicted values not the original to predict the future.
the output of predict funtion is:

```<code>Date
12/17/2015  0.0
12/18/2015  0.0
12/21/2015  0.0
12/22/2015  0.0
12/23/2015  0.0
12/24/2015  0.0
12/28/2015  0.0
12/29/2015  0.0
12/30/2015  0.0
12/31/2015  0.0
1/1/2016    0.0
1/4/2016    0.0
1/5/2016    0.0
1/6/2016    0.0
1/7/2016    0.0
1/8/2016    0.0
1/11/2016   0.0
1/12/2016   0.0
1/13/2016   0.0
1/14/2016   0.0
1/15/2016   0.0
1/18/2016   0.0
1/19/2016   0.0
</code>```

while the output of forecast is:

```<code>12/17/2015  227.398678
12/18/2015  227.343661
12/21/2015  227.374336
12/22/2015  227.357233
12/23/2015  227.366769
12/24/2015  227.361453
12/28/2015  227.364416
12/29/2015  227.362761
12/30/2015  227.363684
12/31/2015  227.363169
1/1/2016    227.363456
1/4/2016    227.363296
1/5/2016    227.363385
1/6/2016    227.363336
1/7/2016    227.363363
1/8/2016    227.363348
1/11/2016   227.363357
1/12/2016   227.363352
1/13/2016   227.363354
1/14/2016   227.363353
1/15/2016   227.363354
1/18/2016   227.363353
1/19/2016   227.363354
</code>```

**trying to predict stock market using ARIMA but the predicted values are always zero if the differencing value is greater than zero how should i solve this problem.
another question when using forecast funtion instead of predict function it gives me another result. **

Body:
I'm t**rying to predict stock market using ARIMA but the predicted values are always zero if the differencing value is greater than zero how should i solve this problem.
another question when using forecast funtion instead of predict function it gives me another result. **
this is my code

from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_absolute_error
import pandas as pd
df = pd.read_csv('D:\SBIN.csv',  names = ['Date','Price'], header = 0, index_col = 0)
#series=pd.DataFrame(df)
print(len(df))
X = df.values
size = int(len(X) * 0.955)
print(size)
train = df[:size]
print(len(train))
test = df[size:]
history = [x for x in train.Price]
print(history)
predictions = list()
for t in range(len(test)):
    history_df = pd.DataFrame(history)
    model = ARIMA(history_df.astype(float), order=(1,1,1))

    model_fit = model.fit()
    print(model_fit.summary())
    predicted = model_fit.predict(start=0,end=0)
    yhat = predicted
    predictions.append(yhat)
    history.append(yhat)
predict=pd.DataFrame(predictions,index = test.index)
print(predict)

in other websites and papers they use history.append(test[i]) instead of history.append(yhat) but i think they should use the second as we should fit the model based on the predicted values not the original to predict the future.
the output of predict funtion is:

Date
12/17/2015  0.0
12/18/2015  0.0
12/21/2015  0.0
12/22/2015  0.0
12/23/2015  0.0
12/24/2015  0.0
12/28/2015  0.0
12/29/2015  0.0
12/30/2015  0.0
12/31/2015  0.0
1/1/2016    0.0
1/4/2016    0.0
1/5/2016    0.0
1/6/2016    0.0
1/7/2016    0.0
1/8/2016    0.0
1/11/2016   0.0
1/12/2016   0.0
1/13/2016   0.0
1/14/2016   0.0
1/15/2016   0.0
1/18/2016   0.0
1/19/2016   0.0

while the output of forecast is:

12/17/2015  227.398678
12/18/2015  227.343661
12/21/2015  227.374336
12/22/2015  227.357233
12/23/2015  227.366769
12/24/2015  227.361453
12/28/2015  227.364416
12/29/2015  227.362761
12/30/2015  227.363684
12/31/2015  227.363169
1/1/2016    227.363456
1/4/2016    227.363296
1/5/2016    227.363385
1/6/2016    227.363336
1/7/2016    227.363363
1/8/2016    227.363348
1/11/2016   227.363357
1/12/2016   227.363352
1/13/2016   227.363354
1/14/2016   227.363353
1/15/2016   227.363354
1/18/2016   227.363353
1/19/2016   227.363354

**trying to predict stock market using ARIMA but the predicted values are always zero if the differencing value is greater than zero how should i solve this problem.
another question when using forecast funtion instead of predict function it gives me another result. **


问:
How can I access the Bazel Cache Directory in a .bzl file?
For some background, my specific use case is actually in Rules Python's compile_pip_requirements rule. I do not want to use the default caching location for pip packages, so I am passing args to pip through compile_pip_requirements via:

```<code>compile_pip_requirements(
...

extra_args = [
            "--allow-unsafe",
            "--cache-dir",
            "/tmp/pip-compile",
        ],
...)
</code>```

I can easily hardcode the tmp dir there, but I would like to specifically use the same directory that Bazel uses to cache everything else, without making any magic assumptions about where that cache dir is.

I have tried to use $(bazel info | grep output_base | awk '{print $2}') but Bazel appears to only accept its own Make Variables within a variable expression, not to mention that this does not feel like a safe option anyway.

I have also tangled a bit with those make variables (most promisingly, $(location //foo)), but it seems this only returns the location of a given module relative to WORKSPACE.

Thanks!

Body:
For some background, my specific use case is actually in Rules Python's compile_pip_requirements rule. I do not want to use the default caching location for pip packages, so I am passing args to pip through compile_pip_requirements via:

compile_pip_requirements(
...

extra_args = [
            "--allow-unsafe",
            "--cache-dir",
            "/tmp/pip-compile",
        ],
...)

I can easily hardcode the tmp dir there, but I would like to specifically use the same directory that Bazel uses to cache everything else, without making any magic assumptions about where that cache dir is.

I have tried to use $(bazel info | grep output_base | awk '{print $2}') but Bazel appears to only accept its own Make Variables within a variable expression, not to mention that this does not feel like a safe option anyway.

I have also tangled a bit with those make variables (most promisingly, $(location //foo)), but it seems this only returns the location of a given module relative to WORKSPACE.

Thanks!


问:
Animate the camera with react-three-fiber
So what I am trying to do is animate the camera after it finds the mesh id.
Right now it works, but it teleports to the mesh instead of animating the camera to the make. I have tried react-sprint and @react-three/drei, but I just can't figure this out.

CodeSandbox link


问:
Boto3 S3 Paginator not returning filtered results
I'm trying to list the items in my S3 bucket from the last few months. I'm able to get results from the normal paginator (page_iterator), but the filtered_iterator isn't yielding anything when I iterate over it.

I've been referencing the documentation here. I've double checked my filter string both using JmesPath site and the AWS CLI, and it works in both places. I'm at a loss at this point on what I need to do.

Current Code:

client = boto3.client('s3', region_name='us-west-2')
paginator = client.get_paginator('list_objects_v2')
operation_parameters = {'Bucket': self.bucket_name,
                        'Prefix': file_path_prefix}
page_iterator = paginator.paginate(**operation_parameters)
filtered_iterator = page_iterator.search("Contents[?LastModified>='2022-10-31'][]")

for key_data in filtered_iterator:
    print('page2', key_data)
```


问:
How do I set the PS1 (prompt) macOS Monterey 12.6.2
How do I set the PS1 (prompt) in terminal on my macbook pro using Monterey 12.6.2.
I am trying to have the prompt in terminal to display my current directory. In terminal and on the command line, I used PS1=\W and variations of that, but it is not working as it did in other version of the macOS.

I would like to see my prompt displaying my current working directory when I am using terminal.