问:
React native share modules configuration via git between apps
I have react-native two apps that share several modules such as react-native-ble-plx which require changes to AndroidManifest and Podfile and other files in the /android and /ios folder. For example in Android Manifest the permissions need to be configured properly.

I share the javascript code via an npm module, however the app configurations I currently update manually per each app. Part of the configuration will be the same, but each app may have further modules installed.
As I will need to create more applications with same basic modules, this way of sharing will likely become cumbersome when updates are required.

Is there a reasonable way to share these configurations via git (or some other tool)?


来源: stackexchange

问:
Why does UPPER() in WHERE condition return result in upper-case when accessed via VIEW & GROUP_CONCAT in MySQL 8; MySQL 5 works as expected
I want to understand the following situation:

I have a VIEW that selects data utilizing (among others) GROUP_CONCAT. When I select data from that VIEW using UPPER on the concatted content in my WHERE clause, MySQL 8 returns those values in upper case, while MySQL 5 returns those (correctly) how they where stored.

When I cast the concatted content as CHAR, MySQL 8 returns those values correctly again.

I've prepared a DB Fiddle link which demonstrates this behaviour: (External) DB Fiddle Link

Thank you in advance for any explanation.

ContentLicense: CC BY-SA 4.0


问:
Windows command line - incorrect formatting
I am trying to read data in memory from emulated Android device. I am using tools  Frida and Objections in Windows command line. When I try to search for some string in memory, I will get this

instead of something like

Is it possible to display it correctly in Windows command line, or not?


问:
Why my modal doesn't render correct event information after updating any event on fullcalendar
I'm using Fullcalendar Js (5.6) and laravel lilvewire on a laravel application (8.75).

I create a calendar and display some events on it. I make a modal which opened when I click on an event. This modal contains a form with filled inputs with event informations.

Here it's how I render the form with filled inputs :

eventClick: info => {

  info.jsEvent.preventDefault();

  let modal = document.getElementById('modal')

  let deleteBtn = modal.querySelector('#delete')

  if(deleteBtn.hasAttribute('hidden')) {
    deleteBtn.removeAttribute('hidden')
  }

  if(info.event.extendedProps.report) {
    deleteBtn.setAttribute('disabled', '')
  } else {
    deleteBtn.removeAttribute('disabled')
  }

  modal.querySelector('#modal-title').innerText = 'Modify an event'

  modal.querySelector('input[id="title"]').setAttribute('value', info.event.title)

  if(info.event.extendedProps.description != null) {

    modal.querySelector('input[id="description"]').setAttribute('value', info.event.extendedProps.description)
  }

  modal.querySelector('input[id="start"]').setAttribute('value', (new Date((info.event.start).toString().split('GMT')[0]+' UTC').toISOString()).substr(0,23))

  if(info.event.allDay) {

    modal.querySelector('input[id="allDay"]').setAttribute('checked', true)
  }

}
```
<p>When I submit my form to update the title for example ("newTitle"), I can see changes on the calendar view but if I clicked again on the event I've changed, title input is empty (other datas are correct and well displayed on the inputs). If I clicked on another event that is not modified I have the same issue, empty title and other datas correct and well displayed.</p>
<p>I logged :</p>
<ul>
<li>infos.event.title</li>
</ul>
<p>-> result : <code>newTitle</code>
-> The new title is correct on the event informations</p>
<ul>
<li>modal.querySelector('input[id="title"]')</li>
</ul>
<p>-> result : <code><input id="title" type="text" value="newTitle"></code>
-> The DOM input element has the correct value</p>
<ul>
<li>modal.querySelector('input[id="title"]').value.length</li>
</ul>
<p>-> result : <code>0</code>
-> It's weird that the length of value is zero??</p>
<p>It was an example with title but I have the same weird behavior with the other inputs if I modify them.</p>
<p>Here is my Calendar component where I get events :</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Event;
use App\Models\Client;
use Illuminate\Support\Arr;

class Calendar extends Component
{
    public $events = [];
    public $clients = [];

    public function mount($events)
    {
        $this->events = json_encode($events);
    }

    public function render()
    {
        return view('livewire.calendar');
    }

    public function eventUpdate($event)
    {
        $e = Event::find($event['id']);
        $e->title = $event['title'];
        $e->description = $event['description'];
        $e->start = $event['start'];
        $e->end = $event['end'];
        $e->allDay = $event['allDay'];

        if($e->isDirty()) {
            $e->update($event);
        }
    }
}

</code>```

I've already try to get the events on the render method and call @this.render() after submitting the form but it's still the same.
If I reload the page after submitting, all is correct, title is well displayed even on the calendar view than into the modal when I clicked on it.

Does anyone can see the issue that can cause this on my code?

Thanks a lot

Body:
I'm using Fullcalendar Js (5.6) and laravel lilvewire on a laravel application (8.75).

I create a calendar and display some events on it. I make a modal which opened when I click on an event. This modal contains a form with filled inputs with event informations.

Here it's how I render the form with filled inputs :

eventClick: info => {

  info.jsEvent.preventDefault();

  let modal = document.getElementById('modal')

  let deleteBtn = modal.querySelector('#delete')

  if(deleteBtn.hasAttribute('hidden')) {
    deleteBtn.removeAttribute('hidden')
  }

  if(info.event.extendedProps.report) {
    deleteBtn.setAttribute('disabled', '')
  } else {
    deleteBtn.removeAttribute('disabled')
  }

  modal.querySelector('#modal-title').innerText = 'Modify an event'

  modal.querySelector('input[id="title"]').setAttribute('value', info.event.title)

  if(info.event.extendedProps.description != null) {

    modal.querySelector('input[id="description"]').setAttribute('value', info.event.extendedProps.description)
  }

  modal.querySelector('input[id="start"]').setAttribute('value', (new Date((info.event.start).toString().split('GMT')[0]+' UTC').toISOString()).substr(0,23))

  if(info.event.allDay) {

    modal.querySelector('input[id="allDay"]').setAttribute('checked', true)
  }

}

When I submit my form to update the title for example ("newTitle"), I can see changes on the calendar view but if I clicked again on the event I've changed, title input is empty (other datas are correct and well displayed on the inputs). If I clicked on another event that is not modified I have the same issue, empty title and other datas correct and well displayed.

I logged :

infos.event.title

-> result : newTitle
-> The new title is correct on the event informations

modal.querySelector('input[id="title"]')

-> result : <input id="title" type="text" value="newTitle">
-> The DOM input element has the correct value

modal.querySelector('input[id="title"]').value.length

-> result : 0
-> It's weird that the length of value is zero??

It was an example with title but I have the same weird behavior with the other inputs if I modify them.

Here is my Calendar component where I get events :

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Event;
use App\Models\Client;
use Illuminate\Support\Arr;

class Calendar extends Component
{
    public $events = [];
    public $clients = [];

    public function mount($events)
    {
        $this->events = json_encode($events);
    }

    public function render()
    {
        return view('livewire.calendar');
    }

    public function eventUpdate($event)
    {
        $e = Event::find($event['id']);
        $e->title = $event['title'];
        $e->description = $event['description'];
        $e->start = $event['start'];
        $e->end = $event['end'];
        $e->allDay = $event['allDay'];

        if($e->isDirty()) {
            $e->update($event);
        }
    }
}

I've already try to get the events on the render method and call @this.render() after submitting the form but it's still the same.
If I reload the page after submitting, all is correct, title is well displayed even on the calendar view than into the modal when I clicked on it.

Does anyone can see the issue that can cause this on my code?

Thanks a lot


问:
Power Apps: View "Edit History" Of A Forms Responses
I developed an App where users can fill out a form. Upon hitting :Submit: > the responses are Patched to a DataVerse list > The DataVerse List of Patched responses are then displayed in a Gallery. In this Gallery users can EDIT the responses or view the summary. I need to have an additional option to VIEW CHANGES made, if the user edits a Tile.

Currently, the user can make edits and REPATCH a NEW submission. So if a record is edited 3 times, there are 3 new Gallery tiles, which isnt what I want. I was given suggestions to use the Primary unique ID for the original submission, and some secondary ID for edits and then attach the secondary ID to the main one so all "edit/resubmissions" can be displayed when the primary is called, but I have no idea how to do that... PLEASE if you have any suggestions or have created an "edit history" for form responses that WASNT based off the employee ID/User ID rather it was based off submission ticket/request, I really need the help.


问:
What happens when an image tag produces a redirect?
I have following piece of code

let doCall = (url: URL, params: object): Promise<void> => {
      return new Promise(resolve => {
        ...
        let img = new Image();

        img.addEventListener('load', () => resolve());
        img.addEventListener('error', () => resolve());
        window.setTimeout(() => resolve(), this.maxCallDelayMs);

        img.src = url.toString();
      });
```
<p>This snippet is not really used to load any images, but instead as an HTTP request. The HTTP endpoint though, I am consuming here, is producing some redirects. The number of redirects is case specific. I want to somehow intercept these redirects from Javascript.</p>
<p>I do not aim to intercept these redirects in a way that stops the redirection. I would like to intercept these redirects because the HTTP endpoint enriches the request parameters with information valuable to the Javascript snippet execution.</p>
<p>In order to do so, I am wondering what is actually going on in the background.</p>
<p>I know that if this was a vanilla ajax call like so</p>
<pre class="lang-js prettyprint-override"><code>return new Promise(resolve => {
        ...
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', url.toString());
        httpRequest.send();

        httpRequest.onreadystatechange = function () {
          ...
          resolve();
        };
      });
</code>```

intercepting the requests would be impossible based on that.

Is it the same case with the initial snippet? Namely, using an img tag to consume an endpoint? Meaning that all the redirections will be performed by the browser and the end result would be the loading of an image? Or in my case, the end of the redirection chain with a 200 HTTP status?

Body:
I have following piece of code

let doCall = (url: URL, params: object): Promise<void> => {
      return new Promise(resolve => {
        ...
        let img = new Image();

        img.addEventListener('load', () => resolve());
        img.addEventListener('error', () => resolve());
        window.setTimeout(() => resolve(), this.maxCallDelayMs);

        img.src = url.toString();
      });

This snippet is not really used to load any images, but instead as an HTTP request. The HTTP endpoint though, I am consuming here, is producing some redirects. The number of redirects is case specific. I want to somehow intercept these redirects from Javascript.

I do not aim to intercept these redirects in a way that stops the redirection. I would like to intercept these redirects because the HTTP endpoint enriches the request parameters with information valuable to the Javascript snippet execution.

In order to do so, I am wondering what is actually going on in the background.

I know that if this was a vanilla ajax call like so

return new Promise(resolve => {
        ...
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', url.toString());
        httpRequest.send();

        httpRequest.onreadystatechange = function () {
          ...
          resolve();
        };
      });

intercepting the requests would be impossible based on that.

Is it the same case with the initial snippet? Namely, using an img tag to consume an endpoint? Meaning that all the redirections will be performed by the browser and the end result would be the loading of an image? Or in my case, the end of the redirection chain with a 200 HTTP status?


问:
tune hyperparameters of XGBRanker
I try to optimize my hyperparameters of my XGBoost Ranker model, but I can't

Here is what my table (df on code) looks like :

query
relevance
features

1
5
5.4.7....

1
3
6........

2
5
3........

2
3
8........

3
2
1........

Then I split my table on train test with on the test table only one query:

```<code>gss = GroupShuffleSplit(test_size=1, n_splits=1,).split(df, groups=df['query'])
X_train_inds, X_test_inds = next(gss)

train_data= df.iloc[X_train_inds]
X_train=train_data.drop(columns=["relevance"])
Y_train=train_data.relevance

test_data= df.iloc[X_test_inds]
X_test=test_data.drop(columns=["relevance"])
Y_test=test_data.relevance

</code>```

and constitute groups which is the number of lines by query:

```<code>groups = train_data.groupby('query').size().to_frame('size')['size'].to_numpy()
</code>```

And then I run my model and try to optimize the hyperparameters with a RandomizedSearchCV:

```<code>param_dist = {'n_estimators': randint(40, 1000),
              'learning_rate': uniform(0.01, 0.59),
              'subsample': uniform(0.3, 0.6),
              'max_depth': [3, 4, 5, 6, 7, 8, 9],
              'colsample_bytree': uniform(0.5, 0.4),
              'min_child_weight': [0.05, 0.1, 0.02]
              }

scoring = sklearn.metrics.make_scorer(sklearn.metrics.ndcg_score, k=10,
                                      greater_is_better=True)

model = xgb.XGBRanker(
    tree_method='hist',
    booster='gbtree',
    objective='rank:ndcg',)
clf = RandomizedSearchCV(model,
                         param_distributions=param_dist,
                         cv=5,
                         n_iter=5,
                         scoring=scoring,
                         error_score=0,
                         verbose=3,
                         n_jobs=-1)
clf.fit(X_train,Y_train, group=groups)
</code>```

Then I have the following error message which it seems be related to my construction of groups but I don't see why (Knowing that without the randomsearch the model works) :

Check failed: group_ptr_.back() == num_row_ (11544 vs. 9235) : Invalid group structure.  Number of rows obtained from groups doesn't equal to actual number of rows given by data.

Same problem as here:(Tuning XGBRanker produces error for groups)

Title: tune hyperparameters of XGBRanker

Body:
I try to optimize my hyperparameters of my XGBoost Ranker model, but I can't

Here is what my table (df on code) looks like :

query
relevance
features

1
5
5.4.7....

1
3
6........

2
5
3........

2
3
8........

3
2
1........

Then I split my table on train test with on the test table only one query:

gss = GroupShuffleSplit(test_size=1, n_splits=1,).split(df, groups=df['query'])
X_train_inds, X_test_inds = next(gss)

train_data= df.iloc[X_train_inds]
X_train=train_data.drop(columns=["relevance"])
Y_train=train_data.relevance

test_data= df.iloc[X_test_inds]
X_test=test_data.drop(columns=["relevance"])
Y_test=test_data.relevance

and constitute groups which is the number of lines by query:

groups = train_data.groupby('query').size().to_frame('size')['size'].to_numpy()

And then I run my model and try to optimize the hyperparameters with a RandomizedSearchCV:

param_dist = {'n_estimators': randint(40, 1000),
              'learning_rate': uniform(0.01, 0.59),
              'subsample': uniform(0.3, 0.6),
              'max_depth': [3, 4, 5, 6, 7, 8, 9],
              'colsample_bytree': uniform(0.5, 0.4),
              'min_child_weight': [0.05, 0.1, 0.02]
              }

scoring = sklearn.metrics.make_scorer(sklearn.metrics.ndcg_score, k=10,
                                      greater_is_better=True)

model = xgb.XGBRanker(
    tree_method='hist',
    booster='gbtree',
    objective='rank:ndcg',)
clf = RandomizedSearchCV(model,
                         param_distributions=param_dist,
                         cv=5,
                         n_iter=5,
                         scoring=scoring,
                         error_score=0,
                         verbose=3,
                         n_jobs=-1)
clf.fit(X_train,Y_train, group=groups)

Then I have the following error message which it seems be related to my construction of groups but I don't see why (Knowing that without the randomsearch the model works) :

Check failed: group_ptr_.back() == num_row_ (11544 vs. 9235) : Invalid group structure.  Number of rows obtained from groups doesn't equal to actual number of rows given by data.

Same problem as here:(Tuning XGBRanker produces error for groups)


问:
React/Redux store state doesn't save JSON data?
I am using Redux to create a search bar and React to render out JSON data into a card. I am using thunk middleware and pass an initial state to React. When I make a search, I can successfully fetch data from my API, and a card is created. However, the data in the card is empty, which suggests the API data is not being stored in the properly.

Store.js

```<code>import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import searchReducer from './reducers/searchreducers';

const store = createStore(searchReducer, composeWithDevTools(applyMiddleware(thunk)));

export default store;
</code>```

searchreducers.js

```<code>const initState = {
    brand: "",
    result: "",
    loading: false
};

const searchReducer = (state=initState, action) => {
    switch (action.type) {
            case "LOADING":
                return {
                    ...state,
                    brand: action.payload,
                    loading: true
                };
            case "LOAD_RESULT":
                return {
                    ...state,
                    brand: action.payload,
                    loading: false,
                    error: false
                };
            case "SET_ERROR":
                return {
                    ...state,
                    error: action.payload,
                    loading: false,
                };
            default:
                return state;
    }
}

export default searchReducer;
</code>```

actions.js

```<code>import axios from 'axios';

export const loading = (brand) => {
    return {
        type: "LOADING",
        payload: brand
    }
}

export const loadResult = (result) => {
    return {
        type: "LOAD_RESULT",
        payload: result
    }
}

export const getResult = (searchTerm) => {
    return async (dispatch) => {
        dispatch(loading(searchTerm))
        try {
            const { data } = await axios.get(
                `http://makeup-api.herokuapp.com/api/v1/products.json?brand=${searchTerm}`
            )
            console.log(data[0]) //returns data correctly
            dispatch(loadResult(data[0]))
        } catch (err) {
            console.error(err)
            dispatch({
                type: "SET_ERROR",
                payload: err
            })
        }
    }
}
</code>```

Result.js
render card

```<code>import React from 'react';

const Result = (result) => {
    return(
        <div className="card">
            <img src={result.image_link} alt={result.name}/>
            <h1>{result.brand}</h1>
            <h3>{result.name}</h3>
            <p>{result.description}</p>
        </div>
    )
}
 export default Result
</code>```

page.js

```<code>const Search = () => {
    const result = useSelector(state => state.result)
    const loading = useSelector(state => state.loading)
    const dispatch = useDispatch();

    useEffect(console.log(result)) //returns empty

    const renderResult = () => {
        return loading ? <p>Loading...</p> : <Result result={result}/>
    }

    const search = searchTerm => dispatch(getResult(searchTerm))

    return(
        <>
            <div id="search">
                <SearchForm getResult={search}/>
                <h1>Result</h1>
                {renderResult()}
            </div>
        </>
    )
};

export default Search;
</code>```

My first theory is that it's because the data is in json form but when I JSON.parse(data), it some up as [object Object] is not a valid JSON.

Also changed const Result = (result) => {...} to const Result = ({result}) => {..} but keys come up as undefined (may also be due to data format).

Body:
I am using Redux to create a search bar and React to render out JSON data into a card. I am using thunk middleware and pass an initial state to React. When I make a search, I can successfully fetch data from my API, and a card is created. However, the data in the card is empty, which suggests the API data is not being stored in the properly.

Store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import searchReducer from './reducers/searchreducers';

const store = createStore(searchReducer, composeWithDevTools(applyMiddleware(thunk)));

export default store;

searchreducers.js

const initState = {
    brand: "",
    result: "",
    loading: false
};

const searchReducer = (state=initState, action) => {
    switch (action.type) {
            case "LOADING":
                return {
                    ...state,
                    brand: action.payload,
                    loading: true
                };
            case "LOAD_RESULT":
                return {
                    ...state,
                    brand: action.payload,
                    loading: false,
                    error: false
                };
            case "SET_ERROR":
                return {
                    ...state,
                    error: action.payload,
                    loading: false,
                };
            default:
                return state;
    }
}

export default searchReducer;

actions.js

import axios from 'axios';

export const loading = (brand) => {
    return {
        type: "LOADING",
        payload: brand
    }
}

export const loadResult = (result) => {
    return {
        type: "LOAD_RESULT",
        payload: result
    }
}

export const getResult = (searchTerm) => {
    return async (dispatch) => {
        dispatch(loading(searchTerm))
        try {
            const { data } = await axios.get(
                `http://makeup-api.herokuapp.com/api/v1/products.json?brand=${searchTerm}`
            )
            console.log(data[0]) //returns data correctly
            dispatch(loadResult(data[0]))
        } catch (err) {
            console.error(err)
            dispatch({
                type: "SET_ERROR",
                payload: err
            })
        }
    }
}

Result.js
render card

import React from 'react';

const Result = (result) => {
    return(

{result.brand}

{result.name}

{result.description}

    )
}
 export default Result

page.js

const Search = () => {
    const result = useSelector(state => state.result)
    const loading = useSelector(state => state.loading)
    const dispatch = useDispatch();

    useEffect(console.log(result)) //returns empty

    const renderResult = () => {
        return loading ?
Loading...
 : <Result result={result}/>
    }

    const search = searchTerm => dispatch(getResult(searchTerm))

    return(
        <>

                <SearchForm getResult={search}/>

Result

                {renderResult()}

        </>
    )
};

export default Search;

My first theory is that it's because the data is in json form but when I JSON.parse(data), it some up as [object Object] is not a valid JSON.

Also changed const Result = (result) => {...} to const Result = ({result}) => {..} but keys come up as undefined (may also be due to data format).


问:
How are task executor of tasklet and partition handler different in spring batch?
I am running spring batch with partitioning. i.e. Partition/Read/Process/Write , where process step spends more time in I/O than a CPU intensive processing.

The problem with current partitioning scheme is that , it is creating some hot partitions, that is - Some of the partitions have more data to process as compared to others. So The job processes most of the records very fast, but last few records are processed slow because a few partitioned threads have more data and they are executing the records one by one, causing the job to complete slower.

Conceptually, I want to be able to spawn each partitioned step in to parallel threads (say 4 threads) , so that hot partitions are also processed in parallel , rather than 1 record at a time.

Here is the batch config I am currently using (before optimisation) for running partition/read/process logic for a job.

```<code><batch:job id="Scheduler">
    <batch:step id="Scheduler">
        <batch:partition step="ScheduleStep" partitioner="Partitioner">
            <batch:handler grid-size="30" task-executor="asyncTaskExecutor"/>
        </batch:partition>
    </batch:step>
</batch:job>

<batch:step id="ScheduleStep">
    <batch:tasklet>
        <batch:chunk reader="tsV2Reader" processor="tsV2Processor"
                     writer="tsV2Writer" commit-interval="1"/>
    </batch:tasklet>
</batch:step>

<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" value="30"/>
</bean>
</code>```

I want to decrease partitions from 30 to say 10 and let each partition thread spawn its 4 threads, so that even if hot partition exists it still executes 4 records in parallel instead of 1. i.e. Overall 10 x 4 = 40 threads

So I changed the above config by adding task-executor at tasklet level with concurrencyLimit of 4 and changed gridSize and concurrencyLimit in config above to 10. i.e. -

```<code><batch:job id="Scheduler">
    <batch:step id="Scheduler">
        <batch:partition step="ScheduleStep" partitioner="Partitioner">
            <batch:handler **grid-size="10"** task-executor="asyncTaskExecutor"/>
        </batch:partition>
    </batch:step>
</batch:job>

<batch:step id="ScheduleStep">
    <batch:tasklet **task-executor="taskletTaskExecutor" throttle-limit="4"**>
        <batch:chunk reader="tsV2Reader" processor="tsV2Processor"
                     writer="tsV2Writer" commit-interval="1"/>
    </batch:tasklet>
</batch:step>

<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" **value="10"** />
</bean>

**<bean id="taskletTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" value="4"/>
</bean>**
</code>```

It seems to slow down the processing instead of speeding it up. May be the concurrenyLimit (4) of tasklet is being applied to all the threads. That I am not sure. I tried looking up the documentation on how the taskExecutor config for tasklet and handler is interpreted together under the hood, but not able to find relevant information. If someone can help with internals/understanding of these configs in question and how to achieve what I am looking for, will be of great help.

Body:
I am running spring batch with partitioning. i.e. Partition/Read/Process/Write , where process step spends more time in I/O than a CPU intensive processing.

The problem with current partitioning scheme is that , it is creating some hot partitions, that is - Some of the partitions have more data to process as compared to others. So The job processes most of the records very fast, but last few records are processed slow because a few partitioned threads have more data and they are executing the records one by one, causing the job to complete slower.

Conceptually, I want to be able to spawn each partitioned step in to parallel threads (say 4 threads) , so that hot partitions are also processed in parallel , rather than 1 record at a time.

Here is the batch config I am currently using (before optimisation) for running partition/read/process logic for a job.

<batch:job id="Scheduler">
    <batch:step id="Scheduler">
        <batch:partition step="ScheduleStep" partitioner="Partitioner">
            <batch:handler grid-size="30" task-executor="asyncTaskExecutor"/>
        </batch:partition>
    </batch:step>
</batch:job>

<batch:step id="ScheduleStep">
    <batch:tasklet>
        <batch:chunk reader="tsV2Reader" processor="tsV2Processor"
                     writer="tsV2Writer" commit-interval="1"/>
    </batch:tasklet>
</batch:step>

<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" value="30"/>
</bean>

I want to decrease partitions from 30 to say 10 and let each partition thread spawn its 4 threads, so that even if hot partition exists it still executes 4 records in parallel instead of 1. i.e. Overall 10 x 4 = 40 threads

So I changed the above config by adding task-executor at tasklet level with concurrencyLimit of 4 and changed gridSize and concurrencyLimit in config above to 10. i.e. -

<batch:job id="Scheduler">
    <batch:step id="Scheduler">
        <batch:partition step="ScheduleStep" partitioner="Partitioner">
            <batch:handler **grid-size="10"** task-executor="asyncTaskExecutor"/>
        </batch:partition>
    </batch:step>
</batch:job>

<batch:step id="ScheduleStep">
    <batch:tasklet **task-executor="taskletTaskExecutor" throttle-limit="4"**>
        <batch:chunk reader="tsV2Reader" processor="tsV2Processor"
                     writer="tsV2Writer" commit-interval="1"/>
    </batch:tasklet>
</batch:step>

<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" **value="10"** />
</bean>

**<bean id="taskletTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
    <property name="concurrencyLimit" value="4"/>
</bean>**

It seems to slow down the processing instead of speeding it up. May be the concurrenyLimit (4) of tasklet is being applied to all the threads. That I am not sure. I tried looking up the documentation on how the taskExecutor config for tasklet and handler is interpreted together under the hood, but not able to find relevant information. If someone can help with internals/understanding of these configs in question and how to achieve what I am looking for, will be of great help.


问:
How to turn off webdriver mode in selenium python?
I found an option that turns it off:

```<code>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'
options = webdriver.FirefoxOptions()
options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe"
options.set_preference('devtools.jsonview.enabled', False)
options.set_preference("general.useragent.override", ua)
options.set_preference("dom.webdriver.enabled", False)
options.set_preference('devtools.jsonview.enabled', False)
options.set_preference("useAutomationExtension", False)

driver = webdriver.Firefox(options=options, executable_path='geckodriver.exe')
action=ActionChains(driver)
driver.get('https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html')
</code>```

But any way I get this:

How to turn it off and make browser undetectable?

Body:
I found an option that turns it off:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'
options = webdriver.FirefoxOptions()
options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe"
options.set_preference('devtools.jsonview.enabled', False)
options.set_preference("general.useragent.override", ua)
options.set_preference("dom.webdriver.enabled", False)
options.set_preference('devtools.jsonview.enabled', False)
options.set_preference("useAutomationExtension", False)

driver = webdriver.Firefox(options=options, executable_path='geckodriver.exe')
action=ActionChains(driver)
driver.get('https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html')

But any way I get this:

How to turn it off and make browser undetectable?


问:
Using JPA Criteria API to fetch a list
I have an entity Tutor with two relationships in class Schedule. Code below defines the relationship between the two entities.

```<code>public class Tutor{
   //list of schedules created by tutor
   @OneToMany
   List<Schedule> schedules;
 }
</code>```

then

```<code>public class Schedule{

    //tutor who created this schedule
    @ManyToOne
    Tutor tutor;

    //tutors who would be examiners of this schedule
    @ManyToMany
    @JoinTable
    List<Tutor> examiners;
   }
</code>```

how can i query Tutor and fetch all Schedule(s) where Tutor is an examiner using criteria api

Title: Using JPA Criteria API to fetch a list

Body:
I have an entity Tutor with two relationships in class Schedule. Code below defines the relationship between the two entities.

public class Tutor{
   //list of schedules created by tutor
   @OneToMany
   List<Schedule> schedules;
 }

then

public class Schedule{

    //tutor who created this schedule
    @ManyToOne
    Tutor tutor;

    //tutors who would be examiners of this schedule
    @ManyToMany
    @JoinTable
    List<Tutor> examiners;
   }

how can i query Tutor and fetch all Schedule(s) where Tutor is an examiner using criteria api


问:
How the hibernate selects ojdbc jars if multiple jars are available?
We have 4 ojdbc jars namely ojdbc14.jar, ojdbc6.jar, ojdbc7.jar and ojdbc8.jar in the "lib" folder of the java application.
And we have declared the necessary configurations for the driver in XML file as shown below,

```<code><property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
</code>```

In the above options, Which ojdbc jar does hibernate choose? whether it will select the first jar or will select one of the ojdbc jars at random.

And based on what logic does Hibernate select the appropriate ojdbc jar file?

Thanks in advance.

Body:
We have 4 ojdbc jars namely ojdbc14.jar, ojdbc6.jar, ojdbc7.jar and ojdbc8.jar in the "lib" folder of the java application.
And we have declared the necessary configurations for the driver in XML file as shown below,

<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />

In the above options, Which ojdbc jar does hibernate choose? whether it will select the first jar or will select one of the ojdbc jars at random.

And based on what logic does Hibernate select the appropriate ojdbc jar file?

Thanks in advance.


问:
SMTP connect() failed Office 365 OVH
I am using PHPMailer to send mails from website to a specific address

Here is my configuration :

```<code>$mail = new PHPMailer();

$mail->CharSet = 'UTF-8';                                       // Format d'encodage à utiliser pour les caractères

$mail->SMTPDebug = 4;                                           // Valeur entre 0 (normal) et 4 (full debug). Attention : mettre cette valeur > 0 dévoule certains paramètres confidentiels !

$mail->isSMTP();
$mail->Host = 'smtp.office365.com';                             // Adresse IP ou DNS du serveur SMTP
$mail->Port = 587;                                              // Port TCP du serveur SMTP (port SMTP chez OVH : 465=avec_SSL et 587=sans_SSL/avec_tls)
$mail->SMTPAuth = TRUE;                                         // Utiliser l'authentification

$mail->SMTPSecure = 'TLS';

$mail->Username   = 'email@xyz.x';
$mail->Password   = 'PWD';
</code>```

I enabled and enforced the multifactor authentication and created an app password that i put in $mail->Password.

I still get the same erreur :

```<code>2023-01-09 14:32:53 Connection: opening to smtp.office365.com:587, timeout=300, options=array()
2023-01-09 14:32:53 Connection failed. Error #2: stream_socket_client(): Unable to connect to smtp.office365.com:587 (Connection refused) [/home/vendor/phpmailer/phpmailer/src/SMTP.php line 388]
2023-01-09 14:32:53 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

I tried every solution i found on google but nothing seems to work.. the website host is
** OVH **.

I tried with and without the MFA but i get the same results.. if anyone was facing the same problem and found a working solution i'd be so grateful !

Thanks in advance

Title: SMTP connect() failed Office 365 OVH

Body:
I am using PHPMailer to send mails from website to a specific address

Here is my configuration :

$mail = new PHPMailer();

$mail->CharSet = 'UTF-8';                                       // Format d'encodage à utiliser pour les caractères

$mail->SMTPDebug = 4;                                           // Valeur entre 0 (normal) et 4 (full debug). Attention : mettre cette valeur > 0 dévoule certains paramètres confidentiels !

$mail->isSMTP();
$mail->Host = 'smtp.office365.com';                             // Adresse IP ou DNS du serveur SMTP
$mail->Port = 587;                                              // Port TCP du serveur SMTP (port SMTP chez OVH : 465=avec_SSL et 587=sans_SSL/avec_tls)
$mail->SMTPAuth = TRUE;                                         // Utiliser l'authentification

$mail->SMTPSecure = 'TLS';

$mail->Username   = 'email@xyz.x';
$mail->Password   = 'PWD';

I enabled and enforced the multifactor authentication and created an app password that i put in $mail->Password.

I still get the same erreur :

2023-01-09 14:32:53 Connection: opening to smtp.office365.com:587, timeout=300, options=array()
2023-01-09 14:32:53 Connection failed. Error #2: stream_socket_client(): Unable to connect to smtp.office365.com:587 (Connection refused) [/home/vendor/phpmailer/phpmailer/src/SMTP.php line 388]
2023-01-09 14:32:53 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I tried every solution i found on google but nothing seems to work.. the website host is
** OVH **.

I tried with and without the MFA but i get the same results.. if anyone was facing the same problem and found a working solution i'd be so grateful !

Thanks in advance


问:
Add an object file(.obj) into a shared library file(.so)
I am using an open source program and there is a shared library file(.so).

And I would like to add my object file(.obj) into the .so file, but I do not know how to do it.

Could anyone let me know how to add mycode.obj to lib.so in Ubuntu?

I have tried g++ -o newlib.so -shared lib.so mycode.obj. This makes a .so file but I do not think it contains lib.so correctly.

Thanks in advance.


问:
Adding guilds.json authorized users to the server
Is it possible to add users with guilds.json permission to the server at once? How can I write Python code that does this? In short, it is a code that adds it to the server in bulk when I run the code.</p>


问:
Crash on iOS: com.apple.main-thread | EXC_BREAKPOINT (SIGTRAP)
Crashes are reported into firebase console, and it's happening very rarely without any concrete repro steps. Below is my crash log:

Any Idea why would this happen?

```<code>Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000104f9d960
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler \[9693\]

Triggered by Thread:  0

Kernel Triage:
VM - pmap_enter failed with resource shortage
VM - pmap_enter failed with resource shortage
VM - pmap_enter failed with resource shortage

Thread 0 name:   Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   MyApp                                  0x104f9d960 0x104940000 + 6674784
1   MyApp                                  0x104f9ca0c 0x104940000 + 6670860
2   Combine                                0x1bf1e34b0 Subscribers.Sink.receive(_:) + 96
3   Combine                                0x1bf1e2da8 protocol witness for Subscriber.receive(_:) in conformance Subscribers.Sink\<A, B\> + 24
4   Combine                                0x1bf1ea9fc closure #1 in Publishers.ReceiveOn.Inner.receive(\_:) + 288
5   libswiftDispatch.dylib                 0x1c0cddc04 thunk for @escaping @callee_guaranteed () -\> () + 36
6   libdispatch.dylib                      0x1a6d9ae6c \_dispatch_call_block_and_release + 32
7   libdispatch.dylib                      0x1a6d9ca30 \_dispatch_client_callout + 20
8   libdispatch.dylib                      0x1a6daaf48 \_dispatch_main_queue_drain + 928
9   libdispatch.dylib                      0x1a6daab98 _dispatch_main_queue_callback_4CF + 44
10  CoreFoundation                         0x1a70ed800 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
11  CoreFoundation                         0x1a70a7704 \__CFRunLoopRun + 2532
12  CoreFoundation                         0x1a70babc8 CFRunLoopRunSpecific + 600
13  GraphicsServices                       0x1c3226374 GSEventRunModal + 164
14  UIKitCore                              0x1a9a2eb58 -\[UIApplication run\] + 1100
15  UIKitCore                              0x1a97b0090 UIApplicationMain + 364
16  SwiftUI                                0x1aef14f24 closure #1 in KitRendererCommon(_:) + 164
17  SwiftUI                                0x1aee42e08 runApp\<A\>(:) + 252
18  SwiftUI                                0x1aee240f4 static App.main() + 128
19  MyApp                                  0x104944840 0x104940000 + 18496
20  dyld                                   0x105d7dda4 start + 520

</code>```

Tried symbolicating the crash using the dysm file too, yet unable to get to the root cause.

Any help would be appreciated.

Body:
Crashes are reported into firebase console, and it's happening very rarely without any concrete repro steps. Below is my crash log:

Any Idea why would this happen?

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000104f9d960
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler \[9693\]

Triggered by Thread:  0

Kernel Triage:
VM - pmap_enter failed with resource shortage
VM - pmap_enter failed with resource shortage
VM - pmap_enter failed with resource shortage

Thread 0 name:   Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   MyApp                                  0x104f9d960 0x104940000 + 6674784
1   MyApp                                  0x104f9ca0c 0x104940000 + 6670860
2   Combine                                0x1bf1e34b0 Subscribers.Sink.receive(_:) + 96
3   Combine                                0x1bf1e2da8 protocol witness for Subscriber.receive(_:) in conformance Subscribers.Sink\ + 24
4   Combine                                0x1bf1ea9fc closure #1 in Publishers.ReceiveOn.Inner.receive(\_:) + 288
5   libswiftDispatch.dylib                 0x1c0cddc04 thunk for @escaping @callee_guaranteed () -\> () + 36
6   libdispatch.dylib                      0x1a6d9ae6c \_dispatch_call_block_and_release + 32
7   libdispatch.dylib                      0x1a6d9ca30 \_dispatch_client_callout + 20
8   libdispatch.dylib                      0x1a6daaf48 \_dispatch_main_queue_drain + 928
9   libdispatch.dylib                      0x1a6daab98 _dispatch_main_queue_callback_4CF + 44
10  CoreFoundation                         0x1a70ed800 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
11  CoreFoundation                         0x1a70a7704 \__CFRunLoopRun + 2532
12  CoreFoundation                         0x1a70babc8 CFRunLoopRunSpecific + 600
13  GraphicsServices                       0x1c3226374 GSEventRunModal + 164
14  UIKitCore                              0x1a9a2eb58 -\[UIApplication run\] + 1100
15  UIKitCore                              0x1a97b0090 UIApplicationMain + 364
16  SwiftUI                                0x1aef14f24 closure #1 in KitRendererCommon(_:) + 164
17  SwiftUI                                0x1aee42e08 runApp\(:) + 252
18  SwiftUI                                0x1aee240f4 static App.main() + 128
19  MyApp                                  0x104944840 0x104940000 + 18496
20  dyld                                   0x105d7dda4 start + 520

Tried symbolicating the crash using the dysm file too, yet unable to get to the root cause.

Any help would be appreciated.


问:
How to add "Or" or "OrElse" in MakeComparison
I have a method for dynamic creating a query. This works fine. But I also want to add "Or" or "OrElse". I have searched the internet but can't find an example. I would be also nice to have also an "in" in the query.
When I try "or" or "OrElse" I see in the logfile that it put an "And" and not an "Or".

I also get this error: The binary operator OrElse is not defined for the types 'System.Nullable1[System.Int16]' and 'System.Nullable1[System.Int16

```<code>private static Expression MakeComparison(Expression left, string comparison, string value)
{
    switch (comparison)
    {
        case "==":
        case "IsEqualTo":
            return MakeBinary(ExpressionType.Equal, left, value);
        case "!=":
        case "IsNotEqualTo":
            return MakeBinary(ExpressionType.NotEqual, left, value);
        case ">":
        case "IsGreaterThan":
            return MakeBinary(ExpressionType.GreaterThan, left, value);
        case ">=":
        case "IsGreaterThanOrEqualTo":
            return MakeBinary(ExpressionType.GreaterThanOrEqual, left, value);
        case "<":
        case "IsLessThan":
            return MakeBinary(ExpressionType.LessThan, left, value);
        case "<=":
        case "IsLessThanOrEqualTo":
            return MakeBinary(ExpressionType.LessThanOrEqual, left, value);
        case "OrElse":
            return MakeBinary(ExpressionType.OrElse, left, value);
        case "Or":
            return MakeBinary(ExpressionType.Or, left, value);
        case "Contains":
        case "StartsWith":
        case "EndsWith":
            return Expression.Call(MakeString(left), comparison, Type.EmptyTypes, Expression.Constant(value, typeof(string)));
        default:
            throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
    }

    private static Expression MakeBinary(ExpressionType type, Expression left, string value)
    {
        object typedValue = value;
        if (left.Type != typeof(string))
        {
            if (string.IsNullOrEmpty(value))
            {
                typedValue = null;
                if (Nullable.GetUnderlyingType(left.Type) == null)
                    left = Expression.Convert(left, typeof(Nullable<>).MakeGenericType(left.Type));
            }
            else
            {
                var valueType = Nullable.GetUnderlyingType(left.Type) ?? left.Type;
                typedValue = valueType.IsEnum ? Enum.Parse(valueType, value) :
                    valueType == typeof(Guid) ? Guid.Parse(value) :
                    Convert.ChangeType(value, valueType);
            }
        }
        var right = Expression.Constant(typedValue, left.Type);
        return Expression.MakeBinary(type, left, right);
    }
}
</code>```

Body:
I have a method for dynamic creating a query. This works fine. But I also want to add "Or" or "OrElse". I have searched the internet but can't find an example. I would be also nice to have also an "in" in the query.
When I try "or" or "OrElse" I see in the logfile that it put an "And" and not an "Or".

I also get this error: The binary operator OrElse is not defined for the types 'System.Nullable1[System.Int16]' and 'System.Nullable1[System.Int16

private static Expression MakeComparison(Expression left, string comparison, string value)
{
    switch (comparison)
    {
        case "==":
        case "IsEqualTo":
            return MakeBinary(ExpressionType.Equal, left, value);
        case "!=":
        case "IsNotEqualTo":
            return MakeBinary(ExpressionType.NotEqual, left, value);
        case ">":
        case "IsGreaterThan":
            return MakeBinary(ExpressionType.GreaterThan, left, value);
        case ">=":
        case "IsGreaterThanOrEqualTo":
            return MakeBinary(ExpressionType.GreaterThanOrEqual, left, value);
        case "<":
        case "IsLessThan":
            return MakeBinary(ExpressionType.LessThan, left, value);
        case "<=":
        case "IsLessThanOrEqualTo":
            return MakeBinary(ExpressionType.LessThanOrEqual, left, value);
        case "OrElse":
            return MakeBinary(ExpressionType.OrElse, left, value);
        case "Or":
            return MakeBinary(ExpressionType.Or, left, value);
        case "Contains":
        case "StartsWith":
        case "EndsWith":
            return Expression.Call(MakeString(left), comparison, Type.EmptyTypes, Expression.Constant(value, typeof(string)));
        default:
            throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
    }

    private static Expression MakeBinary(ExpressionType type, Expression left, string value)
    {
        object typedValue = value;
        if (left.Type != typeof(string))
        {
            if (string.IsNullOrEmpty(value))
            {
                typedValue = null;
                if (Nullable.GetUnderlyingType(left.Type) == null)
                    left = Expression.Convert(left, typeof(Nullable<>).MakeGenericType(left.Type));
            }
            else
            {
                var valueType = Nullable.GetUnderlyingType(left.Type) ?? left.Type;
                typedValue = valueType.IsEnum ? Enum.Parse(valueType, value) :
                    valueType == typeof(Guid) ? Guid.Parse(value) :
                    Convert.ChangeType(value, valueType);
            }
        }
        var right = Expression.Constant(typedValue, left.Type);
        return Expression.MakeBinary(type, left, right);
    }
}


问:
Radio button align horizontally, but not vertically
My radio buttons align horizontally, but not vertically. I would like my radio buttons to line up with the length of my text. I don't know if it's because my css is placed in the wrong div.. here is my code for my cshtml view:

```<code><h1 style="text-align:center"><b>INSPECTION DE TYPE HEBDOMADAIRE</b></h1>
<div class="container">
@{
    int itemCounter = 0;
    int camionCounter = 0;
}
@foreach (var camion in Model)
{
    <br />
    <h2 style="text-align:center">@camion.CamionNumero</h2>
    <hr style="margin-bottom:0px; margin-top:0px" />
    camionCounter++;

    <table class="table">
        <thead>
            <tr>
                <th>
                    <div>
                        @if (camion.composanteContent != null)
                        {
                            foreach (var composante in camion.composanteContent)
                            {
                                <h3><u>@composante.ComposanteName</u></h3>

                                if (composante.itemContent != null)
                                {
                                    foreach (var item in composante.itemContent)
                                    {
                                        <div class="item-radio-comment-container">
                                            <div style="font-size: 1.2em;" id="itemText_@(itemCounter)">· @item.ItemName</div>
                                            <div class="radio">
                                                <label>
                                                        <input type="radio" id="chkOK_@(itemCounter)" name="chkInventaire_@(camion.CamionNumero)_@(composante.ComposanteName)_@(item.ItemName)">
                                                        <span class="cr"><i class="cr-icon glyphicon glyphicon-ok-sign" color="green"></i></span>
                                                        Ok
                                                    </label>
                                                <label>
                                                        <input type="radio" id="chkAVerif_@(itemCounter)" name="chkInventaire_@(camion.CamionNumero)_@(composante.ComposanteName)_@(item.ItemName)">
                                                        <span class="cr"><i class="cr-icon glyphicon glyphicon-ok-sign" color="darkorange"></i></span>
                                                        À Vérifier
                                                    </label>
                                                </div>
                                                <div style="display: inline-block; padding: 10px; display: none;" id="dvComment_@(itemCounter)">
                                                    <input type="text" class="form-control" style="width:20em;" id="txtComment_@(itemCounter)" placeholder="Veuillez entrer votre commentaire.." />
                                                </div>
                                            </div>
                                        <script type="text/javascript">
                                            $(document).ready(function () {
                                                $("#chkAVerif_@(itemCounter)").click(function () {
                                                    $("#dvComment_@(itemCounter)").show();
                                                    $('#itemText_@(itemCounter)').css('text-decoration', 'none');
                                                });
                                                $("#chkOK_@(itemCounter)").click(function () {
                                                    $("#dvComment_@(itemCounter)").hide();
                                                    $('#itemText_@(itemCounter)').css('text-decoration', 'line-through');
                                                });
                                            });
                                        </script>
                                        itemCounter++;
                                    }
                                }
                            }
                        }
                        <hr />
                    </div>
                </th>
            </tr>
        </thead>
    </table>
}
</code>```

Here is my css or did i try with item-radio-comment-container to make my radio button and my dvComment all align vertically so it is the same length relying on the text of the longest item while remaining on the same line horizontally :

```<code>html {
font-size: 14px;
}

@media (min-width: 768px) {
html {
    font-size: 16px;
}
}

html {
position: relative;
min-height: 100%;
}

body {
margin-bottom: 60px;
}

.checkbox label:after,
.radio label:after {
content: '';
display: table;
clear: both;
}

.checkbox .cr,
.radio .cr {
position: relative;
display: inline-block;
border: 1px solid #a9a9a9;
border-radius: .25em;
width: 1.3em;
height: 1.3em;
float: left;
margin-right: .5em;
}

.radio .cr {
border-radius: 50%;
}

.checkbox .cr .cr-icon,
.radio .cr .cr-icon {
    position: absolute;
    font-size: .8em;
    line-height: 0;
    top: 50%;
    left: 20%;
}

.radio .cr .cr-icon {
    margin-left: 0.04em;
}

.checkbox label input[type="checkbox"],
.radio label input[type="radio"] {
display: none;
}

.checkbox label input[type="checkbox"] + .cr > .cr-icon,
.radio label input[type="radio"] + .cr > .cr-icon {
    transform: scale(3) rotateZ(-20deg);
    opacity: 0;
    transition: all .3s ease-in;
}

.checkbox label input[type="checkbox"]:checked + .cr > .cr-icon,
.radio label input[type="radio"]:checked + .cr > .cr-icon {
    transform: scale(1) rotateZ(0deg);
    opacity: 1;
}

.checkbox label input[type="checkbox"]:disabled + .cr,
.radio label input[type="radio"]:disabled + .cr {
    opacity: .5;
}

.radio input[type="radio"] {
vertical-align: middle;
}

.item-radio-comment-container {
display: flex;
align-items: center;
}

@media (max-width: 767px) {
.item-radio-comment-container {
    display: block;
}
}
</code>```

And here is a picture of the result :

Body:
My radio buttons align horizontally, but not vertically. I would like my radio buttons to line up with the length of my text. I don't know if it's because my css is placed in the wrong div.. here is my code for my cshtml view:

INSPECTION DE TYPE HEBDOMADAIRE

@{
    int itemCounter = 0;
    int camionCounter = 0;
}
@foreach (var camion in Model)
{

@camion.CamionNumero

    camionCounter++;

                        @if (camion.composanteContent != null)
                        {
                            foreach (var composante in camion.composanteContent)
                            {

@composante.ComposanteName

                                if (composante.itemContent != null)
                                {
                                    foreach (var item in composante.itemContent)
                                    {

· @item.ItemName

                                                        <input type="radio" id="chkOK_@(itemCounter)" name="chkInventaire_@(camion.CamionNumero)_@(composante.ComposanteName)_@(item.ItemName)">

                                                        Ok

                                                        <input type="radio" id="chkAVerif_@(itemCounter)" name="chkInventaire_@(camion.CamionNumero)_@(composante.ComposanteName)_@(item.ItemName)">

                                                        À Vérifier

                                                    <input type="text" class="form-control" style="width:20em;" id="txtComment_@(itemCounter)" placeholder="Veuillez entrer votre commentaire.." />

                                        itemCounter++;
                                    }
                                }
                            }
                        }

}

Here is my css or did i try with item-radio-comment-container to make my radio button and my dvComment all align vertically so it is the same length relying on the text of the longest item while remaining on the same line horizontally :

html {
font-size: 14px;
}

@media (min-width: 768px) {
html {
    font-size: 16px;
}
}

html {
position: relative;
min-height: 100%;
}

body {
margin-bottom: 60px;
}

.checkbox label:after,
.radio label:after {
content: '';
display: table;
clear: both;
}

.checkbox .cr,
.radio .cr {
position: relative;
display: inline-block;
border: 1px solid #a9a9a9;
border-radius: .25em;
width: 1.3em;
height: 1.3em;
float: left;
margin-right: .5em;
}

.radio .cr {
border-radius: 50%;
}

.checkbox .cr .cr-icon,
.radio .cr .cr-icon {
    position: absolute;
    font-size: .8em;
    line-height: 0;
    top: 50%;
    left: 20%;
}

.radio .cr .cr-icon {
    margin-left: 0.04em;
}

.checkbox label input[type="checkbox"],
.radio label input[type="radio"] {
display: none;
}

.checkbox label input[type="checkbox"] + .cr > .cr-icon,
.radio label input[type="radio"] + .cr > .cr-icon {
    transform: scale(3) rotateZ(-20deg);
    opacity: 0;
    transition: all .3s ease-in;
}

.checkbox label input[type="checkbox"]:checked + .cr > .cr-icon,
.radio label input[type="radio"]:checked + .cr > .cr-icon {
    transform: scale(1) rotateZ(0deg);
    opacity: 1;
}

.checkbox label input[type="checkbox"]:disabled + .cr,
.radio label input[type="radio"]:disabled + .cr {
    opacity: .5;
}

.radio input[type="radio"] {
vertical-align: middle;
}

.item-radio-comment-container {
display: flex;
align-items: center;
}

@media (max-width: 767px) {
.item-radio-comment-container {
    display: block;
}
}

And here is a picture of the result :


问:
Why isn't NFC connecting to reader?
I was trying to use the nfcpy module, but I don't know how to connect to the reader, it also might be connecting to card...

I tried nfc.ContactlessFrontend(), but that didn't work... it could also be connecting to the card.

```<code>import nfc
import time
import keyboard
print("Hold a reader close!")
time.sleep(2)
wire = nfc.ContactlessFrontend()
print("Hold a card close to the reader! I give you 5 seconds!")
time.sleep(5)
party = wire.connect(rdwr={'on-connect': lambda tag: False})
info = party.ndef.message
print(info)
print("Press x to write it on your write-able card! I'll give you 3 seconds!")
time.sleep(3)
if keyboard.is_pressed('x'):
  party = wire.connect(rdwr={'on-connect': lambda tag: False})
  party.write(info)
  print("DONE!!! U HAVE HACKED!!!!!")
party.disconnect()
wire.close()
</code>```

This is my error:

```<code>Traceback (most recent call last):
  File "main.py", line 9, in <module>
    party = wire.connect(rdwr={'on-connect': lambda tag: False})
  File "/home/runner/HACKED/venv/lib/python3.8/site-packages/nfc/clf/__init__.py", line 496, in connect
    raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
OSError: [Errno 19] No such device
</code>```

Title: Why isn't NFC connecting to reader?

Body:
I was trying to use the nfcpy module, but I don't know how to connect to the reader, it also might be connecting to card...

I tried nfc.ContactlessFrontend(), but that didn't work... it could also be connecting to the card.

import nfc
import time
import keyboard
print("Hold a reader close!")
time.sleep(2)
wire = nfc.ContactlessFrontend()
print("Hold a card close to the reader! I give you 5 seconds!")
time.sleep(5)
party = wire.connect(rdwr={'on-connect': lambda tag: False})
info = party.ndef.message
print(info)
print("Press x to write it on your write-able card! I'll give you 3 seconds!")
time.sleep(3)
if keyboard.is_pressed('x'):
  party = wire.connect(rdwr={'on-connect': lambda tag: False})
  party.write(info)
  print("DONE!!! U HAVE HACKED!!!!!")
party.disconnect()
wire.close()

This is my error:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    party = wire.connect(rdwr={'on-connect': lambda tag: False})
  File "/home/runner/HACKED/venv/lib/python3.8/site-packages/nfc/clf/__init__.py", line 496, in connect
    raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
OSError: [Errno 19] No such device


问:
Tick mark not displaying while using html-to-pdf github action
I create an html file using a node js script. It contains a table where I display tick mark based on certain conditions. The code to display the tick mark in the table cell is as follows:

```<code><td style='text-align: center;background-color:#93C572;border-radius: 10px;font-family:Tahoma;font-size:14px;border-bottom: thin solid;border-color:#DEDEDE;border-width: 2px 10px;'>" + "Passed \u2714" + "</td>
</code>```

It displays perfectly fine in html but when I try to convert html to pdf using html-to-pdf github action, it is displaying the pdf without the tick mark.

Code in github action which is converting it:

```<code>- name: Convert HTML to PDF report
        if: always()
        uses: fifsky/html-to-pdf-action@master
        with:
          htmlFile: results.html
          outputFile: AntmanPerformanceReport.pdf
          pdfOptions: '{"format": "A4", "margin": {"top": "10mm", "left": "10mm", "right": "10mm", "bottom": "10mm"}, "landscape": true, "printBackground": true}'
</code>```

HTML:

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>

Processing Performance Testing Report

        Request Period
        Datadog
        Max Throughput
        Test Length

        9-1-2023
         K6 Datadog dashboard
        1.00 TPS
        0.28030098333333336 mins

Scenario: Full Card Visa

        Component
        Availability SLO
        Latency SLO

         Gateway
        ✔
        ✔

         Prism
        !
        ✔

         Vault
        ✔
        ✔

         Card Processing
        ✔
        ✔

         Access
        !
        ✔

         Harmonia
        ✔
        ✔

         Routing
        ✔
        ✔

```

PDF:

How to display the tick mark in the PDF?

Body:
I create an html file using a node js script. It contains a table where I display tick mark based on certain conditions. The code to display the tick mark in the table cell is as follows:

" + "Passed \u2714" + "

It displays perfectly fine in html but when I try to convert html to pdf using html-to-pdf github action, it is displaying the pdf without the tick mark.

Code in github action which is converting it:

- name: Convert HTML to PDF report
        if: always()
        uses: fifsky/html-to-pdf-action@master
        with:
          htmlFile: results.html
          outputFile: AntmanPerformanceReport.pdf
          pdfOptions: '{"format": "A4", "margin": {"top": "10mm", "left": "10mm", "right": "10mm", "bottom": "10mm"}, "landscape": true, "printBackground": true}'

HTML:

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>

Processing Performance Testing Report

        Request Period
        Datadog
        Max Throughput
        Test Length

        9-1-2023
         K6 Datadog dashboard
        1.00 TPS
        0.28030098333333336 mins

Scenario: Full Card Visa

        Component
        Availability SLO
        Latency SLO

         Gateway
        ✔
        ✔

         Prism
        !
        ✔

         Vault
        ✔
        ✔

         Card Processing
        ✔
        ✔

         Access
        !
        ✔

         Harmonia
        ✔
        ✔

         Routing
        ✔
        ✔

PDF:

How to display the tick mark in the PDF?


问:
Handle success actions in angular when moved out of the component
I have a angular code, which allows the user to delete the file from the UI. The function dispatches the call to delete the file from the FTP server and then if its success, it dispatches another function to delete the data in DB.
While the call to delete the file in the FTP server is inprogress and waiting for the response from the API, if the user moves out, the 2nd dispatch call is never triggered. How do I handle this?

//1st dispatch call - to delete the file from FTP

```<code>delete(documentId: string) {
    this.isMaxSizeError = false;
    this.isFileTypeError = false;
    const document = this.getDocument(documentId);
    if (isNullOrUndefined(document) || document.isDelete) { return; }
    const versionId = document.version;
    document.isDelete = true;
    this.dispatcher.fire(
      new DeleteFilesAction({
        xPath: this.xPath,
        documentId,
        versionId
      })
    );
  }
</code>```

//Success action of dispatcher

```<code>  return this.organisationSelectors.actionSuccessOfSubtype$(OrganisationActionNames.DELETE_FILES).pipe(
      filter(a => a.payload.xPath === this.xPath))
      .subscribe((result) => {
        const response = result.payload as DocumentDeleteResponse;
        if (response.status) {
          this.onNgModelChange(
            this.data.documents.filter(x => x.id !== response.documentId)
          );
          this.dispatcher.fire(new DeleteDocumentFromDB(response.documentId, response.eventId));
        }
      });
</code>```

The call DeleteDocumentFromDB is not triggered.

Body:
I have a angular code, which allows the user to delete the file from the UI. The function dispatches the call to delete the file from the FTP server and then if its success, it dispatches another function to delete the data in DB.
While the call to delete the file in the FTP server is inprogress and waiting for the response from the API, if the user moves out, the 2nd dispatch call is never triggered. How do I handle this?

//1st dispatch call - to delete the file from FTP

delete(documentId: string) {
    this.isMaxSizeError = false;
    this.isFileTypeError = false;
    const document = this.getDocument(documentId);
    if (isNullOrUndefined(document) || document.isDelete) { return; }
    const versionId = document.version;
    document.isDelete = true;
    this.dispatcher.fire(
      new DeleteFilesAction({
        xPath: this.xPath,
        documentId,
        versionId
      })
    );
  }

//Success action of dispatcher

  return this.organisationSelectors.actionSuccessOfSubtype$(OrganisationActionNames.DELETE_FILES).pipe(
      filter(a => a.payload.xPath === this.xPath))
      .subscribe((result) => {
        const response = result.payload as DocumentDeleteResponse;
        if (response.status) {
          this.onNgModelChange(
            this.data.documents.filter(x => x.id !== response.documentId)
          );
          this.dispatcher.fire(new DeleteDocumentFromDB(response.documentId, response.eventId));
        }
      });

The call DeleteDocumentFromDB is not triggered.


问:
How to clean up the database after ALL tests in phpUnit?
Is there a function in phpUnit that allows you to clean up the database after running all the available tests?

So far I've been able to implement this via a database schema drop update, but this happens after each test class.

```<code>public static function tearDownAfterClass(): void
{
    exec('php bin/console doctrine:schema:drop --env test -f');
    exec('php bin/console doctrine:schema:update --env test -f');
}
</code>```

tearDown() is generally performed after each test in the test class.

Is it possible to set a function that will be executed after all phpunit tests?

Body:
Is there a function in phpUnit that allows you to clean up the database after running all the available tests?

So far I've been able to implement this via a database schema drop update, but this happens after each test class.

public static function tearDownAfterClass(): void
{
    exec('php bin/console doctrine:schema:drop --env test -f');
    exec('php bin/console doctrine:schema:update --env test -f');
}

tearDown() is generally performed after each test in the test class.

Is it possible to set a function that will be executed after all phpunit tests?


问:
What is the code flow of the magento-functional-testing-framework?
This is the directory structure for the mftf

```<code>├── ActionGroup
│
├── Data
│
├── Metadata
│
├── Page
│
├── Section
│
├── Suite
│
└── Test
</code>```

If I run the mftf command:

php -d memory_limit=-1 vendor/bin/mftf generate:tests
AdminLoginSuccessfulTest

then I want to know exactly how the execution of the code gets started.

To be accurate which XML file is being called first is it the file under the test folder or is it under the page folder or section folder first,I want to know the exact code flow from start to end for the mftf for the command:

php -d memory_limit=-1 vendor/bin/mftf generate:tests
AdminLoginSuccessfulTest

Body:
This is the directory structure for the mftf

├── ActionGroup
│
├── Data
│
├── Metadata
│
├── Page
│
├── Section
│
├── Suite
│
└── Test

If I run the mftf command:

php -d memory_limit=-1 vendor/bin/mftf generate:tests
AdminLoginSuccessfulTest

then I want to know exactly how the execution of the code gets started.

To be accurate which XML file is being called first is it the file under the test folder or is it under the page folder or section folder first,I want to know the exact code flow from start to end for the mftf for the command:

php -d memory_limit=-1 vendor/bin/mftf generate:tests
AdminLoginSuccessfulTest


问:
Integrating google Speech Listener on WearOS app (Samsung Galaxy 4, 5, Google Pixel)
We developed an app that needs to work on all smartwatches with wearOS. The app is installed on Ticwatch and it works perfectly well.

In the same app, with the same wearOS version, we are facing an issue on Samsung smartwatch Galaxy 4, 5 and Pixel with a speech listener. We get the following error:

E/SpeechRecognizer: no selected voice recognition service
(The smartwatch is properly installed with all the latest versions)

does anyone have an idea, of what can it be or what we need to do in order to make it work on Samsung Galaxy 4 and 5 or Google Pixel?

#In order to isolate the issue,we have created a simple app.

#After installation of the simple app (Main activity code below) on the latest devices with two #different options for voice recognition, we have the same problems on both of them.

#Please see the screens of the debug mode.*

#If we cannot solve it, our startup will not be able to start POC.
#(*To make you sure: all libraries are updated to the latest android version.)

#[]#(https://i.stack.imgur.com/T8X8l.jpg)
#
#

#MainActivity.kt -

```<code>package com.sustav.mytest.view.speech_listener_demo

import android.Manifest
import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.sustav.mytest.view.speech_listener_demo.databinding.ActivityMainBinding
import java.util.*

class MainActivity : Activity() {
    private lateinit var binding: ActivityMainBinding
    private val RecordAudioRequestCode = 1
    private var speechRecognizer: SpeechRecognizer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            checkPermission()
        }

        Log.d("SPEECH", "Is available: ${SpeechRecognizer.isRecognitionAvailable(this)}")

        //First approach E/SpeechRecognizer: no selected voice recognition service
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
        //Second approach E/SpeechRecognizer: bind to recognition service failed
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
            ComponentName.unflattenFromString("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"));

        val voice = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
          voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())

        setUpSpeechListener()

        binding.mybutton.setOnClickListener {
            speechRecognizer!!.startListening(voice)
        }
    }

    private fun setUpSpeechListener() {
        speechRecognizer!!.setRecognitionListener(object : RecognitionListener {
            override fun onReadyForSpeech(bundle: Bundle) {}
            override fun onBeginningOfSpeech() {
                binding.text.text = "Listening..."
                binding.text.hint = "Listening..."
            }

            override fun onRmsChanged(v: Float) {}
            override fun onBufferReceived(bytes: ByteArray) {}
            override fun onEndOfSpeech() {}
            override fun onError(i: Int) {}
            override fun onResults(bundle: Bundle) {
                binding.mybutton.setImageResource(R.drawable.ic_mic_black_off)
                val data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
                binding.text.text = data!![0]
                binding.text.hint = "Listening..."
            }

            override fun onPartialResults(bundle: Bundle) {}
            override fun onEvent(i: Int, bundle: Bundle) {}
        })
    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                RecordAudioRequestCode
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == RecordAudioRequestCode && grantResults.size > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) Toast.makeText(
                this,
                "Permission Granted",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    override fun onDestroy() {
        speechRecognizer!!.destroy()
        super.onDestroy()
    }
}

</code>```

Body:
We developed an app that needs to work on all smartwatches with wearOS. The app is installed on Ticwatch and it works perfectly well.

In the same app, with the same wearOS version, we are facing an issue on Samsung smartwatch Galaxy 4, 5 and Pixel with a speech listener. We get the following error:

E/SpeechRecognizer: no selected voice recognition service
(The smartwatch is properly installed with all the latest versions)

does anyone have an idea, of what can it be or what we need to do in order to make it work on Samsung Galaxy 4 and 5 or Google Pixel?

#In order to isolate the issue,we have created a simple app.

#After installation of the simple app (Main activity code below) on the latest devices with two #different options for voice recognition, we have the same problems on both of them.

#Please see the screens of the debug mode.*

#If we cannot solve it, our startup will not be able to start POC.
#(*To make you sure: all libraries are updated to the latest android version.)

#[]#(https://i.stack.imgur.com/T8X8l.jpg)
#
#

#MainActivity.kt -

package com.sustav.mytest.view.speech_listener_demo

import android.Manifest
import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.sustav.mytest.view.speech_listener_demo.databinding.ActivityMainBinding
import java.util.*

class MainActivity : Activity() {
    private lateinit var binding: ActivityMainBinding
    private val RecordAudioRequestCode = 1
    private var speechRecognizer: SpeechRecognizer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            checkPermission()
        }

        Log.d("SPEECH", "Is available: ${SpeechRecognizer.isRecognitionAvailable(this)}")

        //First approach E/SpeechRecognizer: no selected voice recognition service
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
        //Second approach E/SpeechRecognizer: bind to recognition service failed
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
            ComponentName.unflattenFromString("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"));

        val voice = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
          voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())

        setUpSpeechListener()

        binding.mybutton.setOnClickListener {
            speechRecognizer!!.startListening(voice)
        }
    }

    private fun setUpSpeechListener() {
        speechRecognizer!!.setRecognitionListener(object : RecognitionListener {
            override fun onReadyForSpeech(bundle: Bundle) {}
            override fun onBeginningOfSpeech() {
                binding.text.text = "Listening..."
                binding.text.hint = "Listening..."
            }

            override fun onRmsChanged(v: Float) {}
            override fun onBufferReceived(bytes: ByteArray) {}
            override fun onEndOfSpeech() {}
            override fun onError(i: Int) {}
            override fun onResults(bundle: Bundle) {
                binding.mybutton.setImageResource(R.drawable.ic_mic_black_off)
                val data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
                binding.text.text = data!![0]
                binding.text.hint = "Listening..."
            }

            override fun onPartialResults(bundle: Bundle) {}
            override fun onEvent(i: Int, bundle: Bundle) {}
        })
    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                RecordAudioRequestCode
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == RecordAudioRequestCode && grantResults.size > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) Toast.makeText(
                this,
                "Permission Granted",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    override fun onDestroy() {
        speechRecognizer!!.destroy()
        super.onDestroy()
    }
}


问:
Loader not working while the data is being processed
I think is because it gets caught in the loop of the components and doesnt let the component render the loader, but i dont know how to fix it.

```<code>const Simulate = (props) => {
    const [isLoading, setIsLoading] = useState(true);

    const steps = props.nodes[0].data.fields.arrivals;
    const duracionPrueba = props.nodes[0].data.fields.duracionPrueba;
    let stepsTime = arrivalSteps(steps, duracionPrueba);

    let visitas = []

    let llegadas = {};
    let finalizadas = {};
    let tiempoRespuesta = {};
    let errores = {};
    let filtrados = {};
    let concurrencia = {};
    let cola = {};

    let [nodesPath, tree] = NodesPath(props.edges)

    let leaves = [];
    findLeaves(tree, leaves);
    weightNodes(tree, props.nodes, props.edges);
    let segundo = 1;

    useEffect(() => {

        steps.forEach((step, i) => {
            let timeStep = 1;
            while (timeStep <= stepsTime[i]) {
                console.log(segundo)

                runPath(nodesPath, props.nodes, step, llegadas, visitas, finalizadas, tree);

                checkFinish(visitas, leaves, errores, filtrados, concurrencia, cola, tiempoRespuesta, props.nodes);

                segundo = segundo + 1;
                timeStep = timeStep + 1;

            }
        });
        while (visitas.length > 0) {
            console.log(segundo);
            runPath(nodesPath, props.nodes, 0, llegadas, visitas, finalizadas, tree);

            checkFinish(visitas, leaves, errores, filtrados, concurrencia, cola, tiempoRespuesta, props.nodes);

            segundo++;

        }

        let simulateResults = {
            duracionPrueba: duracionPrueba,
            tiempoTotal: segundo,
            tiempoRespuesta: tiempoRespuesta,
            concurrencia: concurrencia,
            cola: cola,
            errores: errores,
            filtrados: filtrados,
            llegadas: llegadas,
            finalizadas: finalizadas,
        };
        props.handleSimulate(simulateResults);
        setIsLoading(false);

    })

    if (isLoading) {
        return(
            <Modal
                open={isLoading}
                aria-labelledby="modal-modal-title"
                aria-describedby="modal-modal-description"
            >
                <Box sx={{style}} className='loader'>
                <CircularProgress style={{transform: 'translate(-50%, -50%)'}} />
                </Box>
            </Modal>
        )
    }

}
</code>```

I tried to put the processing data code on a useEffect hook but it didnt work.

Body:
I think is because it gets caught in the loop of the components and doesnt let the component render the loader, but i dont know how to fix it.

const Simulate = (props) => {
    const [isLoading, setIsLoading] = useState(true);

    const steps = props.nodes[0].data.fields.arrivals;
    const duracionPrueba = props.nodes[0].data.fields.duracionPrueba;
    let stepsTime = arrivalSteps(steps, duracionPrueba);

    let visitas = []

    let llegadas = {};
    let finalizadas = {};
    let tiempoRespuesta = {};
    let errores = {};
    let filtrados = {};
    let concurrencia = {};
    let cola = {};

    let [nodesPath, tree] = NodesPath(props.edges)

    let leaves = [];
    findLeaves(tree, leaves);
    weightNodes(tree, props.nodes, props.edges);
    let segundo = 1;

    useEffect(() => {

        steps.forEach((step, i) => {
            let timeStep = 1;
            while (timeStep <= stepsTime[i]) {
                console.log(segundo)

                runPath(nodesPath, props.nodes, step, llegadas, visitas, finalizadas, tree);

                checkFinish(visitas, leaves, errores, filtrados, concurrencia, cola, tiempoRespuesta, props.nodes);

                segundo = segundo + 1;
                timeStep = timeStep + 1;

            }
        });
        while (visitas.length > 0) {
            console.log(segundo);
            runPath(nodesPath, props.nodes, 0, llegadas, visitas, finalizadas, tree);

            checkFinish(visitas, leaves, errores, filtrados, concurrencia, cola, tiempoRespuesta, props.nodes);

            segundo++;

        }

        let simulateResults = {
            duracionPrueba: duracionPrueba,
            tiempoTotal: segundo,
            tiempoRespuesta: tiempoRespuesta,
            concurrencia: concurrencia,
            cola: cola,
            errores: errores,
            filtrados: filtrados,
            llegadas: llegadas,
            finalizadas: finalizadas,
        };
        props.handleSimulate(simulateResults);
        setIsLoading(false);

    })

    if (isLoading) {
        return(
            <Modal
                open={isLoading}
                aria-labelledby="modal-modal-title"
                aria-describedby="modal-modal-description"
            >
                <Box sx={{style}} className='loader'>
                <CircularProgress style={{transform: 'translate(-50%, -50%)'}} />
                </Box>
            </Modal>
        )
    }

}

I tried to put the processing data code on a useEffect hook but it didnt work.


问:
How to run asyncio within a flask app for a websockets data stream?
I am looking for the best way incorporate this websockets streamer into a web app interface via Flask. Currently this code does not work. The stream runs, but the webpage is stuck. How do you add such a stream to a flask page?

```<code>import asyncio
from aioflask import Flask, request, Response

app = Flask(__name__)

@app.route('/')

async def index():

  async def read_stream():

      await stream_client.login()
      await stream_client.quality_of_service(StreamClient.QOSLevel.EXPRESS)

      def process_message(message):

        data_content = message['content'][0]

        return Response(json.dumps(message, indent=4))

      stream_client.add_chart_equity_handler(process_message)

      await stream_client.chart_equity_subs(['SPY'])

      while True:
          await stream_client.handle_message()

if __name__ == '__main__':

  app.run(debug=True)
</code>```

I tried implementing this code from the docs:

```<code>
async def get_data():
    data = await async_db_query(...)
    return jsonify(data)
</code>```

but I am unsure how to use this, and it doesn't appear that the stream is starting.

Body:
I am looking for the best way incorporate this websockets streamer into a web app interface via Flask. Currently this code does not work. The stream runs, but the webpage is stuck. How do you add such a stream to a flask page?

import asyncio
from aioflask import Flask, request, Response

app = Flask(__name__)

@app.route('/')

async def index():

  async def read_stream():

      await stream_client.login()
      await stream_client.quality_of_service(StreamClient.QOSLevel.EXPRESS)

      def process_message(message):

        data_content = message['content'][0]

        return Response(json.dumps(message, indent=4))

      stream_client.add_chart_equity_handler(process_message)

      await stream_client.chart_equity_subs(['SPY'])

      while True:
          await stream_client.handle_message()

if __name__ == '__main__':

  app.run(debug=True)

I tried implementing this code from the docs:

async def get_data():
    data = await async_db_query(...)
    return jsonify(data)

but I am unsure how to use this, and it doesn't appear that the stream is starting.


问:
How to pass a parameter to a post confirmation Lambda using Cognito Hosted UI
I want to pass a parameter for a post-confirmation AWS Lambda function in an AWS Cognito Hosted UI sign-up URL.

I have the following workflow:
A user chooses a plan on a pricing page, then passes authentication, and then I want to save the chosen plan in a Dynamo table using a post-confirmation Lambda function.

Is it possible to do it?


问:
Alertmanager `inhibit_rules` not working?
I'm trying to configure something that seems very simple:
"If the datasource (prometheus) is down, don't spam alerts, and only notify that Prometheus is down"

Immediately I went to inhibit_rules, and after trying probably several hundred combinations I cannot make it work under any condition.

This is my config:

```<code>inhibit_rules:
  - source_matchers:
      - 'alertname = prometheus-up'
    target_matchers:
      - 'datasource = prometheus'
    equal:
      - 'datasource'
</code>```

Now I've honestly tried any label combination I can think of, used different labels, no labels, no equal, NOTHING works, all alerts are fires whenever the datasource is down.

What am I missing here? the Prometheus/Alertmanager docs are terrible and provide no help, and no examples exist expect very simple use cases.

Body:
I'm trying to configure something that seems very simple:
"If the datasource (prometheus) is down, don't spam alerts, and only notify that Prometheus is down"

Immediately I went to inhibit_rules, and after trying probably several hundred combinations I cannot make it work under any condition.

This is my config:

inhibit_rules:
  - source_matchers:
      - 'alertname = prometheus-up'
    target_matchers:
      - 'datasource = prometheus'
    equal:
      - 'datasource'

Now I've honestly tried any label combination I can think of, used different labels, no labels, no equal, NOTHING works, all alerts are fires whenever the datasource is down.

What am I missing here? the Prometheus/Alertmanager docs are terrible and provide no help, and no examples exist expect very simple use cases.


问:
Exclude a delivery date based on product in cart for Woocommerce
I am trying to exclude a certain delivery date on my delivery date picker on the checkout page, based on the product the customer has in the cart. E.g if someone has added product ID 6610 in their cart, I don't want them to be able to select the 14th Feb as a delivery date.

I cannot get this to work and I don't know why. Can anyone assist please? Thanks

```<code>// Hook into WooCommerce's "woocommerce_checkout_fields" filter
add_filter( 'woocommerce_checkout_fields', 'block_delivery_dates_checkout_form' );

function block_delivery_dates_checkout_form( $fields ) {
  // Array of dates to be blocked for the specified product
  $blocked_dates = array('2023-02-14');

  // Iterate over all products in the cart
  foreach ( WC()->cart->get_cart() as $cart_item ) {
    // Check if the product is the one we want to block delivery for
    if ( $cart_item['product_id'] == 6610 ) {
      // Loop through each date in the array of blocked dates
      foreach ( $blocked_dates as $date ) {
        // Add the date to the "exclude" option in the delivery date field
        $fields['delivery_date']['exclude'][] = $date;
      }
    }
  }

  return $fields;
}
</code>```

Body:
I am trying to exclude a certain delivery date on my delivery date picker on the checkout page, based on the product the customer has in the cart. E.g if someone has added product ID 6610 in their cart, I don't want them to be able to select the 14th Feb as a delivery date.

I cannot get this to work and I don't know why. Can anyone assist please? Thanks

// Hook into WooCommerce's "woocommerce_checkout_fields" filter
add_filter( 'woocommerce_checkout_fields', 'block_delivery_dates_checkout_form' );

function block_delivery_dates_checkout_form( $fields ) {
  // Array of dates to be blocked for the specified product
  $blocked_dates = array('2023-02-14');

  // Iterate over all products in the cart
  foreach ( WC()->cart->get_cart() as $cart_item ) {
    // Check if the product is the one we want to block delivery for
    if ( $cart_item['product_id'] == 6610 ) {
      // Loop through each date in the array of blocked dates
      foreach ( $blocked_dates as $date ) {
        // Add the date to the "exclude" option in the delivery date field
        $fields['delivery_date']['exclude'][] = $date;
      }
    }
  }

  return $fields;
}


问:
Issue Importing Models to Diffusion Bee
When trying to import a Protogen model (.ckpt file type) to Diffusion Bee, I keep getting this error:

Error Traceback (most recent call last):
File "convert_model.py", line 28, in
KeyError: 'state_dict'
[83158] Failed to execute script 'convert_model' due to unhandled exception!

The model should import without issue.

Title: Issue Importing Models to Diffusion Bee


问:
How to trigger an action from a Typescript class containing a form only when one certain field of the form is modified?
I have a Typescript class containing the code executed after the submission of modifications of some fields of a form. I was asked to program the deconnection of the user after he has submitted the modification of his email address.
The line of code doing so is

```<code>this.keycloak.logout().then(() => this.keycloak.clearToken())
</code>```

But if I add this sole line, without control, it deconnects whatever the field modified

```<code>export class MonProfilComponent implements OnInit {
  form!: FormGroup;
  //....
  donneePersonnelle!: DonneePersonnelle;

  /**
  * Constructor
  */
  constructor(
    private monService: MonService,
    protected readonly keycloak: KeycloakService) {
     this.form = new FormGroup(
      {
        phoneNumber: new FormControl('', [
        ...
        ...
       ]),
        emailAddress: new FormControl('', Validators.required)
      });
     }

async ngOnInit(): Promise<void> {
   //method that fills the form with the data already in database
   this.monService
     .obtenirMesInformationsPersonnelles()
     .subscribe((resultat) => {
    ...
   )}
 }

//method performing actions after the submission of modifications of one or several fields
  submit() {
    this.donneePersonnelle = new DonneePersonnelle();

    this.donneePersonnelle.emailAddress =
    this.form.controls['emailAdress'].value;

    this.donneePersonnelle.phoneNumber =
    this.form.controls['phoneNumber'].value;

   //call of the service modifying the data in the database
  }
}
</code>```

I tried

```<code> if (this.form.controls['emailAddress'].valueChanges {
  this.keycloak.logout().then(() => this.keycloak.clearToken())
 }
</code>```

But the result is not what I expected

Body:
I have a Typescript class containing the code executed after the submission of modifications of some fields of a form. I was asked to program the deconnection of the user after he has submitted the modification of his email address.
The line of code doing so is

this.keycloak.logout().then(() => this.keycloak.clearToken())

But if I add this sole line, without control, it deconnects whatever the field modified

export class MonProfilComponent implements OnInit {
  form!: FormGroup;
  //....
  donneePersonnelle!: DonneePersonnelle;

  /**
  * Constructor
  */
  constructor(
    private monService: MonService,
    protected readonly keycloak: KeycloakService) {
     this.form = new FormGroup(
      {
        phoneNumber: new FormControl('', [
        ...
        ...
       ]),
        emailAddress: new FormControl('', Validators.required)
      });
     }

async ngOnInit(): Promise<void> {
   //method that fills the form with the data already in database
   this.monService
     .obtenirMesInformationsPersonnelles()
     .subscribe((resultat) => {
    ...
   )}
 }

//method performing actions after the submission of modifications of one or several fields
  submit() {
    this.donneePersonnelle = new DonneePersonnelle();

    this.donneePersonnelle.emailAddress =
    this.form.controls['emailAdress'].value;

    this.donneePersonnelle.phoneNumber =
    this.form.controls['phoneNumber'].value;

   //call of the service modifying the data in the database
  }
}

I tried

 if (this.form.controls['emailAddress'].valueChanges {
  this.keycloak.logout().then(() => this.keycloak.clearToken())
 }

But the result is not what I expected