问:
How can I improve performance of my neural network model?
I'm trying to build a model on python to predict an operational parameter (ROP- Rate of Penetration) while drilling an oil well. I'm working with a neural network trained with PSO using pyswarms library. Input layer consists of 11 neurons and output layer just 1 neuron (ROP). I'm still searching for the "right" number of hidden layers.I don't have enough knowledge about machine learning, so any suggestion will be accepted.The loss function to minimize is MAE, due to it is not affected by outliers.

To track the performance of the model I'm not sure about what loss function I have to use. That's why after every run, I print MAE, RMSE, MSE R2 and R. The problem is that the values for train are "high" (loss functions) or "low" (R o R2) and for validation data is quite close.

I would like you to give oppinion about my "work".I'm not really sure about if the model is overfitting, underfitting or data quality is low.

Whole dataset consists of 6 wells (F-1A, F-1B, F-1C, F-11A,F-11B,F-11T2), for each well we have 12 parameters (including ROP that is the target). The number of samples for each well is different:
For instance:
Well F-1A: 60 000 samples (aprox)
Well F-1B: 20 000  samples (aprox)
Well F-1C: 25 000 samples (aprox)

So I consider that is enough to train my model on one well, for example on Well F-11A and then validate on Well F-1B.

On one of those runs I got this result:

```<code>Input layer: 11
Hidden layers: 2 (8 neurons and 10 neurons)
Output layer: 1

Options : {'c1': 0.68, 'c2': 0.7, 'w': 0.73}
n_particles = 100
iters = 100

The results for loss functions, R2 and R for each dataset are:
ROP Train Data r^2=  0.4955
ROP Train Data r=  0.7039
ROP Train Data MAE = 3.272725
ROP Train Data MSE = 19.528535
ROP Train Data RMSE = 4.41911

ROP Validation Data r^2=  0.5169
ROP Validation Data r=  0.719
ROP Validation Data MAE = 10.755544
ROP Validation Data MSE = 124.405781
ROP Validation Data RMSE = 11.153734
</code>```

I dont know well what is the interpretation of this values. What I have to do next? Because I have realized  that on the right plot, the curve of the Predicted Validation data (green curve) follow the trend of the Actual Validation data (blue curve) but the predicted values seems to be lower (as if they had been displaced)

Body:
I'm trying to build a model on python to predict an operational parameter (ROP- Rate of Penetration) while drilling an oil well. I'm working with a neural network trained with PSO using pyswarms library. Input layer consists of 11 neurons and output layer just 1 neuron (ROP). I'm still searching for the "right" number of hidden layers.I don't have enough knowledge about machine learning, so any suggestion will be accepted.The loss function to minimize is MAE, due to it is not affected by outliers.

To track the performance of the model I'm not sure about what loss function I have to use. That's why after every run, I print MAE, RMSE, MSE R2 and R. The problem is that the values for train are "high" (loss functions) or "low" (R o R2) and for validation data is quite close.

I would like you to give oppinion about my "work".I'm not really sure about if the model is overfitting, underfitting or data quality is low.

Whole dataset consists of 6 wells (F-1A, F-1B, F-1C, F-11A,F-11B,F-11T2), for each well we have 12 parameters (including ROP that is the target). The number of samples for each well is different:
For instance:
Well F-1A: 60 000 samples (aprox)
Well F-1B: 20 000  samples (aprox)
Well F-1C: 25 000 samples (aprox)

So I consider that is enough to train my model on one well, for example on Well F-11A and then validate on Well F-1B.

On one of those runs I got this result:

Input layer: 11
Hidden layers: 2 (8 neurons and 10 neurons)
Output layer: 1

Options : {'c1': 0.68, 'c2': 0.7, 'w': 0.73}
n_particles = 100
iters = 100

The results for loss functions, R2 and R for each dataset are:
ROP Train Data r^2=  0.4955
ROP Train Data r=  0.7039
ROP Train Data MAE = 3.272725
ROP Train Data MSE = 19.528535
ROP Train Data RMSE = 4.41911

ROP Validation Data r^2=  0.5169
ROP Validation Data r=  0.719
ROP Validation Data MAE = 10.755544
ROP Validation Data MSE = 124.405781
ROP Validation Data RMSE = 11.153734

I dont know well what is the interpretation of this values. What I have to do next? Because I have realized  that on the right plot, the curve of the Predicted Validation data (green curve) follow the trend of the Actual Validation data (blue curve) but the predicted values seems to be lower (as if they had been displaced)


来源: stackexchange

问:
React Native / Expo custom font: German umlauts out of bounds
I've added a custom font (FS Me as an OTF file) to a React Native / Expo app using useFonts from expo-font. Unfortunately, I'm running into an issue where German umlauts (ä, ö, ü) are not visible due to the viewbox of the Text element being too small. For example, take this text: Über uns.

In the app, this simply renders as Uber uns because the two dots above the "U" are out of the Text boundary. When I increase the line height to 1.4x the font size, the umlauts show. However, this a) adds some sort of padding on the bottom of the text and b) it's obviously not a very good solution to increase the line height everywhere. Increasing it on a case-to-case basis isn't a viable solution either.

I'm using a custom Text component which sets a default font like this:

import React from 'react';
import {
  TextProps,
  Text as RNText, // eslint-disable-line no-restricted-imports
  StyleSheet,
  StyleProp,
} from 'react-native';

// Animated.createAnimatedComponent requires a class component
// eslint-disable-next-line react/prefer-stateless-function
class Text extends React.Component<TextProps> {
  render() {
    const { children, style } = this.props;
    let styles = style;
    let objStyle: StyleProp<any> = {};
    if (Array.isArray(style)) objStyle = StyleSheet.flatten(style);
    else if (style) objStyle = { ...(style as object) };
    if (!objStyle.fontFamily || objStyle.fontFamily === 'FS_Me') {
      objStyle.fontFamily = 'FS_Me_400_Regular';
      if (objStyle.fontWeight === 'bold' || objStyle.fontWeight === '700') {
        objStyle.fontFamily = 'FS_Me_700_Bold';
        objStyle.fontWeight = undefined;
      }
      if (objStyle.fontWeight === 'light' || objStyle.fontWeight === '300') {
        objStyle.fontFamily = 'FS_Me_300_Light';
        if (objStyle.fontStyle === 'italic') {
          objStyle.fontFamily = 'FS_Me_300_Light_Italic';
        }
        objStyle.fontWeight = undefined;
      }
      objStyle.backgroundColor = 'red';
      styles = objStyle;
    }

    return (
      <RNText allowFontScaling={false} {...this.props} style={styles}>
        {children}
      </RNText>
    );
  }
}

export default Text;
```

However, this also happens when I'm using the core RN Text component and only change the font family.

Does anyone have an idea why this happens?

ContentLicense: CC BY-SA 4.0

Body:
I've added a custom font (FS Me as an OTF file) to a React Native / Expo app using useFonts from expo-font. Unfortunately, I'm running into an issue where German umlauts (ä, ö, ü) are not visible due to the viewbox of the Text element being too small. For example, take this text: Über uns.

In the app, this simply renders as Uber uns because the two dots above the "U" are out of the Text boundary. When I increase the line height to 1.4x the font size, the umlauts show. However, this a) adds some sort of padding on the bottom of the text and b) it's obviously not a very good solution to increase the line height everywhere. Increasing it on a case-to-case basis isn't a viable solution either.

I'm using a custom Text component which sets a default font like this:

import React from 'react';
import {
  TextProps,
  Text as RNText, // eslint-disable-line no-restricted-imports
  StyleSheet,
  StyleProp,
} from 'react-native';

// Animated.createAnimatedComponent requires a class component
// eslint-disable-next-line react/prefer-stateless-function
class Text extends React.Component<TextProps> {
  render() {
    const { children, style } = this.props;
    let styles = style;
    let objStyle: StyleProp<any> = {};
    if (Array.isArray(style)) objStyle = StyleSheet.flatten(style);
    else if (style) objStyle = { ...(style as object) };
    if (!objStyle.fontFamily || objStyle.fontFamily === 'FS_Me') {
      objStyle.fontFamily = 'FS_Me_400_Regular';
      if (objStyle.fontWeight === 'bold' || objStyle.fontWeight === '700') {
        objStyle.fontFamily = 'FS_Me_700_Bold';
        objStyle.fontWeight = undefined;
      }
      if (objStyle.fontWeight === 'light' || objStyle.fontWeight === '300') {
        objStyle.fontFamily = 'FS_Me_300_Light';
        if (objStyle.fontStyle === 'italic') {
          objStyle.fontFamily = 'FS_Me_300_Light_Italic';
        }
        objStyle.fontWeight = undefined;
      }
      objStyle.backgroundColor = 'red';
      styles = objStyle;
    }

    return (
      <RNText allowFontScaling={false} {...this.props} style={styles}>
        {children}
      </RNText>
    );
  }
}

export default Text;

However, this also happens when I'm using the core RN Text component and only change the font family.

Does anyone have an idea why this happens?


问:
Why does cjs file extension on babel.config break module-resolver?
I have created a minimal reproducable example with a detailed README here.

In my expo app, I was having trouble using the babel module-resolver to use path aliases. My Metro bundling would fail when I used path aliases.

I learned that when I changed my babel.config file extension from .cjs to .js, the problem was resolved.

However, I do not understand why that would have any effect on whether the module-resolver plugin would work.

As described on babel's documentation, "Babel can be configured using any file extension natively supported by Node.js", with cjs specifically enumerated. And as I understand it, Expo by default creates a CommonJS babel.config file as it uses module.exports.

I have never created a GitHub issue, but perhaps this question is better suited as a babel-plugin-module-resolver issue, or I need to narrow down this issue further to determine whether Expo, or other babel plugins are relevant.

In short:

I tried creating a new expo app with npx create-expo-app to see if something about my project was effecting this issue. I then added a path alias to a test component and imported the component with the path alias. I ran expo which resulted in a bundle success. I then renamed babel.config.cjs and ran expo again with --clear, which resulted in a bundle failure "Unable to resolve [path alias]..."

I expected the cjs file extension to have no effect on whether the module-resolver caused an error.

What resulted was the module-resolver being fixed once I renamed babel.config.cjs to babel.config.js


问:
How to configure IDP-initiated login using Azure
I am trying to configure my Azure AD B2C account to use IDP-Initiated SAML login. I have been able to configure the custom policies to enable Open ID and SAML logins using SP-Initiated logins but am unable to get IDP-Initiated to work.
For reference, I am trying to use Salesforce to login.
I see in Azures documentation: "We don't currently support scenarios where the initiating identity provider is an external identity provider federated with Azure AD B2C, such as Active Directory Federation Services or Salesforce. IdP-initiated flow is supported only for local account authentication in Azure AD B2C."
If I am unable to set up IDP-Initiated using Azure AD-B2C is there another service under Azure that would allow me to set this up?

I have tried to edit the custom policies in my Azure AD B2C to include IDPInitiatedProfile to true
     <Metadata> ...  <Item Key="IdpInitiatedProfileEnabled">true</Item> </Metadata>
And configured the policy following the template provided here: https://samltestsp.azurewebsites.net/B2CPolicy
I was able to get the test on the provided website to work but it will not work with my salesforce account.


问:
Add animation to annotation
Is there a way to add an animation to an annotation?

I have the following

```<code>point1: {
  type: 'point',
  drawTime: 'afterDraw',
  xValue: 1,
  yValue: 119,
  radius: 18,
  backgroundColor: 'rgba(255, 99, 132, 0.25)',
  borderColor: 'rgba(255, 99, 132, 0.25)'
 }
</code>```

And I'd like to change the radius size.

Title: Add animation to annotation

Body:
Is there a way to add an animation to an annotation?

I have the following

point1: {
  type: 'point',
  drawTime: 'afterDraw',
  xValue: 1,
  yValue: 119,
  radius: 18,
  backgroundColor: 'rgba(255, 99, 132, 0.25)',
  borderColor: 'rgba(255, 99, 132, 0.25)'
 }

And I'd like to change the radius size.


问:
self hosted owin dotnet api force redirect http to https
I'm hosting a .net API as a windows service and I use https to access this service. The service works over https but I now want to redirect clients using the service to the https instead of http endpoint without them explicitly having to change their api base URL. Is there a wat of doing this?</p>


问:
ggplot2 geom_col() does not show all items
I'm new to R and I'm trying to plot a small survey where I used a likert-scale.

I'm using

```<code>ggplot(Likert, aes(x=Anzahl, y=Frage, fill=Zustimmung)) + geom_col()
</code>```

to display the data. There are probably better ways to do this and I probably should use data frames as I currently don't use them.

Now the actual Problem: The variable "Zustimung" has 5 different specifications but only 4 of them are shown and there are sorted weirdly.

I've found a few different posts online which seem to be regarding this issue but I can't understand them. Could someone please explain why this problem occures and how I can fix this?

Body:
I'm new to R and I'm trying to plot a small survey where I used a likert-scale.

I'm using

ggplot(Likert, aes(x=Anzahl, y=Frage, fill=Zustimmung)) + geom_col()

to display the data. There are probably better ways to do this and I probably should use data frames as I currently don't use them.

Now the actual Problem: The variable "Zustimung" has 5 different specifications but only 4 of them are shown and there are sorted weirdly.

I've found a few different posts online which seem to be regarding this issue but I can't understand them. Could someone please explain why this problem occures and how I can fix this?


问:
client->authorize never shows the login page
I have this :

```<code>$client->setAuthConfig('credentials.json');
$client->useApplicationDefaultCredentials(true);
$client->setIncludeGrantedScopes(true);
$client->setRedirectUri('https://local.example.com'); # powered by MAMP

// returns a Guzzle HTTP Client
$httpClient = $client->authorize();
</code>```

RedirectUri is correct in both code and console.

But just returns :

```<code>{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}
</code>```

$httpClient = $client->authorize() doesn't show the google login page.

Shouldn't it atleast show the oAuth login page ?

Body:
I have this :

$client->setAuthConfig('credentials.json');
$client->useApplicationDefaultCredentials(true);
$client->setIncludeGrantedScopes(true);
$client->setRedirectUri('https://local.example.com'); # powered by MAMP

// returns a Guzzle HTTP Client
$httpClient = $client->authorize();

RedirectUri is correct in both code and console.

But just returns :

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

$httpClient = $client->authorize() doesn't show the google login page.

Shouldn't it atleast show the oAuth login page ?


问:
auth_request doesn't work at nginx config
I try in my nginx config to use the auth_request. I have an backend running on localhost:8081/welcome. It checks the token in the cookie. If the token is invalid, the server responds with 500. If it succeeds I have a 404 not found. I don't know why because on localhost:4500 is running another service.
I try to call the /protected route and get the error.

When I call /api/application everything works fine.

This is my the part of my config:

```<code>   location /api/ {
        proxy_pass http://localhost:4500;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header content-type "application/json";
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Connection 'upgrade';
    }
    location /api/application {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location /protected {
        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location = /auth {
        internal;
        proxy_pass http://localhost:8081/welcome;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
    }
</code>```

Do you have any suggestions, why I get a 404 not found?

Thank you very much!

Body:
I try in my nginx config to use the auth_request. I have an backend running on localhost:8081/welcome. It checks the token in the cookie. If the token is invalid, the server responds with 500. If it succeeds I have a 404 not found. I don't know why because on localhost:4500 is running another service.
I try to call the /protected route and get the error.

When I call /api/application everything works fine.

This is my the part of my config:

   location /api/ {
        proxy_pass http://localhost:4500;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header content-type "application/json";
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Connection 'upgrade';
    }
    location /api/application {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location /protected {
        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location = /auth {
        internal;
        proxy_pass http://localhost:8081/welcome;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
    }

Do you have any suggestions, why I get a 404 not found?

Thank you very much!


问:
Tkinter - Get object value on double click
I have a program that there is a page that registers animals and another page that shows the list of animal names with the animal ID in a listbox. I was able to double click on the animal's name to access a new window, but I need to show all data for the selected animal in this new window and I'm not getting it.

Page that shows the name and ID of all registered animals and leads to the next window, which would need to show the data of the animal that I double-clicked

```<code>import tkinter as tk

class Vpets(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.titleFont = ('Bodoni MT Black', 15, 'bold')
        self.titleFont2 = ('Bodoni MT', 13, 'bold')
        self.labelFont = ('Georgia', 11, 'bold')
        self.standardFont = ('Georgia', 11)
        self.buttonFont = ('Century', 8, 'bold')

        self.firstContainer = tk.Frame(self)
        self.firstContainer.pack(pady=20, padx=20)

        self.title = tk.Label(self.firstContainer, text='HAPPY FAMILY - VET CLINIC', font=self.titleFont)
        self.title.pack(pady=5)

        self.title2 = tk.Label(self.firstContainer, text='------ PETS ------', font=self.titleFont2)
        self.title2.pack(pady=5)

        self.secondContainer = tk.Frame(self)
        self.secondContainer.pack(pady=7)

        self.listPet = tk.Listbox(self.secondContainer, width=50, height=10, font=self.labelFont)
        self.listPet.pack(side='left', expand=True, fill="both")
        self.listPet.bind('<Double-1>', lambda x: controller.show_frame('VPet'))

        self.sb = tk.Scrollbar()
        self.sb.pack(side='right',fill="y")
        self.sb.configure(command=self.listPet.yview)
        self.listPet.configure(yscrollcommand=self.sb.set)

        self.thirdContainer = tk.Frame(self)
        self.thirdContainer.pack(pady=20)

        self.save = tk.Button(self.thirdContainer, text='Return to menu', font=self.buttonFont, width=15, bg='#B0C4DE',
                              command=lambda: controller.show_frame('Menu'))
        self.save.pack()

    def update_pet(self,  items):
        for item in items:
            self.listPet.insert('end', item)`
</code>```

Page showing all data for the selected animal

```<code>import tkinter as tk

class VPet(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.titleFont = ('Bodoni MT Black', 15, 'bold')
        self.titleFont2 = ('Bodoni MT', 13, 'bold')
        self.labelFont = ('Georgia', 11, 'bold')
        self.standardFont = ('Georgia', 11)
        self.buttonFont = ('Century', 8, 'bold')

        self.firstContainer = tk.Frame(self)
        self.firstContainer.pack(pady=20, padx=20)

        self.title = tk.Label(self.firstContainer, text='HAPPY FAMILY - VET CLINIC', font=self.titleFont)
        self.title.pack(pady=5)

        self.title2 = tk.Label(self.firstContainer, text='------ PETS ------', font=self.titleFont2)
        self.title2.pack(pady=5)

        self.secondContainer = tk.Frame(self)
        self.secondContainer.pack(pady=7)

        self.petID = tk.Label(self.secondContainer, text='', font=self.labelFont)
        self.petID.pack(side='left')

        self.petName = tk.Label(self.secondContainer, text='', font=self.labelFont)
        self.petName.pack(side='left')

        self.thirdContainer = tk.Frame(self)
        self.thirdContainer.pack(pady=20)

        self.save = tk.Button(self.thirdContainer, text='Return to menu', font=self.buttonFont, width=15, bg='#B0C4DE',
                              command=lambda: controller.show_frame('Menu'))
        self.save.pack()

    def onepet(self, names, IDs, species, breed, age):
        self.petName['text'] = names
        self.petID['text'] = IDs`
</code>```

I'm trying to show only the information of the animal that I selected in the double click, but the information of all the animals is coming out.

Body:
I have a program that there is a page that registers animals and another page that shows the list of animal names with the animal ID in a listbox. I was able to double click on the animal's name to access a new window, but I need to show all data for the selected animal in this new window and I'm not getting it.

Page that shows the name and ID of all registered animals and leads to the next window, which would need to show the data of the animal that I double-clicked

import tkinter as tk

class Vpets(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.titleFont = ('Bodoni MT Black', 15, 'bold')
        self.titleFont2 = ('Bodoni MT', 13, 'bold')
        self.labelFont = ('Georgia', 11, 'bold')
        self.standardFont = ('Georgia', 11)
        self.buttonFont = ('Century', 8, 'bold')

        self.firstContainer = tk.Frame(self)
        self.firstContainer.pack(pady=20, padx=20)

        self.title = tk.Label(self.firstContainer, text='HAPPY FAMILY - VET CLINIC', font=self.titleFont)
        self.title.pack(pady=5)

        self.title2 = tk.Label(self.firstContainer, text='------ PETS ------', font=self.titleFont2)
        self.title2.pack(pady=5)

        self.secondContainer = tk.Frame(self)
        self.secondContainer.pack(pady=7)

        self.listPet = tk.Listbox(self.secondContainer, width=50, height=10, font=self.labelFont)
        self.listPet.pack(side='left', expand=True, fill="both")
        self.listPet.bind('<Double-1>', lambda x: controller.show_frame('VPet'))

        self.sb = tk.Scrollbar()
        self.sb.pack(side='right',fill="y")
        self.sb.configure(command=self.listPet.yview)
        self.listPet.configure(yscrollcommand=self.sb.set)

        self.thirdContainer = tk.Frame(self)
        self.thirdContainer.pack(pady=20)

        self.save = tk.Button(self.thirdContainer, text='Return to menu', font=self.buttonFont, width=15, bg='#B0C4DE',
                              command=lambda: controller.show_frame('Menu'))
        self.save.pack()

    def update_pet(self,  items):
        for item in items:
            self.listPet.insert('end', item)`

Page showing all data for the selected animal

import tkinter as tk

class VPet(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.titleFont = ('Bodoni MT Black', 15, 'bold')
        self.titleFont2 = ('Bodoni MT', 13, 'bold')
        self.labelFont = ('Georgia', 11, 'bold')
        self.standardFont = ('Georgia', 11)
        self.buttonFont = ('Century', 8, 'bold')

        self.firstContainer = tk.Frame(self)
        self.firstContainer.pack(pady=20, padx=20)

        self.title = tk.Label(self.firstContainer, text='HAPPY FAMILY - VET CLINIC', font=self.titleFont)
        self.title.pack(pady=5)

        self.title2 = tk.Label(self.firstContainer, text='------ PETS ------', font=self.titleFont2)
        self.title2.pack(pady=5)

        self.secondContainer = tk.Frame(self)
        self.secondContainer.pack(pady=7)

        self.petID = tk.Label(self.secondContainer, text='', font=self.labelFont)
        self.petID.pack(side='left')

        self.petName = tk.Label(self.secondContainer, text='', font=self.labelFont)
        self.petName.pack(side='left')

        self.thirdContainer = tk.Frame(self)
        self.thirdContainer.pack(pady=20)

        self.save = tk.Button(self.thirdContainer, text='Return to menu', font=self.buttonFont, width=15, bg='#B0C4DE',
                              command=lambda: controller.show_frame('Menu'))
        self.save.pack()

    def onepet(self, names, IDs, species, breed, age):
        self.petName['text'] = names
        self.petID['text'] = IDs`

I'm trying to show only the information of the animal that I selected in the double click, but the information of all the animals is coming out.


问:
RSpec any_args matcher failing with wrong number of arguments?
I've added the following allow statement to spec_helper.rb to fix an issue in my codebase where tons of specs had added expect().receive on the metrics class making tests brittle to new metrics calls in underlying classes.

```<code>allow(MetricsClass).to receive(:increment).with(any_args)
</code>```

Unfortunately, I'm running in errors

```<code> ArgumentError:
   Wrong number of arguments. Expected 1, got 2.
</code>```

The function definition:

```<code>def self.increment(counter_name, by: 1, **tags)
</code>```

The line in the code where this failure happens:

```<code>  MetricsClass.increment("string", **info)
</code>```

Info itself is a hash

```<code>puts info
{"class/method"=>true}
</code>```

ruby 2.7.6
rspec 3.12.0

Relevant RSpec configuration:

```<code>RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
     mocks.verify_partial_doubles = true
  end
end
</code>```

Body:
I've added the following allow statement to spec_helper.rb to fix an issue in my codebase where tons of specs had added expect().receive on the metrics class making tests brittle to new metrics calls in underlying classes.

allow(MetricsClass).to receive(:increment).with(any_args)

Unfortunately, I'm running in errors

 ArgumentError:
   Wrong number of arguments. Expected 1, got 2.

The function definition:

def self.increment(counter_name, by: 1, **tags)

The line in the code where this failure happens:

  MetricsClass.increment("string", **info)

Info itself is a hash

puts info
{"class/method"=>true}

ruby 2.7.6
rspec 3.12.0

Relevant RSpec configuration:

RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
     mocks.verify_partial_doubles = true
  end
end


问:
Safety and translation of query params in Ruby on Rails
I have a two part question. I'm passing params to links in order to sort and filter in my Ruby on Rails app. Is this type of resulting url safe?

```<code>/realestates?column=salesprice&direction=desc
</code>```

If not, what would be the best way to hide the column name?

The second part of my question is what's the best way to translate these params to different languages. I have i18n set up. This is an example of a link with parameters:

```<code><%= link_to realestates_path(column: :salesprice, direction: 'desc') do %>
 <i class="fa fa-caret-down"></i>Order by price
<% end %>
</code>```

Thank you!

Body:
I have a two part question. I'm passing params to links in order to sort and filter in my Ruby on Rails app. Is this type of resulting url safe?

/realestates?column=salesprice&direction=desc

If not, what would be the best way to hide the column name?

The second part of my question is what's the best way to translate these params to different languages. I have i18n set up. This is an example of a link with parameters:

<%= link_to realestates_path(column: :salesprice, direction: 'desc') do %>
 Order by price
<% end %>

Thank you!


问:
How django process the model fields into form inputs
I would like to understand the lifecycle of how Django identifies my model fields and render them as form fields with the whole metadata that the field needs it to process the user input and also the display of that field.</p>


问:
Config superset to each user access to their own dataset and database
I set up superset to use LDAP in order authentication but I have one problem.

All users have Gamma Role by default and everyone can view other users' dataSources and databases.
How can it be set so that each user can see only the datasources he created?

```<code>Modify LDAP configuration
AUTH_TYPE = AUTH_LDAP
AUTH_ROLE_ADMIN ='Admin'
AUTH_LDAP_USE_TLS = False
AUTH_USER_REGISTRATION_ROLE= "Admin"
AUTH_LDAP_FIRSTNAME_FIELD = "givenName"
AUTH_LDAP_LASTNAME_FIELD = "sn"
AUTH_LDAP_EMAIL_FIELD = "mail"
AUTH_USER_REGISTRATION = True
AUTH_LDAP_SERVER = "ldap://xxx.xxx.xxx.xxx:389"
AUTH_LDAP_SEARCH = "cn=hall.net,ou=groups,dc=dataops,dc=dg"
AUTH_LDAP_USERNAME_FORMAT = "uid=%s,ou=groups1,dc=dataops,dc=dg"
AUTH_LDAP_UID_FIELD = "uid"
AUTH_ROLES_MAPPING = {
"cn=hall.net,ou=groups,dc=dataops,dc=dg": ["Admin"],
"cn=hall.biz,ou=groups,dc=dataops,dc=dg": ["Admin"],
}

#AUTH_LDAP_GROUP_FIELD = "memberOf"

AUTH_ROLES_SYNC_AT_LOGIN = False

PERMANENT_SESSION_LIFETIME = 1800
AUTH_LDAP_BIND_USER = "cn=supersetadmin_MX4G,cn=hall.net,ou=groups,dc=dataops,dc=dg"
AUTH_LDAP_BIND_PASSWORD = "6P8HIKBZCZ"
AUTH_ROLE_PUBLIC = 'Public'
PUBLIC_ROLE_LIKE = 'Alpha'
</code>```

Body:
I set up superset to use LDAP in order authentication but I have one problem.

All users have Gamma Role by default and everyone can view other users' dataSources and databases.
How can it be set so that each user can see only the datasources he created?

Modify LDAP configuration
AUTH_TYPE = AUTH_LDAP
AUTH_ROLE_ADMIN ='Admin'
AUTH_LDAP_USE_TLS = False
AUTH_USER_REGISTRATION_ROLE= "Admin"
AUTH_LDAP_FIRSTNAME_FIELD = "givenName"
AUTH_LDAP_LASTNAME_FIELD = "sn"
AUTH_LDAP_EMAIL_FIELD = "mail"
AUTH_USER_REGISTRATION = True
AUTH_LDAP_SERVER = "ldap://xxx.xxx.xxx.xxx:389"
AUTH_LDAP_SEARCH = "cn=hall.net,ou=groups,dc=dataops,dc=dg"
AUTH_LDAP_USERNAME_FORMAT = "uid=%s,ou=groups1,dc=dataops,dc=dg"
AUTH_LDAP_UID_FIELD = "uid"
AUTH_ROLES_MAPPING = {
"cn=hall.net,ou=groups,dc=dataops,dc=dg": ["Admin"],
"cn=hall.biz,ou=groups,dc=dataops,dc=dg": ["Admin"],
}

#AUTH_LDAP_GROUP_FIELD = "memberOf"

AUTH_ROLES_SYNC_AT_LOGIN = False

PERMANENT_SESSION_LIFETIME = 1800
AUTH_LDAP_BIND_USER = "cn=supersetadmin_MX4G,cn=hall.net,ou=groups,dc=dataops,dc=dg"
AUTH_LDAP_BIND_PASSWORD = "6P8HIKBZCZ"
AUTH_ROLE_PUBLIC = 'Public'
PUBLIC_ROLE_LIKE = 'Alpha'


问:
Custom Window WPF
How to create a class that inherits from the Window class.I want this class to have render in visual studio designer.

What I have

What I want

Only, as you can see, I will extend the standard class. And I would really like to see my visualization, instead of the standard one. But I don't even know how to approach it.

I would be very grateful if you could help me find a solution.

-- Changed

At the moment, all the layout is in the window class.

Window Source Code

```<code><Window.DataContext>
    <vm:ApplicationViewModel/>
</Window.DataContext>
<Border Style="{StaticResource WindowBorderStyle}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <!-- Menu -->
        <Border Grid.Column="0" CornerRadius="10 0 0 10">
            <Border.Background>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#223266" Offset="0"/>
                    <GradientStop Color="#27396b" Offset="1"/>
                </LinearGradientBrush>
            </Border.Background>
            <StackPanel>

                <!-- UserPanel -->
                <ContentPresenter Margin="0 35 0 0" Content="{Binding UserViewModel}"/>
                <Separator Height="0.8" Margin="20 30" Background="#46558A"/>
                <ContentPresenter Content="{Binding MenuViewModel}"/>

            </StackPanel>
        </Border>

        <!-- Main page-->

        <Border Grid.Column="1" CornerRadius="0 10 10 0" MouseDown="Border_MouseDown" >
            <Border.Background>
                <LinearGradientBrush StartPoint="1,0" EndPoint="0,1">
                    <GradientStop Color="#41518f" Offset="0"/>
                    <GradientStop Color="#2c386c" Offset="1"/>
                </LinearGradientBrush>
            </Border.Background>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="32"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <!-- Header -->
                <StackPanel Grid.Row="0" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,5,5,5">
                    <cc:HeaderButton Icon="EyeSlash" IsEnabled="False" />
                    <cc:HeaderButton Icon="WindowMinimize" Command="{Binding MinimizeWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}"/>
                    <cc:HeaderButton Command="{Binding NormalizeOfMaximizeWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}">
                        <cc:HeaderButton.Style>
                            <Style TargetType="{x:Type cc:HeaderButton}">
                                <Setter Property="Icon" Value="WindowMaximize"/>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" Value="Maximized">
                                        <Setter Property="Icon" Value="WindowRestore"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </cc:HeaderButton.Style>
                    </cc:HeaderButton>
                    <cc:HeaderButton Icon="WindowClose" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}"/>
                </StackPanel>

                <Grid Grid.Row="1">
                    <ContentPresenter Content="{Binding MenuViewModel.SelectedMenuElement.ViewModel}"/>
                </Grid>

            </Grid>
        </Border>
    </Grid>
</Border>
</code>```

It seems to me that it would be right to share the responsibility.

Title: Custom Window WPF

Body:
How to create a class that inherits from the Window class.I want this class to have render in visual studio designer.

What I have

What I want

Only, as you can see, I will extend the standard class. And I would really like to see my visualization, instead of the standard one. But I don't even know how to approach it.

I would be very grateful if you could help me find a solution.

-- Changed

At the moment, all the layout is in the window class.

Window Source Code

<Window.DataContext>
    <vm:ApplicationViewModel/>
</Window.DataContext>
<Border Style="{StaticResource WindowBorderStyle}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Border Grid.Column="0" CornerRadius="10 0 0 10">
            <Border.Background>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#223266" Offset="0"/>
                    <GradientStop Color="#27396b" Offset="1"/>
                </LinearGradientBrush>
            </Border.Background>
            <StackPanel>

                <ContentPresenter Margin="0 35 0 0" Content="{Binding UserViewModel}"/>
                <Separator Height="0.8" Margin="20 30" Background="#46558A"/>
                <ContentPresenter Content="{Binding MenuViewModel}"/>

            </StackPanel>
        </Border>

        <Border Grid.Column="1" CornerRadius="0 10 10 0" MouseDown="Border_MouseDown" >
            <Border.Background>
                <LinearGradientBrush StartPoint="1,0" EndPoint="0,1">
                    <GradientStop Color="#41518f" Offset="0"/>
                    <GradientStop Color="#2c386c" Offset="1"/>
                </LinearGradientBrush>
            </Border.Background>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="32"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <StackPanel Grid.Row="0" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,5,5,5">
                    <cc:HeaderButton Icon="EyeSlash" IsEnabled="False" />
                    <cc:HeaderButton Icon="WindowMinimize" Command="{Binding MinimizeWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}"/>
                    <cc:HeaderButton Command="{Binding NormalizeOfMaximizeWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}">
                        <cc:HeaderButton.Style>

                            </Style>
                        </cc:HeaderButton.Style>
                    </cc:HeaderButton>
                    <cc:HeaderButton Icon="WindowClose" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=BaseWindow}"/>
                </StackPanel>

                <Grid Grid.Row="1">
                    <ContentPresenter Content="{Binding MenuViewModel.SelectedMenuElement.ViewModel}"/>
                </Grid>

            </Grid>
        </Border>
    </Grid>
</Border>

It seems to me that it would be right to share the responsibility.


问:
Changing the caption font size, color, and style in PPTX qmd
How do I, correctly, change the format of a plot caption in a qmd file? With a pptx output.

I'll provide my MWE:

```<code>---
title: "My Work"
subtitle: "2023"
author: "Me"
format: pptx
reference-doc: template.pptx
mainfont: Open Sans
sansfont: Open Sans
slide-level: 1
---

# Slide 1
```{r, fig.align = "center", fig.cap="Caption"}
    # code for the graph
```
</code>```

The only command that I found that can help me modify it, is obviously, the fig.caption. But besides that, I have no control over the way the caption is presented, in terms of style, and I would like to know other alternatives.

With simply fig.caption = "Caption"I get something like this:

When what I was looking for, is the following:

In case the changes aren't obvious, the part "Figure 1" has a style bold, with a darkblue color, and the rest "Overlaying Graphs" has a normal lettering style, and the color is lightgray.

Can anyone help?

Body:
How do I, correctly, change the format of a plot caption in a qmd file? With a pptx output.

I'll provide my MWE:

---
title: "My Work"
subtitle: "2023"
author: "Me"
format: pptx
reference-doc: template.pptx
mainfont: Open Sans
sansfont: Open Sans
slide-level: 1
---

# Slide 1
```{r, fig.align = "center", fig.cap="Caption"}
    # code for the graph
```

The only command that I found that can help me modify it, is obviously, the fig.caption. But besides that, I have no control over the way the caption is presented, in terms of style, and I would like to know other alternatives.

With simply fig.caption = "Caption"I get something like this:

When what I was looking for, is the following:

In case the changes aren't obvious, the part "Figure 1" has a style bold, with a darkblue color, and the rest "Overlaying Graphs" has a normal lettering style, and the color is lightgray.

Can anyone help?


问:
A component is changing the controlled value state of Select to be uncontrolled
I am using Material Ui dropdown but not able to change value. whenever I change a value I get this error message

twilio-flex.min.js:612 Material-UI: A component is changing the
controlled value state of Select to be uncontrolled. Elements should
not switch from uncontrolled to controlled (or vice versa). Decide
between using a controlled or uncontrolled Select element for the
lifetime of the component. The nature of the state is determined
during the first render, it's considered controlled if the value is
not undefined.

https://i.stack.imgur.com/TiGk5.png

Dropdown.js

import React from "react";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import ExpandMoreRoundedIcon from "@material-ui/icons/ExpandMoreRounded";
import dropDownStyle from "./dropdownStyle";

const DropDown = ({ value, handleChange, items }) => {
  console.log("Dropdown ", value);
  console.log("Dropdown handleChange", handleChange);
  console.log("Dropdown items", items);

  const classes = dropDownStyle();

  const menuProps = {
    classes: {
      list: classes.list,
      paper: classes.paper,
    },
    anchorOrigin: {
      vertical: "bottom",
      horizontal: "center",
    },
    transformOrigin: {
      vertical: "top",
      horizontal: "center",
    },
    getContentAnchorEl: null,
  };

  return (
    <FormControl className={classes.formControl}>
      <Select
        value={value}
        onChange={handleChange}
        disableUnderline
        IconComponent={ExpandMoreRoundedIcon}
        MenuProps={menuProps}
        classes={{
          select: classes.select,
          icon: classes.selectIcon,
        }}
      >
        {items.map((item) => (
          <MenuItem key={item.key} value={item.value}>
            {item.value}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};

export default DropDown;```
</div>
</div>
</p>
<p>dropdownStyle.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { makeStyles } from "@material-ui/core/styles";

const dropDownStyle = makeStyles({
  formControl: {
    "& .MuiInputBase-root": {
      color: "#4553da",
      borderColor: "#4454f4",
      borderWidth: "2px",
      borderStyle: "solid",
      borderRadius: "100px",
      minWidth: "120px",
      justifyContent: "center",
      backgroundColor: "#4454f4",
    },
    "& .MuiSelect-select.MuiSelect-select": {
      paddingRight: "0px",
    },
  },
  select: {
    width: "auto",
    fontSize: "12px",
    "&:focus": {
      backgroundColor: "transparent",
    },
  },
  selectIcon: {
    position: "relative",
    color: "#6EC177",
    fontSize: "14px",
  },
  paper: {
    borderRadius: 12,
    marginTop: 8,
  },
  list: {
    paddingTop: 0,
    paddingBottom: 0,
    "& li": {
      fontWeight: 200,
      paddingTop: 8,
      paddingBottom: 8,
      fontSize: "12px",
    },
    "& li.Mui-selected": {
      color: "white",
      background: "#4553da",
    },
    "& li.Mui-selected:hover": {
      background: "#4d95f1",
    },
  },
});

export default dropDownStyle;</code>```

VoicecallComponent.js

class VoiceCallComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log("Connector: --- VoiceCallComponent setting state ---");
    this.state = {
      functionsBaseUrl: this.props.functionsBaseUrl,
      settingsBaseUrl: this.props.settingsBaseUrl,
      calldisposition: "",
    };

  }

  handleSelectChange = (e) => {
    const value = e.target.value;
    this.setState({ calldisposition: value });
    this.props.task.attributes.calldisposition = value;
    this.props.task.setAttributes(this.props.task.attributes);
  };

  render() {
    return(

          <FormControl
            fullWidth
            size="small"
            style={{ fontfamily: "sans-serif", textAlign: "center" }}
          >
            <DropDown
              style={{ color: "black", gap: "3" }}
              value={this.state.calldisposition}
              handleChange={this.handleSelectChange}
              items={[
                { key: "", val: "--Select--" },
                { key: "214680006", val: "Contacted" },
                { key: "214680000", val: "Bad Number" },
                { key: "214680001", val: "Hung up on Call" },
                { key: "214680002", val: "No Answer - Left Voicemail" },
                {
                  key: "214680003",
                  val: "No Answer - Unable to Leave Voicemail",
                },
                {
                  key: "214680004",
                  val: "No Answer - Did Not Leave Voicemail",
                },
                { key: "214680005", val: "Wrong Number" },
                { key: "214680008", val: "Transfer" },
                { key: "000000000", val: "Non-CRM Call" },
              ]}
            ></DropDown>
          </FormControl>

    );
 }```

Body:
I am using Material Ui dropdown but not able to change value. whenever I change a value I get this error message

twilio-flex.min.js:612 Material-UI: A component is changing the
controlled value state of Select to be uncontrolled. Elements should
not switch from uncontrolled to controlled (or vice versa). Decide
between using a controlled or uncontrolled Select element for the
lifetime of the component. The nature of the state is determined
during the first render, it's considered controlled if the value is
not undefined.

https://i.stack.imgur.com/TiGk5.png

Dropdown.js

import React from "react";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import ExpandMoreRoundedIcon from "@material-ui/icons/ExpandMoreRounded";
import dropDownStyle from "./dropdownStyle";

const DropDown = ({ value, handleChange, items }) => {
  console.log("Dropdown ", value);
  console.log("Dropdown handleChange", handleChange);
  console.log("Dropdown items", items);

  const classes = dropDownStyle();

  const menuProps = {
    classes: {
      list: classes.list,
      paper: classes.paper,
    },
    anchorOrigin: {
      vertical: "bottom",
      horizontal: "center",
    },
    transformOrigin: {
      vertical: "top",
      horizontal: "center",
    },
    getContentAnchorEl: null,
  };

  return (
    <FormControl className={classes.formControl}>
      <Select
        value={value}
        onChange={handleChange}
        disableUnderline
        IconComponent={ExpandMoreRoundedIcon}
        MenuProps={menuProps}
        classes={{
          select: classes.select,
          icon: classes.selectIcon,
        }}
      >
        {items.map((item) => (
          <MenuItem key={item.key} value={item.value}>
            {item.value}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};

export default DropDown;

dropdownStyle.js

import { makeStyles } from "@material-ui/core/styles";

const dropDownStyle = makeStyles({
  formControl: {
    "& .MuiInputBase-root": {
      color: "#4553da",
      borderColor: "#4454f4",
      borderWidth: "2px",
      borderStyle: "solid",
      borderRadius: "100px",
      minWidth: "120px",
      justifyContent: "center",
      backgroundColor: "#4454f4",
    },
    "& .MuiSelect-select.MuiSelect-select": {
      paddingRight: "0px",
    },
  },
  select: {
    width: "auto",
    fontSize: "12px",
    "&:focus": {
      backgroundColor: "transparent",
    },
  },
  selectIcon: {
    position: "relative",
    color: "#6EC177",
    fontSize: "14px",
  },
  paper: {
    borderRadius: 12,
    marginTop: 8,
  },
  list: {
    paddingTop: 0,
    paddingBottom: 0,
    "& li": {
      fontWeight: 200,
      paddingTop: 8,
      paddingBottom: 8,
      fontSize: "12px",
    },
    "& li.Mui-selected": {
      color: "white",
      background: "#4553da",
    },
    "& li.Mui-selected:hover": {
      background: "#4d95f1",
    },
  },
});

export default dropDownStyle;

VoicecallComponent.js

class VoiceCallComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log("Connector: --- VoiceCallComponent setting state ---");
    this.state = {
      functionsBaseUrl: this.props.functionsBaseUrl,
      settingsBaseUrl: this.props.settingsBaseUrl,
      calldisposition: "",
    };

  }

  handleSelectChange = (e) => {
    const value = e.target.value;
    this.setState({ calldisposition: value });
    this.props.task.attributes.calldisposition = value;
    this.props.task.setAttributes(this.props.task.attributes);
  };

  render() {
    return(

          <FormControl
            fullWidth
            size="small"
            style={{ fontfamily: "sans-serif", textAlign: "center" }}
          >
            <DropDown
              style={{ color: "black", gap: "3" }}
              value={this.state.calldisposition}
              handleChange={this.handleSelectChange}
              items={[
                { key: "", val: "--Select--" },
                { key: "214680006", val: "Contacted" },
                { key: "214680000", val: "Bad Number" },
                { key: "214680001", val: "Hung up on Call" },
                { key: "214680002", val: "No Answer - Left Voicemail" },
                {
                  key: "214680003",
                  val: "No Answer - Unable to Leave Voicemail",
                },
                {
                  key: "214680004",
                  val: "No Answer - Did Not Leave Voicemail",
                },
                { key: "214680005", val: "Wrong Number" },
                { key: "214680008", val: "Transfer" },
                { key: "000000000", val: "Non-CRM Call" },
              ]}
            ></DropDown>
          </FormControl>

    );
 }


问:
Is it possible to set the Text Tone for a contact in iOS?
I'd like to write an iOS app that reads all of the user's contacts and then sets the Text Tone for each contact to a specific vibration pattern. However I don't see Text Tone information available on the CNContact object. Is there any way to do what I'm trying to accomplish?</p>


问:
Why am I getting a result even though int value exceeds the limit?
This is just a basic sum method.

```<code>public int Sum(int a, int b)
{
    return a + b;
}
</code>```

If I call the function as below

```<code>int result = Sum(int.MaxValue, int.MaxValue);
</code>```

Why am I gettin ‘-2’ in the result variable even though there is an overflow. Shouldn't I get a stackoverflow exception?

Body:
This is just a basic sum method.

public int Sum(int a, int b)
{
    return a + b;
}

If I call the function as below

int result = Sum(int.MaxValue, int.MaxValue);

Why am I gettin ‘-2’ in the result variable even though there is an overflow. Shouldn't I get a stackoverflow exception?


问:
Force routing without context
am working on chat app , now am stuck on the idea of , if one of the two users left the page i wanna force the other user also to leave the page and back to home screen , i tried many things , boolean , conditions , will pop , nothing work  , how can i implement a function to do this job , am using flutter , much appreciate .

i tried using boolean to set a condition to check if user exist , i tried to use will pop , i saw a couple of articles bout it , i even tried to set timer to force the second user to leave , but nothing happened , the problem is there's no action from the other user that make him leave the page , with or without on press , while the first user did the action and pressed the button to leave .

this is the button in the home page who do logic to match through firebase

child: ElevatedButton(
onPressed: () async {
var res = await FirebaseFirestore.instance
.doc(
'match/$_currentValue1$_currentValue2$_currentThumbValue')
.get();
var value = res.exists;
print('RESULT = $value');

```<code>                        /// If Code Is Not Exist
                        try {
                          if (value == false) {
                            /// Create Code In Match Document
                            await FirebaseFirestore.instance
                                .collection('match')
                                .doc('$_currentValue1$_currentValue2$_currentThumbValue')
                                .set({
                              'user1Id': FirebaseAuth.instance.currentUser!.uid,
                              'user1Name': userInfo['displayName'] ?? 'username',
                              'user2Id': '',
                              'user2Name': '',
                            });
                            print('Match Created By ${userInfo['displayName']}');

                            /// Create Code Reference In Real Time
                            await codeRef.set({
                              'code': '$_currentValue1$_currentValue2$_currentThumbValue',
                              'user1Id': FirebaseAuth.instance.currentUser!.uid,
                              'user1Name': userInfo['displayName'] ?? 'username',
                              'user2Id': '',
                              'user2Name': '',
                            });

                            /// Timer To Delete Code If No Match Found
                            var counter = 10;
                            Timer.periodic(const Duration(seconds: 1),
                                (timer) async {
                              setState(() {
                                isMatchVisible = false;
                              });
                              print(timer.tick);
                              print('Data Value During Countdown : $value');
                              counter--;

                              /// Check If User2 Exist Im Match Document
                              DocumentSnapshot documentSnapshot =
                                  await FirebaseFirestore.instance
                                      .collection('match')
                                      .doc('$_currentValue1$_currentValue2$_currentThumbValue')
                                      .get();

                              ///
                              if (documentSnapshot.get('user2Id') != '') {
                                timer.cancel();

                                var goToPageUser1 = 2;
                                Timer.periodic(const Duration(seconds: 2),
                                    (timer) async {
                                  goToPageUser1--;
                                  if (goToPageUser1 == 0) {
                                    timer.cancel();

                                    /// Go To Chat Screen
                                    await Get.toNamed(
                                      '/ChatScreen',
                                      arguments:
                                          '$_currentValue1$_currentValue2$_currentThumbValue',
                                      parameters: {
                                        'name1': userInfo['displayName'],
                                        'Id1': user!.uid,
                                      },
                                      preventDuplicates: false,
                                    );
                                  }
                                });
                              } else {
                                if (counter == 0) {
                                  var failCounter = 5;
                                  Timer.periodic(const Duration(seconds: 1),
                                      (timer) {
                                    setState(() {
                                      showFailResult = true;
                                    });
                                    failCounter--;
                                    if (failCounter == 0) {
                                      timer.cancel();
                                      setState(() {
                                        showFailResult = false;
                                      });
                                    }
                                  });

                                  /// Delete Code From Match Collection
                                  DocumentReference docCode = FirebaseFirestore
                                      .instance
                                      .collection('match')
                                      .doc(
                                          '${_currentValue1.toString()}${_currentValue2.toString()}${_currentThumbValue.toString()}');
                                  await docCode
                                      .delete()
                                      .then((value) =>
                                          print('Match Code Deleted'))
                                      .catchError((error) => print(
                                          "Failed To Delete Match Code: $error"));

                                  /// Delete Room From Real Time
                                  await codeRef.remove();

                                  print('Cancel timer');
                                  timer.cancel();
                                  setState(() {
                                    value = false;
                                    isMatchVisible = true;
                                    print(
                                        'Data Value After Countdown : $value');
                                  });
                                }
                              }
                            });

                            /// If Code Is Exist
                          } else if (value == true) {
                            /// Update Match Document For User1 AND User2
                            await FirebaseFirestore.instance
                                .collection('match')
                                .doc(
                                  '${_currentValue1.toString()}${_currentValue2.toString()}${_currentThumbValue.toString()}',
                                )
                                .update({
                              'user2Id':
                                  FirebaseAuth.instance.currentUser!.uid,
                              'user2Name':
                                  userInfo['displayName'] ?? 'username',
                            });

                            /// Update Match Code In Real Time
                            await codeRef.update({
                              'user2Id':
                                  FirebaseAuth.instance.currentUser!.uid,
                              'user2Name':
                                  userInfo['displayName'] ?? 'username',
                            });

                            var goToPageUser2 = 2;
                            Timer.periodic(const Duration(seconds: 2),
                                (timer) async {
                              goToPageUser2--;
                              if (goToPageUser2 == 0) {
                                timer.cancel();

                                /// Go To Chat Screen
                                await Get.toNamed(
                                  '/ChatScreen',
                                  arguments:
                                      '$_currentValue1$_currentValue2$_currentThumbValue',
                                  parameters: {
                                    'name2': userInfo['displayName'],
                                    'Id2': user!.uid,
                                  },
                                  preventDuplicates: false,
                                );
                              }
                            });
                          }
                        } on FirebaseAuthException catch (e) {
                          showSnackBar(context, e.message!);
                        }
                      },
                      child: SizedBox(
                        width: 100,
                        height: 50,
                        child: Center(
                          child: Text(
                            'Match'.tr,
                            style: const TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                        ),
                      ),
                    ),
</code>```

Title: Force routing without context

Body:
am working on chat app , now am stuck on the idea of , if one of the two users left the page i wanna force the other user also to leave the page and back to home screen , i tried many things , boolean , conditions , will pop , nothing work  , how can i implement a function to do this job , am using flutter , much appreciate .

i tried using boolean to set a condition to check if user exist , i tried to use will pop , i saw a couple of articles bout it , i even tried to set timer to force the second user to leave , but nothing happened , the problem is there's no action from the other user that make him leave the page , with or without on press , while the first user did the action and pressed the button to leave .

this is the button in the home page who do logic to match through firebase

child: ElevatedButton(
onPressed: () async {
var res = await FirebaseFirestore.instance
.doc(
'match/$_currentValue1$_currentValue2$_currentThumbValue')
.get();
var value = res.exists;
print('RESULT = $value');

                        /// If Code Is Not Exist
                        try {
                          if (value == false) {
                            /// Create Code In Match Document
                            await FirebaseFirestore.instance
                                .collection('match')
                                .doc('$_currentValue1$_currentValue2$_currentThumbValue')
                                .set({
                              'user1Id': FirebaseAuth.instance.currentUser!.uid,
                              'user1Name': userInfo['displayName'] ?? 'username',
                              'user2Id': '',
                              'user2Name': '',
                            });
                            print('Match Created By ${userInfo['displayName']}');

                            /// Create Code Reference In Real Time
                            await codeRef.set({
                              'code': '$_currentValue1$_currentValue2$_currentThumbValue',
                              'user1Id': FirebaseAuth.instance.currentUser!.uid,
                              'user1Name': userInfo['displayName'] ?? 'username',
                              'user2Id': '',
                              'user2Name': '',
                            });

                            /// Timer To Delete Code If No Match Found
                            var counter = 10;
                            Timer.periodic(const Duration(seconds: 1),
                                (timer) async {
                              setState(() {
                                isMatchVisible = false;
                              });
                              print(timer.tick);
                              print('Data Value During Countdown : $value');
                              counter--;

                              /// Check If User2 Exist Im Match Document
                              DocumentSnapshot documentSnapshot =
                                  await FirebaseFirestore.instance
                                      .collection('match')
                                      .doc('$_currentValue1$_currentValue2$_currentThumbValue')
                                      .get();

                              ///
                              if (documentSnapshot.get('user2Id') != '') {
                                timer.cancel();

                                var goToPageUser1 = 2;
                                Timer.periodic(const Duration(seconds: 2),
                                    (timer) async {
                                  goToPageUser1--;
                                  if (goToPageUser1 == 0) {
                                    timer.cancel();

                                    /// Go To Chat Screen
                                    await Get.toNamed(
                                      '/ChatScreen',
                                      arguments:
                                          '$_currentValue1$_currentValue2$_currentThumbValue',
                                      parameters: {
                                        'name1': userInfo['displayName'],
                                        'Id1': user!.uid,
                                      },
                                      preventDuplicates: false,
                                    );
                                  }
                                });
                              } else {
                                if (counter == 0) {
                                  var failCounter = 5;
                                  Timer.periodic(const Duration(seconds: 1),
                                      (timer) {
                                    setState(() {
                                      showFailResult = true;
                                    });
                                    failCounter--;
                                    if (failCounter == 0) {
                                      timer.cancel();
                                      setState(() {
                                        showFailResult = false;
                                      });
                                    }
                                  });

                                  /// Delete Code From Match Collection
                                  DocumentReference docCode = FirebaseFirestore
                                      .instance
                                      .collection('match')
                                      .doc(
                                          '${_currentValue1.toString()}${_currentValue2.toString()}${_currentThumbValue.toString()}');
                                  await docCode
                                      .delete()
                                      .then((value) =>
                                          print('Match Code Deleted'))
                                      .catchError((error) => print(
                                          "Failed To Delete Match Code: $error"));

                                  /// Delete Room From Real Time
                                  await codeRef.remove();

                                  print('Cancel timer');
                                  timer.cancel();
                                  setState(() {
                                    value = false;
                                    isMatchVisible = true;
                                    print(
                                        'Data Value After Countdown : $value');
                                  });
                                }
                              }
                            });

                            /// If Code Is Exist
                          } else if (value == true) {
                            /// Update Match Document For User1 AND User2
                            await FirebaseFirestore.instance
                                .collection('match')
                                .doc(
                                  '${_currentValue1.toString()}${_currentValue2.toString()}${_currentThumbValue.toString()}',
                                )
                                .update({
                              'user2Id':
                                  FirebaseAuth.instance.currentUser!.uid,
                              'user2Name':
                                  userInfo['displayName'] ?? 'username',
                            });

                            /// Update Match Code In Real Time
                            await codeRef.update({
                              'user2Id':
                                  FirebaseAuth.instance.currentUser!.uid,
                              'user2Name':
                                  userInfo['displayName'] ?? 'username',
                            });

                            var goToPageUser2 = 2;
                            Timer.periodic(const Duration(seconds: 2),
                                (timer) async {
                              goToPageUser2--;
                              if (goToPageUser2 == 0) {
                                timer.cancel();

                                /// Go To Chat Screen
                                await Get.toNamed(
                                  '/ChatScreen',
                                  arguments:
                                      '$_currentValue1$_currentValue2$_currentThumbValue',
                                  parameters: {
                                    'name2': userInfo['displayName'],
                                    'Id2': user!.uid,
                                  },
                                  preventDuplicates: false,
                                );
                              }
                            });
                          }
                        } on FirebaseAuthException catch (e) {
                          showSnackBar(context, e.message!);
                        }
                      },
                      child: SizedBox(
                        width: 100,
                        height: 50,
                        child: Center(
                          child: Text(
                            'Match'.tr,
                            style: const TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                        ),
                      ),
                    ),


问:
Why laravel eloquent insert function missing values after 50k entries while using chunks?
I have an excel sheet that has more than 1 million rows in it. I want to insert and update these rows of data to a table. I have used "Maatwebsite" excel library and imported excel to a temporary table. After this, I want to insert temporary table data into the actual table.

Following is the code for fetching data from the temp table.

```<code>$temp_products = ProductTemp::limit(100000)->get()->map(function(ProductTemp $temp_product) {
        return [
            'msrp' => $temp_product->msrp,
            'price' => $temp_product->unit_price,
            'product_overview' => $temp_product->part_description,
            'manufacturer_id' => $temp_product->manufacturer_id,
            'upc' => $temp_product->upc,
            'manufacturer_part_number' => $temp_product->part_no
        ];
    });
</code>```

Then I tried both the chunk() and array_chunk() functions to divide data into parts.

```<code>//$chunks = $temp_products->chunk(5000);
$arr_chunks = array_chunk($temp_products->toArray(), 5000);
</code>```

Then I loop through them to insert rows in a actual table like this with the array_chunk() function.

```<code>foreach($arr_chunks as $chunk)
    {
        Product::insert($chunk);
    }
</code>```

and with chunk() function like this.

```<code>foreach($arr_chunks as $chunk)
        {
            Product::insert($chunk->toArray());
        }
</code>```

I have also tried the sleep() function with this but not helping. After 50, 000 entries it's missing values or adding more. Also, I tried chunks of 100, and 1000 but the result is the same and the page never finishes loading.

Here is the full function code, this might help with what I have tried more and what I am missing.

```<code>public function insertFromTempTable()
    {
        // dd("HERE 1111111 22222222222 4444444444");
        $temp_products = ProductTemp::all()->map(function (ProductTemp $temp_product) {
            return [
                'msrp' => $temp_product->msrp,
                'price' => $temp_product->unit_price,
                'product_overview' => $temp_product->part_description,
                'manufacturer_id' => $temp_product->manufacturer_id,
                'upc' => $temp_product->upc,
                'manufacturer_part_number' => $temp_product->part_no,
            ];
        });
        // dd($temp_products);
        $inc = 0;
        dump("Started on: " . Carbon::now()->toDateTimeString());
        // sleep(10);
        // foreach ($temp_products as $value) {
        //     Product::insert($temp_products[$inc]);
        //     $inc++;
        // }
        // dd($temp_products->toArray());
        // Product::insert($temp_products->toArray());
        // $chunks = $temp_products->chunk(100);
        $chunk_sub = 5000;
        $arr_chunks = array_chunk($temp_products->toArray(), $chunk_sub);
        // dd($arr_chunks[0]);
        // dd(gettype($chunks[0]->toArray()));
        // dd($chunks[0]->toArray());
        $chunk_temp = 0;
        foreach ($arr_chunks as $chunk) {
            // dd($chunk->toArray());
            // dump(count($chunk->toArray()));
            // Product::insert($chunk->toArray());
            $chunk_temp = $chunk_temp + $chunk_sub;

            Product::insert($chunk);

        }

        // $temp_products->chunk(2, function ($subset) {
        //     dd("HHHHHHH");
        //     $subset->each(function ($item) {
        //         dd($item);
        //     });
        // });

        dump("Ended on: " . Carbon::now()->toDateTimeString());
    }
</code>```

After inserting I want to compare an excel sheet on daily basis, that might have more than 1 million rows. That will check for MSRP and price columns and update them. Please let me know which will be the best solution for all of this.

UPDATE 01:

I have tried using a raw query. There were 104, 8575 rows in the temp table but after the query run, there are 103, 9229 rows in the products table. Following is the code for the raw query.

```<code>$results = DB::table('products')->insertUsing(
        ['msrp', 'price', 'product_overview', 'manufacturer_id', 'upc', 'manufacturer_part_number',],
        function ($query) {
            $query
                ->select(['msrp', 'unit_price', 'part_description', 'manufacturer_id', 'upc', 'part_no',])
                ->from('products_temp');
        }
    );
</code>```

When I dump and die the $results variable it output 104, 8575.

Body:
I have an excel sheet that has more than 1 million rows in it. I want to insert and update these rows of data to a table. I have used "Maatwebsite" excel library and imported excel to a temporary table. After this, I want to insert temporary table data into the actual table.

Following is the code for fetching data from the temp table.

$temp_products = ProductTemp::limit(100000)->get()->map(function(ProductTemp $temp_product) {
        return [
            'msrp' => $temp_product->msrp,
            'price' => $temp_product->unit_price,
            'product_overview' => $temp_product->part_description,
            'manufacturer_id' => $temp_product->manufacturer_id,
            'upc' => $temp_product->upc,
            'manufacturer_part_number' => $temp_product->part_no
        ];
    });

Then I tried both the chunk() and array_chunk() functions to divide data into parts.

//$chunks = $temp_products->chunk(5000);
$arr_chunks = array_chunk($temp_products->toArray(), 5000);

Then I loop through them to insert rows in a actual table like this with the array_chunk() function.

foreach($arr_chunks as $chunk)
    {
        Product::insert($chunk);
    }

and with chunk() function like this.

foreach($arr_chunks as $chunk)
        {
            Product::insert($chunk->toArray());
        }

I have also tried the sleep() function with this but not helping. After 50, 000 entries it's missing values or adding more. Also, I tried chunks of 100, and 1000 but the result is the same and the page never finishes loading.

Here is the full function code, this might help with what I have tried more and what I am missing.

public function insertFromTempTable()
    {
        // dd("HERE 1111111 22222222222 4444444444");
        $temp_products = ProductTemp::all()->map(function (ProductTemp $temp_product) {
            return [
                'msrp' => $temp_product->msrp,
                'price' => $temp_product->unit_price,
                'product_overview' => $temp_product->part_description,
                'manufacturer_id' => $temp_product->manufacturer_id,
                'upc' => $temp_product->upc,
                'manufacturer_part_number' => $temp_product->part_no,
            ];
        });
        // dd($temp_products);
        $inc = 0;
        dump("Started on: " . Carbon::now()->toDateTimeString());
        // sleep(10);
        // foreach ($temp_products as $value) {
        //     Product::insert($temp_products[$inc]);
        //     $inc++;
        // }
        // dd($temp_products->toArray());
        // Product::insert($temp_products->toArray());
        // $chunks = $temp_products->chunk(100);
        $chunk_sub = 5000;
        $arr_chunks = array_chunk($temp_products->toArray(), $chunk_sub);
        // dd($arr_chunks[0]);
        // dd(gettype($chunks[0]->toArray()));
        // dd($chunks[0]->toArray());
        $chunk_temp = 0;
        foreach ($arr_chunks as $chunk) {
            // dd($chunk->toArray());
            // dump(count($chunk->toArray()));
            // Product::insert($chunk->toArray());
            $chunk_temp = $chunk_temp + $chunk_sub;

            Product::insert($chunk);

        }

        // $temp_products->chunk(2, function ($subset) {
        //     dd("HHHHHHH");
        //     $subset->each(function ($item) {
        //         dd($item);
        //     });
        // });

        dump("Ended on: " . Carbon::now()->toDateTimeString());
    }

After inserting I want to compare an excel sheet on daily basis, that might have more than 1 million rows. That will check for MSRP and price columns and update them. Please let me know which will be the best solution for all of this.

UPDATE 01:

I have tried using a raw query. There were 104, 8575 rows in the temp table but after the query run, there are 103, 9229 rows in the products table. Following is the code for the raw query.

$results = DB::table('products')->insertUsing(
        ['msrp', 'price', 'product_overview', 'manufacturer_id', 'upc', 'manufacturer_part_number',],
        function ($query) {
            $query
                ->select(['msrp', 'unit_price', 'part_description', 'manufacturer_id', 'upc', 'part_no',])
                ->from('products_temp');
        }
    );

When I dump and die the $results variable it output 104, 8575.


问:
How to implement general method for serial port communication with different request and response object?
I create a program for communication with electricity meter and I need some help to make code more compact.

The implementation is pretty simple. I create classes for every request and response and base classes Request and Response respectively. The process of communication is also pretty simple. There is an initialization of class fields and method Create that returns array of bytes. Then this array sends thround serial port. The resulting array of bytes from meter is used to create response classes.

So I have a usual workflow like this:

Create an object of the specific request class.

Call Create method to get byte array.

Perform communication with the meter and get byte array.

Create specific response class and return it.

```<code>public async Task<LocationResponse> ReadLocationAsync()
{
    ReadSettingsRequest request = new ReadSettingsRequest(Address, MeterSettings.Location, new byte[0]);
    byte[] outputBuffer = request.Create();
    byte[] inputBuffer = await SerialPort.PerformDataExchange(outputBuffer, LocationResponse.Length, token);
    return new LocationResponse(inputBuffer);
}

public async Task<SoftwareVersionResponse> ReadSoftwareVersionAsync(CancellationToken token = default)
{
    ReadSettingsRequest request = new ReadSettingsRequest(Address, MeterSettings.SoftwareVersion, new byte[0]);
    byte[] outputBuffer = request.Create();
    byte[] inputBuffer = await SerialPort.PerformDataExchange(outputBuffer, SoftwareVersionResponse.Length, token);
    return new SoftwareVersionResponse(inputBuffer);
}
</code>```

The problem is I have too many requests and responses and I just copy and paste old code now. I'm afraid this is bad practise, so is there any way to combine these steps in one method and use it for different requests and responses? The best I could imagine is to move the Create method to PerformDataExchange but this is unlikely solving the problem.

Body:
I create a program for communication with electricity meter and I need some help to make code more compact.

The implementation is pretty simple. I create classes for every request and response and base classes Request and Response respectively. The process of communication is also pretty simple. There is an initialization of class fields and method Create that returns array of bytes. Then this array sends thround serial port. The resulting array of bytes from meter is used to create response classes.

So I have a usual workflow like this:

Create an object of the specific request class.

Call Create method to get byte array.

Perform communication with the meter and get byte array.

Create specific response class and return it.

public async Task<LocationResponse> ReadLocationAsync()
{
    ReadSettingsRequest request = new ReadSettingsRequest(Address, MeterSettings.Location, new byte[0]);
    byte[] outputBuffer = request.Create();
    byte[] inputBuffer = await SerialPort.PerformDataExchange(outputBuffer, LocationResponse.Length, token);
    return new LocationResponse(inputBuffer);
}

public async Task<SoftwareVersionResponse> ReadSoftwareVersionAsync(CancellationToken token = default)
{
    ReadSettingsRequest request = new ReadSettingsRequest(Address, MeterSettings.SoftwareVersion, new byte[0]);
    byte[] outputBuffer = request.Create();
    byte[] inputBuffer = await SerialPort.PerformDataExchange(outputBuffer, SoftwareVersionResponse.Length, token);
    return new SoftwareVersionResponse(inputBuffer);
}

The problem is I have too many requests and responses and I just copy and paste old code now. I'm afraid this is bad practise, so is there any way to combine these steps in one method and use it for different requests and responses? The best I could imagine is to move the Create method to PerformDataExchange but this is unlikely solving the problem.


问:
Cloudfront unable to access encrypted file in S3
I have encrypted all files in S3, after that I am unable to access them using cloudfront, all the policies are same as before when files were not encrypted but still not accessable after encryption. I have used Origin Access Control but no luck.</p>


问:
Change weight and color of System Symbol UIImage in Swift
I'm trying to change the weight, scale, and color of the system symbol since that isn't an option to do all this in one go in the UIImage.SymbolConfiguration I've tried to do this in an extra step. The color doesn't apply but the SymbolConfiguration do so now I'm wondering what I am doing wrong.

Code:

    let backButtonImage: UIImage = {
        var config = UIImage.SymbolConfiguration(pointSize: 24, weight: .heavy, scale: .large)
        let image = UIImage(systemName: "chevron.backward")!
        let coloredImage = image.withTintColor(.label)
        let finalImage = coloredImage.withConfiguration(config)

        return finalImage
    }()
```

* Edit: I'm trying to set that image as UIBarButtonItem

Body:
I'm trying to change the weight, scale, and color of the system symbol since that isn't an option to do all this in one go in the UIImage.SymbolConfiguration I've tried to do this in an extra step. The color doesn't apply but the SymbolConfiguration do so now I'm wondering what I am doing wrong.

Code:

    let backButtonImage: UIImage = {
        var config = UIImage.SymbolConfiguration(pointSize: 24, weight: .heavy, scale: .large)
        let image = UIImage(systemName: "chevron.backward")!
        let coloredImage = image.withTintColor(.label)
        let finalImage = coloredImage.withConfiguration(config)

        return finalImage
    }()

* Edit: I'm trying to set that image as UIBarButtonItem


问:
Pure MapReduce in PySpark retuning top n occurencies per group
I have a RDD with key-value pairs (dummy_key, text)

I need code in PySpark a operation to return n top most frequent words per category with count that can be extracted from text (it is first word in text). While this is easy without aggregation I have troubles to do it per category.

I would be grateful for any help.


问:
from package import * - strategy to avoid importing everything in python
I know that it is not a good idea to use the from package import * syntax in python to import everything from a package. I want a strategy to avoid importing everything, just those items that are required.
For example, below is some code - how would I go about finding which parts of the PyQt5.Qt package I should import, rather than * ?

```<code>import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel
from PyQt5.Qt import *

class MyLabel(QLabel):
    def __init__(self, text, obj):
        super(MyLabel, self).__init__(text, obj)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.setText('Left')
        if event.button() == Qt.RightButton:
            self.setText('Right')

# Creating the main window
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Sample QTWidget App'
        self.left = 0
        self.top = 0
        self.width = 400
        self.height = 150
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = MyLabel("Click-Me", self)
        self.label.setGeometry(150, 50, 100, 20)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

Body:
I know that it is not a good idea to use the from package import * syntax in python to import everything from a package. I want a strategy to avoid importing everything, just those items that are required.
For example, below is some code - how would I go about finding which parts of the PyQt5.Qt package I should import, rather than * ?

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel
from PyQt5.Qt import *

class MyLabel(QLabel):
    def __init__(self, text, obj):
        super(MyLabel, self).__init__(text, obj)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.setText('Left')
        if event.button() == Qt.RightButton:
            self.setText('Right')

# Creating the main window
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Sample QTWidget App'
        self.left = 0
        self.top = 0
        self.width = 400
        self.height = 150
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = MyLabel("Click-Me", self)
        self.label.setGeometry(150, 50, 100, 20)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


问:
Schedule emails to be sent based on the time provided by the user django
I am trying to schedule emails to send based on the date and time user will provide. I looked into celery beat but I didn't find any thing that can help with dynamic time.

I also looked into this post: Gmail Schedule Send Email in Django

Can anyone please guide me on how can I send schedule emails based on the time user will provide to the system instead of checking into the system again and again like every five minutes or so to send email.


问:
Why does my array change its values from the correct ones to random ones when it exits the while loop?
I am trying to take a string of numbers and commas, then separate the numbers from the commas and turn them into ints and store them into an array. I print out the array in the while loop, and it works perfectly fine, but when I try printing the array outside of the while loop it outputs random numbers that change every time. I'm assuming it has something to do with  pointers or data storage but I don't know why.

I know that the numbers in the array are correct and ints since I can do mathematical operations to them without resulting in errors, but for some reason as soon as it exits the while loop all the numbers change to random ones.

```<code>int commaCount = CntComma(point);
int numArray[commaCount];

//run a while loop to take strings and turn them into ints, then store them in a 1D array
while(point.find(",") != std::string::npos){
    int i = 0;
    int commaLocate = point.find(",");
    string subPart1 = point.substr(0, commaLocate);
    numArray[i] = stoi(subPart1);
    point = point.substr(commaLocate + 1, (point.length()-1) - subPart1.length());
    i++;
}
</code>```

Body:
I am trying to take a string of numbers and commas, then separate the numbers from the commas and turn them into ints and store them into an array. I print out the array in the while loop, and it works perfectly fine, but when I try printing the array outside of the while loop it outputs random numbers that change every time. I'm assuming it has something to do with  pointers or data storage but I don't know why.

I know that the numbers in the array are correct and ints since I can do mathematical operations to them without resulting in errors, but for some reason as soon as it exits the while loop all the numbers change to random ones.

int commaCount = CntComma(point);
int numArray[commaCount];

//run a while loop to take strings and turn them into ints, then store them in a 1D array
while(point.find(",") != std::string::npos){
    int i = 0;
    int commaLocate = point.find(",");
    string subPart1 = point.substr(0, commaLocate);
    numArray[i] = stoi(subPart1);
    point = point.substr(commaLocate + 1, (point.length()-1) - subPart1.length());
    i++;
}


问:
Why my validation loss is always in a certain range of values?
I have been working with an convolutional autoencoder model. My encoder works fine but I am facing problem with my decoder. I have tried two different model.

For Model 1, training loss starts with 0.0436 and then after some epochs, the value was in range betweek 0.0280 and 0.0320. For validation, loss starts with 0.0306 and then after some epochs it the loss was in between 0.0275 and 0.0285.

For Model 2, the training loss decreased nicely but for the validation loss, it started with 0.2702 but after some epochs, the value was in range between 0.1450 and 0.1550.

I have used 15000 images from MS Coco, 'mse' as a loss function, 'Adam' as an optimizer with 0.00001 learning rate.

I have tried to use dropout layer, regularization but nothing is working. First I have tried it with 3000 images but later I increased the dataset into 15000 but still getting same problem. Total number of parameter of my model is 221,449,088.


问:
How to track an item in non network areas using react native and php
Good day sir/ma, I am working on a project that intends to track items in places where there is not GSM network, so I want to be able to lift the GPS coordinates of this item/s and send them to my PHP application even though the item/s might be in a place where there's no GSM reception and internet connection, please how do I go about this.</p>


问:
Why does sending zero bytes via openssl `s_client` send a 19 byte payload?
I'm playing around with openssl s_client and I tried sending various payloads with/without padding and analysing the stack trace output. One case I don't understand is when I send empty bytes without padding I see the following output:

```<code>New, TLSv1.3, Cipher is TLS_AES_128_GCM_SHA256
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 21 (unable to verify the first certificate)
---
write to 0x107ede0 [0x109a7f3] (24 bytes => 24 (0x18))
0000 - 17 03 03 00 13 a2 03 0c-67 c0 aa 77 08 7d 37 cb   ........g..w.}7.
0010 - 39 82 68 19 ba a2 39 bd-
</code>```

I used a 16-byte aead tag cipher and since the content type field is 1 byte I would expect the total payload size to be 16 + 1 = 17 bytes. However, as evident in the stack trace openssl wrote a record with header 17 03 03 00 13 or 0x13 = 19 bytes. Why was 19 bytes sent instead of the expected 17 bytes? What are these two bytes?

Body:
I'm playing around with openssl s_client and I tried sending various payloads with/without padding and analysing the stack trace output. One case I don't understand is when I send empty bytes without padding I see the following output:

New, TLSv1.3, Cipher is TLS_AES_128_GCM_SHA256
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 21 (unable to verify the first certificate)
---
write to 0x107ede0 [0x109a7f3] (24 bytes => 24 (0x18))
0000 - 17 03 03 00 13 a2 03 0c-67 c0 aa 77 08 7d 37 cb   ........g..w.}7.
0010 - 39 82 68 19 ba a2 39 bd-

I used a 16-byte aead tag cipher and since the content type field is 1 byte I would expect the total payload size to be 16 + 1 = 17 bytes. However, as evident in the stack trace openssl wrote a record with header 17 03 03 00 13 or 0x13 = 19 bytes. Why was 19 bytes sent instead of the expected 17 bytes? What are these two bytes?