Title: postgreSQL question: get data by last date of each record and subtract from last date number of days

Body:
Please help me make a request. i'm at a dead end.
There are 2 tables:

“Trains”:

+----+---------+
| id | numbers |
+----+---------+
|  1 |     101 |
|  2 |     102 |
|  3 |     103 |
|  4 |     104 |
|  5 |     105 |
+----+---------+

“Passages”:

+----+--------------+-------+---------------------+
| id | train_number | speed |      date_time      |
+----+--------------+-------+---------------------+
|  1 |          101 |    26 | 2021-11-10 16:26:30 |
|  2 |          101 |    28 | 2021-11-12 16:26:30 |
|  3 |          102 |    24 | 2021-11-14 16:26:30 |
|  4 |          103 |    27 | 2021-11-15 16:26:30 |
|  5 |          101 |    29 | 2021-11-16 16:26:30 |
+----+--------------+-------+---------------------+

The goal is to go through the train numbers from the Trains table, take from the existing ones from the Passages table by the latest date (date_time) and the number of passages for “the last date for each train” - N days. as I understand date_time - interval "N days". should get something like:

+----+--------+---------------------+----------------+
| id | train  |    last_passage     | count_passages |
+----+--------+---------------------+----------------+
|  1 |    101 | 2021-11-10 16:26:30 |              2 |
|  2 |    102 | 2021-11-14 16:26:30 |              1 |
|  3 |    103 | 2021-11-15 16:26:30 |              1 |
|  4 |    104 | null                |              0 |
|  5 |    105 | null                |              0 |
+----+--------+---------------------+----------------+

ps: "count_passages" - for example, last passage date minus 4 days

I tried through "where in" but I can’t create the necessary and correct request


来源: stackexchange

问:
Nuxtjs 3 typed useAsyncData
i'm using nuxt3 useAsyncData to fetch data from an api and it's working ok
but i'm unable to type the returned data

```<code><template>
  <div>
    {{ data }}
    <CommonTopHeader/>
    <NuxtPage/>
  </div>
</template>
<script setup lang="ts">
const {$httpInstance} = useNuxtApp()
const data = await useAsyncData('categories', () => $httpInstance.get('v1/categories/list'))
</script>
</code>```

it's working ok but the ide is unable to auto-complete the {{data}}

$httpInstance is a plugin:

```<code>import axios, {
    AxiosError,
    AxiosInstance,
    AxiosRequestConfig,
    AxiosResponse,
} from 'axios';
import {useRuntimeConfig} from "#app";

export default defineNuxtPlugin((nuxtApp) => {
    const config = useRuntimeConfig()
    const onRequest = (config: AxiosRequestConfig): AxiosRequestConfig => {
        return config;
    };

    const onRequestError = (error: AxiosError): Promise<AxiosError> => {
        return Promise.resolve(error);
    };

    const onResponse = (response: AxiosResponse): AxiosResponse => {
        return response.data;
    };

    const onResponseError = (error: AxiosError): Promise<unknown> => {
        return Promise.resolve(error.response?.data);
    };

    function setupInterceptorsTo(axiosInstance: AxiosInstance): AxiosInstance {
        axiosInstance.interceptors.request.use(onRequest, onRequestError);
        axiosInstance.interceptors.response.use(onResponse, onResponseError);
        return axiosInstance;
    }

    const instance = setupInterceptorsTo(
        axios.create({
            baseURL: config.public.apiBase,
        }),
    );
    return {
        provide: {
            httpInstance: instance,
        },
    };
});

</code>```

so how can i add a type to data object ?

the ide to auto-complete when i write ``data.```

ContentLicense: CC BY-SA 4.0

Title: Nuxtjs 3 typed useAsyncData

Body:
i'm using nuxt3 useAsyncData to fetch data from an api and it's working ok
but i'm unable to type the returned data

<template>

    {{ data }}
    <CommonTopHeader/>
    <NuxtPage/>

</template>

it's working ok but the ide is unable to auto-complete the {{data}}

$httpInstance is a plugin:

import axios, {
    AxiosError,
    AxiosInstance,
    AxiosRequestConfig,
    AxiosResponse,
} from 'axios';
import {useRuntimeConfig} from "#app";

export default defineNuxtPlugin((nuxtApp) => {
    const config = useRuntimeConfig()
    const onRequest = (config: AxiosRequestConfig): AxiosRequestConfig => {
        return config;
    };

    const onRequestError = (error: AxiosError): Promise<AxiosError> => {
        return Promise.resolve(error);
    };

    const onResponse = (response: AxiosResponse): AxiosResponse => {
        return response.data;
    };

    const onResponseError = (error: AxiosError): Promise<unknown> => {
        return Promise.resolve(error.response?.data);
    };

    function setupInterceptorsTo(axiosInstance: AxiosInstance): AxiosInstance {
        axiosInstance.interceptors.request.use(onRequest, onRequestError);
        axiosInstance.interceptors.response.use(onResponse, onResponseError);
        return axiosInstance;
    }

    const instance = setupInterceptorsTo(
        axios.create({
            baseURL: config.public.apiBase,
        }),
    );
    return {
        provide: {
            httpInstance: instance,
        },
    };
});

so how can i add a type to data object ?

the ide to auto-complete when i write ``data.```


问:
Why does Firebase Realtime Database say I have more connections than I actually do?
I am utilizing Firebase's realtime database to host a chatroom type thing. Ever since I started, the analytics have only shown the maximum number of connections I have had. Here is an example of what the analytics look like:

Even when I click on the information "?" next to connections it says, "The number of simultaneous realtime connections to your database". You can even see in the graph that the number has gone down but the number on the left stays at 100/100.

Does anyone know why this is or how I can see the actual number of realtime connections?


问:
Return child of page in wordpress search
I'm making a search (wordpress) that should return only the child of a page. It is currently returning all pages. I need it to return only the children of a page in the results.

The parent page is 'products' so the url is like this:

www.helpme.com/products/child-page-1

www.helpme.com/products/child-page-2

My code:

```<code>
  if(have_posts()){

        while(have_posts()){
            the_post();
            if ( $post->post_parent == 'products' ){
               something
            }
        }
    }

  ?>

can you help me, please ?
</code>```

Body:
I'm making a search (wordpress) that should return only the child of a page. It is currently returning all pages. I need it to return only the children of a page in the results.

The parent page is 'products' so the url is like this:

www.helpme.com/products/child-page-1

www.helpme.com/products/child-page-2

My code:

  if(have_posts()){

        while(have_posts()){
            the_post();
            if ( $post->post_parent == 'products' ){
               something
            }
        }
    }

  ?>

can you help me, please ?


问:
DirectX screen capture on Windows 10/11
I'm trying to create a screen taking app that can get a raw bitmap of a desktop window from the GPU. I did it via GDI and it works properly, but using both DirectX and DXGI Duplication api, I have black screen or an error.

```<code>void dump_buffer() {
IDirect3D9* d3d = nullptr;
d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;
out("1");
ZeroMemory(&d3dpp, sizeof(d3dpp));//COCK?
D3DDISPLAYMODE  d3ddm;
if(FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
    err("IDirect3D9");
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = FALSE;
IDirect3DDevice9* d3ddev = nullptr;
out("2");
d3d->CreateDevice(
        D3DADAPTER_DEFAULT, // Используем видеокарту, установленную в Windows по умолчанию (= в качестве основной).
        D3DDEVTYPE_HAL, // Используем аппаратный рендеринг (Hardware Abstraction Layer).
        GetDesktopWindow(), // Дескриптор) окна
        D3DCREATE_SOFTWARE_VERTEXPROCESSING, // Не использовать "фишки" T&L для лучшей совместимости с бОльшим числом видеоадаптеров.
        &d3dpp, // Указатель на заранее заполненную структуру параметров отображения (D3DPRESENT_PARAMETERS).
        &d3ddev // Указатель на создаваемый объект устройства Direct3D.
);
if (d3ddev == nullptr)
    err("IDirect3DDevice9");
out("3");
IDirect3DSurface9 *pRenderTarget = nullptr;
IDirect3DSurface9 *pDestTarget = nullptr;
// sanity checks.

// get the render target surface.
HRESULT hr = d3ddev->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)){
    err("GetRenderTarget");
}
// get the current adapter display mode.
// hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);
out("4");
D3DDISPLAYMODE mode;
hr = d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode);
if (FAILED(hr)){
    err("GetAdapterDisplayMode");
}
// create a destination surface.
out(mode.Width);
out(mode.Height);
out(mode.Format);
hr = d3ddev->CreateOffscreenPlainSurface(mode.Width,
                                         mode.Height,
                                         mode.Format,
                                         D3DPOOL_SYSTEMMEM,
                                         &pDestTarget,
                                         nullptr);
if (FAILED(hr)){
    err(("CreateOffscreenPlainSurface"));
}
out("5");
//copy the render target to the destination surface.
hr = d3ddev->GetRenderTargetData(pRenderTarget, pDestTarget);
if (FAILED(hr)){
    err(DXGetErrorDescription9A(hr));
    err(("GetRenderTargetData"));
}
//save its contents to a bitmap file.
out("6");
hr = D3DXSaveSurfaceToFile(file,
                           D3DXIFF_BMP,
                           pDestTarget,
                           nullptr,
                           nullptr);
out("7");
// clean up.
pRenderTarget->Release();
pDestTarget->Release();
</code>```

}

p.s: Do I understand correctly that when using GetDesktopWindow() am I capturing a desktop containing an image of the entire screen?

Some help in solving this problem is needed

Title: DirectX screen capture on Windows 10/11

Body:
I'm trying to create a screen taking app that can get a raw bitmap of a desktop window from the GPU. I did it via GDI and it works properly, but using both DirectX and DXGI Duplication api, I have black screen or an error.

void dump_buffer() {
IDirect3D9* d3d = nullptr;
d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;
out("1");
ZeroMemory(&d3dpp, sizeof(d3dpp));//COCK?
D3DDISPLAYMODE  d3ddm;
if(FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
    err("IDirect3D9");
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = FALSE;
IDirect3DDevice9* d3ddev = nullptr;
out("2");
d3d->CreateDevice(
        D3DADAPTER_DEFAULT, // Используем видеокарту, установленную в Windows по умолчанию (= в качестве основной).
        D3DDEVTYPE_HAL, // Используем аппаратный рендеринг (Hardware Abstraction Layer).
        GetDesktopWindow(), // Дескриптор) окна
        D3DCREATE_SOFTWARE_VERTEXPROCESSING, // Не использовать "фишки" T&L для лучшей совместимости с бОльшим числом видеоадаптеров.
        &d3dpp, // Указатель на заранее заполненную структуру параметров отображения (D3DPRESENT_PARAMETERS).
        &d3ddev // Указатель на создаваемый объект устройства Direct3D.
);
if (d3ddev == nullptr)
    err("IDirect3DDevice9");
out("3");
IDirect3DSurface9 *pRenderTarget = nullptr;
IDirect3DSurface9 *pDestTarget = nullptr;
// sanity checks.

// get the render target surface.
HRESULT hr = d3ddev->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)){
    err("GetRenderTarget");
}
// get the current adapter display mode.
// hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);
out("4");
D3DDISPLAYMODE mode;
hr = d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode);
if (FAILED(hr)){
    err("GetAdapterDisplayMode");
}
// create a destination surface.
out(mode.Width);
out(mode.Height);
out(mode.Format);
hr = d3ddev->CreateOffscreenPlainSurface(mode.Width,
                                         mode.Height,
                                         mode.Format,
                                         D3DPOOL_SYSTEMMEM,
                                         &pDestTarget,
                                         nullptr);
if (FAILED(hr)){
    err(("CreateOffscreenPlainSurface"));
}
out("5");
//copy the render target to the destination surface.
hr = d3ddev->GetRenderTargetData(pRenderTarget, pDestTarget);
if (FAILED(hr)){
    err(DXGetErrorDescription9A(hr));
    err(("GetRenderTargetData"));
}
//save its contents to a bitmap file.
out("6");
hr = D3DXSaveSurfaceToFile(file,
                           D3DXIFF_BMP,
                           pDestTarget,
                           nullptr,
                           nullptr);
out("7");
// clean up.
pRenderTarget->Release();
pDestTarget->Release();

}

p.s: Do I understand correctly that when using GetDesktopWindow() am I capturing a desktop containing an image of the entire screen?

Some help in solving this problem is needed


问:
maven-release-plugin: release commits should not be on the current branch
I'm trying to develop a release pipeline and the maven-release-plugin is 95% of what I want.

What I'd like it to do is have the release commits (the ones tagged with v1.0.0 or whatever) not be part of the main branch. I don't want to create another branch either, I just want the tag commit to be its own thing. Similar to how spring framework does it.

Can it be done with this plugin?


问:
How to use empyrical ortogonal funcion (EOF) to process my data
I would like to use the Empirical Orthogonal Function in my lat/long/time/temperature dataset. First problem I face is to convert my .csv data into .nc (I need to obtain a three dimension but I failed).

In the follow my code and what I get:

import pandas as pd

import xarray
new_df =df[['TIME','LAT','LONG','Temperat']].copy()
print("DataFrame Shape:",new_df.shape)
display(new_df.head(5))

xr = xarray.Dataset.from_dataframe(new_df)

xr.to_netcdf('test.nc')
```

image of the dataset

Body:
I would like to use the Empirical Orthogonal Function in my lat/long/time/temperature dataset. First problem I face is to convert my .csv data into .nc (I need to obtain a three dimension but I failed).

In the follow my code and what I get:

import pandas as pd

import xarray
new_df =df[['TIME','LAT','LONG','Temperat']].copy()
print("DataFrame Shape:",new_df.shape)
display(new_df.head(5))

xr = xarray.Dataset.from_dataframe(new_df)

xr.to_netcdf('test.nc')

image of the dataset


问:
Fetch list of active third party NotificationListenerServices?
It is possible for Android developers to use AccessibilityManager.getEnabledAccessibilityServiceList() to look up info on active accessibility agents on the user's phone so as to warn them if any of them appear fishy; for example, if they came from packages that are known malware.  Info in the AccessibilityServiceInfo class helps with this.

Is there an equivalent for NotificationListenerServices?  Notification listener services can do quite concerning things as well -- read one time passcodes, send fraudulent messages by hitting reply with imposter text in a WhatsApp notification, etc.


问:
Why is the mean in my model almost the same for all values?
I am currently in the process of creating a deep learning model to forecast stock prices. I am using AutoGluon since I am relatively new to deep learning/ML.

My pandas dataframe consists of the historical daily close price of about 1800 different stocks. This is about 8 million rows total. Here is how I have preprocessed my data:

```<code>import pandas as pd
import matplotlib.pyplot as plt
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor
from datetime import datetime, timedelta, time
import random
import numpy as np

df = pd.read_csv(
    "/content/drive/MyDrive/stock_data/training_data_formatted.csv",
    parse_dates=["Date"],
)
values_to_remove = ['Date', 'Close', 'ID']
df["Date"] = pd.to_datetime(df["Date"], errors="coerce", dayfirst=True)
df = df[~df['Date'].isin(values_to_remove) & ~df['ID'].isin(values_to_remove) & ~df['Close'].isin(values_to_remove)]
df = df.drop(columns=['Unnamed: 0'])

#add time and microseconds to make a unique index since stocks have overlapping dates.
df['Date'] = df['Date'].apply(lambda x: x.replace(hour=12, minute=0, second=0))
df['Date'] = pd.to_datetime(df['Date'])

microseconds = df.groupby(['Date']).cumcount()
df['Date'] += np.array(microseconds, dtype='m8[us]')

ts_dataframe = TimeSeriesDataFrame.from_data_frame(
    df,
    id_column="ID",  # column that contains unique ID of each time series
    timestamp_column="Date",
)

#add frequency so model understands
def forward_fill_missing(ts_dataframe: TimeSeriesDataFrame, freq="D") -> TimeSeriesDataFrame:
    original_index = ts_dataframe.index.get_level_values("timestamp")
    start = original_index.min()
    end = original_index.max()
    filled_index = pd.date_range(start=start, end=end, freq=freq, name="timestamp")
    return ts_dataframe.droplevel("item_id").reindex(filled_index, method="ffill")

ts_dataframe = ts_dataframe.groupby("item_id").apply(forward_fill_missing)
</code>```

I first trained the model on best_quality and with no hyperparameter adjustment. This trained all the available models on Autogluon and I used a weighted ensemble of the models. However, the mean of my predictions was simply a straight line (I assume this has to do with overfitting). Here is the code:

```<code>prediction_length = 30

test_data = ts_dataframe

# last prediction_length timesteps of each time series are excluded, akin to `x[:-48]`
train_data = ts_dataframe.slice_by_timestep(None, -prediction_length)

predictor = TimeSeriesPredictor(
    path="/content/drive/MyDrive/TrainedModel",
    target="Close",
    prediction_length=prediction_length,
    eval_metric="MAPE",
)

predictor.fit(
    train_data,
    presets="best_quality",
    num_gpus=1
)

</code>```

I then decided to only use only DeepAR from AutoGluon with configured hyperparameters. I have tried a different bunch of configurations, however, I don't get a model which gives even a halfway decent forecast. This is the configuration I last did:

```<code>
predictor.fit(
    train_data,
    hyperparameters={
            "DeepAR": {
                "num_layers": 5,
                "hidden_size": 100,
                "learning_rate": 0.1,
                "batch_size": 128,
                "num_batches_per_epoch": 80,
                "epochs": 300
            },
        },
    num_gpus=1
)
</code>```

This configuration gives slightly better results than the weighted ensemble, however it's still an almost linear mean which doesn't quite capture the ups and downs in the trend.

I don't know whether this is because of the way I'm preprocessing the data or because I'm doing something extremely wrong in configuring the hyper params.

I should note that to test the model, I am passing it the entire historical data of just one stock.

I'm relatively new to ML, so I apologize if I've made an extremely rookie error, but I'd really appreciate it if someone could guide me as to where I'm going wrong.

If there's something I'd left out, or any more info I could give to make things clearer, please let me know.

Thanks!

Body:
I am currently in the process of creating a deep learning model to forecast stock prices. I am using AutoGluon since I am relatively new to deep learning/ML.

My pandas dataframe consists of the historical daily close price of about 1800 different stocks. This is about 8 million rows total. Here is how I have preprocessed my data:

import pandas as pd
import matplotlib.pyplot as plt
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor
from datetime import datetime, timedelta, time
import random
import numpy as np

df = pd.read_csv(
    "/content/drive/MyDrive/stock_data/training_data_formatted.csv",
    parse_dates=["Date"],
)
values_to_remove = ['Date', 'Close', 'ID']
df["Date"] = pd.to_datetime(df["Date"], errors="coerce", dayfirst=True)
df = df[~df['Date'].isin(values_to_remove) & ~df['ID'].isin(values_to_remove) & ~df['Close'].isin(values_to_remove)]
df = df.drop(columns=['Unnamed: 0'])

#add time and microseconds to make a unique index since stocks have overlapping dates.
df['Date'] = df['Date'].apply(lambda x: x.replace(hour=12, minute=0, second=0))
df['Date'] = pd.to_datetime(df['Date'])

microseconds = df.groupby(['Date']).cumcount()
df['Date'] += np.array(microseconds, dtype='m8[us]')

ts_dataframe = TimeSeriesDataFrame.from_data_frame(
    df,
    id_column="ID",  # column that contains unique ID of each time series
    timestamp_column="Date",
)

#add frequency so model understands
def forward_fill_missing(ts_dataframe: TimeSeriesDataFrame, freq="D") -> TimeSeriesDataFrame:
    original_index = ts_dataframe.index.get_level_values("timestamp")
    start = original_index.min()
    end = original_index.max()
    filled_index = pd.date_range(start=start, end=end, freq=freq, name="timestamp")
    return ts_dataframe.droplevel("item_id").reindex(filled_index, method="ffill")

ts_dataframe = ts_dataframe.groupby("item_id").apply(forward_fill_missing)

I first trained the model on best_quality and with no hyperparameter adjustment. This trained all the available models on Autogluon and I used a weighted ensemble of the models. However, the mean of my predictions was simply a straight line (I assume this has to do with overfitting). Here is the code:

prediction_length = 30

test_data = ts_dataframe

# last prediction_length timesteps of each time series are excluded, akin to `x[:-48]`
train_data = ts_dataframe.slice_by_timestep(None, -prediction_length)

predictor = TimeSeriesPredictor(
    path="/content/drive/MyDrive/TrainedModel",
    target="Close",
    prediction_length=prediction_length,
    eval_metric="MAPE",
)

predictor.fit(
    train_data,
    presets="best_quality",
    num_gpus=1
)

I then decided to only use only DeepAR from AutoGluon with configured hyperparameters. I have tried a different bunch of configurations, however, I don't get a model which gives even a halfway decent forecast. This is the configuration I last did:

predictor.fit(
    train_data,
    hyperparameters={
            "DeepAR": {
                "num_layers": 5,
                "hidden_size": 100,
                "learning_rate": 0.1,
                "batch_size": 128,
                "num_batches_per_epoch": 80,
                "epochs": 300
            },
        },
    num_gpus=1
)

This configuration gives slightly better results than the weighted ensemble, however it's still an almost linear mean which doesn't quite capture the ups and downs in the trend.

I don't know whether this is because of the way I'm preprocessing the data or because I'm doing something extremely wrong in configuring the hyper params.

I should note that to test the model, I am passing it the entire historical data of just one stock.

I'm relatively new to ML, so I apologize if I've made an extremely rookie error, but I'd really appreciate it if someone could guide me as to where I'm going wrong.

If there's something I'd left out, or any more info I could give to make things clearer, please let me know.

Thanks!


问:
How do I get Environment variables in the main method of a spring boot application?
```<code>`@SpringBootApplication
public class RegexApplication {
@Resource
private static Environment environment;
@Autowired
private static Environment environment;

public static void main(String[] args) {
    SpringApplication.run(RegexApplication.class, args);

    System.out.println(environment.getProperty("spring.application.name"));
}

}`
</code>```

I just want to print this out so I can see what the default spring.application.name is. But I'm having a hard time understanding how to do it.

I tried @Autowired and @Resource both don't seem to work.

Body:
`@SpringBootApplication
public class RegexApplication {
@Resource
private static Environment environment;
@Autowired
private static Environment environment;

public static void main(String[] args) {
    SpringApplication.run(RegexApplication.class, args);

    System.out.println(environment.getProperty("spring.application.name"));
}

}`

I just want to print this out so I can see what the default spring.application.name is. But I'm having a hard time understanding how to do it.

I tried @Autowired and @Resource both don't seem to work.


问:
Filter and load more with jQuery does not work
I have created a filter system with jQuery and I would like to have it filter on specific classes, which already works. But now I also want to have a load more button, based on the filter's input.

When the page is loaded, I would like to have it filter on 'all', but when another filter is clicked, then the filter should show the filtered classes with a load more button after 4 results.

I have the filter system and the load more after 4 results when the function is activated on click. But now the problem is that when it is not clicked, then nothing is filtered, also without a load more button based on the prefilter.

```<code><div class="filter">
    <ul>
        <li class="list hoofd activefilter" data-filter="all">
        All
        </li>
        <li class="list hoofd" data-filter="red">
        Red
        </li>
        <li class="list" data-filter="blue">
        Blue
        </li>
        <li class="list" data-filter="yellow">
        Yellow
        </li>
    </ul>
</div>
</code>```
```<code><div class="artikel red">
</div>
<div class="artikel blue">
</div>
<div class="artikel yellow">
</div>
</code>```
```<code><script>
    $(document).ready(function() {
        $('.list').click(function() {
            const value = $(this).attr('data-filter');

            if (value == 'all') {
                $('.artikel').show('1000');
            } else {
                $('.artikel').not('.' + value).hide('1000');
                $('.artikel').filter('.' + value).slice(0, 4).show('1000');

                $("#load").on("click", function(e) {
                    e.preventDefault();
                    $(".artikel:hidden").filter('.' + value).slice(0, 4).slideDown();

                    if ($(".artikel:hidden").filter('.' + value).length == 0) {
                        $("#load").hide();
                    }
                    else {
                        $("#load").show();
                    }
                });
            }
        })

        // add active class on selected item
        $('.list').click(function() {
            $(this).addClass('activefilter').siblings().removeClass('activefilter');
        })
    })
</script>
</code>```

Body:
I have created a filter system with jQuery and I would like to have it filter on specific classes, which already works. But now I also want to have a load more button, based on the filter's input.

When the page is loaded, I would like to have it filter on 'all', but when another filter is clicked, then the filter should show the filtered classes with a load more button after 4 results.

I have the filter system and the load more after 4 results when the function is activated on click. But now the problem is that when it is not clicked, then nothing is filtered, also without a load more button based on the prefilter.

        All

        Red

        Blue

        Yellow


问:
Visual Studio 2022 & ASP.NET Core 6 : show connections
I have an issue where I'm running out of worker_connections in NGINX and I wanted to do a stress test on my app to make sure all connections are good and not building up somewhere (it's a huge project).

How can I see how many current connections are made to the app? Either by database, client, httpClient requests, etc?

I’m running this on AWS EB. 8 t2.small instances at a rate of 500 requests per second on the load balancer.


问:
roots are empty in BasicRobot.robot.hierarchy Swing-assertj
I’m trying to test swing dialog in desktop application, bit robot couldn’t get any dialog and also the roots is empty

I need to get access to this dialog , it appears in access bridge explore


问:
How to increment an object and save it?
In app.jsn i got an increment function, which should increase listVoca, a list of object thus {word:'word', translation: 'translation', count:0}

```<code>incrementVoca = indexToIncrement => {
    this.setState(prevState => {
        let listVoca = [...prevState.listVoca];
        let vocaToIncrement = listVoca[indexToIncrement];
        vocaToIncrement['point']++;
        listVoca[indexToIncrement] = vocaToIncrement;
        return {listVoca};
    },() => {
    AsyncStorage.setItem('listVoca', JSON.stringify(this.state.listVoca));
  });
}
</code>```

I call it with the increment function by pressing a button :

```<code>{increment=()=>{
 this.props.screenProps.incrementVoca(this.state.index)
       this.takeRandomVoca();
 }
</code>```

However, the count is not incremented, and this.takeRandomVoca() is not called. Can please someone explaine me why ?

Title: How to increment an object and save it?

Body:
In app.jsn i got an increment function, which should increase listVoca, a list of object thus {word:'word', translation: 'translation', count:0}

incrementVoca = indexToIncrement => {
    this.setState(prevState => {
        let listVoca = [...prevState.listVoca];
        let vocaToIncrement = listVoca[indexToIncrement];
        vocaToIncrement['point']++;
        listVoca[indexToIncrement] = vocaToIncrement;
        return {listVoca};
    },() => {
    AsyncStorage.setItem('listVoca', JSON.stringify(this.state.listVoca));
  });
}

I call it with the increment function by pressing a button :

{increment=()=>{
 this.props.screenProps.incrementVoca(this.state.index)
       this.takeRandomVoca();
 }

However, the count is not incremented, and this.takeRandomVoca() is not called. Can please someone explaine me why ?


问:
Get refreshToken react-native firebase and @react-native-google-signin/google-signin
I need to get my accessToken and my refreshToken when I authenticate with fireabse. I have read a lot of the documentation and I can't understand how to get the refreshToken.
I get the accessToken from the GoogleSignIn.getTokens() method.
But I can't get the refreshToken from any method or function that these libraries provide me.
I need accessToken and refreshToken to send it to my backend. In other applications I am already receiving it, through other methods, but what would be the problem here? is the library wrong? I am not understanding the documentation? Why can't I really understand where to get it from or if the idToken updates itself or maybe the refreshToken is not sent anymore?

my code =>

```<code>import { GoogleSignin } from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';

GoogleSignin.configure({
  webClientId:
    'xxxxxxxxxxxxxxxxxxxxx',
});

const onGoogleButtonPress = async () => {
  // Get the users ID token
  const { idToken } = await GoogleSignin.signIn();

  // Create a Google credential with the token
  const googleCredential = auth.GoogleAuthProvider.credential(idToken);

  // Sign-in the user with the credential
  return auth().signInWithCredential(googleCredential);
};

export { onGoogleButtonPress };
</code>```

React Native Info =>

react: 18.1.0 => 18.1.0
react-native: 0.70.6 => 0.70.6

Package.json ->

```<code>{
  "name": "asset_management_mobile",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@invertase/react-native-apple-authentication": "^2.2.2",
    "@react-native-firebase/app": "^15.4.0",
    "@react-native-firebase/auth": "^15.4.0",
    "@react-native-google-signin/google-signin": "^8.0.0",
    "@react-native-masked-view/masked-view": "0.2.0",
    "@react-navigation/bottom-tabs": "^6.5.2",
    "@react-navigation/native": "^6.0.12",
    "@react-navigation/stack": "^6.2.3",
    "@types/react-native-background-timer": "^2.0.0",
    "convert-string": "^0.1.0",
    "depcheck": "^1.4.3",
    "deprecated-react-native-prop-types": "^2.3.0",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-android-open-settings": "^1.3.0",
    "react-native-background-timer": "^2.4.1",
    "react-native-ble-manager": "^8.4.3",
    "react-native-bluetooth-state-manager": "^1.3.4",
    "react-native-gesture-handler": "^2.6.0",
    "react-native-gradle-plugin": "^0.70.2",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-permissions": "^3.6.1",
    "react-native-reanimated": "^2.10.0",
    "react-native-safe-area-context": "^4.3.3",
    "react-native-screens": "^3.17.0",
    "react-native-splash-screen": "^3.3.0",
    "react-native-svg": "^13.1.0",
    "react-native-swiper": "^1.6.0",
    "react-native-vision-camera": "^2.15.2",
    "vision-camera-code-scanner": "^0.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/runtime": "^7.14.6",
    "@react-native-community/eslint-config": "^3.0.0",
    "@types/convert-string": "^0.1.1",
    "@types/jest": "^29.0.0",
    "@types/react": "^18.0.18",
    "@types/react-native": "^0.69.6",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.0.1",
    "babel-plugin-module-resolver": "^4.1.0",
    "eslint": "^8.23.0",
    "jest": "^29.0.1",
    "metro-react-native-babel-preset": "^0.72.1",
    "react-native-svg-transformer": "^1.0.0",
    "react-native-typescript-transformer": "^1.2.13",
    "react-test-renderer": "^18.2.0",
    "ts-jest": "^28.0.8",
    "typescript": "^4.3.5"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache"
  }
}
</code>```

I need your help!! Thanks!

Body:
I need to get my accessToken and my refreshToken when I authenticate with fireabse. I have read a lot of the documentation and I can't understand how to get the refreshToken.
I get the accessToken from the GoogleSignIn.getTokens() method.
But I can't get the refreshToken from any method or function that these libraries provide me.
I need accessToken and refreshToken to send it to my backend. In other applications I am already receiving it, through other methods, but what would be the problem here? is the library wrong? I am not understanding the documentation? Why can't I really understand where to get it from or if the idToken updates itself or maybe the refreshToken is not sent anymore?

my code =>

import { GoogleSignin } from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';

GoogleSignin.configure({
  webClientId:
    'xxxxxxxxxxxxxxxxxxxxx',
});

const onGoogleButtonPress = async () => {
  // Get the users ID token
  const { idToken } = await GoogleSignin.signIn();

  // Create a Google credential with the token
  const googleCredential = auth.GoogleAuthProvider.credential(idToken);

  // Sign-in the user with the credential
  return auth().signInWithCredential(googleCredential);
};

export { onGoogleButtonPress };

React Native Info =>

react: 18.1.0 => 18.1.0
react-native: 0.70.6 => 0.70.6

Package.json ->

{
  "name": "asset_management_mobile",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@invertase/react-native-apple-authentication": "^2.2.2",
    "@react-native-firebase/app": "^15.4.0",
    "@react-native-firebase/auth": "^15.4.0",
    "@react-native-google-signin/google-signin": "^8.0.0",
    "@react-native-masked-view/masked-view": "0.2.0",
    "@react-navigation/bottom-tabs": "^6.5.2",
    "@react-navigation/native": "^6.0.12",
    "@react-navigation/stack": "^6.2.3",
    "@types/react-native-background-timer": "^2.0.0",
    "convert-string": "^0.1.0",
    "depcheck": "^1.4.3",
    "deprecated-react-native-prop-types": "^2.3.0",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-android-open-settings": "^1.3.0",
    "react-native-background-timer": "^2.4.1",
    "react-native-ble-manager": "^8.4.3",
    "react-native-bluetooth-state-manager": "^1.3.4",
    "react-native-gesture-handler": "^2.6.0",
    "react-native-gradle-plugin": "^0.70.2",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-permissions": "^3.6.1",
    "react-native-reanimated": "^2.10.0",
    "react-native-safe-area-context": "^4.3.3",
    "react-native-screens": "^3.17.0",
    "react-native-splash-screen": "^3.3.0",
    "react-native-svg": "^13.1.0",
    "react-native-swiper": "^1.6.0",
    "react-native-vision-camera": "^2.15.2",
    "vision-camera-code-scanner": "^0.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/runtime": "^7.14.6",
    "@react-native-community/eslint-config": "^3.0.0",
    "@types/convert-string": "^0.1.1",
    "@types/jest": "^29.0.0",
    "@types/react": "^18.0.18",
    "@types/react-native": "^0.69.6",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.0.1",
    "babel-plugin-module-resolver": "^4.1.0",
    "eslint": "^8.23.0",
    "jest": "^29.0.1",
    "metro-react-native-babel-preset": "^0.72.1",
    "react-native-svg-transformer": "^1.0.0",
    "react-native-typescript-transformer": "^1.2.13",
    "react-test-renderer": "^18.2.0",
    "ts-jest": "^28.0.8",
    "typescript": "^4.3.5"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache"
  }
}

I need your help!! Thanks!


问:
Get list of file for a user excluding sharewithme?
We have a Apps Script that change the owner of some documentation in a shared folder on a generic account. Employee put their documentation into the folder and the script flip the owner to the generic account and give Editor access to the previos owner. In that way if employee leave the company, the ownership stay to that generic account.

BUT

recently user started to share documents and folders with that generic account instead of moving it directly into the generic account drive/folder.

So at the end, we don't want all the files and folder that are "SharedWithMe" to have owner changed. We only want those that are contained directly under the generic account drive.

I'm looking to find a query that I can be use as params with the  DriveApp.searchFolders() and DriveApp.searchFiles() method so that only "local" files/folder are processed by my script

For now I have this to get only file that the generic account is not already the owner..

```<code>var files = DriveApp.searchFiles('not "username@domain.com" in owners');
</code>```

I need to add to that a kind of exclusion of all files/folder that are only sharewithme

For now I try

var files = DriveApp.searchFiles('not "username@domain.com" in owners and sharedWithMe=false');

var files = DriveApp.searchFiles('not "username@domain.com" in owners and sharedWithMe!=true');

var files = DriveApp.searchFiles('not "username@domain.com" in owners and not sharedWithMe=true');
...etc..etc..

I also test only the query using the File.list API Explorer and the only thing that return some results is q = sharedWithMe=true  or q = sharedWithMe

These bug tracker (https://issuetracker.google.com/issues/36759777) workaround doesn't apply as we are looking only for file that the account is not already the owner....the goal of our script is to change the owner to the generic acount..

So how to exclude in the list of files/folder returned all those sharewithme...?

Body:
We have a Apps Script that change the owner of some documentation in a shared folder on a generic account. Employee put their documentation into the folder and the script flip the owner to the generic account and give Editor access to the previos owner. In that way if employee leave the company, the ownership stay to that generic account.

BUT

recently user started to share documents and folders with that generic account instead of moving it directly into the generic account drive/folder.

So at the end, we don't want all the files and folder that are "SharedWithMe" to have owner changed. We only want those that are contained directly under the generic account drive.

I'm looking to find a query that I can be use as params with the  DriveApp.searchFolders() and DriveApp.searchFiles() method so that only "local" files/folder are processed by my script

For now I have this to get only file that the generic account is not already the owner..

var files = DriveApp.searchFiles('not "username@domain.com" in owners');

I need to add to that a kind of exclusion of all files/folder that are only sharewithme

For now I try

var files = DriveApp.searchFiles('not "username@domain.com" in owners and sharedWithMe=false');

var files = DriveApp.searchFiles('not "username@domain.com" in owners and sharedWithMe!=true');

var files = DriveApp.searchFiles('not "username@domain.com" in owners and not sharedWithMe=true');
...etc..etc..

I also test only the query using the File.list API Explorer and the only thing that return some results is q = sharedWithMe=true  or q = sharedWithMe

These bug tracker (https://issuetracker.google.com/issues/36759777) workaround doesn't apply as we are looking only for file that the account is not already the owner....the goal of our script is to change the owner to the generic acount..

So how to exclude in the list of files/folder returned all those sharewithme...?


问:
SwiftUI: Navigation View does not update on layout direction change (forced by environment variable)
I have created an app that supports two languages English and another language which uses the right to left layout direction opposing the English language. I have created an in app language picker which modifies a variable inside a view model and based on that variable both the locale and layout direction will be inferred, here is my code for the app entry point. I have a NavigationView inside the parentView:

@main
struct RecheckApp: App {
    @StateObject var viewModel = ViewModel()
    var layoutDirection : LayoutDirection {
        viewModel.language == "ku" ? .rightToLeft : .leftToRight
    }
    var body: some Scene {
        WindowGroup {
            ParentView()
                .environment(\.colorScheme, .dark)
                .preferredColorScheme(.dark)
                .environment(\.locale, .init(identifier: viewModel.language))
                .environment(\.layoutDirection, layoutDirection)
                .environmentObject(viewModel)

        }
    }
}
```

When the language variable changes everything updates as expected, the layouts will shift from an LTR layout to RTL layout and the texts will be updated accordingly.  the only problem is that the navigation view does not behave correctly when i try to navigate back, it still preserves the behavior it started with, for example when i navigate to another view, i would have either to press the back button or swipe from the left edge of the screen to right if it was in an LTR layout, but when i change the layout to RTL still i have to swipe from LTR in order to go back. that means there is something inside the Navigation View that does not update or get recreated when the layout changes.
Please refer to this link to watch and understand the behavior I'm talking about.

I don't know what to do to solve this problem, can you please provide a solution for such inconvenience in the NavigationView ?

I have not used a NavigationStack because of the compatibility requirements i have since NavigationStack supports from iOS16

Body:
I have created an app that supports two languages English and another language which uses the right to left layout direction opposing the English language. I have created an in app language picker which modifies a variable inside a view model and based on that variable both the locale and layout direction will be inferred, here is my code for the app entry point. I have a NavigationView inside the parentView:

@main
struct RecheckApp: App {
    @StateObject var viewModel = ViewModel()
    var layoutDirection : LayoutDirection {
        viewModel.language == "ku" ? .rightToLeft : .leftToRight
    }
    var body: some Scene {
        WindowGroup {
            ParentView()
                .environment(\.colorScheme, .dark)
                .preferredColorScheme(.dark)
                .environment(\.locale, .init(identifier: viewModel.language))
                .environment(\.layoutDirection, layoutDirection)
                .environmentObject(viewModel)

        }
    }
}

When the language variable changes everything updates as expected, the layouts will shift from an LTR layout to RTL layout and the texts will be updated accordingly.  the only problem is that the navigation view does not behave correctly when i try to navigate back, it still preserves the behavior it started with, for example when i navigate to another view, i would have either to press the back button or swipe from the left edge of the screen to right if it was in an LTR layout, but when i change the layout to RTL still i have to swipe from LTR in order to go back. that means there is something inside the Navigation View that does not update or get recreated when the layout changes.
Please refer to this link to watch and understand the behavior I'm talking about.

I don't know what to do to solve this problem, can you please provide a solution for such inconvenience in the NavigationView ?

I have not used a NavigationStack because of the compatibility requirements i have since NavigationStack supports from iOS16


问:
Minimize or bring back sheet in SwiftUI
I have a Voip calling app using CallKit and when call received, it will open a view call IncomingView in a sheet in my SwiftUI app. So far so good. But i want to minimize the sheet and can navigate to other pages and preferably shows a green bar at the navigation (similar to WhatApp) that indicates the call is going on and when i tap there, it should bring back my "IncomingView".

here is my code:

```<code>  struct MainView: View {
     let acceptPublishser = NotificationCenter.default
            .publisher(for: Notification.Name.DidCallAccepted)
let endPublisher = NotificationCenter.default
        .publisher(for: Notification.Name.DidCallEnd)
     var body: some View {
       NavigationView {
                TabView {
                    TabListView()

                        .tabItem {
                            Label("Home", systemImage: "house.fill")
                        }

                    ContactListView()
                        .tabItem {
                            Label("Contacts", systemImage: "person.crop.circle")
                        }

                    ProfileView()
                        .tabItem {
                            Label("Profile", systemImage: "person.crop.circle")
                        }
                }
                .padding(0)
                .onAppear(){
                    self.showModal = MyCallDelegate.shared.isIncomingCall
                }
                .sheet(isPresented: $showModal){
                    IncomingCallView() // -> Present IncomingCallview() as sheet
                }
                .accentColor(Color(.green))
            }.onReceive(self.acceptPublishser, perform: { output in
                showModal = true
            })
            .onReceive(self.endPublisher, perform: { output in
                showModal = false
            })
    }
    }

    struct IncomingCallView: View {
     var body: some View {

            VStack{
                Spacer()
                Text("callerId").foregroundColor(.white)
                Text("Timer").foregroundColor(.white)
    }
    }
</code>```

Title: Minimize or bring back sheet in SwiftUI

Body:
I have a Voip calling app using CallKit and when call received, it will open a view call IncomingView in a sheet in my SwiftUI app. So far so good. But i want to minimize the sheet and can navigate to other pages and preferably shows a green bar at the navigation (similar to WhatApp) that indicates the call is going on and when i tap there, it should bring back my "IncomingView".

here is my code:

  struct MainView: View {
     let acceptPublishser = NotificationCenter.default
            .publisher(for: Notification.Name.DidCallAccepted)
let endPublisher = NotificationCenter.default
        .publisher(for: Notification.Name.DidCallEnd)
     var body: some View {
       NavigationView {
                TabView {
                    TabListView()

                        .tabItem {
                            Label("Home", systemImage: "house.fill")
                        }

                    ContactListView()
                        .tabItem {
                            Label("Contacts", systemImage: "person.crop.circle")
                        }

                    ProfileView()
                        .tabItem {
                            Label("Profile", systemImage: "person.crop.circle")
                        }
                }
                .padding(0)
                .onAppear(){
                    self.showModal = MyCallDelegate.shared.isIncomingCall
                }
                .sheet(isPresented: $showModal){
                    IncomingCallView() // -> Present IncomingCallview() as sheet
                }
                .accentColor(Color(.green))
            }.onReceive(self.acceptPublishser, perform: { output in
                showModal = true
            })
            .onReceive(self.endPublisher, perform: { output in
                showModal = false
            })
    }
    }

    struct IncomingCallView: View {
     var body: some View {

            VStack{
                Spacer()
                Text("callerId").foregroundColor(.white)
                Text("Timer").foregroundColor(.white)
    }
    }


问:
Getting Invalid time value when i try to type date
// using this code blow, getting error when trying to type date. Getting Invalid time
//value
//when i try to type date
import { TextField } from '@mui/material';
import { DateTimePicker } from '@mui/x-date-pickers';
import { useInput } from 'react-admin';
import { useWatch } from 'react-hook-form';
import { parseISO, formatISO } from 'date-fns';</p>
```<code>const AMCDateInput = ({ source, label, minSource, maxSource, ...rest }) => {

  const { id, field, fieldState, formState, isRequired } = useInput({
    source,
    format: (v) => {
      return v ? parseISO(v) : null;
    },
    parse: (v) => {
      return formatISO(v);
    },
  });

  const minBound = useWatch({ name: minSource, exact: true });
  const maxBound = useWatch({ name: maxSource, exact: true });

  return (
    <>
      <DateTimePicker
        renderInput={(props) => <TextField fullWidth {...props} />}
        label={label}
        minutesStep={5}
        minDateTime={minBound?.length > 0 ? parseISO(minBound) : null}
        maxDateTime={maxBound?.length > 0 ? parseISO(maxBound) : null}
        ampm={false}
        {...field}
        {...rest}
      />
    </>
  );
};

export default AMCDateInput;
//getting error
</code>```

Body:
// using this code blow, getting error when trying to type date. Getting Invalid time
//value
//when i try to type date
import { TextField } from '@mui/material';
import { DateTimePicker } from '@mui/x-date-pickers';
import { useInput } from 'react-admin';
import { useWatch } from 'react-hook-form';
import { parseISO, formatISO } from 'date-fns';

const AMCDateInput = ({ source, label, minSource, maxSource, ...rest }) => {

  const { id, field, fieldState, formState, isRequired } = useInput({
    source,
    format: (v) => {
      return v ? parseISO(v) : null;
    },
    parse: (v) => {
      return formatISO(v);
    },
  });

  const minBound = useWatch({ name: minSource, exact: true });
  const maxBound = useWatch({ name: maxSource, exact: true });

  return (
    <>
      <DateTimePicker
        renderInput={(props) => <TextField fullWidth {...props} />}
        label={label}
        minutesStep={5}
        minDateTime={minBound?.length > 0 ? parseISO(minBound) : null}
        maxDateTime={maxBound?.length > 0 ? parseISO(maxBound) : null}
        ampm={false}
        {...field}
        {...rest}
      />
    </>
  );
};

export default AMCDateInput;
//getting error


问:
RxPy and asyncio for Server-Client communication
I am trying to develop an application consisting of a Server and a bunch of Clients that should work like this:

each Client itself will listen to an independent websocket consisting of some information

they will then process this information and redirect the processed message to the Server

the Server will do some processing (send some information trhough another websocket and wait for response)

once the Server gets the response, it will redirect it to the Client

Since it consists of asynchronous responses and communication between classes my first idea was to use the combo RxPy + asyncio. Here is a toy model of my problema that I tryied to develop:

Here is the Server:

```<code>import reactivex as rx
import random

import reactivex.operators as ops

class Server:
    def __init__(self, clients):
        self.clients = clients
        self.stream = rx.Subject()

    def info(self, msg):
        print(msg)

    async def start(self, loop):

        done = asyncio.Future()

        def on_completed():
            done.set_result(True)

        async def react(item):
            msg = {'alias': 'server', 'action': 'received', 'from': item['alias'], 'request': item['request']}
            self.info(msg)

            await asyncio.sleep(random.randint(1,3))

            response = {'alias': 'server', 'action': 'send', 'request': msg['request'] ** 2}
            self.info(response)
            self.stream.on_next(response)

        client_listener = rx.empty()
        for client in self.clients:
            client_listener= rx.merge(client_listener, client.stream(self.stream, loop))

        client_listener.subscribe(
            on_next = lambda x: react(x),
            on_error = print,
            on_completed = print('completed server')
        )

        await done
</code>```

Here is the Client:

```<code>import reactivex.operators as ops

class Client:
    def __init__(self, alias):
        self.alias = alias

    def info(self, msg):
        print(msg)

    def stream(self, controller, loop):

        def on_subscribe(observer, scheduler):

            for i in range(10):
                msg = {'alias': self.alias, 'action': 'send', 'request': i}
                self.info(msg)
                observer.on_next(msg)
            loop.call_soon(observer.on_completed())

        controller.subscribe(
            on_next = lambda msg: self.info({'alias': self.alias, 'action': 'received', 'from': msg['alias'], 'request': msg['request']})
        )

        return rx.create(on_subscribe)
</code>```

And here is how I am trying to run it:

```<code>import asyncio

loop = asyncio.get_event_loop()

client_1 = Client('client_1')
client_2 = Client('client_2')

loop.run_until_complete(Server([client_1, client_2]).start(loop=loop))
loop.close()
</code>```

When I try executing the above code I get the followin:

```<code>RuntimeError                              Traceback (most recent call last)
Cell In[3], line 8
      5 client_1 = Client('client_1')
      6 client_2 = Client('client_2')
----> 8 loop.run_until_complete(Server([client_1, client_2]).start(loop=loop))
      9 loop.close()

File ~\Anaconda3\envs\nfs_hom\lib\asyncio\base_events.py:625, in BaseEventLoop.run_until_complete(self, future)
    614 """Run until the Future is done.
    615
    616 If the argument is a coroutine, it is wrapped in a Task.
   (...)
    622 Return the Future's result, or raise its exception.
    623 """
    624 self._check_closed()
--> 625 self._check_running()
    627 new_task = not futures.isfuture(future)
    628 future = tasks.ensure_future(future, loop=self)

File ~\Anaconda3\envs\nfs_hom\lib\asyncio\base_events.py:584, in BaseEventLoop._check_running(self)
    582 def _check_running(self):
    583     if self.is_running():
--> 584         raise RuntimeError('This event loop is already running')
    585     if events._get_running_loop() is not None:
    586         raise RuntimeError(
    587             'Cannot run the event loop while another loop is running')

RuntimeError: This event loop is already running
</code>```

Could you help me understand where I am getting it wrong and/or where I should change my approach for the problem?

Body:
I am trying to develop an application consisting of a Server and a bunch of Clients that should work like this:

each Client itself will listen to an independent websocket consisting of some information

they will then process this information and redirect the processed message to the Server

the Server will do some processing (send some information trhough another websocket and wait for response)

once the Server gets the response, it will redirect it to the Client

Since it consists of asynchronous responses and communication between classes my first idea was to use the combo RxPy + asyncio. Here is a toy model of my problema that I tryied to develop:

Here is the Server:

import reactivex as rx
import random

import reactivex.operators as ops

class Server:
    def __init__(self, clients):
        self.clients = clients
        self.stream = rx.Subject()

    def info(self, msg):
        print(msg)

    async def start(self, loop):

        done = asyncio.Future()

        def on_completed():
            done.set_result(True)

        async def react(item):
            msg = {'alias': 'server', 'action': 'received', 'from': item['alias'], 'request': item['request']}
            self.info(msg)

            await asyncio.sleep(random.randint(1,3))

            response = {'alias': 'server', 'action': 'send', 'request': msg['request'] ** 2}
            self.info(response)
            self.stream.on_next(response)

        client_listener = rx.empty()
        for client in self.clients:
            client_listener= rx.merge(client_listener, client.stream(self.stream, loop))

        client_listener.subscribe(
            on_next = lambda x: react(x),
            on_error = print,
            on_completed = print('completed server')
        )

        await done

Here is the Client:

import reactivex.operators as ops

class Client:
    def __init__(self, alias):
        self.alias = alias

    def info(self, msg):
        print(msg)

    def stream(self, controller, loop):

        def on_subscribe(observer, scheduler):

            for i in range(10):
                msg = {'alias': self.alias, 'action': 'send', 'request': i}
                self.info(msg)
                observer.on_next(msg)
            loop.call_soon(observer.on_completed())

        controller.subscribe(
            on_next = lambda msg: self.info({'alias': self.alias, 'action': 'received', 'from': msg['alias'], 'request': msg['request']})
        )

        return rx.create(on_subscribe)

And here is how I am trying to run it:

import asyncio

loop = asyncio.get_event_loop()

client_1 = Client('client_1')
client_2 = Client('client_2')

loop.run_until_complete(Server([client_1, client_2]).start(loop=loop))
loop.close()

When I try executing the above code I get the followin:

RuntimeError                              Traceback (most recent call last)
Cell In[3], line 8
      5 client_1 = Client('client_1')
      6 client_2 = Client('client_2')
----> 8 loop.run_until_complete(Server([client_1, client_2]).start(loop=loop))
      9 loop.close()

File ~\Anaconda3\envs\nfs_hom\lib\asyncio\base_events.py:625, in BaseEventLoop.run_until_complete(self, future)
    614 """Run until the Future is done.
    615
    616 If the argument is a coroutine, it is wrapped in a Task.
   (...)
    622 Return the Future's result, or raise its exception.
    623 """
    624 self._check_closed()
--> 625 self._check_running()
    627 new_task = not futures.isfuture(future)
    628 future = tasks.ensure_future(future, loop=self)

File ~\Anaconda3\envs\nfs_hom\lib\asyncio\base_events.py:584, in BaseEventLoop._check_running(self)
    582 def _check_running(self):
    583     if self.is_running():
--> 584         raise RuntimeError('This event loop is already running')
    585     if events._get_running_loop() is not None:
    586         raise RuntimeError(
    587             'Cannot run the event loop while another loop is running')

RuntimeError: This event loop is already running

Could you help me understand where I am getting it wrong and/or where I should change my approach for the problem?


问:
Why do list comprehensions and lists generated from multiplication have different element assignments?
```<code>nums = [1,1,1,2,2,0,3]

lst1 = [[]] * (len(nums) + 1)
lst2 = [[] for i in range(len(nums) + 1)]

print(lst1)        #[[], [], [], [], [], [], [], []]
print(lst2)        #[[], [], [], [], [], [], [], []]

lst1[3].append(2)
lst2[3].append(2)

print(lst1)        #[[2], [2], [2], [2], [2], [2], [2], [2]]
print(lst2)        #[[], [], [], [2], [], [], [], []]
</code>```

Why does lst1 append the element everywhere? Is it because only one empty list is created and is shared by reference? Why would that even be useful?

Body:
nums = [1,1,1,2,2,0,3]

lst1 = [[]] * (len(nums) + 1)
lst2 = [[] for i in range(len(nums) + 1)]

print(lst1)        #[[], [], [], [], [], [], [], []]
print(lst2)        #[[], [], [], [], [], [], [], []]

lst1[3].append(2)
lst2[3].append(2)

print(lst1)        #[[2], [2], [2], [2], [2], [2], [2], [2]]
print(lst2)        #[[], [], [], [2], [], [], [], []]

Why does lst1 append the element everywhere? Is it because only one empty list is created and is shared by reference? Why would that even be useful?


问:
how to handle Recoverable errors while using REST APIs
My app's upsteram is kafka and it is connected to downstream component via REST api , now incase of 500 series error while using REST API what are the different methods we can use to recover affected events?

Currently I am thinking to have a file based solution where I will be storing those affected messages and an asynchronous thread which will retry publishing those events in a fibonacci time manner.

Any other suggestion please tell . My app is hosted on multiple VMs and running in load balancing mode.

Thanks


问:
An attempt was made to access a socket in a way forbidden by its access permissions - Flask in VSCode
I am working on a simple flask app using visual studio using a Windows 10 Home. Occasionally when I try to run using the 'flask run', I get the error message:

An attempt was made to access a socket in a way forbidden by its access permissions

I have observed that this happens sometimes and seems to correct itself randomly in the past

Right now, I am stuck as the error will not go away.

I do not know what is causing this issue or what to do

I have tried a number of ideas I found on stack overflow but I still have the same problem. I have:

Restarted the computer

Set startup type to 'disabled' in Internet Connection Sharing Properties

Temporarily disabling Windows Defender

Started VSCode as Administrator


问:
Escape a from User targeted Cell in Excel
With Python and win32com lib i write data in a continuously running excel workbook. Once in a while it needs to do some edit "by hand". When I forgot to jump out of the cell and the cursor is still blinking inside, the Python Script stop working with this error:

```<code>\lib\site-packages\win32com\client\gencache.py", line 541, in EnsureDispatch
raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
</code>```

for causing that error it just needs the "Standard" lines and any cell
edit.
Example:

```<code>import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(r'C:\Users\Patrick\Desktop\PyWin32.xlsx')
ws = wb.Worksheets("Tabelle1")

ws.Cells(2, 2).Value = 123
</code>```

Is there a way to detect this matter by Python and let it get the cursor out?

Body:
With Python and win32com lib i write data in a continuously running excel workbook. Once in a while it needs to do some edit "by hand". When I forgot to jump out of the cell and the cursor is still blinking inside, the Python Script stop working with this error:

\lib\site-packages\win32com\client\gencache.py", line 541, in EnsureDispatch
raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object

for causing that error it just needs the "Standard" lines and any cell
edit.
Example:

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(r'C:\Users\Patrick\Desktop\PyWin32.xlsx')
ws = wb.Worksheets("Tabelle1")

ws.Cells(2, 2).Value = 123

Is there a way to detect this matter by Python and let it get the cursor out?


问:
Create array of python class objects from objects in json file in Python
I have a json file like this ('./serverApi/comuni.json' is the json file)

```<code>[
  {
    "nome": "Abano Terme",
    "codice": "028001",
    "zona": { "codice": "2", "nome": "Nord-est" },
    "regione": { "codice": "05", "nome": "Veneto" },
    "provincia": { "codice": "028", "nome": "Padova" },
    "sigla": "PD",
    "codiceCatastale": "A001",
    "cap": ["35031"],
    "popolazione": 19349
  },
  {
    "nome": "Abbadia Cerreto",
    "codice": "098001",
    "zona": { "codice": "1", "nome": "Nord-ovest" },
    "regione": { "codice": "03", "nome": "Lombardia" },
    "provincia": { "codice": "098", "nome": "Lodi" },
    "sigla": "LO",
    "codiceCatastale": "A004",
    "cap": ["26834"],
    "popolazione": 297
  }, {and so on}
]
</code>```

I need to turn it into an object array with some of the properties through a python class. This is my attempt, something is clearly missing, hope you can help

```<code>import json

class Comune:
    def __init__(self, nome: str, provincia: object, regione: str):
            self.nome = nome
            self.provincia = provincia
            self.regione = regione

    def __repr__(self):
        return json.dumps({
          "nome":self.nome,
          "provincia":self.provincia,
          "regione":self.regione
        })

    @staticmethod
    def comuni_decoder(obj):
        return Comune(obj['nome'], obj['provincia']['nome'], obj['regione']['nome'])

with open('./serverApi/comuni.json', 'r', encoding="utf-8") as c:
    comuni_pre = json.load(c, object_hook=Comune.comuni_decoder)
    #comuni_post = [vars(c) for c in comuni_pre]

#print(comuni_pre)
</code>```

I keep receiving this error:

```<code>return Comune(obj['nome'], obj['provincia']['nome'], obj['regione']['nome'])
                               ~~~^^^^^^^^^^^^^
KeyError: 'provincia'
</code>```

EDIT: I've found a solution but I don't know if it is the best possibile

```<code>import json

class Comune:
    def __init__(self, nome, provincia, regione):
        self.nome = nome
        self.provincia = provincia
        self.regione = regione

    def __repr__(self):
        return json.dumps({"nome":self.nome, "provincia":self.provincia, "regione":self.regione}, indent=4)

with open("./serverApi/comuni.json") as json_file:
    data = json.load(json_file)

comuni = []

for comune in data:
    nome = comune["nome"]
    provincia = comune["provincia"]["nome"]
    regione = comune["regione"]["nome"]
    comuni.append(Comune(nome, provincia, regione))

comuni2 = [vars(c) for c in comuni]
</code>```

"comuni2" is what I need to be able to work properly with a list, is there a better solution?

Body:
I have a json file like this ('./serverApi/comuni.json' is the json file)

[
  {
    "nome": "Abano Terme",
    "codice": "028001",
    "zona": { "codice": "2", "nome": "Nord-est" },
    "regione": { "codice": "05", "nome": "Veneto" },
    "provincia": { "codice": "028", "nome": "Padova" },
    "sigla": "PD",
    "codiceCatastale": "A001",
    "cap": ["35031"],
    "popolazione": 19349
  },
  {
    "nome": "Abbadia Cerreto",
    "codice": "098001",
    "zona": { "codice": "1", "nome": "Nord-ovest" },
    "regione": { "codice": "03", "nome": "Lombardia" },
    "provincia": { "codice": "098", "nome": "Lodi" },
    "sigla": "LO",
    "codiceCatastale": "A004",
    "cap": ["26834"],
    "popolazione": 297
  }, {and so on}
]

I need to turn it into an object array with some of the properties through a python class. This is my attempt, something is clearly missing, hope you can help

import json

class Comune:
    def __init__(self, nome: str, provincia: object, regione: str):
            self.nome = nome
            self.provincia = provincia
            self.regione = regione

    def __repr__(self):
        return json.dumps({
          "nome":self.nome,
          "provincia":self.provincia,
          "regione":self.regione
        })

    @staticmethod
    def comuni_decoder(obj):
        return Comune(obj['nome'], obj['provincia']['nome'], obj['regione']['nome'])

with open('./serverApi/comuni.json', 'r', encoding="utf-8") as c:
    comuni_pre = json.load(c, object_hook=Comune.comuni_decoder)
    #comuni_post = [vars(c) for c in comuni_pre]

#print(comuni_pre)

I keep receiving this error:

return Comune(obj['nome'], obj['provincia']['nome'], obj['regione']['nome'])
                               ~~~^^^^^^^^^^^^^
KeyError: 'provincia'

EDIT: I've found a solution but I don't know if it is the best possibile

import json

class Comune:
    def __init__(self, nome, provincia, regione):
        self.nome = nome
        self.provincia = provincia
        self.regione = regione

    def __repr__(self):
        return json.dumps({"nome":self.nome, "provincia":self.provincia, "regione":self.regione}, indent=4)

with open("./serverApi/comuni.json") as json_file:
    data = json.load(json_file)

comuni = []

for comune in data:
    nome = comune["nome"]
    provincia = comune["provincia"]["nome"]
    regione = comune["regione"]["nome"]
    comuni.append(Comune(nome, provincia, regione))

comuni2 = [vars(c) for c in comuni]

"comuni2" is what I need to be able to work properly with a list, is there a better solution?


问:
Prevent Tom-Select from removing select options with duplicate values
https://jsfiddle.net/8drp9xu2/4/

```<code><select id="tom-select-example" autocomplete="off">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="3">Option that Tom Select removes</option>
  </select>
</code>```

This example above should summarize my issue. I want to keep options with matching/duplicate values, but Tom-Select appears to remove those by default. This seems like a simple solution that I'm just not seeing, is there an option to prevent Tom-Select from removing duplicate values?

Tried the 'hideSelected' and 'duplicates' options. I don't think they are related to my issue. Not finding anything that prevents Tom-Select from removing options that have different names but same values.

Body:
https://jsfiddle.net/8drp9xu2/4/

<select id="tom-select-example" autocomplete="off">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="3">Option that Tom Select removes</option>
  </select>

This example above should summarize my issue. I want to keep options with matching/duplicate values, but Tom-Select appears to remove those by default. This seems like a simple solution that I'm just not seeing, is there an option to prevent Tom-Select from removing duplicate values?

Tried the 'hideSelected' and 'duplicates' options. I don't think they are related to my issue. Not finding anything that prevents Tom-Select from removing options that have different names but same values.


问:
Read html tags in Freemarker inside Word (docx) template, received from Java
I have a problem with docx template not recognizing html tags like . I can read simple parameters, object parameters and iterate over them, but I have problem with parsing these damn tags...

Problem:
I have a String in Java App, for example: "This is example of string". I am sending this String to Freemarker template in Word (docx). Now I except, that when I will genrate raport using this templete, I will receive:

This is example of string

Instead I am receiving:

```<code>This is <b>example</b> of string
</code>```

I did some research and it looks like Word doesn't supply html tagging, nor other tagging. What I already tried was for example wrapping into [#escape x as x?html][/#escape] or using different tags like , < bold> and so on. I was looking also inside a docx structure, where I found that there are tags like <w:t>,<w:r> and tried to wrap those inside Java String, but result was the same. Partially workaround was using key:value LinkedHashMap where i printed key as a normal font, and value was bolded inside Word. It was ok until I came across double for loop (key is also esencial to print out in raport, so I can't artificially create random key). I would be very grateful for any tips how to achieve my goal because I'm out of ideas;)

PS: I tried also write some kind of instruction in JavaScript inside docx template, but it never worked out, perhaps it is becasuse I am not used to js;x

Body:
I have a problem with docx template not recognizing html tags like . I can read simple parameters, object parameters and iterate over them, but I have problem with parsing these damn tags...

Problem:
I have a String in Java App, for example: "This is example of string". I am sending this String to Freemarker template in Word (docx). Now I except, that when I will genrate raport using this templete, I will receive:

This is example of string

Instead I am receiving:

This is example of string

I did some research and it looks like Word doesn't supply html tagging, nor other tagging. What I already tried was for example wrapping into [#escape x as x?html][/#escape] or using different tags like , < bold> and so on. I was looking also inside a docx structure, where I found that there are tags like <w:t>,<w:r> and tried to wrap those inside Java String, but result was the same. Partially workaround was using key:value LinkedHashMap where i printed key as a normal font, and value was bolded inside Word. It was ok until I came across double for loop (key is also esencial to print out in raport, so I can't artificially create random key). I would be very grateful for any tips how to achieve my goal because I'm out of ideas;)

PS: I tried also write some kind of instruction in JavaScript inside docx template, but it never worked out, perhaps it is becasuse I am not used to js;x


问:
How to print from a blob returned from a google drive URL
I am trying to print a pdf file that is being returned from google drive URL and i am getting a blob object. I just want print not show the document.
This is the code

```<code>import React, {
    useState,
    useEffect,
    useRef
} from 'react';
import ReactToPrint from 'react-to-print';
import axios from 'axios';

export default function App() {

    const onButtonClick = () => {
        const url =
                'https://www.googleapis.com/drive/v3/files/1UrNAOCZ2XJOYqonHixbiSURCxRDwW6q3?alt=media';
                // 'https://drive.google.com/u/1/uc?id=1UrNAOCZ2XJOYqonHixbiSURCxRDwW6q3&export=download'
        axios.get(url, {
            headers: {
                Authorization:
                    'Bearer ya29.a0AX9GBdUTREkuCHO-leYJOphq-5S0KLMFyqtFatlGkJ2hSyK7xuOoRfl5aWyfCLOfVwdfFO3bCoNJduaKY7fenb_TSEjHV5C4EGWW_6B6v8RhAwfOFNnpcvo5R5isFrw8_OrWqDJd_sWJCU0dL4SHdU5owy5jIvAaCgYKAR0SARISFQHUCsbCORo9OVB6FGBTSWK54ZgFhA0166'
            }
        })
        .then(response => {
            let blob = new Blob([response], {type:'application/pdf'})
            console.log(blob)
            const fileURL = window.URL.createObjectURL(blob);
            console.log(fileURL)
            window.open(fileURL, '_blank');
            window.print()
        })
        .catch(err => {
            console.log(err)
        })

    }

    return (

        <>
        <center>
            <h1>Welcome to Geeks for Geeks</h1>
            <h3>Click on below button to Print PDF file</h3>
            <button onClick={onButtonClick}>
                Print PDF
            </button>
        </center>
    </>
    );

}

</code>```

this is the console

But i geitting my index page as print instead of the actual file

This is the network call

So I am getting the blob just cant print it. Help Please

Body:
I am trying to print a pdf file that is being returned from google drive URL and i am getting a blob object. I just want print not show the document.
This is the code

import React, {
    useState,
    useEffect,
    useRef
} from 'react';
import ReactToPrint from 'react-to-print';
import axios from 'axios';

export default function App() {

    const onButtonClick = () => {
        const url =
                'https://www.googleapis.com/drive/v3/files/1UrNAOCZ2XJOYqonHixbiSURCxRDwW6q3?alt=media';
                // 'https://drive.google.com/u/1/uc?id=1UrNAOCZ2XJOYqonHixbiSURCxRDwW6q3&export=download'
        axios.get(url, {
            headers: {
                Authorization:
                    'Bearer ya29.a0AX9GBdUTREkuCHO-leYJOphq-5S0KLMFyqtFatlGkJ2hSyK7xuOoRfl5aWyfCLOfVwdfFO3bCoNJduaKY7fenb_TSEjHV5C4EGWW_6B6v8RhAwfOFNnpcvo5R5isFrw8_OrWqDJd_sWJCU0dL4SHdU5owy5jIvAaCgYKAR0SARISFQHUCsbCORo9OVB6FGBTSWK54ZgFhA0166'
            }
        })
        .then(response => {
            let blob = new Blob([response], {type:'application/pdf'})
            console.log(blob)
            const fileURL = window.URL.createObjectURL(blob);
            console.log(fileURL)
            window.open(fileURL, '_blank');
            window.print()
        })
        .catch(err => {
            console.log(err)
        })

    }

    return (

        <>

Welcome to Geeks for Geeks

Click on below button to Print PDF file

            <button onClick={onButtonClick}>
                Print PDF
            </button>

    </>
    );

}

this is the console

But i geitting my index page as print instead of the actual file

This is the network call

So I am getting the blob just cant print it. Help Please


问:
Updated state not displaying in React
I have an application that adds team members to a business but am having trouble showing the new members when added. The app verifies the user exist on the backend and grabs all of their data when they are added. I can see that the members info has been added to the local state but it will not display it until I do a full refresh of the page. I've even tried updating the state using useEffect but nothing is working.

Add Team Member Component:

```<code>import React, {useState} from 'react';
import {addTeamMember} from "../../../../redux/actions/business";

function BusinessPageMembers (props) {

const [allMembers, setAllMembers] = useState([]);

useEffect(() => {
    setAllMembers(props?.business?.all_team_members)
},[props.business])

const addMember = () => {
    const user = email
    const profile = email
    const business = props.business.business_page.business
    const member_details = { roll, title, user, profile, business }
    props.addTeamMember(member_details)
    }

const Members = allMembers.map(members => (
    <div key={members.id}>
        <div>
             <Link className='team-member-name' to={`/profile/${members.slug}`}>{[members.first_name, ' ', members.last_name]}</Link>
             <h5>{members.email}</h5>
             <h6>{members.roll}</h6>
             <h6>{members.title}</h6>
         </div>))

return (
         <div>
                {Members}
         </div>

    );
}

function mapStateToProps(state) {
return {
    business: state.business,
};
 }

  export default connect(mapStateToProps, {addTeamMember})(BusinessPageMembers);
</code>```

Add Team Member Redux Action:

```<code>import axios from 'axios'
import {ADDING_TEAM_MEMBER,TEAM_MEMBER_ADDED,} from "./types";

export const addTeamMember = (member_details) => (dispatch) => {
   dispatch({ type: ADDING_TEAM_MEMBER })
   axios.post('/api/team-member/add/', member_details)
    .then(res => {
        dispatch ({
            type: TEAM_MEMBER_ADDED,
            payload: res.data
        })
    }).catch(err => dispatch(returnErrors(err.response.data, err.response.status)))
}
</code>```

Add Team Member Redux Reducer:

```<code>import {TEAM_MEMBER_ADDED, ADDING_TEAM_MEMBER} from "../actions/types";

const initialState = {
all_team_members: [],
adding_member: false,
}

export default function (state = initialState, action) {
switch (action.type) {
    case ADDING_TEAM_MEMBER:
        return {
            ...state,
            adding_member: true
        }
    case TEAM_MEMBER_ADDED:
        return {
            ...state,
            all_team_members: [...state.all_team_members, action.payload],
            adding_member: false
        }
    case ALL_TEAM_MEMBERS:
        return {
            ...state,
            all_team_members: action.payload,
        }
    default:
        return state
}
}
</code>```

Page right after you hit add member

The new member has been added to the new state but not being displayed

The page after doing a complete refresh

Thank you so much :)

Title: Updated state not displaying in React

Body:
I have an application that adds team members to a business but am having trouble showing the new members when added. The app verifies the user exist on the backend and grabs all of their data when they are added. I can see that the members info has been added to the local state but it will not display it until I do a full refresh of the page. I've even tried updating the state using useEffect but nothing is working.

Add Team Member Component:

import React, {useState} from 'react';
import {addTeamMember} from "../../../../redux/actions/business";

function BusinessPageMembers (props) {

const [allMembers, setAllMembers] = useState([]);

useEffect(() => {
    setAllMembers(props?.business?.all_team_members)
},[props.business])

const addMember = () => {
    const user = email
    const profile = email
    const business = props.business.business_page.business
    const member_details = { roll, title, user, profile, business }
    props.addTeamMember(member_details)
    }

const Members = allMembers.map(members => (

             <Link className='team-member-name' to={`/profile/${members.slug}`}>{[members.first_name, ' ', members.last_name]}</Link>

{members.email}

{members.roll}

{members.title}

))

return (

                {Members}

    );
}

function mapStateToProps(state) {
return {
    business: state.business,
};
 }

  export default connect(mapStateToProps, {addTeamMember})(BusinessPageMembers);

Add Team Member Redux Action:

import axios from 'axios'
import {ADDING_TEAM_MEMBER,TEAM_MEMBER_ADDED,} from "./types";

export const addTeamMember = (member_details) => (dispatch) => {
   dispatch({ type: ADDING_TEAM_MEMBER })
   axios.post('/api/team-member/add/', member_details)
    .then(res => {
        dispatch ({
            type: TEAM_MEMBER_ADDED,
            payload: res.data
        })
    }).catch(err => dispatch(returnErrors(err.response.data, err.response.status)))
}

Add Team Member Redux Reducer:

import {TEAM_MEMBER_ADDED, ADDING_TEAM_MEMBER} from "../actions/types";

const initialState = {
all_team_members: [],
adding_member: false,
}

export default function (state = initialState, action) {
switch (action.type) {
    case ADDING_TEAM_MEMBER:
        return {
            ...state,
            adding_member: true
        }
    case TEAM_MEMBER_ADDED:
        return {
            ...state,
            all_team_members: [...state.all_team_members, action.payload],
            adding_member: false
        }
    case ALL_TEAM_MEMBERS:
        return {
            ...state,
            all_team_members: action.payload,
        }
    default:
        return state
}
}

Page right after you hit add member

The new member has been added to the new state but not being displayed

The page after doing a complete refresh

Thank you so much :)


问:
how can I run functions by sequential in firebase request to get one single completion
Actually, this is not a complex logic but I'm confused a little bit.

I'm getting user IDs from collection called "following" on my firebase (firestore) and adding an array, and then I'm getting posts those users from another collection called "posts" with "fetchPosts" func. At the end, I'm putting these posts to an array and sending via completion handler. This is what I want.

However I need use closures and functions for this. When I use this functions these are not running sequential so completion is returning empty value.

I tried DispatchQueue group logic (enter, leave etc.), OperationQueues but I couldn't find a solution. maybe I couldn't use right way I'm not sure so I'm open different mindset and algorithm logic.

I want to run following functions sequential.

part 1 > part 2 > part 3 > part 4 and then part 5 (completion)

I mean e.g. I want to run part 3 after part 1 and part 2 are finished. I want to run completion after all of them finished. But it is working like this now:

part 1 > part 1 > part 5 > part 2 > part 2 . . .

If I put these functions in each other, it returns more than one completion. I don't want it because I will use pagination logic after solving this issue.

I understand that this is about threading but I couldn't handle it. How can I run this parts sequential.

This is my code:

```<code>guard let cuid = Auth.auth().currentUser?.uid as? String else { return }

let firestoreDatabase = Firestore.firestore()

firestoreDatabase.collection("following").document(cuid).getDocument(source: .server) { document, error in

    if let document = document, document.exists {

        guard let userIdsDictionary = document.data() as? [String : Int] else {return}

        // part 1
        userIdsDictionary.forEach { (key, value) in

            self.getUsername(uid: key) { uName in

                // part 2
                self.userNamesDictFollowingVC.append(uName)
            }
        }

        // part 3
        self.userNamesDictFollowingVC.forEach { uName in

            self.fetchPosts(username: uName) { postList in

                // part 4
                self.postList.append(contentsOf: postList)
            }
        }

        // part 5 (the last one)
        completion(self.postList)
    }
}
</code>```

Body:
Actually, this is not a complex logic but I'm confused a little bit.

I'm getting user IDs from collection called "following" on my firebase (firestore) and adding an array, and then I'm getting posts those users from another collection called "posts" with "fetchPosts" func. At the end, I'm putting these posts to an array and sending via completion handler. This is what I want.

However I need use closures and functions for this. When I use this functions these are not running sequential so completion is returning empty value.

I tried DispatchQueue group logic (enter, leave etc.), OperationQueues but I couldn't find a solution. maybe I couldn't use right way I'm not sure so I'm open different mindset and algorithm logic.

I want to run following functions sequential.

part 1 > part 2 > part 3 > part 4 and then part 5 (completion)

I mean e.g. I want to run part 3 after part 1 and part 2 are finished. I want to run completion after all of them finished. But it is working like this now:

part 1 > part 1 > part 5 > part 2 > part 2 . . .

If I put these functions in each other, it returns more than one completion. I don't want it because I will use pagination logic after solving this issue.

I understand that this is about threading but I couldn't handle it. How can I run this parts sequential.

This is my code:

guard let cuid = Auth.auth().currentUser?.uid as? String else { return }

let firestoreDatabase = Firestore.firestore()

firestoreDatabase.collection("following").document(cuid).getDocument(source: .server) { document, error in

    if let document = document, document.exists {

        guard let userIdsDictionary = document.data() as? [String : Int] else {return}

        // part 1
        userIdsDictionary.forEach { (key, value) in

            self.getUsername(uid: key) { uName in

                // part 2
                self.userNamesDictFollowingVC.append(uName)
            }
        }

        // part 3
        self.userNamesDictFollowingVC.forEach { uName in

            self.fetchPosts(username: uName) { postList in

                // part 4
                self.postList.append(contentsOf: postList)
            }
        }

        // part 5 (the last one)
        completion(self.postList)
    }
}


问:
NiFi - ListS3 listing files with exact path but different dates
I have to list and collect several specific files on a S3 bucket from different dates.
The path looks like the following:
/path/to/20221201/files/specificfile/
/path/to/20221202/files/specificfile/
The "files" and "specificfile" folders contain several different files, where I am only interest in a specific one from each.

I tried changing the date with * thinking it would list any date, but I get no result.
Any suggestions?
Thanks


问:
Android Espresso Configure Shards by Class
For Android Espresso Testing, i'm using the following commands to run our tests:

```<code>    ./gradlew pixel4api30DebugAndroidTest
-Pandroid.testInstrumentationRunnerArguments.class=com.aaa.bbb.ccc.Suites.TestSuite
-Pandroid.experimental.androidTest.numManagedDeviceShards=2
</code>```

This splits all the tests in the TestSuites across 2 pixel 4 emulators.

If I have the following in the TestSuite:

TestClass1

Test1

Test2

Test3

TestClass2

Test1

Test2

Test3

It may run TestClass1.Test1 on 1 emulator and TestClass1.Test2 on emulator 2.  (it could pick any emulator to run any of the tests on).

Is there a way to force it to split the shards by TestClasses?  So it will run TestClass1 and all tests on one emulator, TestClass2 and all tests on an emulator.

I believe if you have used Spoon in the past, you may have been able to accomplish this by using singleInstrumentationCall property as noted here: https://github.com/jaredsburrows/gradle-spoon-plugin

Body:
For Android Espresso Testing, i'm using the following commands to run our tests:

    ./gradlew pixel4api30DebugAndroidTest
-Pandroid.testInstrumentationRunnerArguments.class=com.aaa.bbb.ccc.Suites.TestSuite
-Pandroid.experimental.androidTest.numManagedDeviceShards=2

This splits all the tests in the TestSuites across 2 pixel 4 emulators.

If I have the following in the TestSuite:

TestClass1

Test1

Test2

Test3

TestClass2

Test1

Test2

Test3

It may run TestClass1.Test1 on 1 emulator and TestClass1.Test2 on emulator 2.  (it could pick any emulator to run any of the tests on).

Is there a way to force it to split the shards by TestClasses?  So it will run TestClass1 and all tests on one emulator, TestClass2 and all tests on an emulator.

I believe if you have used Spoon in the past, you may have been able to accomplish this by using singleInstrumentationCall property as noted here: https://github.com/jaredsburrows/gradle-spoon-plugin


问:
How to fix an attribute error on a saved model
I have my model saved as a numpy array. I am trying to pickle the model to run predictions on a new dataset. However I keep running into an attribute error.

model = y_pred_binary

filename = 'transfer_prediction_model.pkl'

pickle.dump(model, open(filename, 'wb'))
ickled_model = pickle.load(open(filename, 'rb'))
df = pd.read_csv(f"transfer_students_prediction_dataset.csv")
predictions = pickled_model.predict(df.drop('on_time_graduation', axis = 1))
print(predictions)
```
```AttributeError                            Traceback (most recent call last)
Input In [24], in <cell line: 3>()
      `1 pickled_model = pickle.load(open(filename, 'rb'))
      2 df = pd.read_csv(f"transfer_students_prediction_dataset.csv")
----> 3 predictions = pickled_model.predict(df.drop('on_time_graduation', axis = 1))
      4 print(predictions)`

AttributeError: 'numpy.ndarray' object has no attribute 'predict'`
```

I have tried using other methods such as joblib or fitting the model using sklearn but I still run into the same problem.

Body:
I have my model saved as a numpy array. I am trying to pickle the model to run predictions on a new dataset. However I keep running into an attribute error.

model = y_pred_binary

filename = 'transfer_prediction_model.pkl'

pickle.dump(model, open(filename, 'wb'))
ickled_model = pickle.load(open(filename, 'rb'))
df = pd.read_csv(f"transfer_students_prediction_dataset.csv")
predictions = pickled_model.predict(df.drop('on_time_graduation', axis = 1))
print(predictions)

AttributeError                            Traceback (most recent call last)
Input In [24], in <cell line: 3>()
      `1 pickled_model = pickle.load(open(filename, 'rb'))
      2 df = pd.read_csv(f"transfer_students_prediction_dataset.csv")
----> 3 predictions = pickled_model.predict(df.drop('on_time_graduation', axis = 1))
      4 print(predictions)`

AttributeError: 'numpy.ndarray' object has no attribute 'predict'`

I have tried using other methods such as joblib or fitting the model using sklearn but I still run into the same problem.


问:
Pathlib list splitting by character instead of full path
I've written a script that accepts a .txt containing a filename manifest from the user, generates a list using pathlib of files in a directory on the user's computer, compares the lists, and spits out another list of files not found from the user's text file. It seems to work fine, but when I reverse the operation to generate a list of files found by pathlib that are not in the user's manifest, I'm hitting a snag. My code looks like this:

```<code>from pathlib import Path

fileList = open("fileList.txt", "r")
data = fileList.read()
fileList_reformatted = data.replace('\n', '').split(",")
print(fileList_reformatted)

p = Path('C:/Users/Common/Downloads/compare/').rglob('*')
filePaths = [x for x in p if x.is_file()]
filePaths_string = str(filePaths)
filePaths_reformatted = filePaths_string.replace('WindowsPath(','').replace('(','').replace(')','').replace('\n','')
filePaths_reformatted.split(",")
print(filePaths_reformatted)

differences1 = []
for element in fileList_reformatted:
    if element not in filePaths_reformatted:
        differences1.append(element)

print("The following files from the manifest were not found:",differences1)

differences2 = []
for element in filePaths_reformatted:
    if element not in fileList_reformatted:
        differences2.append(element)

print("The following unexpected files were found:",differences2)
</code>```

The final operation produces a list of each character in the path one at a time, instead of the full filepath. What am I doing wrong here? Thanks so much.

Body:
I've written a script that accepts a .txt containing a filename manifest from the user, generates a list using pathlib of files in a directory on the user's computer, compares the lists, and spits out another list of files not found from the user's text file. It seems to work fine, but when I reverse the operation to generate a list of files found by pathlib that are not in the user's manifest, I'm hitting a snag. My code looks like this:

from pathlib import Path

fileList = open("fileList.txt", "r")
data = fileList.read()
fileList_reformatted = data.replace('\n', '').split(",")
print(fileList_reformatted)

p = Path('C:/Users/Common/Downloads/compare/').rglob('*')
filePaths = [x for x in p if x.is_file()]
filePaths_string = str(filePaths)
filePaths_reformatted = filePaths_string.replace('WindowsPath(','').replace('(','').replace(')','').replace('\n','')
filePaths_reformatted.split(",")
print(filePaths_reformatted)

differences1 = []
for element in fileList_reformatted:
    if element not in filePaths_reformatted:
        differences1.append(element)

print("The following files from the manifest were not found:",differences1)

differences2 = []
for element in filePaths_reformatted:
    if element not in fileList_reformatted:
        differences2.append(element)

print("The following unexpected files were found:",differences2)

The final operation produces a list of each character in the path one at a time, instead of the full filepath. What am I doing wrong here? Thanks so much.