问:
typescript : How to exclude key of an parent class
I need to create a generic function that takes a property of a class (Genial in the example) and its type as arguments.
The class extends another class (BaseClass in the example).

I want the function to take only the "extended properties" of the extended class, but not accept the properties of the base class.
Here is what I tried to do ([TS PLAYGROUND HERE])1

Basically in this example, I don't want hasId to be a valid parameter for the function.
I tried to use the "Exclude" utility type but it failed with error Type 'K' cannot be used to index type 'T'.(2536).

Thks for your help

```<code>declare class BaseClass {
    public hasId:boolean
    static getNothing():void
}

class Genial extends BaseClass {
    public property2:number = 0
    constructor(){
        super()
    }
}

class GenericClass<T extends BaseClass> {
    myFunction<K extends keyof T>(key:K, value:T[K]) {
        console.log({[key] : value})
        }

    //tried this but Error
    ItriedThisButError<K extends keyof Exclude<T, BaseClass>>(key:K, value:T[K]) {
        console.log({[key] : value})
        }
}

const instance = new GenericClass<Genial>()
const correct = instance.myFunction("property2", 4)
const shouldnotbepossible = instance.myFunction("hasId", false) // <-I dont want this to be possible
</code>```

Body:
I need to create a generic function that takes a property of a class (Genial in the example) and its type as arguments.
The class extends another class (BaseClass in the example).

I want the function to take only the "extended properties" of the extended class, but not accept the properties of the base class.
Here is what I tried to do ([TS PLAYGROUND HERE])<a href="https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEkoGdnwEIpAYWq%20A3gFDynwAOArgEYQCWY8AFigJLABc1A9txCFAB28EmWQAXKOIbwA5iHEA5buKZ1BsgBQBKDgDdudYCIC%20IoknwBxEILpQI8EAA9xt4GkzIceNMTIUNPSM5DDc5CAw4gCeAEwcgpQAttSR8AC88AAMoqRg3IISMJRg4twwOv4BYpQRFdq58GakRCZEFr7wNoKRDLgoyAA8ACpOru6eWP2oAHyEjdRTvgDSINEAgnAAInTI5NDRIMCDy2Nugh7wANZr3ABm8MMzmjfRHMsANPB6DpQgHMMANrLAC62nm1TI%20UKfBAADoINwtARAa8QfAON9fiATA1IaQ2o0APRE8QwOhHeCqXbwaiUcTwACiMDCMEayh6AHk7tNkKtoiczhNrrcHoznJBKKARl8vD4BjNnq93l8fhA-gDgWCIfjochYQikZoUWiMVj1Ti8fjCa12nqGeoJEIwAhMj0AO5dWy9MC8wbdewQZ4Ne2IcpwUoZeCOySCF1wxbeXn8zYgHZ7A5HTQAIlC4UiMVi2a%20ABYQwUJPBkExuJQIMBBCpUuRuKg6LRXdHCrH44n5agU9tdvsoIdgDmWMh2MX4HcHN5wST4IMALSseDAAoM91CBnUtBlWkIFttjvtIhAA" rel="nofollow noreferrer">1

Basically in this example, I don't want hasId to be a valid parameter for the function.
I tried to use the "Exclude" utility type but it failed with error Type 'K' cannot be used to index type 'T'.(2536).

Thks for your help

declare class BaseClass {
    public hasId:boolean
    static getNothing():void
}

class Genial extends BaseClass {
    public property2:number = 0
    constructor(){
        super()
    }
}

class GenericClass<T extends BaseClass> {
    myFunction<K extends keyof T>(key:K, value:T[K]) {
        console.log({[key] : value})
        }

    //tried this but Error
    ItriedThisButError<K extends keyof Exclude<T, BaseClass>>(key:K, value:T[K]) {
        console.log({[key] : value})
        }
}

const instance = new GenericClass<Genial>()
const correct = instance.myFunction("property2", 4)
const shouldnotbepossible = instance.myFunction("hasId", false) // <-I dont want this to be possible


来源: stackexchange

问:
Vs code ssh remote extension is not working
I have been using vs code ssh remote connection to server for a while now. Suddenly it does not work because of timeout. I can ssh to the server via terminal and everything is fine. Network speed is also not a problem. I reinstalled the extension and still not ok. I have no idea what could go wrong, since I have not made any changes that should matter.
Any ideas please?</p>

ContentLicense: CC BY-SA 4.0


问:
Error Setting Up Angular/Components Dev Environment
I have installed dependencies successfully with Yarn. After running 'yarn dev-app' I get a long list of errors.

ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/button/BUILD.bazel:29:10:
Target
'//src/components-examples/material/button:button-types/button-types-example.css'
contains an error and its package is in error and referenced by
'//src/components-examples/material/button:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/button/BUILD.bazel:29:10:
Target
'//src/components-examples/material/button:button-types/button-types-example.html'
contains an error and its package is in error and referenced by
'//src/components-examples/material/button:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/button/BUILD.bazel:29:10:
Target
'//src/components-examples/material/button:button-types/button-types-example.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/button:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/button/BUILD.bazel:29:10:
Target '//src/components-examples/material/button:index.ts' contains
an error and its package is in error and referenced by
'//src/components-examples/material/button:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-harness/bottom-sheet-harness-example.html'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-harness/bottom-sheet-harness-example.spec.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-harness/bottom-sheet-harness-example.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-overview/bottom-sheet-overview-example-sheet.html' contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-overview/bottom-sheet-overview-example.html'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target
'//src/components-examples/material/bottom-sheet:bottom-sheet-overview/bottom-sheet-overview-example.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/bottom-sheet/BUILD.bazel:29:10:
Target '//src/components-examples/material/bottom-sheet:index.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/bottom-sheet:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-harness/badge-harness-example.html'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-harness/badge-harness-example.spec.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-harness/badge-harness-example.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-overview/badge-overview-example.css'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-overview/badge-overview-example.html'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target
'//src/components-examples/material/badge:badge-overview/badge-overview-example.ts'
contains an error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/components-examples/material/badge/BUILD.bazel:28:10:
Target '//src/components-examples/material/badge:index.ts' contains an
error and its package is in error and referenced by
'//src/components-examples/material/badge:source-files'

And some more:

Analyzing: target //src/dev-app:devserver (0 packages loaded, 0
targets configured) ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:16:10:
In rule 'core_tsec_test', size 'medium' is not a valid size. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:16:10:
In rule 'core_tsec_test', timeout 'illegal' is not a valid timeout.
ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:140:18:
In rule 'unit_tests_debug_bin', size 'medium' is not a valid size.
ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:140:18:
In rule 'unit_tests_debug_bin', timeout 'illegal' is not a valid
timeout. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:140:18:
In rule 'unit_tests_debug', size 'medium' is not a valid size. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/core/BUILD.bazel:140:18:
In rule 'unit_tests_debug', timeout 'illegal' is not a valid timeout.
ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/BUILD.bazel:12:11:
In rule 'material_tsec_test', size 'medium' is not a valid size.
ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material/BUILD.bazel:12:11:
In rule 'material_tsec_test', timeout 'illegal' is not a valid
timeout. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material-experimental/BUILD.bazel:11:11:
In rule 'material-experimental_tsec_test', size 'medium' is not a
valid size. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/material-experimental/BUILD.bazel:11:11:
In rule 'material-experimental_tsec_test', timeout 'illegal' is not a
valid timeout. ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/dev-app/BUILD.bazel:129:12:
Target '//src/material:sass_lib' contains an error and its package is
in error and referenced by '//src/dev-app:theme' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/dev-app/BUILD.bazel:129:12:
Target '//src/material-experimental:sass_lib' contains an error and
its package is in error and referenced by '//src/dev-app:theme' ERROR:
C:/users/dell/desktop/personal/angular-material/components/src/dev-app/BUILD.bazel:129:12:
Target '//src/material/core:theming_scss_lib' contains an error and
its package is in error and referenced by '//src/dev-app:theme' ERROR:
Analysis of target '//src/dev-app:devserver' failed; build aborted:

Any ideas on how to debug this?


问:
how can i get google authentications to work with react.js, firebase, redux?
I'm trying to get google authentication to work with firebase and redux and the program compiles but the google authentication won`t work
This is my code:

firebase.js

```<code>import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';

export const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };

  const firebaseApp = firebase.initializeApp(firebaseConfig);
  const db = firebaseApp.firestore();
  const auth = firebase.auth();
  const provider = new firebase.auth.GoogleAuthProvider();
  const storage = firebase.storage();

  export { auth, provider, storage};
  export default db;
</code>```

store index.js

```<code>import { createStore, applyMiddleware } from "redux";
import  ThunkMiddleware  from "redux-thunk";
import rootReducer from "../reducers";

export const store = createStore( rootReducer, applyMiddleware(ThunkMiddleware));

export default store;
</code>```

action index.js

```<code>import { auth, provider } from "../firebase";

export function signInAPI() {
    return (dispatch) => {
        auth
        .signInWithPopup(provider)
        .then((payload) => {
            console.log(payload);
        })
        .catch((error) => alert(error.message));
    };
}
</code>```

login.jsx

```<code>import styled from "styled-components";
import { connect } from "react-redux";
import { signInAPI } from "../actions";

export const Login = (props) => {
    return (
        <Container>
            <Section>
                <Form>
                    <Google onClick={() => props.signIn}>
                        <img src="/images/google.svg" alt="" />
                        Sign in with Google
                    </Google>
                </Form>
            </Section>
        </Container>
    );
};

const mapStateToProps = (state) => {
    return{};
};

const mapDispatchToProps = (dispatch) => ({
    signIn: () => dispatch(signInAPI()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from "react-redux";
import store from "./store";

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <Provider store={store}>
       <App />
    </Provider>
  </React.StrictMode>
);
</code>```

I might also add that I have the latest version of everything as well so do anyone know what the problem could be?

Body:
I'm trying to get google authentication to work with firebase and redux and the program compiles but the google authentication won`t work
This is my code:

firebase.js

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';

export const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };

  const firebaseApp = firebase.initializeApp(firebaseConfig);
  const db = firebaseApp.firestore();
  const auth = firebase.auth();
  const provider = new firebase.auth.GoogleAuthProvider();
  const storage = firebase.storage();

  export { auth, provider, storage};
  export default db;

store index.js

import { createStore, applyMiddleware } from "redux";
import  ThunkMiddleware  from "redux-thunk";
import rootReducer from "../reducers";

export const store = createStore( rootReducer, applyMiddleware(ThunkMiddleware));

export default store;

action index.js

import { auth, provider } from "../firebase";

export function signInAPI() {
    return (dispatch) => {
        auth
        .signInWithPopup(provider)
        .then((payload) => {
            console.log(payload);
        })
        .catch((error) => alert(error.message));
    };
}

login.jsx

import styled from "styled-components";
import { connect } from "react-redux";
import { signInAPI } from "../actions";

export const Login = (props) => {
    return (
        <Container>

                <Form>
                    <Google onClick={() => props.signIn}>

                        Sign in with Google
                    </Google>
                </Form>

        </Container>
    );
};

const mapStateToProps = (state) => {
    return{};
};

const mapDispatchToProps = (dispatch) => ({
    signIn: () => dispatch(signInAPI()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from "react-redux";
import store from "./store";

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <Provider store={store}>
       <App />
    </Provider>
  </React.StrictMode>
);

I might also add that I have the latest version of everything as well so do anyone know what the problem could be?


问:
Time-Series Transformer Model Prediction Accuracy
I have created a transformer model for multivariate time series predictions for a linear regression problem.

Details about the Dataset

I have the hourly varying data i.e., single feature (lagged energy use data). The model improvement could be done by increasing the number of lagged energy use data, which provide more information to the model)  to predict the time sequence (energy consumption of a building). So my input has the shape X.shape = (8783, 168, 1) i.e., 8783 time sequences, each sequence contains lagged energy use data of one week i.e., 24*7 =168 hourly entries/vectors and each vector contains lagged energy use data as input. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

Model Details

I took as a model an example from the official keras site. It is created for classification problems, I modified it for my regression problem by changing the activation of last output layer from sigmoid to relu. Input shape (train_f) = (8783, 168, 1) Output shape (train_P) = (8783,1) When I trained the model for 100 no. of epochs it converges very well for less number of epochs as compared to my reference models (i.e., LSTMs and LSTMS with self attention). After training, when the model is asked to make prediction by feeding in the test data, the prediction performance is also good as compare to the reference models.

For the same model predicting well, in order to improve its performance now I am feeding in the lagged data of energy use of 1 month i.e., 168*4 = 672 hourly entries/vectors and each vector contains lagged energy use data as input. So my input going into the model now has the shape X.shape = (8783, 672, 1). Both the training and prediction accuracy drops in comparison to weekly input data as seen below.

```<code>**lagged energy use data for 1 week i.e., X.shape = (8783, 168, 1)**
            **MSE    RMSE     MAE   R-Score**
Training data   1.0489  1.0242  0.6395  0.9707
Testing data    0.6221  0.7887  0.5648  0.9171

**lagged energy use data for 1 week i.e., X.shape = (8783, 672, 1)**
                **MSE    RMSE     MAE   R-Score**
Training data   1.6424  1.2816  0.7326  0.9567
Testing  data   1.4991  1.2244  0.9233  0.6903
</code>```

I believe that providing more information to the model should result in better predictions. Any suggestions, how to improve the model prediction/test accuracy? Is there something wrong with the model?

```<code>
df_energy = pd.read_excel("/content/drive/MyDrive/Architecture Topology/Building_energy_consumption_record.xlsx")
extract_for_normalization = list(df_energy)[1]

df_data_float = df_energy[extract_for_normalization].astype(float)
df_data_array = df_data_float.to_numpy()
df_data_array_1 = df_data_array.reshape(-1,1)

from sklearn.model_selection import train_test_split
train_X, test_X = train_test_split(df_data_array_1, train_size = 0.7, shuffle = False)
scaler = MinMaxScaler(feature_range=(0, 1))

scaled_train_X=scaler.fit_transform(train_X)

**Converting train_X into required shape (inputs,sequences, features)**

train_f = []  #features input from training data
train_p = [] # prediction values

n_future = 1 #number of days we want to predict into the future
n_past = 672 # no. of time series input features to be considered for training

for val in range(n_past, len(scaled_train_X) - n_future+1):
    train_f.append(scaled_train_X[val - n_past:val, 0:scaled_train_X.shape[1]])
    train_p.append(scaled_train_X[val + n_future - 1:val + n_future, -1])

train_f, train_p = np.array(train_f), np.array(train_p)

**Transformer Model**

def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0):
    # Normalization and Attention
    x = layers.LayerNormalization(epsilon=1e-6)(inputs)
    x = layers.MultiHeadAttention(
        key_dim=head_size, num_heads=num_heads, dropout=dropout
    )(x, x)
    x = layers.Dropout(dropout)(x)
    res = x + inputs

    # Feed Forward Part
    x = layers.LayerNormalization(epsilon=1e-6)(res)
    x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
    x = layers.Dropout(dropout)(x)
    x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
    return x + res

def build_model(
    input_shape,
    head_size,
    num_heads,
    ff_dim,
    num_transformer_blocks,
    mlp_units,
    dropout=0,
    mlp_dropout=0,
):
    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):
        x = transformer_encoder(x, head_size, num_heads, ff_dim, dropout)

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    outputs = layers.Dense(train_p.shape[1])(x)
    return keras.Model(inputs, outputs)

input_shape = (train_f.shape[1], train_f.shape[2])

model = build_model(
    input_shape,
    head_size=256,
    num_heads=4,
    ff_dim=4,
    num_transformer_blocks=4,
    mlp_units=[128],
    mlp_dropout=0.4,
    dropout=0.25,
)

model.compile(loss=tf.keras.losses.mean_absolute_error,
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
              metrics=["mse"])

model.summary()

history = model.fit(train_f, train_p, epochs=100, batch_size = 32, validation_split = 0.25, verbose = 1)

trainYPredict = model.predict(train_f)

**Inverse transform the prediction and keep the last value(output)**

trainYPredict1 = np.repeat(trainYPredict, scaled_train_X.shape[1], axis = -1)
trainYPredict_actual = scaler.inverse_transform(trainYPredict1)[:, -1]

train_p_actual = np.repeat(train_p, scaled_train_X.shape[1], axis = -1)

train_p_actual1 = scaler.inverse_transform(train_p_actual)[:, -1]

Prediction_mse=mean_squared_error(train_p_actual1 ,trainYPredict_actual)
print("Mean Squared Error of prediction is:", str(Prediction_mse))

Prediction_rmse =sqrt(Prediction_mse)
print("Root Mean Squared Error of prediction is:", str(Prediction_rmse))

prediction_r2=r2_score(train_p_actual1 ,trainYPredict_actual)
print("R2 score of predictions is:", str(prediction_r2))

prediction_mae=mean_absolute_error(train_p_actual1 ,trainYPredict_actual)
print("Mean absolute error of prediction is:", prediction_mae)

**Testing of model**

scaled_test_X = scaler.transform(test_X)
test_q = []
test_r = []

for val in range(n_past, len(scaled_test_X) - n_future+1):
    test_q.append(scaled_test_X[val - n_past:val, 0:scaled_test_X.shape[1]])
    test_r.append(scaled_test_X[val + n_future - 1:val + n_future, -1])

test_q, test_r = np.array(test_q), np.array(test_r)

testPredict = model.predict(test_q)
</code>```

Body:
I have created a transformer model for multivariate time series predictions for a linear regression problem.

Details about the Dataset

I have the hourly varying data i.e., single feature (lagged energy use data). The model improvement could be done by increasing the number of lagged energy use data, which provide more information to the model)  to predict the time sequence (energy consumption of a building). So my input has the shape X.shape = (8783, 168, 1) i.e., 8783 time sequences, each sequence contains lagged energy use data of one week i.e., 24*7 =168 hourly entries/vectors and each vector contains lagged energy use data as input. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

Model Details

I took as a model an example from the official keras site. It is created for classification problems, I modified it for my regression problem by changing the activation of last output layer from sigmoid to relu. Input shape (train_f) = (8783, 168, 1) Output shape (train_P) = (8783,1) When I trained the model for 100 no. of epochs it converges very well for less number of epochs as compared to my reference models (i.e., LSTMs and LSTMS with self attention). After training, when the model is asked to make prediction by feeding in the test data, the prediction performance is also good as compare to the reference models.

For the same model predicting well, in order to improve its performance now I am feeding in the lagged data of energy use of 1 month i.e., 168*4 = 672 hourly entries/vectors and each vector contains lagged energy use data as input. So my input going into the model now has the shape X.shape = (8783, 672, 1). Both the training and prediction accuracy drops in comparison to weekly input data as seen below.

**lagged energy use data for 1 week i.e., X.shape = (8783, 168, 1)**
            **MSE    RMSE     MAE   R-Score**
Training data   1.0489  1.0242  0.6395  0.9707
Testing data    0.6221  0.7887  0.5648  0.9171

**lagged energy use data for 1 week i.e., X.shape = (8783, 672, 1)**
                **MSE    RMSE     MAE   R-Score**
Training data   1.6424  1.2816  0.7326  0.9567
Testing  data   1.4991  1.2244  0.9233  0.6903

I believe that providing more information to the model should result in better predictions. Any suggestions, how to improve the model prediction/test accuracy? Is there something wrong with the model?

df_energy = pd.read_excel("/content/drive/MyDrive/Architecture Topology/Building_energy_consumption_record.xlsx")
extract_for_normalization = list(df_energy)[1]

df_data_float = df_energy[extract_for_normalization].astype(float)
df_data_array = df_data_float.to_numpy()
df_data_array_1 = df_data_array.reshape(-1,1)

from sklearn.model_selection import train_test_split
train_X, test_X = train_test_split(df_data_array_1, train_size = 0.7, shuffle = False)
scaler = MinMaxScaler(feature_range=(0, 1))

scaled_train_X=scaler.fit_transform(train_X)

**Converting train_X into required shape (inputs,sequences, features)**

train_f = []  #features input from training data
train_p = [] # prediction values

n_future = 1 #number of days we want to predict into the future
n_past = 672 # no. of time series input features to be considered for training

for val in range(n_past, len(scaled_train_X) - n_future+1):
    train_f.append(scaled_train_X[val - n_past:val, 0:scaled_train_X.shape[1]])
    train_p.append(scaled_train_X[val + n_future - 1:val + n_future, -1])

train_f, train_p = np.array(train_f), np.array(train_p)

**Transformer Model**

def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0):
    # Normalization and Attention
    x = layers.LayerNormalization(epsilon=1e-6)(inputs)
    x = layers.MultiHeadAttention(
        key_dim=head_size, num_heads=num_heads, dropout=dropout
    )(x, x)
    x = layers.Dropout(dropout)(x)
    res = x + inputs

    # Feed Forward Part
    x = layers.LayerNormalization(epsilon=1e-6)(res)
    x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
    x = layers.Dropout(dropout)(x)
    x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
    return x + res

def build_model(
    input_shape,
    head_size,
    num_heads,
    ff_dim,
    num_transformer_blocks,
    mlp_units,
    dropout=0,
    mlp_dropout=0,
):
    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):
        x = transformer_encoder(x, head_size, num_heads, ff_dim, dropout)

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    outputs = layers.Dense(train_p.shape[1])(x)
    return keras.Model(inputs, outputs)

input_shape = (train_f.shape[1], train_f.shape[2])

model = build_model(
    input_shape,
    head_size=256,
    num_heads=4,
    ff_dim=4,
    num_transformer_blocks=4,
    mlp_units=[128],
    mlp_dropout=0.4,
    dropout=0.25,
)

model.compile(loss=tf.keras.losses.mean_absolute_error,
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
              metrics=["mse"])

model.summary()

history = model.fit(train_f, train_p, epochs=100, batch_size = 32, validation_split = 0.25, verbose = 1)

trainYPredict = model.predict(train_f)

**Inverse transform the prediction and keep the last value(output)**

trainYPredict1 = np.repeat(trainYPredict, scaled_train_X.shape[1], axis = -1)
trainYPredict_actual = scaler.inverse_transform(trainYPredict1)[:, -1]

train_p_actual = np.repeat(train_p, scaled_train_X.shape[1], axis = -1)

train_p_actual1 = scaler.inverse_transform(train_p_actual)[:, -1]

Prediction_mse=mean_squared_error(train_p_actual1 ,trainYPredict_actual)
print("Mean Squared Error of prediction is:", str(Prediction_mse))

Prediction_rmse =sqrt(Prediction_mse)
print("Root Mean Squared Error of prediction is:", str(Prediction_rmse))

prediction_r2=r2_score(train_p_actual1 ,trainYPredict_actual)
print("R2 score of predictions is:", str(prediction_r2))

prediction_mae=mean_absolute_error(train_p_actual1 ,trainYPredict_actual)
print("Mean absolute error of prediction is:", prediction_mae)

**Testing of model**

scaled_test_X = scaler.transform(test_X)
test_q = []
test_r = []

for val in range(n_past, len(scaled_test_X) - n_future+1):
    test_q.append(scaled_test_X[val - n_past:val, 0:scaled_test_X.shape[1]])
    test_r.append(scaled_test_X[val + n_future - 1:val + n_future, -1])

test_q, test_r = np.array(test_q), np.array(test_r)

testPredict = model.predict(test_q)


问:
How to find the distance between two modulations in time
I have modulation in signal:

How to find the distance between the centers of two modulations in [s]?


问:
How to Fetch each columns in html from this array of object in Angular project
I have data format coming from backend as

INPUT DATA FORMAT -

MODULE
FRQ
VAL

Module1
1
12

Module1
2
34

Module1
3
43

Module2
1
56

Module2
2
49

Module2
3
11

Module3
1
21

Module3
2
55

Module3
3
66

OUTPUT

```<code>Module 1 | 12 | 34 | 43
Module 2 | 56 | 59 | 11
</code>```

How to display in table using above format using angular and module 1,2,3 is dynamic not fixed so if 8 modules it should display 8 rows as above output.

To get answer if the solution is possible

Body:
I have data format coming from backend as

INPUT DATA FORMAT -

MODULE
FRQ
VAL

Module1
1
12

Module1
2
34

Module1
3
43

Module2
1
56

Module2
2
49

Module2
3
11

Module3
1
21

Module3
2
55

Module3
3
66

OUTPUT

Module 1 | 12 | 34 | 43
Module 2 | 56 | 59 | 11

How to display in table using above format using angular and module 1,2,3 is dynamic not fixed so if 8 modules it should display 8 rows as above output.

To get answer if the solution is possible


问:
how important is 'unsafe-inline' in js and css CSP
I´m developing an app and I came across with the CSP policies. I´ve already done it but I need to put the 'unsafe inline' and 'unsafe eval' in most of the pages because I have inline code or style that changes a little bit the view of the content, but it is important. No mention the responsive js that I have that changes the inline content.

My question here is: is it really necesary to change all my inline style and js, to a separate file and create a class of every little modification that I do with my inline css in order to dont use the 'unsafe'?

I´ve being looking arround and I see that most of the pages uses inline properties, no matter how big the page is.

Thank you for your time!


问:
Socket.io 4.5.4 acknowledgement is automatically acknowledged when it should fail to be acknowledged
I'm trying to emit an event from the server side to a single socket on the client side. The acknowledgement is received quickly with a response of empty array.  However there is nothing client side listening for the event.  Emitting with a randomly generated event name has the same result.  I have checked that the socket ID is correct.  Emitting to a randomly generated socket ID has the same result.

Code:

```<code>const eventName = 'unheard-event';
this.io
  .to(this.combatantA.socketId)
  .timeout(5000)
  .emit(eventName, this.combatantA.name, (err, response) => {
    if (err) {
      // the other side did not acknowledge the event in the given delay
      console.log(`${eventName} err`, err);
    } else {
      console.log(`${eventName} response`, response);
    }
  });
</code>```

Response:

I would expect this to timeout and hit the if(err) block of code in every scenario.

I've combed through the socket.io 4.x documentation and it doesn't cover this anywhere that I can find. https://socket.io/docs/v4/emitting-events/#acknowledgements

Can anyone shed some light on what is happening here?

Body:
I'm trying to emit an event from the server side to a single socket on the client side. The acknowledgement is received quickly with a response of empty array.  However there is nothing client side listening for the event.  Emitting with a randomly generated event name has the same result.  I have checked that the socket ID is correct.  Emitting to a randomly generated socket ID has the same result.

Code:

const eventName = 'unheard-event';
this.io
  .to(this.combatantA.socketId)
  .timeout(5000)
  .emit(eventName, this.combatantA.name, (err, response) => {
    if (err) {
      // the other side did not acknowledge the event in the given delay
      console.log(`${eventName} err`, err);
    } else {
      console.log(`${eventName} response`, response);
    }
  });

Response:

I would expect this to timeout and hit the if(err) block of code in every scenario.

I've combed through the socket.io 4.x documentation and it doesn't cover this anywhere that I can find. https://socket.io/docs/v4/emitting-events/#acknowledgements

Can anyone shed some light on what is happening here?


问:
Get the join of two tables en SQL where the absence of a record in a month of time is replaced by the last value
I'm trying to get a table where the number of rows will always have to be 12xN. Where N is the number of different products that exist in an event table.

Basically I try to obtain the evolution of the value from one month to another.

What SQL logic should I use?

table

idfecha
update_id
value

--------
---------
-----

20220105
123
3

20220221
345
2

20220730
567
4

20221011
678
2

20221102
789
5

dimtime

idfecha
label_month

--------
---------

20220101
enero

20220102
enero

20220103
enero

20220104
enero

20220105
enero

20220106
enero

20220107
enero

20220108
enero

…
…

20221229
diciembre

20221230
diciembre

20221231
diciembre

result

product_id
value

----------
------

aaa
3

aaa
3

aaa
3

aaa
3

aaa
3

aaa
3

aaa
4

aaa
4

aaa
4

aaa
2

aaa
2

aaa
2

ccc
0

ccc
2

ccc
2

ccc
2

ccc
2

ccc
2

ccc
2

ccc
2

ccc
2

ccc
2

ccc
5

ccc
5

I made some attempts with:

GROUP BY dimtime.month_label, table.product_id.

and combining it with a left outer join, where left is the dimtime.

However, I do not get what I want and I am very clear about why.

Even so, I do not arrive at the adequate logic to achieve it.

Do I have to use an over partition?

thank you!


问:
Rails 7 `turbo_stream_from` not updating view
Running Rails 7.0.4 and trying to get a basic turbo_stream_from implemented. According to logs, it's broadcasting/transmitting appropriately, but the view itself is not updating.

My issue appears to be identical to this question, but the solution with Redis not being running/installed is not my issue (Redis is properly installed and running).

Have restarted the app, console and redis a dozen times.

```<code># show.html.erb
<%= turbo_stream_from "documents" %>
</code>```

# document.rb
class Document < ApplicationRecord
  after_update_commit -> { broadcast_update_to "documents", partial: "documents/summary", locals: { document: self }, target: "document_#{self.id}" }
end
```
```# documents/_summary.html.erb

<%= pluralize(time_to_read(document.summary), "minute") %> • <%= word_count(document.summary) %> words

<%= markdown document.summary %>
```
```irb(main):004:0> document.touch
  TRANSACTION (0.6ms)  BEGIN
  Document Update (1.9ms)  UPDATE "documents" SET "updated_at" = $1 WHERE "documents"."id" = $2  [["updated_at", "2023-01-07 18:24:21.823597"], ["id", "05feddd8-2fb7-4432-9eda-7db07616d613"]]
  TRANSACTION (0.3ms)  COMMIT
  Rendered documents/_summary.html.erb (Duration: 0.6ms | Allocations: 96)
[ActionCable] Broadcasting to documents: "<turbo-stream action=\"append\" target=\"document_05feddd8-2fb7-4432-9eda-7db07616d613\"><template>
1 minute • 38 words
\n
-The study of a 2,000-year-old city wall made of concrete reveals the sustainability of the Roman's use of quicklime i...
=> true
```
```12:24:55 web.1    | Started GET "/cable" [WebSocket] for ::1 at 2023-01-07 12:24:55 -0600
12:24:55 web.1    | Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
12:24:55 web.1    | Turbo::StreamsChannel is transmitting the subscription confirmation
12:24:55 web.1    | Turbo::StreamsChannel is streaming from documents
12:25:17 web.1    | Turbo::StreamsChannel transmitting "<turbo-stream action=\"append\" target=\"document_05feddd8-2fb7-4432-9eda-7db07616d613\"><template>
1 minute • 38 words
\n
-The study of a 2,000-year-old city wall made of concrete reveals the sustainability of the Roman's use of quicklime in... (via streamed from documents)
```
<p>This is what I see on the rendered page:</p>
<pre class="lang-html prettyprint-override"><code><turbo-cable-stream-source channel="Turbo::StreamsChannel" signed-stream-name="ImRvY3VtZW50cyI=--a3f0177252c55b1545ca8ef5c030cc9ed23496182d09168cd9ef3441d9510d22"></turbo-cable-stream-source>
</code>```

Body:
Running Rails 7.0.4 and trying to get a basic turbo_stream_from implemented. According to logs, it's broadcasting/transmitting appropriately, but the view itself is not updating.

My issue appears to be identical to this question, but the solution with Redis not being running/installed is not my issue (Redis is properly installed and running).

Have restarted the app, console and redis a dozen times.

# show.html.erb
<%= turbo_stream_from "documents" %>

# document.rb
class Document < ApplicationRecord
  after_update_commit -> { broadcast_update_to "documents", partial: "documents/summary", locals: { document: self }, target: "document_#{self.id}" }
end

# documents/_summary.html.erb

<%= pluralize(time_to_read(document.summary), "minute") %> • <%= word_count(document.summary) %> words

<%= markdown document.summary %>

irb(main):004:0> document.touch
  TRANSACTION (0.6ms)  BEGIN
  Document Update (1.9ms)  UPDATE "documents" SET "updated_at" = $1 WHERE "documents"."id" = $2  [["updated_at", "2023-01-07 18:24:21.823597"], ["id", "05feddd8-2fb7-4432-9eda-7db07616d613"]]
  TRANSACTION (0.3ms)  COMMIT
  Rendered documents/_summary.html.erb (Duration: 0.6ms | Allocations: 96)
[ActionCable] Broadcasting to documents: "<turbo-stream action=\"append\" target=\"document_05feddd8-2fb7-4432-9eda-7db07616d613\"><template>
1 minute • 38 words
\n
-The study of a 2,000-year-old city wall made of concrete reveals the sustainability of the Roman's use of quicklime i...
=> true

12:24:55 web.1    | Started GET "/cable" [WebSocket] for ::1 at 2023-01-07 12:24:55 -0600
12:24:55 web.1    | Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
12:24:55 web.1    | Turbo::StreamsChannel is transmitting the subscription confirmation
12:24:55 web.1    | Turbo::StreamsChannel is streaming from documents
12:25:17 web.1    | Turbo::StreamsChannel transmitting "<turbo-stream action=\"append\" target=\"document_05feddd8-2fb7-4432-9eda-7db07616d613\"><template>
1 minute • 38 words
\n
-The study of a 2,000-year-old city wall made of concrete reveals the sustainability of the Roman's use of quicklime in... (via streamed from documents)

This is what I see on the rendered page:

<turbo-cable-stream-source channel="Turbo::StreamsChannel" signed-stream-name="ImRvY3VtZW50cyI=--a3f0177252c55b1545ca8ef5c030cc9ed23496182d09168cd9ef3441d9510d22"></turbo-cable-stream-source>


问:
Inno Setup - inconsistent (preprocessor / debugger) behavior for string variable with defined symbol inside
I found this very strange behavior when running my script:

When I hover mouse over variable ConfigPath: string; I can see the correct value.
However hovering over symbol {#EPIC_ID} shows me wrong value (saying Internal Error in English).

When I save the preprocessed script the value is correct:

ConfigPath :=
'c:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests\12C916CC456AD69CAD0B65898515C92A.item';

And the weirdest part is that Log (line 177) says just

Reading ""

Like the variable ConfigPath is empty string (which is not!).

This is not happening all the time, it is random and I could not find a way how to reproduce it with 100% accuracy.

Can anybody explain this or reproduce? This may be some internal error how the symbols are expanded but even in that case the ConfigPath string should be not empty.

File Main.iss (the rest of the file does not matter):

```<code>#define EPIC_ID         "12C916CC456AD69CAD0B65898515C92A.item"

#if EPIC_ID
   #include "EpicHelper.iss"
#endif

[Setup]
...
[Code]
</code>```

File EpicHelper.iss (the rest of the file does not matter):

```<code><event('InitializeSetup')>
function InitializeSetupParseConfig(): Boolean;
var
  Json: string;
  ConfigPath: string;

begin
  Result := True;
  ConfigPath := 'c:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests\{#EPIC_ID}';

  if (FileExists(ConfigPath) = false) then
  begin
     Log(Format('File not found: "%s"', [ConfigPath]));
     Exit;
  end;

  Log(Format('Reading "%s"', [ConfigPath]));
end;
</code>```

Body:
I found this very strange behavior when running my script:

When I hover mouse over variable ConfigPath: string; I can see the correct value.
However hovering over symbol {#EPIC_ID} shows me wrong value (saying Internal Error in English).

When I save the preprocessed script the value is correct:

ConfigPath :=
'c:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests\12C916CC456AD69CAD0B65898515C92A.item';

And the weirdest part is that Log (line 177) says just

Reading ""

Like the variable ConfigPath is empty string (which is not!).

This is not happening all the time, it is random and I could not find a way how to reproduce it with 100% accuracy.

Can anybody explain this or reproduce? This may be some internal error how the symbols are expanded but even in that case the ConfigPath string should be not empty.

File Main.iss (the rest of the file does not matter):

#define EPIC_ID         "12C916CC456AD69CAD0B65898515C92A.item"

#if EPIC_ID
   #include "EpicHelper.iss"
#endif

[Setup]
...
[Code]

File EpicHelper.iss (the rest of the file does not matter):

<event('InitializeSetup')>
function InitializeSetupParseConfig(): Boolean;
var
  Json: string;
  ConfigPath: string;

begin
  Result := True;
  ConfigPath := 'c:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests\{#EPIC_ID}';

  if (FileExists(ConfigPath) = false) then
  begin
     Log(Format('File not found: "%s"', [ConfigPath]));
     Exit;
  end;

  Log(Format('Reading "%s"', [ConfigPath]));
end;


问:
Converting a Caffe Model into MLModel
I am following a course on Udemy and now the instructor is converting her Caffe Model into MLModel on Python 2.7 ( I know very outdated). She created this .py file for that

```<code>import coremltools

caffe_model = ('oxford102.caffemodel', 'deploy.prototxt')

labels = 'flower-labels.txt'

coreml_model = coremltools.converters.caffe.convert(
caffe_model,
class_labels=labels,
image_input_names='data'
)

coreml_model.save('FlowerClassifier.mlmodel')
</code>```

Later I realized that it wont work for me because all my versions like Python , Pip are up to date and I realized that I need to use tensor flow for this conversion and also use it in conda environment. I installed miniconda and tensorflow. I have oxford102.caffemodel, deploy.prototxt, flower-labels.txt and convert-script.py files inside a folder named Flower Classification so my question is how can I convert this model into and MLModel as of today?

Title: Converting a Caffe Model into MLModel

Body:
I am following a course on Udemy and now the instructor is converting her Caffe Model into MLModel on Python 2.7 ( I know very outdated). She created this .py file for that

import coremltools

caffe_model = ('oxford102.caffemodel', 'deploy.prototxt')

labels = 'flower-labels.txt'

coreml_model = coremltools.converters.caffe.convert(
caffe_model,
class_labels=labels,
image_input_names='data'
)

coreml_model.save('FlowerClassifier.mlmodel')

Later I realized that it wont work for me because all my versions like Python , Pip are up to date and I realized that I need to use tensor flow for this conversion and also use it in conda environment. I installed miniconda and tensorflow. I have oxford102.caffemodel, deploy.prototxt, flower-labels.txt and convert-script.py files inside a folder named Flower Classification so my question is how can I convert this model into and MLModel as of today?


问:
Intersection Observer - Play Different Audio Depending where on page

if(!!window.IntersectionObserver){
  let target = document.querySelector('#testme');
    let audio = document.querySelector('audio');
    let isPaused = false; /* flag for auto-pausing of the audio */
    let observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.intersectionRatio!=.5  && !audio.paused){
                audio.pause(); isPaused = true;
            }
            else if(isPaused) {audio.play(); isPaused=false}

        });
    }, {threshold: .5});
    observer.observe(target) ;
}

else document.querySelector('#warning').style.display = 'block';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- some warnings, for demo purposes -->
<strong id="warning" hidden>IntersectionObserver is not supported by your browser, so you can't see the effect. Check its browser support here.</strong>
<noscript>⚠ JAVASCRIPT IS DISABLED IN YOUR BROWSER!</noscript>
<div  style="height:600px">
<h1>Click video just to trigger the ability to auto play audio on site, then as you scroll through the page, the respective audio should pause/play depending if it's in the view</h1>

<video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls="" height="200px"></video>
</div>
<br>
<br>
<br>
<hr>

<!-- audio files -->
<div id="testme" style="height:600px; background-color:#CCC">
<audio controls loop src="https://truefa-znfmrrlhm9.live-website.com/wp-content/uploads/2022/12/random_music.mp3" height="10"></audio>
</div>

<hr>
<audio id="testme" controls loop src="https://truefa-znfmrrlhm9.live-website.com/wp-content/uploads/2022/12/random_muisc2.mp3"></audio></code>```

I'm trying to play different audio depending where the user is on the page by leveraging intersection observer

However, the respective audio is not pausing and playing when the various divs are in view. Not sure what I'm missing here for the code to function accordingly...

```<code>if(!!window.IntersectionObserver){
  let target = document.querySelector('#testme');
    let audio = document.querySelector('audio');
    let isPaused = false; /* flag for auto-pausing of the audio */
    let observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.intersectionRatio!=.5  && !audio.paused){
                audio.pause(); isPaused = true;
            }
            else if(isPaused) {audio.play(); isPaused=false}

        });
    }, {threshold: .5});
    observer.observe(target) ;
}

else document.querySelector('#warning').style.display = 'block';
</code>```

https://codepen.io/truefa/pen/PoBWZLV

Body:
if(!!window.IntersectionObserver){
  let target = document.querySelector('#testme');
    let audio = document.querySelector('audio');
    let isPaused = false; /* flag for auto-pausing of the audio */
    let observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.intersectionRatio!=.5  && !audio.paused){
                audio.pause(); isPaused = true;
            }
            else if(isPaused) {audio.play(); isPaused=false}

        });
    }, {threshold: .5});
    observer.observe(target) ;
}

else document.querySelector('#warning').style.display = 'block';

IntersectionObserver is not supported by your browser, so you can't see the effect. Check its browser support here.
⚠ JAVASCRIPT IS DISABLED IN YOUR BROWSER!

Click video just to trigger the ability to auto play audio on site, then as you scroll through the page, the respective audio should pause/play depending if it's in the view

<video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls="" height="200px"></video>

<audio controls loop src="https://truefa-znfmrrlhm9.live-website.com/wp-content/uploads/2022/12/random_music.mp3" height="10"></audio>

<audio id="testme" controls loop src="https://truefa-znfmrrlhm9.live-website.com/wp-content/uploads/2022/12/random_muisc2.mp3"></audio>

I'm trying to play different audio depending where the user is on the page by leveraging intersection observer

However, the respective audio is not pausing and playing when the various divs are in view. Not sure what I'm missing here for the code to function accordingly...

if(!!window.IntersectionObserver){
  let target = document.querySelector('#testme');
    let audio = document.querySelector('audio');
    let isPaused = false; /* flag for auto-pausing of the audio */
    let observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.intersectionRatio!=.5  && !audio.paused){
                audio.pause(); isPaused = true;
            }
            else if(isPaused) {audio.play(); isPaused=false}

        });
    }, {threshold: .5});
    observer.observe(target) ;
}

else document.querySelector('#warning').style.display = 'block';

https://codepen.io/truefa/pen/PoBWZLV


问:
groupby produces a different mean when done at two levels
I have a dataset (df) about the Time spent by different users (UserId). Users can belong to different Groups (1, 2, 3).

```<code>  UserId  Time  Group
0 181915  52    3
1 128004  52    2
2 178974  40    1
3 182887  30    1
4 238434  50    2
</code>```

I am trying to compute the average Time spent by each user Group. I know that this is a easy task.

```<code>df.groupby('Group')['Time'].mean()
</code>```

The code above works just fine. However, I have the following alternative  where I group the data by both 'Group' and 'UserId' and then compute the mean per user within each group, and then take the mean of the computed means for the whole group. Below is an example for Group 1:

```<code>df.groupby(['Group', 'UserId')['Time'].mean().loc[1].mean()
</code>```

However, this produces a different result. I do not understand why it works this way. At the end, I take average of everything. I do not which result should I trust. I appreciate any help.

Body:
I have a dataset (df) about the Time spent by different users (UserId). Users can belong to different Groups (1, 2, 3).

  UserId  Time  Group
0 181915  52    3
1 128004  52    2
2 178974  40    1
3 182887  30    1
4 238434  50    2

I am trying to compute the average Time spent by each user Group. I know that this is a easy task.

df.groupby('Group')['Time'].mean()

The code above works just fine. However, I have the following alternative  where I group the data by both 'Group' and 'UserId' and then compute the mean per user within each group, and then take the mean of the computed means for the whole group. Below is an example for Group 1:

df.groupby(['Group', 'UserId')['Time'].mean().loc[1].mean()

However, this produces a different result. I do not understand why it works this way. At the end, I take average of everything. I do not which result should I trust. I appreciate any help.


问:
Keep getting the 404 Not Found error on Postman when using the Reddit API what seems to me a perfectly legit request
I am trying to simply return an username i specify in the request to test if an user exists.

To replicate the issue:

URL:
https://oauth.reddit.com/api/v1/user/*usernamehere*/about

Type of request: POST

Headers:
User-Agent: My app
Authorization: Bearer MyTokenHere
Content-Type: application/x-www-form-urlencoded

I'm not sure what I'm doing wrong. I am 100% positive the token I am using is valid.

If I change the request to GET I get the Bad Request error.

Anyone can help?

I was expecting some successful payload about an user and not an error


问:
Cannot retrieve event I display in my browser console
I just want to access to an event I display in my browser console that looks like this :

I tried :

```<code>$('#gridDossiers').on('check.bs.table', function (row , $element) {
            console.log("row", row)
            console.log("Data from row :", row.currentTarget.jQuery2240240399670067494632.bootstrap.table)
        })
</code>```

But I get an error : Uncaught TypeError: Cannot read properties of undefined (reading 'bootstrap')
I think because of the "." between bootstrap and table!

Is there a way to retrieve this event?

Body:
I just want to access to an event I display in my browser console that looks like this :

I tried :

$('#gridDossiers').on('check.bs.table', function (row , $element) {
            console.log("row", row)
            console.log("Data from row :", row.currentTarget.jQuery2240240399670067494632.bootstrap.table)
        })

But I get an error : Uncaught TypeError: Cannot read properties of undefined (reading 'bootstrap')
I think because of the "." between bootstrap and table!

Is there a way to retrieve this event?


问:
Optional values when ranging causes "xxpected map[string]interface {}; got interface {}" error in helm template
I have a template.yaml file that looks like the below.

```<code>{{- $root := . }}
{{- range $service, $val := .Values.services }}
---
apiVersion: apps/v1
kind: Deployment
  {{- if and (hasKey (.probes) "readiness") (hasKey (.probes).readiness "enabled") ((.probes).readiness.enabled) }}
readinessProbe:
  {{- if .probes.readiness.custom }}
  {{- toYaml .probes.readiness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey .probes.readiness "port") }}
    port: {{ required "probes.readiness.port is required" .probes.readiness.port }}
    {{- end }}
    {{- if (hasKey .probes.readiness "endpoint") }}
    path: "{{ required "probes.readiness.endpoint is required" .probes.readiness.endpoint }}"
    {{- end }}
    {{- if (hasKey .probes.readiness "scheme") }}
    scheme: {{ .probes.readiness.scheme }}
    {{- end }}
    {{- if (hasKey .probes.readiness "initialDelaySeconds") }}
  initialDelaySeconds: {{ .probes.readiness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "periodSeconds") }}
  periodSeconds: {{ .probes.readiness.periodSeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "timeoutSeconds") }}
  timeoutSeconds: {{ .probes.readiness.timeoutSeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "successThreshold") }}
  successThreshold: {{ .probes.readiness.successThreshold }}
    {{- end }}
    {{- if (hasKey .probes.readiness "failureThreshold") }}
  failureThreshold: {{ .probes.readiness.failureThreshold }}
    {{- end }}
    {{- end }}

{{- else if $root.Values.global.probes.readiness.enabled }}
readinessProbe:
  {{- if $root.Values.global.probes.readiness.custom }}
  {{- toYaml $root.Values.global.probes.readiness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey $root.Values.global.probes.readiness "port") }}
    port: {{ required "probes.readiness.port is required" $root.Values.global.probes.readiness.port }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "endpoint") }}
    path: "{{ required "probes.readiness.endpoint is required" $root.Values.global.probes.readiness.endpoint }}"
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "scheme") }}
    scheme: {{ $root.Values.global.probes.readiness.scheme }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "initialDelaySeconds") }}
  initialDelaySeconds: {{ $root.Values.global.probes.readiness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "periodSeconds") }}
  periodSeconds: {{ $root.Values.global.probes.readiness.periodSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "timeoutSeconds") }}
  timeoutSeconds: {{ $root.Values.global.probes.readiness.timeoutSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "successThreshold") }}
  successThreshold: {{ $root.Values.global.probes.readiness.successThreshold }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "failureThreshold") }}
  failureThreshold: {{ $root.Values.global.probes.readiness.failureThreshold }}
    {{- end }}
    {{- end }}
    {{- end }}
    {{- if and (hasKey (.probes) "liveness") (hasKey (.probes).liveness "enabled") ((.probes).liveness.enabled) }}
  livenessProbe:
    {{- if .probes.liveness.custom }}
    {{- toYaml .probes.liveness.custom | nindent 12 }}
    {{- else }}
  httpGet:
    {{- if (hasKey .probes.liveness "port") }}
    port: {{ required "probes.liveness.port is required" .probes.liveness.port }}
    {{- end }}
    {{- if (hasKey .probes.liveness "endpoint") }}
    path: "{{ required "probes.liveness.endpoint is required" .probes.liveness.endpoint }}"
    {{- end }}
    {{- if (hasKey .probes.liveness "scheme") }}
    scheme: {{ .probes.liveness.scheme }}
    {{- end }}
    {{- if (hasKey .probes.liveness "initialDelaySeconds") }}
  initialDelaySeconds: {{ .probes.liveness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey .probes.liveness "periodSeconds") }}
  periodSeconds: {{ .probes.liveness.periodSeconds }}
    {{- end }}
    {{- if (hasKey .probes.liveness "timeoutSeconds") }}
  timeoutSeconds: {{ .probes.liveness.timeoutSeconds }}
    {{- end }}
  successThreshold: 1
    {{- if (hasKey .probes.liveness "failureThreshold") }}
  failureThreshold: {{ .probes.liveness.failureThreshold }}
    {{- end }}
    {{- end }}
{{- else if $root.Values.global.probes.liveness.enabled }}
livenessProbe:
  {{- if $root.Values.global.probes.liveness.custom }}
  {{- toYaml $root.Values.global.probes.liveness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey $root.Values.global.probes.liveness "port") }}
    port: {{ required "probes.liveness.port is required" $root.Values.global.probes.liveness.port }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "endpoint") }}
    path: "{{ required "probes.liveness.endpoint is required" $root.Values.global.probes.liveness.endpoint }}"
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "scheme") }}
    scheme: {{ $root.Values.global.probes.liveness.scheme }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "initialDelaySeconds") }}
  initialDelaySeconds: {{ $root.Values.global.probes.liveness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "periodSeconds") }}
  periodSeconds: {{ $root.Values.global.probes.liveness.periodSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "timeoutSeconds") }}
  timeoutSeconds: {{ $root.Values.global.probes.liveness.timeoutSeconds }}
    {{- end }}
  successThreshold: 1
    {{- if (hasKey $root.Values.global.probes.liveness "failureThreshold") }}
  failureThreshold: {{ $root.Values.global.probes.liveness.failureThreshold }}
    {{- end }}
    {{- end }}
    {{- end }}
    {{- end }}
</code>```

I have a values.yaml that looks like this:

```<code>global:
  probes:
    readiness:
      enabled: true
      endpoint: /_readiness
      port: 8001
      scheme: HTTP
      initialDelaySeconds: 10
      periodSeconds: 10
      successThreshold: 3
      failureThreshold: 2
    liveness:
      endpoint: /_liveness
      port: 8080
      enabled: true

services:
  kupkake-inator1:
    command:
      - "apps/run.py"
  kupkake-inator2:
    command:
      - "apps/run.py"
    probes:
      readiness:
        enabled: true
        endpoint: /_readiness
        port: 8001
        scheme: HTTP
        initialDelaySeconds: 10
        periodSeconds: 10
        successThreshold: 3
        failureThreshold: 2
  kupkake-inator3:
    command:
      - "apps/run.py"
  kupkake-inator4:
    command:
      - "apps/run.py"
  kupkake-inator5:
    command:
      - "apps/run.py"

</code>```

I get this error with helm template:

Error: template: deployment.yaml:70:54: executing "templates/deployment.yaml" at <.probes>: wrong type for value; expected map[string]interface {}; got interface {}

presumably because kupkake-inator2 has probes set, but only one of liveness or readiness, and not both.

how do i change my template yaml to do the following?

a. check to ensure that if a service does have .probes set, it has both a liveness AND a readiness one set.

or

b. if it has one, but not the other, take the missing one from the global section of the values file (.global.probes.liveness or .global.probes.readiness)

Please note, i am well aware the yaml is not valid kube yaml, i have removed most fields for conciseness.

Body:
I have a template.yaml file that looks like the below.

{{- $root := . }}
{{- range $service, $val := .Values.services }}
---
apiVersion: apps/v1
kind: Deployment
  {{- if and (hasKey (.probes) "readiness") (hasKey (.probes).readiness "enabled") ((.probes).readiness.enabled) }}
readinessProbe:
  {{- if .probes.readiness.custom }}
  {{- toYaml .probes.readiness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey .probes.readiness "port") }}
    port: {{ required "probes.readiness.port is required" .probes.readiness.port }}
    {{- end }}
    {{- if (hasKey .probes.readiness "endpoint") }}
    path: "{{ required "probes.readiness.endpoint is required" .probes.readiness.endpoint }}"
    {{- end }}
    {{- if (hasKey .probes.readiness "scheme") }}
    scheme: {{ .probes.readiness.scheme }}
    {{- end }}
    {{- if (hasKey .probes.readiness "initialDelaySeconds") }}
  initialDelaySeconds: {{ .probes.readiness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "periodSeconds") }}
  periodSeconds: {{ .probes.readiness.periodSeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "timeoutSeconds") }}
  timeoutSeconds: {{ .probes.readiness.timeoutSeconds }}
    {{- end }}
    {{- if (hasKey .probes.readiness "successThreshold") }}
  successThreshold: {{ .probes.readiness.successThreshold }}
    {{- end }}
    {{- if (hasKey .probes.readiness "failureThreshold") }}
  failureThreshold: {{ .probes.readiness.failureThreshold }}
    {{- end }}
    {{- end }}

{{- else if $root.Values.global.probes.readiness.enabled }}
readinessProbe:
  {{- if $root.Values.global.probes.readiness.custom }}
  {{- toYaml $root.Values.global.probes.readiness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey $root.Values.global.probes.readiness "port") }}
    port: {{ required "probes.readiness.port is required" $root.Values.global.probes.readiness.port }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "endpoint") }}
    path: "{{ required "probes.readiness.endpoint is required" $root.Values.global.probes.readiness.endpoint }}"
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "scheme") }}
    scheme: {{ $root.Values.global.probes.readiness.scheme }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "initialDelaySeconds") }}
  initialDelaySeconds: {{ $root.Values.global.probes.readiness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "periodSeconds") }}
  periodSeconds: {{ $root.Values.global.probes.readiness.periodSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "timeoutSeconds") }}
  timeoutSeconds: {{ $root.Values.global.probes.readiness.timeoutSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "successThreshold") }}
  successThreshold: {{ $root.Values.global.probes.readiness.successThreshold }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.readiness "failureThreshold") }}
  failureThreshold: {{ $root.Values.global.probes.readiness.failureThreshold }}
    {{- end }}
    {{- end }}
    {{- end }}
    {{- if and (hasKey (.probes) "liveness") (hasKey (.probes).liveness "enabled") ((.probes).liveness.enabled) }}
  livenessProbe:
    {{- if .probes.liveness.custom }}
    {{- toYaml .probes.liveness.custom | nindent 12 }}
    {{- else }}
  httpGet:
    {{- if (hasKey .probes.liveness "port") }}
    port: {{ required "probes.liveness.port is required" .probes.liveness.port }}
    {{- end }}
    {{- if (hasKey .probes.liveness "endpoint") }}
    path: "{{ required "probes.liveness.endpoint is required" .probes.liveness.endpoint }}"
    {{- end }}
    {{- if (hasKey .probes.liveness "scheme") }}
    scheme: {{ .probes.liveness.scheme }}
    {{- end }}
    {{- if (hasKey .probes.liveness "initialDelaySeconds") }}
  initialDelaySeconds: {{ .probes.liveness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey .probes.liveness "periodSeconds") }}
  periodSeconds: {{ .probes.liveness.periodSeconds }}
    {{- end }}
    {{- if (hasKey .probes.liveness "timeoutSeconds") }}
  timeoutSeconds: {{ .probes.liveness.timeoutSeconds }}
    {{- end }}
  successThreshold: 1
    {{- if (hasKey .probes.liveness "failureThreshold") }}
  failureThreshold: {{ .probes.liveness.failureThreshold }}
    {{- end }}
    {{- end }}
{{- else if $root.Values.global.probes.liveness.enabled }}
livenessProbe:
  {{- if $root.Values.global.probes.liveness.custom }}
  {{- toYaml $root.Values.global.probes.liveness.custom | nindent 12 }}
  {{- else }}
  httpGet:
    {{- if (hasKey $root.Values.global.probes.liveness "port") }}
    port: {{ required "probes.liveness.port is required" $root.Values.global.probes.liveness.port }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "endpoint") }}
    path: "{{ required "probes.liveness.endpoint is required" $root.Values.global.probes.liveness.endpoint }}"
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "scheme") }}
    scheme: {{ $root.Values.global.probes.liveness.scheme }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "initialDelaySeconds") }}
  initialDelaySeconds: {{ $root.Values.global.probes.liveness.initialDelaySeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "periodSeconds") }}
  periodSeconds: {{ $root.Values.global.probes.liveness.periodSeconds }}
    {{- end }}
    {{- if (hasKey $root.Values.global.probes.liveness "timeoutSeconds") }}
  timeoutSeconds: {{ $root.Values.global.probes.liveness.timeoutSeconds }}
    {{- end }}
  successThreshold: 1
    {{- if (hasKey $root.Values.global.probes.liveness "failureThreshold") }}
  failureThreshold: {{ $root.Values.global.probes.liveness.failureThreshold }}
    {{- end }}
    {{- end }}
    {{- end }}
    {{- end }}

I have a values.yaml that looks like this:

global:
  probes:
    readiness:
      enabled: true
      endpoint: /_readiness
      port: 8001
      scheme: HTTP
      initialDelaySeconds: 10
      periodSeconds: 10
      successThreshold: 3
      failureThreshold: 2
    liveness:
      endpoint: /_liveness
      port: 8080
      enabled: true

services:
  kupkake-inator1:
    command:
      - "apps/run.py"
  kupkake-inator2:
    command:
      - "apps/run.py"
    probes:
      readiness:
        enabled: true
        endpoint: /_readiness
        port: 8001
        scheme: HTTP
        initialDelaySeconds: 10
        periodSeconds: 10
        successThreshold: 3
        failureThreshold: 2
  kupkake-inator3:
    command:
      - "apps/run.py"
  kupkake-inator4:
    command:
      - "apps/run.py"
  kupkake-inator5:
    command:
      - "apps/run.py"

I get this error with helm template:

Error: template: deployment.yaml:70:54: executing "templates/deployment.yaml" at <.probes>: wrong type for value; expected map[string]interface {}; got interface {}

presumably because kupkake-inator2 has probes set, but only one of liveness or readiness, and not both.

how do i change my template yaml to do the following?

a. check to ensure that if a service does have .probes set, it has both a liveness AND a readiness one set.

or

b. if it has one, but not the other, take the missing one from the global section of the values file (.global.probes.liveness or .global.probes.readiness)

Please note, i am well aware the yaml is not valid kube yaml, i have removed most fields for conciseness.


问:
convert varchar value to array to varchar sql oracle
i have table named departments has column  named tax_code nvarchar2 datatype saved value 01,33,E1

when i want to use this value in this code

```<code>select id,name from employee
where taxcode in( select tax_code from department)
</code>```

give me the value

```<code>where taxcode in('01,33,E1') this wrong
</code>```

i want this

```<code>where taxcode in('01','33','E1')
</code>```

regards

above in details i explain

Body:
i have table named departments has column  named tax_code nvarchar2 datatype saved value 01,33,E1

when i want to use this value in this code

select id,name from employee
where taxcode in( select tax_code from department)

give me the value

where taxcode in('01,33,E1') this wrong

i want this

where taxcode in('01','33','E1')

regards

above in details i explain


问:
How to get number of active Instances (Nodes) in Mongodb Atlas over time?
I need to get number of active nodes over time in MongodbAtlas. There is no such chart in Metrics.

I tried to search in google and chatgpt, but unfortunately, it did not help.


问:
How to define the boundary conditions of a rectangle being used in a quadtree to hold points in R^2
I am trying to implement a quadtree to store points in R2. My project requires a square centered at (0,0) with side lengths l, so the quadtree must be able to store all points in the closed rectangle [ -l , l ] x [ -l , l ].

I have read the implementations of a few quadtrees used for similar purposes and I am having trouble understanding how to implement the quadtree so that all points that lie on the boundary of the square are can be stored (points inside the boundaries i have no trouble with).

As I understand there should be only one implementation for a node, so the NE, NW, SW, and SE nodes are all instantiations of the same class. So that there is no ambiguity to which quadrant a point properly belongs half open intervals must be used. So a quadrant with boundaries [ -w , w ) x ( -h , h ] gets subdivided into [ 0 , w ) x ( 0 , h ] , [ -w , 0 ) x ( 0 , h ] , [ -w , 0 ) x ( -h , 0 ] , [ 0 , w ) x ( -h , 0 ] . This makes perfect mathematical sense, the original set (quadrant) has been subdivided into four disjoint sets (quadrants) and there is no ambiguity as to which subset (quadrant) a point properly belongs. Now every node and subnode contain their north and west boundaries but do not include their south and east boundaries as they are contained in a neighboring node.

If however quadrants are subdivided using closed intervals instead of half open intervals it becomes ambiguous to which quadrant points that lie on the boundaries between them properly belong.

So i can implement a quadtree to store all points in [ -l , l ) x ( -l , l ] with no problem. This however means I cannot store points that lie on the south and east boundaries as they are not included when using half open intervals.

Am I failing to understand how to subdivide a quadrant into four subquadrants? Is there a way that I can include points that lie on the south and east boundaries of my initial square?

I am using C# right now but I am open to moving to C++ if anyone can point me to an implementation I can read that solves my problem.

Thanks

EDIT: I am editing this to give a more concrete example of my problem in response to Matt Timmermans comment. I really am trying not be repeat myself and beat a dead horse.

Assume I have a class Rectangle that is used in the class QuadtreeNode that has a method Bool Contatins(double x, double y)  (x and y are normal Cartesian coordinates) to determine if ( x , y ) is contained in the rectangle. In order for this to work I am forced to decide which quadrant a point that lies on a boundary must belong, I have decided that a rectangle will include all interior points and include its North and West boundaries, leaving the South and East boundaries to be included in the appropriate neighboring quadrants. So Contains(double x, double y) looks like

```<code>Bool Contains(double x, double y) {
    if( (X_min <= x < X_max) && (Y_min <= y < Y_max) ) {
        return true;
    }
    return false;
}
</code>```

The above check works perfectly for bounds checking any Rectangle created when a quadrant also defined with half open intervals is subdivided into four subquadrants each containing a instance of Rectangle with appropriately calculated X_min, X_max, Y_min, and Y_max. My Problem however is that by making the binary choice as to which quadrant a point that lies on a boundary belongs means that any node with a Rectangle that shares a South or East boundary with my initial Rectangle defined by [ -l , l ] x [ -l , l ] do not include their South or East borders, thus the initial Rectangle cannot include its South or East borders as that Rectangle is the union of the subrecctangles defined with half open intervals.

The rectangle [ -l , l ] x [ -l , l ] is a closed and bounded (compact) set, when subdividing into subquadrants (subsets) as above, the subrectangles are defined by half open intervals and thus not compact. The desire for every rectangle be an instantiation of the same Rectangle class where NE, NW, SE, and SW are not individually subclassed (I don't even fully see if could resolve this) requires this. So essentially I am attempting to use a finite subcover to cover a compact set that by the way the subset boundaries are defined cannot actually be a finite subcover.

Am I being overly concerned with the my mathematical desire for the subquadrants to be disjoint sets? What if all Rectangles contained their boundaries and a point lying on a boundary is simply added to the first subquadrant that can contain it. I can do this by changing the above Contains(double x, double y) to

```<code>Bool Contains(double x, double y) {
    if( (X_min <= x <= X_max) && (Y_min <= y <= Y_max) ) {
        return true;
    }
    return false;
}
</code>```

Apologies in advance if I'm repeated myself needlessly, I am just trying to be a concrete as possible. I suspect my desire for tidy set-theory notions is causing a mental block here and causing me to grossly overthink this.

Thanks

Body:
I am trying to implement a quadtree to store points in R2. My project requires a square centered at (0,0) with side lengths l, so the quadtree must be able to store all points in the closed rectangle [ -l , l ] x [ -l , l ].

I have read the implementations of a few quadtrees used for similar purposes and I am having trouble understanding how to implement the quadtree so that all points that lie on the boundary of the square are can be stored (points inside the boundaries i have no trouble with).

As I understand there should be only one implementation for a node, so the NE, NW, SW, and SE nodes are all instantiations of the same class. So that there is no ambiguity to which quadrant a point properly belongs half open intervals must be used. So a quadrant with boundaries [ -w , w ) x ( -h , h ] gets subdivided into [ 0 , w ) x ( 0 , h ] , [ -w , 0 ) x ( 0 , h ] , [ -w , 0 ) x ( -h , 0 ] , [ 0 , w ) x ( -h , 0 ] . This makes perfect mathematical sense, the original set (quadrant) has been subdivided into four disjoint sets (quadrants) and there is no ambiguity as to which subset (quadrant) a point properly belongs. Now every node and subnode contain their north and west boundaries but do not include their south and east boundaries as they are contained in a neighboring node.

If however quadrants are subdivided using closed intervals instead of half open intervals it becomes ambiguous to which quadrant points that lie on the boundaries between them properly belong.

So i can implement a quadtree to store all points in [ -l , l ) x ( -l , l ] with no problem. This however means I cannot store points that lie on the south and east boundaries as they are not included when using half open intervals.

Am I failing to understand how to subdivide a quadrant into four subquadrants? Is there a way that I can include points that lie on the south and east boundaries of my initial square?

I am using C# right now but I am open to moving to C++ if anyone can point me to an implementation I can read that solves my problem.

Thanks

EDIT: I am editing this to give a more concrete example of my problem in response to Matt Timmermans comment. I really am trying not be repeat myself and beat a dead horse.

Assume I have a class Rectangle that is used in the class QuadtreeNode that has a method Bool Contatins(double x, double y)  (x and y are normal Cartesian coordinates) to determine if ( x , y ) is contained in the rectangle. In order for this to work I am forced to decide which quadrant a point that lies on a boundary must belong, I have decided that a rectangle will include all interior points and include its North and West boundaries, leaving the South and East boundaries to be included in the appropriate neighboring quadrants. So Contains(double x, double y) looks like

Bool Contains(double x, double y) {
    if( (X_min <= x < X_max) && (Y_min <= y < Y_max) ) {
        return true;
    }
    return false;
}

The above check works perfectly for bounds checking any Rectangle created when a quadrant also defined with half open intervals is subdivided into four subquadrants each containing a instance of Rectangle with appropriately calculated X_min, X_max, Y_min, and Y_max. My Problem however is that by making the binary choice as to which quadrant a point that lies on a boundary belongs means that any node with a Rectangle that shares a South or East boundary with my initial Rectangle defined by [ -l , l ] x [ -l , l ] do not include their South or East borders, thus the initial Rectangle cannot include its South or East borders as that Rectangle is the union of the subrecctangles defined with half open intervals.

The rectangle [ -l , l ] x [ -l , l ] is a closed and bounded (compact) set, when subdividing into subquadrants (subsets) as above, the subrectangles are defined by half open intervals and thus not compact. The desire for every rectangle be an instantiation of the same Rectangle class where NE, NW, SE, and SW are not individually subclassed (I don't even fully see if could resolve this) requires this. So essentially I am attempting to use a finite subcover to cover a compact set that by the way the subset boundaries are defined cannot actually be a finite subcover.

Am I being overly concerned with the my mathematical desire for the subquadrants to be disjoint sets? What if all Rectangles contained their boundaries and a point lying on a boundary is simply added to the first subquadrant that can contain it. I can do this by changing the above Contains(double x, double y) to

Bool Contains(double x, double y) {
    if( (X_min <= x <= X_max) && (Y_min <= y <= Y_max) ) {
        return true;
    }
    return false;
}

Apologies in advance if I'm repeated myself needlessly, I am just trying to be a concrete as possible. I suspect my desire for tidy set-theory notions is causing a mental block here and causing me to grossly overthink this.

Thanks


问:
Apply only one confirmation dialog for all file and image inputs
I have few ImageInput and FileInputs and a confirmation dialog. Is there a way for all ImageInput and FileInputs to use on one confirmation dialog only? Rather have to create many confirmation dialogs to cater them.</p>
```<code>import * as React from "react";
import {
  Create,
  SimpleForm,
  ImageInput,
  ImageField,
  FileInput,
  FileField,
  Confirm,
} from 'react-admin';

export const PostCreate = props => {
  const [removeImage, setRemoveImage] = React.useState(null);
  const [openModal, setOpenModal] = React.useState(false);
  return (
    <Create {...props}>
      <SimpleForm>
        <ImageInput
          source="pictures"
          label="Related pictures"
          validateFileRemoval={(file) => {
            const promise = new Promise((resolve, reject) => {
              setRemoveImage({
                fileName: `Image: ${file.title}`,
                delete: () => {
                  resolve(true);
                },
                cancel: () => reject,
              });
            });
            setOpenModal(true);
            return promise.then((result) => true);
          }}
        >
          <ImageField source="src" title="title" />
        </ImageInput>
        <FileInput source="attachments_pdf" accept=".pdf">
          <FileField source="src" title="title" />
        </FileInput>
        <FileInput source="attachments_csv" accept=".csv">
          <FileField source="src" title="title" />
        </FileInput>

        <Confirm
          isOpen={openModal}
          title="Delete image"
          content={`${removeImage ? removeImage.fileName : ''} will be deleted`}
          onConfirm={() => {
            console.log('onConfirm');
            setOpenModal(false);
            removeImage?.delete();
          }}
          onClose={() => {
            setOpenModal(false);
            removeImage?.cancel();
          }}
        />
      </SimpleForm>
    </Create>
  )
};
</code>```

Body:
I have few ImageInput and FileInputs and a confirmation dialog. Is there a way for all ImageInput and FileInputs to use on one confirmation dialog only? Rather have to create many confirmation dialogs to cater them.

import * as React from "react";
import {
  Create,
  SimpleForm,
  ImageInput,
  ImageField,
  FileInput,
  FileField,
  Confirm,
} from 'react-admin';

export const PostCreate = props => {
  const [removeImage, setRemoveImage] = React.useState(null);
  const [openModal, setOpenModal] = React.useState(false);
  return (
    <Create {...props}>
      <SimpleForm>
        <ImageInput
          source="pictures"
          label="Related pictures"
          validateFileRemoval={(file) => {
            const promise = new Promise((resolve, reject) => {
              setRemoveImage({
                fileName: `Image: ${file.title}`,
                delete: () => {
                  resolve(true);
                },
                cancel: () => reject,
              });
            });
            setOpenModal(true);
            return promise.then((result) => true);
          }}
        >
          <ImageField source="src" title="title" />
        </ImageInput>
        <FileInput source="attachments_pdf" accept=".pdf">
          <FileField source="src" title="title" />
        </FileInput>
        <FileInput source="attachments_csv" accept=".csv">
          <FileField source="src" title="title" />
        </FileInput>

        <Confirm
          isOpen={openModal}
          title="Delete image"
          content={`${removeImage ? removeImage.fileName : ''} will be deleted`}
          onConfirm={() => {
            console.log('onConfirm');
            setOpenModal(false);
            removeImage?.delete();
          }}
          onClose={() => {
            setOpenModal(false);
            removeImage?.cancel();
          }}
        />
      </SimpleForm>
    </Create>
  )
};


问:
How to mock the celery apply_async to instead use .s().apply()
I have a function, which indirectly calls a celery task using apply_async() internally.

```<code>def abc(...):
   send_notification.apply_async(...)
</code>```

where send_notification is a celery task method:

```<code>
@app.task(bind=True)
def send_notification(self, ...):
    ...
</code>```

Now, I'm writing a test case for testing abc(), where I'd want to convert invocation of send_notification.apply_async() to send_notification.s(...).apply().

Is this something thats possible using mock/monkeypatch/patch?

Body:
I have a function, which indirectly calls a celery task using apply_async() internally.

def abc(...):
   send_notification.apply_async(...)

where send_notification is a celery task method:

@app.task(bind=True)
def send_notification(self, ...):
    ...

Now, I'm writing a test case for testing abc(), where I'd want to convert invocation of send_notification.apply_async() to send_notification.s(...).apply().

Is this something thats possible using mock/monkeypatch/patch?


问:
How to remove the folder structure generated when building multiple html entry points using Vite.js?
My current vite.config.js looks sorta of like this:

export default defineConfig({
  plugins: [react()],
  build: {
    assetsDir: './',
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)),
        mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)),
        config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)),
      },
      output: {
        dir: 'dist',
      },
    },
  },
});
```
<p>So my project's current folder structure for organization reasons is:</p>
```src/
 |- components
 |- hooks
 |- pages
   `- Config
     `- index.tsx
   `- Main
     `- index.tsx
   `- Mobile
     `- index.tsx
 |- html/
 | `- config.html
 | `- main.html
 | `- mobile.html
```
<p>My build(dist) folder structure is:</p>
```dist
 |- [...bunch of js files]
 | src/
    |- html/
    | `- config.html
    | `- main.html
    | `- mobile.html
```
<p>My ideal final folder structure goal would be:</p>
```dist
 |- [...bunch of js files]
 |- config.html
 |- main.html
 |- mobile.html
```

I know I can just re-structure the project folder structure by putting the HTML files outside the src folder, in the root folder. But I'm aiming at being organized. I know this is possible using Webpack and I couldn't figure out how to do it on Vite.js with HTML files. Any direction or help would be awesome.

Body:
My current vite.config.js looks sorta of like this:

export default defineConfig({
  plugins: [react()],
  build: {
    assetsDir: './',
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)),
        mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)),
        config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)),
      },
      output: {
        dir: 'dist',
      },
    },
  },
});

So my project's current folder structure for organization reasons is:

src/
 |- components
 |- hooks
 |- pages
   `- Config
     `- index.tsx
   `- Main
     `- index.tsx
   `- Mobile
     `- index.tsx
 |- html/
 | `- config.html
 | `- main.html
 | `- mobile.html

My build(dist) folder structure is:

dist
 |- [...bunch of js files]
 | src/
    |- html/
    | `- config.html
    | `- main.html
    | `- mobile.html

My ideal final folder structure goal would be:

dist
 |- [...bunch of js files]
 |- config.html
 |- main.html
 |- mobile.html

I know I can just re-structure the project folder structure by putting the HTML files outside the src folder, in the root folder. But I'm aiming at being organized. I know this is possible using Webpack and I couldn't figure out how to do it on Vite.js with HTML files. Any direction or help would be awesome.


问:
jupyter notebook vscode doesn't display dataframe right
I used to always have my dataframes displayed correctly in a nice table in jupyter notebook but now everytime I display one, it's like I printed it unformated.

I tried to use display(df_main) but it's still not displaying it correctly.


问:
How can I compare predicted FDIInflow to real FDIInflow of the time series with setting of the forecasts to start at 2005 to the end of the data
I am using these time-series data to forecast FDIInflow with dates starting from 2005 t0 2018

```<code>Date    FDIInflow   ZInvestProm     InvestProm_X_InvestFacil
0   2005    4   -1.87092    -4.61
1   2005    1   -0.89043    -3.86
2   2005    9   0.29874     0.81
3   2005    2   1.29473     5.81
4   2005    10  0.10375     0.01
</code>```

I now grouped the variables as:

```<code>grouped = grouped.set_index('Date')
grouped.index
</code>```

Got this as output:

```<code>Int64Index([2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
            2016, 2017, 2018],
           dtype='int64', name='Date')
</code>```

I now visualized the outcome:

```<code>y.plot(figsize = (15, 6))
plt.show()
</code>```

and got:
enter image description here
Decompose:

```<code>from statsmodels.tsa.seasonal import seasonal_decompose
decompose_result = seasonal_decompose(grouped.FDIInflow, model='additive', period =4)
decompose_result.plot()
</code>```

Obtained optimal combination:

```<code>model = sm.tsa.statespace.SARIMAX(y, order = (1, 1, 1),
                                  seasonal_order = (1, 0, 1, 12)
                                 )
result = model.fit()
print(result.summary().tables[1])
</code>```

Moving to forecasting, after fitting the ARIMA model using above optimal combination of p, d, q. And succesfully ran the model diagnostic to investigate any unusual behavior, I attemped to compare predicted FDI to real FDI of the time series by setting the forecasts to start at 2005 to the end of the data.I ended up with error with this code:

```<code>prediction = result.get_prediction(start = pd.to_datetime('2005'), dynamic = False)
prediction_ci = prediction.conf_int()
prediction_ci
</code>```

enter image description here

Body:
I am using these time-series data to forecast FDIInflow with dates starting from 2005 t0 2018

Date    FDIInflow   ZInvestProm     InvestProm_X_InvestFacil
0   2005    4   -1.87092    -4.61
1   2005    1   -0.89043    -3.86
2   2005    9   0.29874     0.81
3   2005    2   1.29473     5.81
4   2005    10  0.10375     0.01

I now grouped the variables as:

grouped = grouped.set_index('Date')
grouped.index

Got this as output:

Int64Index([2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
            2016, 2017, 2018],
           dtype='int64', name='Date')

I now visualized the outcome:

y.plot(figsize = (15, 6))
plt.show()

and got:
enter image description here
Decompose:

from statsmodels.tsa.seasonal import seasonal_decompose
decompose_result = seasonal_decompose(grouped.FDIInflow, model='additive', period =4)
decompose_result.plot()

Obtained optimal combination:

model = sm.tsa.statespace.SARIMAX(y, order = (1, 1, 1),
                                  seasonal_order = (1, 0, 1, 12)
                                 )
result = model.fit()
print(result.summary().tables[1])

Moving to forecasting, after fitting the ARIMA model using above optimal combination of p, d, q. And succesfully ran the model diagnostic to investigate any unusual behavior, I attemped to compare predicted FDI to real FDI of the time series by setting the forecasts to start at 2005 to the end of the data.I ended up with error with this code:

prediction = result.get_prediction(start = pd.to_datetime('2005'), dynamic = False)
prediction_ci = prediction.conf_int()
prediction_ci

enter image description here


问:
Using playwright locators in electron app
I have some playwright code that I use to automate chrome.  Is there a way to use page.locator within an electron app so I can use the same playwright code to drive the electron webview?

https://github.com/microsoft/playwright/blob/e55a2bdf16c1ded0465e6a0aaf98e383ce2bd0c0/docs/src/other-locators.md

How would I integrate this lib so that I can use these matchers rather than rolling my own using cheerio or something similar?


问:
How to use async function without Hooks in React Native
I am currently developing an React Native app that involves realtime chatting feature.

The goal is to have a socket.js that will export default a socket.

(Initializing socket this way is the best in my opinion as it can ensure that io('xxx') only run once)

I want the socket to be created with a userToken that I stored in my EncryptedStorage and this means involving async await function.

(Creating socket like this because I will need the userToken to match the socket.id and put them both into a JSON in my server side)

socket.js

```<code>import { io } from "socket.io-client";
import BASE_URL from "../screens/BASE_URL";
import EncryptedStorage from 'react-native-encrypted-storage'

async function get_token() {
  return await EncryptedStorage.getItem('userToken')
}

export default socket = io(`${BASE_URL}`, {
  transports: ['websocket'],
  extraHeaders: {
    Authorization: `Bearer ${await get_token()}`
  }
})
</code>```

Using this code made the Authorization header in my server side shows Bearer [object Object] instead of the real user token

(I am confident that the server side code is working fine because before I added the userToken in, it was able to receive the connection)

What I have tried

I tried turning the socket into a function, something like this:

```<code>export default async function socket(){
  return io(`${BASE_URL}`, {
    transports: ['websocket'],
    extraHeaders: {
      Authorization: `Bearer ${await get_token()}`
    }
  })
}
</code>```

But now the socket won't even get connected to my socket.io server.

I also tried something like

```<code>export default socket = io(`${BASE_URL}`, {
  transports: ['websocket'],
  extraHeaders: {
    Authorization: `Bearer `
  }
});

get_token().then(token => {
  socket.extraHeaders.Authorization += token;
});
</code>```

But it just skips the get_token() function and proceed to export my socket

Will appreciate any help and/or suggestion provided. Thank you!

Body:
I am currently developing an React Native app that involves realtime chatting feature.

The goal is to have a socket.js that will export default a socket.

(Initializing socket this way is the best in my opinion as it can ensure that io('xxx') only run once)

I want the socket to be created with a userToken that I stored in my EncryptedStorage and this means involving async await function.

(Creating socket like this because I will need the userToken to match the socket.id and put them both into a JSON in my server side)

socket.js

import { io } from "socket.io-client";
import BASE_URL from "../screens/BASE_URL";
import EncryptedStorage from 'react-native-encrypted-storage'

async function get_token() {
  return await EncryptedStorage.getItem('userToken')
}

export default socket = io(`${BASE_URL}`, {
  transports: ['websocket'],
  extraHeaders: {
    Authorization: `Bearer ${await get_token()}`
  }
})

Using this code made the Authorization header in my server side shows Bearer [object Object] instead of the real user token

(I am confident that the server side code is working fine because before I added the userToken in, it was able to receive the connection)

What I have tried

I tried turning the socket into a function, something like this:

export default async function socket(){
  return io(`${BASE_URL}`, {
    transports: ['websocket'],
    extraHeaders: {
      Authorization: `Bearer ${await get_token()}`
    }
  })
}

But now the socket won't even get connected to my socket.io server.

I also tried something like

export default socket = io(`${BASE_URL}`, {
  transports: ['websocket'],
  extraHeaders: {
    Authorization: `Bearer `
  }
});

get_token().then(token => {
  socket.extraHeaders.Authorization += token;
});

But it just skips the get_token() function and proceed to export my socket

Will appreciate any help and/or suggestion provided. Thank you!