问:
Does React_Native_Share allow us to share other file type than images and pdf?
I used this website to convert the file into bas64 type eConversion to Base64
I am able to export pdf and images (jpeg/png) but not xslx and csv file types. My app needs user the ability to export/download excel files.

```<code> const myCustomShare = async () => {

    const shareOptions = {
      message: `Your data to export`,
      url: data:@file/csv;base64,{base64 value},
    };

    try {
      const ShareResponse = await Share.open(shareOptions);
      console.log(JSON.stringify(ShareResponse));
    } catch (error) {
      console.log("Error => ", error);
    }
  };
</code>```

data:@file/csv;base64,{base64 value} && data:@file/xslx;base64,{base64 value}. I have these as the url for csv and excel respectively.
Thank you in advance,

Body:
I used this website to convert the file into bas64 type eConversion to Base64
I am able to export pdf and images (jpeg/png) but not xslx and csv file types. My app needs user the ability to export/download excel files.

 const myCustomShare = async () => {

    const shareOptions = {
      message: `Your data to export`,
      url: data:@file/csv;base64,{base64 value},
    };

    try {
      const ShareResponse = await Share.open(shareOptions);
      console.log(JSON.stringify(ShareResponse));
    } catch (error) {
      console.log("Error => ", error);
    }
  };

data:@file/csv;base64,{base64 value} && data:@file/xslx;base64,{base64 value}. I have these as the url for csv and excel respectively.
Thank you in advance,


来源: stackexchange

问:
Can't Grant SLAVE MONITOR to user on MariaDB 10.6 Primary
We recently replaced an old MariaDB 10.3 primary with one of it's replicas which is running 10.6.x. Hoping that this would resolve a weird Primary/replica issue that we have had since creating the replicas.

The Struggle:
Per the MariaDB documentation in order for a user to have access to SHOW REPLICA STATUS (formerly SHOW SLAVE STATUS) in MariaDB 10.3 that user needed the REPLICATION CLIENT privilege. Furthermore REPLICATION CLIENT was renamed to BINLOG MONITOR in mariadb 10.5.2 and this Privilege does show up as BINLOG MONITOR when granting the REPLICATION CLIENT privilege on versions of 10.5.2 or newer. However, according to the mariadb kb (and confirmed by my experience) "Unlike REPLICATION CLIENT prior to MariaDB 10.5, SHOW REPLICA STATUS isn't included in this privilege, and REPLICA MONITOR is required". This has created a bit of a headache for me.

The old problem:
Due to the cups and ball trick MDB has decided to play with the SHOW REPLICA STATUS privilege I couldn't grant REPLICA MONITOR on the old primary without getting an error (because that privilege doesn't exist on 10.3) and REPLICATION CLIENT wasn't sufficient on the replicas (because SHOW REPLICA STATUS was moved to REPLICA MONITOR). This lead me to EOL the old primary and promote one of the 10.6 replicas to primary.

The new problem (or just the old problem persisting):
The problem however is the new primary which is running 10.6 is behaving almost exactly like the old primary (which, again was on 10.3). The only difference is when I grant REPLICA MONITOR now I don't get an error but the grant doesn't stick. I can FLUSH PRIVILEGES and SHOW GRANTS... on the user but it isn't there.

So the question is what would cause a mariadb 10.6 Primary to behave like the former 10.3 primary in this scenario? is there some config or system variable I am unaware of?

FWIW the machine was rebooted a few times during the fail-over process but if that is the fix it can be done again. I have also tried granting SLAVE MONITOR which is the former version of REPLICA MONITOR but it doesn't stick either. I also tried granting BINLOG MONITOR which does stick but as I've already covered isn't sufficient on 10.6.

ContentLicense: CC BY-SA 4.0


问:
`CustomScrollView` with `SliverFillRemaining` show jittery effect
I wanted my button to shift below the content when the keyboard opens or there is no space on the screen, and when there is more space it should stick to the bottom of the screen. For that, I use a CustomScrollView but now the jittery effect is there. How can I make this transition smooth?
Here is the video of the screen:
Rendered Screen

In order to align my button on the bottom of the screen, So I used a CustomScrollView with two sliver widgets SliverToBoxAdapter and SliverFillRemaining with hasScrollBody: false and aligned the button by wrapping in a Align and set alignment: Alignment.bottomCenter.
Widget Tree


问:
Issue in pgloader in version postgres Version 14
Error - Pgloader 19 fell through ECASE  expression wanted one of (0 2 3 4 5 6 7 8)

Current version - pgloder version 3.6.2
Postgres Version -14

It working in 12 version successfully


问:
facebook localhost development problem - works occasionally
I am trying to integrate facebook login in my application and the development is on localhost...
problem is I get the login button sometimes when I open the site.
Most of the cases, I have to refresh the page again and again and still it does not appear.
Well the internet is up and running..
It works fine whenever the login button appears...</p>

ContentLicense: CC BY-SA 3.0


问:
React Native - Flatlist not scrolling in custom dropdown
I have Flatlist that doesn't scroll.

I can't find the problem why its not scrolling.

When I'm trying to scroll, It does nothing. It doesn't give me to scroll past the Produce item.

It looks like this (I have more items after Produce):

This is my code:

```<code>const Dropdown: FC<Props> = ({ label, data, onSelect, current, style }) => {

        const [dropdownTop, setDropdownTop] = useState(0);
        const [visible, setVisible] = useState(false);
        const [selected, setSelected] = useState(current);

        const DropdownButton = useRef();

        const toggleDropdown = (): void => {
            visible ? setVisible(false) : openDropdown();
        };

        const openDropdown = (): void => {
            DropdownButton.current.measure((_fx, _fy, _w, h, _px, _py) => {
                setDropdownTop(_py + h - 10);
            });
            setVisible(true);
        };

        const renderDropdown = (): ReactElement<any, any> => {
            return (
                <Modal visible={visible} transparent animationType='none'>
                    <TouchableOpacity
                        style={styles.overlay}
                        onPress={() => setVisible(false)}>

                        <View style={[styles.dropdown, { top: dropdownTop }]}>
                            <FlatList
                                data={data}
                                renderItem={renderItem}
                                keyExtractor={(item, index) => index.toString()}
                                contentContainerStyle={{
                                    flexGrow: 1,
                                    flex: 1,
                                }}
                            />
                        </View>
                    </TouchableOpacity>
                </Modal>
            )
        };

        const renderItem = ({ item }): ReactElement<any, any> => (
            <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
                <Text style={{ color: "#616161" }}>{item.label}</Text>
            </TouchableOpacity>
        )

        const onItemPress = (item): void => {
            setSelected(item);
            onSelect(item);
            setVisible(false);
        };

        return (
            <TouchableOpacity
                ref={DropdownButton}
                style={[styles.button, style]}
                activeOpacity={0.6}
                onPress={toggleDropdown}>
                {renderDropdown()}
                <Text style={styles.buttonSecondText}>{label}</Text>
                <Text style={styles.buttonText}>{(selected && selected.label) || null}</Text>
            </TouchableOpacity>
        )
    }

    export default Dropdown

    const styles = StyleSheet.create({
        item: {
            paddingHorizontal: 10,
            paddingVertical: 10,
            // borderBottomWidth: 1,
            borderWidth: 1,
        },

        button: {
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#FFF',
            elevation: 10,
            width: '100%',
            paddingHorizontal: 13,
            paddingVertical: 13,
            borderRadius: 10,
            zIndex: 1,
        },

        buttonSecondText: {
            flex: 2,
            color: '#000',
            textAlign: 'left',
        },

        buttonText: {
            flex: 2,
            textAlign: 'right',
            color: '#000',
        },

        dropdown: {
            position: 'absolute',
            backgroundColor: '#FFF',
            paddingHorizontal: 20,
            width: '100%',
            shadowColor: '#000000',
            shadowRadius: 4,
            shadowOffset: { height: 4, width: 0 },
            shadowOpacity: 0.5,
        },
    });
</code>```

I can't understand where is my problem and why its not scrolling.

Maybe its because its inside a Modal? I'm first time trying to use Modal in React Native

Body:
I have Flatlist that doesn't scroll.

I can't find the problem why its not scrolling.

When I'm trying to scroll, It does nothing. It doesn't give me to scroll past the Produce item.

It looks like this (I have more items after Produce):

This is my code:

const Dropdown: FC<Props> = ({ label, data, onSelect, current, style }) => {

        const [dropdownTop, setDropdownTop] = useState(0);
        const [visible, setVisible] = useState(false);
        const [selected, setSelected] = useState(current);

        const DropdownButton = useRef();

        const toggleDropdown = (): void => {
            visible ? setVisible(false) : openDropdown();
        };

        const openDropdown = (): void => {
            DropdownButton.current.measure((_fx, _fy, _w, h, _px, _py) => {
                setDropdownTop(_py + h - 10);
            });
            setVisible(true);
        };

        const renderDropdown = (): ReactElement<any, any> => {
            return (
                <Modal visible={visible} transparent animationType='none'>
                    <TouchableOpacity
                        style={styles.overlay}
                        onPress={() => setVisible(false)}>

                        <View style={[styles.dropdown, { top: dropdownTop }]}>
                            <FlatList
                                data={data}
                                renderItem={renderItem}
                                keyExtractor={(item, index) => index.toString()}
                                contentContainerStyle={{
                                    flexGrow: 1,
                                    flex: 1,
                                }}
                            />
                        </View>
                    </TouchableOpacity>
                </Modal>
            )
        };

        const renderItem = ({ item }): ReactElement<any, any> => (
            <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
                <Text style={{ color: "#616161" }}>{item.label}</Text>
            </TouchableOpacity>
        )

        const onItemPress = (item): void => {
            setSelected(item);
            onSelect(item);
            setVisible(false);
        };

        return (
            <TouchableOpacity
                ref={DropdownButton}
                style={[styles.button, style]}
                activeOpacity={0.6}
                onPress={toggleDropdown}>
                {renderDropdown()}
                <Text style={styles.buttonSecondText}>{label}</Text>
                <Text style={styles.buttonText}>{(selected && selected.label) || null}</Text>
            </TouchableOpacity>
        )
    }

    export default Dropdown

    const styles = StyleSheet.create({
        item: {
            paddingHorizontal: 10,
            paddingVertical: 10,
            // borderBottomWidth: 1,
            borderWidth: 1,
        },

        button: {
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#FFF',
            elevation: 10,
            width: '100%',
            paddingHorizontal: 13,
            paddingVertical: 13,
            borderRadius: 10,
            zIndex: 1,
        },

        buttonSecondText: {
            flex: 2,
            color: '#000',
            textAlign: 'left',
        },

        buttonText: {
            flex: 2,
            textAlign: 'right',
            color: '#000',
        },

        dropdown: {
            position: 'absolute',
            backgroundColor: '#FFF',
            paddingHorizontal: 20,
            width: '100%',
            shadowColor: '#000000',
            shadowRadius: 4,
            shadowOffset: { height: 4, width: 0 },
            shadowOpacity: 0.5,
        },
    });

I can't understand where is my problem and why its not scrolling.

Maybe its because its inside a Modal? I'm first time trying to use Modal in React Native


问:
Python + Selenium: how to automatically add test name and ids parameter or number to screenshot name?
I am learning how to write tests in Python + Selenium based on Page Object.

In general, the test code itself looks like this:

```<code>pytest.mark.parametrize("first_name", [double_first_name, empty_form, long_first_name],
                     ids=["double_first_name", "empty_form", "long_first_name"])
def test_reg_form_name(browser, first_name):
    passport_reg_page = RegForm(browser)
    passport_reg_page.go_to_site()
    passport_reg_page.reg_page()
    passport_reg_page.reg_first_name(first_name)
    passport_reg_page.reg_button()
    passport_reg_page = RegFormExpectations(browser)
    passport_reg_page.reg_expect_name()
    assert rt_passport_reg_page.reg_expect_name()
    browser.save_screenshot('screenshots/test_reg_1.png')
</code>```

How to write and call a function so that the name of the test + parameter ids is automatically added to the name of the screenshot, or at least the name of the test + the number of each parameter run? For example:

```<code>browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"ids"}.png')
</code>```

or

```<code>browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"001,002,003..."}.png')
</code>```

I've been proposed to try:

```<code>def test_name(self, request):
    testname = request.node.name
    return testname
</code>```

but got notice "Method 'test_name' may be 'static'"

Also the next method helps to get def name but I see no sense to write its name for further getting it:

```<code>browser.save_screenshot(f'screenshots/{test_reg_page.__name__}_1.png')
</code>```

Body:
I am learning how to write tests in Python + Selenium based on Page Object.

In general, the test code itself looks like this:

pytest.mark.parametrize("first_name", [double_first_name, empty_form, long_first_name],
                     ids=["double_first_name", "empty_form", "long_first_name"])
def test_reg_form_name(browser, first_name):
    passport_reg_page = RegForm(browser)
    passport_reg_page.go_to_site()
    passport_reg_page.reg_page()
    passport_reg_page.reg_first_name(first_name)
    passport_reg_page.reg_button()
    passport_reg_page = RegFormExpectations(browser)
    passport_reg_page.reg_expect_name()
    assert rt_passport_reg_page.reg_expect_name()
    browser.save_screenshot('screenshots/test_reg_1.png')

How to write and call a function so that the name of the test + parameter ids is automatically added to the name of the screenshot, or at least the name of the test + the number of each parameter run? For example:

browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"ids"}.png')

or

browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"001,002,003..."}.png')

I've been proposed to try:

def test_name(self, request):
    testname = request.node.name
    return testname

but got notice "Method 'test_name' may be 'static'"

Also the next method helps to get def name but I see no sense to write its name for further getting it:

browser.save_screenshot(f'screenshots/{test_reg_page.__name__}_1.png')


问:
Adding a filter menu on folium heatmap with time
I'm working with a car accidents dataset, and I want to create a folium heatmap with time, that shows all the casualties with their location. Here's a sample of the data called df_weather_casualties:

```<code>|Date2      | Latitude   | Longitude | Number_of_Casualties | Weather_Details
----------------------------------------------------------------------------------
|2005-01-04 | 51.489096 | -0.191170  | 1                    |  Raining no high winds
|2005-01-05 | 51.520075 | -0.211708  | 1                    |  Fine no high winds
|2005-01-06 | 51.525301 | -0.206458  | 1                    |  Fine no high winds
|2005-01-06 | 51.482442 | -0.173862  | 1                    |  Fine no high winds
|2005-01-10 | 51.495752 | -0.156618  | 1                    |  Fine no high winds
</code>```

Because there are duplicate dates (as there are multiple casualties in a day) I've created a time index with:

```<code>time_index = list(df_weather_casualties['Date2'].sort_values().astype('str').unique())
</code>```

I've created a list of lists meaning each element of the data will contain another list which represents Latitude, Longitude, Number_of_Casualties, and Weather_Details of each date with the following code:

```<code>df_weather_casualties['Date2'] = df_weather_casualties['Date2'].sort_values(ascending=True)
weather_casualties_data = []
for _, d in df_weather_casualties.groupby('Date2'):
    weather_casualties_data.append([[row['Latitude'], row['Longitude'], row['Number_of_Casualties'], row['Weather_Details']] for _, row in d.iterrows()])
</code>```

So the first element looks like this:

```<code>[[51.516575, -0.08126, 1, 'Fine no high winds'],
 [51.512515, -0.130576, 1, 'Fine no high winds'],
 [51.542651, -0.148234, 1, 'Raining no high winds']]
</code>```

I've created a folium map with the following code:

```<code>hmt = folium.Map(location=[55.000, -2.0000],
              tiles='cartodbdark_matter',
              zoom_start=5,
              control_scale=True)

HeatMapWithTime(
    weather_casualties_data,
    index=time_index,
    auto_play=False,
    blur=1.0,
    radius=8,
    max_opacity=0.4
    ).add_to(hmt)

hmt
</code>```

How can I add a filter menu to the map that filters through different "Weather_Detail" values, only showing the accidents belonging to each weather detail? I've seen people do it, but I've been unable to figure it out.

This code does what I want with a normal map, but I'm trying to get it to work with the time element:

```<code>hm = folium.Map(location=[55.000, -2.0000],
              tiles='cartodbdark_matter',
              zoom_start=5,
              control_scale=True)

for weather in df_weather_casualties["Weather_Details"].unique():
    weather_group = folium.FeatureGroup(name=weather)
    HeatMap(data=df_weather_casualties[df_weather_casualties["Weather_Details"] == weather][["Latitude", "Longitude"]], blur=1.0, radius=8, max_opacity=0.4).add_to(weather_group)
    weather_group.add_to(hm)

folium.LayerControl().add_to(hm)

hm
</code>```

Any help or pointers would be great.

Thanks.

Body:
I'm working with a car accidents dataset, and I want to create a folium heatmap with time, that shows all the casualties with their location. Here's a sample of the data called df_weather_casualties:

|Date2      | Latitude   | Longitude | Number_of_Casualties | Weather_Details
----------------------------------------------------------------------------------
|2005-01-04 | 51.489096 | -0.191170  | 1                    |  Raining no high winds
|2005-01-05 | 51.520075 | -0.211708  | 1                    |  Fine no high winds
|2005-01-06 | 51.525301 | -0.206458  | 1                    |  Fine no high winds
|2005-01-06 | 51.482442 | -0.173862  | 1                    |  Fine no high winds
|2005-01-10 | 51.495752 | -0.156618  | 1                    |  Fine no high winds

Because there are duplicate dates (as there are multiple casualties in a day) I've created a time index with:

time_index = list(df_weather_casualties['Date2'].sort_values().astype('str').unique())

I've created a list of lists meaning each element of the data will contain another list which represents Latitude, Longitude, Number_of_Casualties, and Weather_Details of each date with the following code:

df_weather_casualties['Date2'] = df_weather_casualties['Date2'].sort_values(ascending=True)
weather_casualties_data = []
for _, d in df_weather_casualties.groupby('Date2'):
    weather_casualties_data.append([[row['Latitude'], row['Longitude'], row['Number_of_Casualties'], row['Weather_Details']] for _, row in d.iterrows()])

So the first element looks like this:

[[51.516575, -0.08126, 1, 'Fine no high winds'],
 [51.512515, -0.130576, 1, 'Fine no high winds'],
 [51.542651, -0.148234, 1, 'Raining no high winds']]

I've created a folium map with the following code:

hmt = folium.Map(location=[55.000, -2.0000],
              tiles='cartodbdark_matter',
              zoom_start=5,
              control_scale=True)

HeatMapWithTime(
    weather_casualties_data,
    index=time_index,
    auto_play=False,
    blur=1.0,
    radius=8,
    max_opacity=0.4
    ).add_to(hmt)

hmt

How can I add a filter menu to the map that filters through different "Weather_Detail" values, only showing the accidents belonging to each weather detail? I've seen people do it, but I've been unable to figure it out.

This code does what I want with a normal map, but I'm trying to get it to work with the time element:

hm = folium.Map(location=[55.000, -2.0000],
              tiles='cartodbdark_matter',
              zoom_start=5,
              control_scale=True)

for weather in df_weather_casualties["Weather_Details"].unique():
    weather_group = folium.FeatureGroup(name=weather)
    HeatMap(data=df_weather_casualties[df_weather_casualties["Weather_Details"] == weather][["Latitude", "Longitude"]], blur=1.0, radius=8, max_opacity=0.4).add_to(weather_group)
    weather_group.add_to(hm)

folium.LayerControl().add_to(hm)

hm

Any help or pointers would be great.

Thanks.


问:
React Native Paper - Redux ToolKit : Redux doesn't track change in fonts between different themes
I am building an application using React Native and Expo.

I'm using Redux ToolKit to store the state of different themes in React Native Paper. In this example, I switch between two themes (one light and one dark) with a simple switch. I can change the colors without any problem and I can see in the debugger that Redux follows perfectly the state changes between the two themes.

However, if I change the font size for only the light theme with the configureFonts function recommended by Paper, Redux (and so my application) does not follow the font size changes between the two themes.

Here is my redux slice (themeSlice.js):

```<code>import { createSlice, current } from '@reduxjs/toolkit'
import { MD3LightTheme, MD3DarkTheme, configureFonts } from 'react-native-paper';

const fontConfigLight = {
  "labelLarge": {
    "fontSize": 20,
    "fontWeight": "500",
    "letterSpacing": 0.1,
    "lineHeight": 25,
  }
};

const lightTheme = {
  ...MD3LightTheme,
  fonts: configureFonts({config: fontConfigLight}),
};

const darkTheme = {
  ...MD3DarkTheme,
};

export const themeSlice = createSlice({
  name: 'counter',
  initialState: lightTheme,
  reducers: {
    switchTheme: (state, action) => {
      if (action.payload === 'light'){
        // console.log('light theme : labelLarge', current(state.fonts.labelLarge))
        return lightTheme
      } else {
        // console.log('dark theme : labelLarge', current(state.fonts.labelLarge))
        return darkTheme
      }
    },
  }
})

export const { switchTheme } = themeSlice.actions

export default themeSlice.reducer
</code>```

and I use the reducer in the SwitchPaper.js file :

```<code>import { useState } from 'react';
import { Switch } from 'react-native-paper';
import { useDispatch } from 'react-redux'
import { switchTheme } from './themeSlice'

const ThemeSwitch = () => {

    const [isSwitchOn, setIsSwitchOn] = useState(false);
    const dispatch = useDispatch()

    const onToggleSwitch = () => {

        setIsSwitchOn(!isSwitchOn)

        if (isSwitchOn) {
            dispatch(switchTheme('light'))
        } else {
            dispatch(switchTheme('dark'))
        }
    }
    return (
        <Switch value={isSwitchOn} onValueChange={onToggleSwitch} />
    );
};

export default ThemeSwitch;
</code>```

I suspect that the configureFonts function causes a conflict with the immutability of the Redux store as I sometimes get the error : TypeError: Cannot assign to read only property 'labelLarge' of object '#'.

I am looking for a solution to change fonts between themes while keeping my themes in the global Redux state.

EDIT:

a non-elegant way to solve the problem would be to change darkTheme to :

```<code>const darkTheme = {
  ...MD3DarkTheme,
  myOwnProperty: true,
  fonts: {
    ...MD3DarkTheme.fonts,
    "labelLarge": {
      fontFamily: "System",
      letterSpacing: 0.5,
      fontWeight: "500",
      lineHeight: 16,
      fontSize: 11
    }
  }
};
</code>```

wishing that the function configureFonts was not there for a particular (and good) reason ...

Body:
I am building an application using React Native and Expo.

I'm using Redux ToolKit to store the state of different themes in React Native Paper. In this example, I switch between two themes (one light and one dark) with a simple switch. I can change the colors without any problem and I can see in the debugger that Redux follows perfectly the state changes between the two themes.

However, if I change the font size for only the light theme with the configureFonts function recommended by Paper, Redux (and so my application) does not follow the font size changes between the two themes.

Here is my redux slice (themeSlice.js):

import { createSlice, current } from '@reduxjs/toolkit'
import { MD3LightTheme, MD3DarkTheme, configureFonts } from 'react-native-paper';

const fontConfigLight = {
  "labelLarge": {
    "fontSize": 20,
    "fontWeight": "500",
    "letterSpacing": 0.1,
    "lineHeight": 25,
  }
};

const lightTheme = {
  ...MD3LightTheme,
  fonts: configureFonts({config: fontConfigLight}),
};

const darkTheme = {
  ...MD3DarkTheme,
};

export const themeSlice = createSlice({
  name: 'counter',
  initialState: lightTheme,
  reducers: {
    switchTheme: (state, action) => {
      if (action.payload === 'light'){
        // console.log('light theme : labelLarge', current(state.fonts.labelLarge))
        return lightTheme
      } else {
        // console.log('dark theme : labelLarge', current(state.fonts.labelLarge))
        return darkTheme
      }
    },
  }
})

export const { switchTheme } = themeSlice.actions

export default themeSlice.reducer

and I use the reducer in the SwitchPaper.js file :

import { useState } from 'react';
import { Switch } from 'react-native-paper';
import { useDispatch } from 'react-redux'
import { switchTheme } from './themeSlice'

const ThemeSwitch = () => {

    const [isSwitchOn, setIsSwitchOn] = useState(false);
    const dispatch = useDispatch()

    const onToggleSwitch = () => {

        setIsSwitchOn(!isSwitchOn)

        if (isSwitchOn) {
            dispatch(switchTheme('light'))
        } else {
            dispatch(switchTheme('dark'))
        }
    }
    return (
        <Switch value={isSwitchOn} onValueChange={onToggleSwitch} />
    );
};

export default ThemeSwitch;

I suspect that the configureFonts function causes a conflict with the immutability of the Redux store as I sometimes get the error : TypeError: Cannot assign to read only property 'labelLarge' of object '#'.

I am looking for a solution to change fonts between themes while keeping my themes in the global Redux state.

EDIT:

a non-elegant way to solve the problem would be to change darkTheme to :

const darkTheme = {
  ...MD3DarkTheme,
  myOwnProperty: true,
  fonts: {
    ...MD3DarkTheme.fonts,
    "labelLarge": {
      fontFamily: "System",
      letterSpacing: 0.5,
      fontWeight: "500",
      lineHeight: 16,
      fontSize: 11
    }
  }
};

wishing that the function configureFonts was not there for a particular (and good) reason ...


问:
JS: How can I get a random Key or Value of a object / dictionary / JSON in JavaScript?
So...basically I wanted to program a vocabulary trainer.

I stored all words in a dictionary (and don't spam the comments with "This is not a JSON", i know),
the key was the English word, the value was the German/French word.
I wanted that in the vocabulary test, he asked a random word and I had to put the translation in the input bar below, then you press check and it checked it.

I also wanted that the asked word could be an English (Key) or a German (Value) word.

So I wanted that it uses a key or a value.

DISCLAIMER: This is not a duplicate! There was no question on this forum that helped me!

Here is the JS function to generate a random new Word:

function nextWord() {
  const AttemptInput = document.querySelector("#input")
  AttemptInput.value = '' //The input field gets cleared at the beginning

  let ObjKeys = Object.keys(Vocab) // I get all the Keys of my Vocab dictionary

  RandomKey = ObjKeys[Math.floor(Math.random() * ObjKeys.length)] // He gets a random key so a random word from the dict

  WordLabel.innerHTML = `${RandomKey}?`; // He puts the Vocabulary as a text into a textlabel and adds a question mark

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>On load of the test page it runs that function</code>```

Now it only asks English words but i wanted to use english and german words.
So in the addVocab() function I just added a new line that also adds the german word as a key and the english word as value. But that didnt work that well...I also tried to use Object.entries but like Object.values and Key.value didn't work....now I hope that somebody can help me...

Body:
So...basically I wanted to program a vocabulary trainer.

I stored all words in a dictionary (and don't spam the comments with "This is not a JSON", i know),
the key was the English word, the value was the German/French word.
I wanted that in the vocabulary test, he asked a random word and I had to put the translation in the input bar below, then you press check and it checked it.

I also wanted that the asked word could be an English (Key) or a German (Value) word.

So I wanted that it uses a key or a value.

DISCLAIMER: This is not a duplicate! There was no question on this forum that helped me!

Here is the JS function to generate a random new Word:

function nextWord() {
  const AttemptInput = document.querySelector("#input")
  AttemptInput.value = '' //The input field gets cleared at the beginning

  let ObjKeys = Object.keys(Vocab) // I get all the Keys of my Vocab dictionary

  RandomKey = ObjKeys[Math.floor(Math.random() * ObjKeys.length)] // He gets a random key so a random word from the dict

  WordLabel.innerHTML = `${RandomKey}?`; // He puts the Vocabulary as a text into a textlabel and adds a question mark

}

On load of the test page it runs that function

Now it only asks English words but i wanted to use english and german words.
So in the addVocab() function I just added a new line that also adds the german word as a key and the english word as value. But that didnt work that well...I also tried to use Object.entries but like Object.values and Key.value didn't work....now I hope that somebody can help me...


问:
Inequality constraints of convex relaxation with McCormick envelope
I have a nonconvex optimization problem for which I am calculating a lower bound using the McCormick envelope. Each bilinear term is replaced with an auxiliary variable which has the following constraints defined:

w_{ij} >= x_i^L * x_j + x_i * x_j^L - x_i^L * x_j^L

w_{ij} >= x_i^U * x_j + x_i * x_j^U - x_i^U * x_j^U

w_{ij} <= x_i^U * x_j + x_i * x_j^L - x_i^U * x_j^L

w_{ij} <= x_i^L * x_j + x_i * x_j^U - x_i^L * x_j^U

where
x_U <= x <= x_L

I am given a function taking in several arguments:

```<code>def convex_bounds(n,m,c,H,Q,A,b,lb,ub):
    #   n is the number of optimization variables
    #   m is the number of eq constraints
    #   H = positive, semidefinite matrix from objetcive function (n x n)
    #   Q is (mxn) x n
    #   A is m x n
    #   b is RHS of non linear eq constraints (m x 1)
    #   c,lb,ub are vectors size (n x 1)
    ......................................
    # Create matrix B & b_ineq for inequality constraints
    # where B*x <= b_ineq
    B = np.eye(3)
    b_ineq = np.array((10,10,10))
    ## these values would work in a scenario with no bilinear terms

</code>```

My problem is that I don't know how to specify the inequality constraints matrix B and vector b_ineq. For this particular exercise my variables are x1, x2 and x3 with bounds 0 (x_L) and 10 (x_U). My bilinear terms are x_12 and x_23 (which will lead to auxiliary variables w_12 and w_23). How can I specify the known bounds (0 and 10) for x1,x2 and x3 and the calculated ones (as in the theory pasted above) in B and b_ineq?

I don't actually know how to proceed with this.

Body:
I have a nonconvex optimization problem for which I am calculating a lower bound using the McCormick envelope. Each bilinear term is replaced with an auxiliary variable which has the following constraints defined:

w_{ij} >= x_i^L * x_j + x_i * x_j^L - x_i^L * x_j^L

w_{ij} >= x_i^U * x_j + x_i * x_j^U - x_i^U * x_j^U

w_{ij} <= x_i^U * x_j + x_i * x_j^L - x_i^U * x_j^L

w_{ij} <= x_i^L * x_j + x_i * x_j^U - x_i^L * x_j^U

where
x_U <= x <= x_L

I am given a function taking in several arguments:

def convex_bounds(n,m,c,H,Q,A,b,lb,ub):
    #   n is the number of optimization variables
    #   m is the number of eq constraints
    #   H = positive, semidefinite matrix from objetcive function (n x n)
    #   Q is (mxn) x n
    #   A is m x n
    #   b is RHS of non linear eq constraints (m x 1)
    #   c,lb,ub are vectors size (n x 1)
    ......................................
    # Create matrix B & b_ineq for inequality constraints
    # where B*x <= b_ineq
    B = np.eye(3)
    b_ineq = np.array((10,10,10))
    ## these values would work in a scenario with no bilinear terms

My problem is that I don't know how to specify the inequality constraints matrix B and vector b_ineq. For this particular exercise my variables are x1, x2 and x3 with bounds 0 (x_L) and 10 (x_U). My bilinear terms are x_12 and x_23 (which will lead to auxiliary variables w_12 and w_23). How can I specify the known bounds (0 and 10) for x1,x2 and x3 and the calculated ones (as in the theory pasted above) in B and b_ineq?

I don't actually know how to proceed with this.


问:
How to visualise STL container contents in debugger using Clion and GCC on an M1 Mac
I have a large C++ project that makes use of C++20 features and I'd like to be able to work on it using CLion on an M1 Mac. Since clang doesn't yet support all of C++20, I have installed g++-12 and configured Clion to use this.

Everything seems to work fine, except when debugging I cannot see a reasonable visualisation of the contents of STL containers.

For a simple Hello World with a vector:

If I switch the C++ compiler back to default (clang) in toolchains, it produces a nice visualisation as expected.

I've tried unchecking/checking the "Enable GNU C++ library renderers" option in Debugger->Data Views->C++, and supplying "stdlib=libstdc++" as mentioned here https://blog.jetbrains.com/clion/2015/02/clion-eap-news-cmake-3-1-stl-renderers-in-debugger-pty-and-more/.

Neither have made a difference.

Any ideas would be much appreciated.


问:
adonis 5 auth using sms service
Hi I wanted to ask what is the best approach for implementing an auth system with my sms service from a third party provider, do I have to create a custom provider or is there another way.
I need advice on this matter, currently Im using google auth with adonis.</p>

Title: adonis 5 auth using sms service


问:
Cant seem to find why this Xunit test wont work in .net, it works on the frondend
I am trying to test a Food waste sytem in which students can reserve mealboxes so they can pick them up at a cheap price.
the test im trying to run is as follows: Dont allow someone to reserve 2 mealboxes for the same pickup date

```<code>        [Fact]
        //unhappy
        public void MealBox_Student_Already_Reserved_Same_Date()
        {
            // Arrange
            var repositoryManagerMock = new Mock<IRepositoryManager>();

            ServiceManager _ss = new ServiceManager(repositoryManagerMock.Object);

            var MealboxList = new List<MealBox>();

            var Student = new Student
            {
                Id = 1,
                FirstName = "Test",
                LastName = "Student",
                Email = "test@gmail.com",
                DateOfBirth = DateTime.Now.AddYears(-15),
                StudentNumber = "210897",
                StudyCity = City.Breda,
                MobileNumber = "0612345678",
                ReservedMealBoxes = MealboxList
            };

            MealboxList.Add(new MealBox
            {
                Id = 1,
                Name = "Test MealBox",
                PickupDateTime = DateTime.Now.AddDays(1),
                LatestPickupTime = DateTime.Now.TimeOfDay,
                IndicationalIs18Plus = false,
                IsHotMeal = false,
                Price = 10,
                MealType = MealType.ColdLunch,
                ExampleProductsBasedOnHistory = new List<Product>(),
                ReservedBy = Student,
                ReservedById = 1,
                OfferedAtCanteen = null,
                OfferedAtCanteenId = 1
            });

            var MealBox = new MealBox
            {
                Id = 2,
                Name = "Test MealBox",
                PickupDateTime = DateTime.Now.AddDays(1),
                LatestPickupTime = DateTime.Now.TimeOfDay,
                IndicationalIs18Plus = false,
                IsHotMeal = false,
                Price = 10,
                MealType = MealType.ColdLunch,
                ExampleProductsBasedOnHistory = new List<Product>(),
                ReservedBy = null,
                ReservedById = null,
                OfferedAtCanteen = null,
                OfferedAtCanteenId = 1
            };

            repositoryManagerMock.Setup(x => x.MealBox.GetById(2)).Returns(MealBox);
            repositoryManagerMock.Setup(x => x.Student.GetByEmail(Student.Email)).Returns(Student);

            // Act
            ServiceResponse message = _ss.MealBox.Reserve(2, Student.Email);

            // Assert
            Assert.Equal("You have already reserved a mealbox for this date", message.Message);

        }
</code>```

this is my validator

```<code>        public ServiceResponse Reserve(int id, string email)
        {
            var response = new ServiceResponse();

            var student = _repositoryManager.Student.GetByEmail(email);
            if (student == null)
            {
                response.Success = false;
                response.Message = "Student not found";
                return response;
            }

            var mealBox = _repositoryManager.MealBox.GetById(id);
            if (mealBox == null)
            {
                response.Success = false;
                response.Message = "MealBox not found";
                return response;
            }

            var resultOfChecks = MealBoxReserveChecks(response, mealBox, student);
            if (!resultOfChecks.Success)
            {
                return resultOfChecks;
            }

            mealBox.ReservedById = student.Id;

            try
            {
                _repositoryManager.MealBox.Update(mealBox);
                _repositoryManager.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            response.Success = true;
            response.Message = "MealBox reserved successfully!";
            return response;
        }

        private ServiceResponse MealBoxReserveChecks(ServiceResponse response, MealBox mealBox, Student student)
        {
            if (mealBox.ReservedBy != null)
            {
                response.Success = false;
                response.Message = "MealBox already reserved";
                return response;
            }

            if (mealBox.IndicationalIs18Plus)
            {
                int hasToBePickedUp = Int32.Parse(mealBox.PickupDateTime.ToString("yyyyMMdd"));
                int dateOfBirth = Int32.Parse(student.DateOfBirth.ToString("yyyyMMdd"));

                if (((hasToBePickedUp - dateOfBirth) / 10000) < 18)
                {
                    response.Success = false;
                    response.Message = "You are not 18+ and cannot reserve this mealbox";
                    return response;
                }
            }

            var reservedMealBoxes = _repositoryManager.MealBox.GetAll().Where(mb => mb.ReservedById == student.Id).ToList();

            if (reservedMealBoxes.Any(mb => mb.PickupDateTime.Day == mealBox.PickupDateTime.Day))
            {
                response.Success = false;
                response.Message = "You have already reserved a mealbox for this date";
                return response;
            }

            response.Success = true;
            return response;
        }
</code>```

in Xunit with this code my mealbox will still be reserved succesfully, which is so weird

someone know the answer to my problem?

I tried many things such as changing the way the mealbox is added to the user, but nothing worked.

the goal is to get the error that you already have a mealbox reserved for this date

Body:
I am trying to test a Food waste sytem in which students can reserve mealboxes so they can pick them up at a cheap price.
the test im trying to run is as follows: Dont allow someone to reserve 2 mealboxes for the same pickup date

        [Fact]
        //unhappy
        public void MealBox_Student_Already_Reserved_Same_Date()
        {
            // Arrange
            var repositoryManagerMock = new Mock<IRepositoryManager>();

            ServiceManager _ss = new ServiceManager(repositoryManagerMock.Object);

            var MealboxList = new List<MealBox>();

            var Student = new Student
            {
                Id = 1,
                FirstName = "Test",
                LastName = "Student",
                Email = "test@gmail.com",
                DateOfBirth = DateTime.Now.AddYears(-15),
                StudentNumber = "210897",
                StudyCity = City.Breda,
                MobileNumber = "0612345678",
                ReservedMealBoxes = MealboxList
            };

            MealboxList.Add(new MealBox
            {
                Id = 1,
                Name = "Test MealBox",
                PickupDateTime = DateTime.Now.AddDays(1),
                LatestPickupTime = DateTime.Now.TimeOfDay,
                IndicationalIs18Plus = false,
                IsHotMeal = false,
                Price = 10,
                MealType = MealType.ColdLunch,
                ExampleProductsBasedOnHistory = new List<Product>(),
                ReservedBy = Student,
                ReservedById = 1,
                OfferedAtCanteen = null,
                OfferedAtCanteenId = 1
            });

            var MealBox = new MealBox
            {
                Id = 2,
                Name = "Test MealBox",
                PickupDateTime = DateTime.Now.AddDays(1),
                LatestPickupTime = DateTime.Now.TimeOfDay,
                IndicationalIs18Plus = false,
                IsHotMeal = false,
                Price = 10,
                MealType = MealType.ColdLunch,
                ExampleProductsBasedOnHistory = new List<Product>(),
                ReservedBy = null,
                ReservedById = null,
                OfferedAtCanteen = null,
                OfferedAtCanteenId = 1
            };

            repositoryManagerMock.Setup(x => x.MealBox.GetById(2)).Returns(MealBox);
            repositoryManagerMock.Setup(x => x.Student.GetByEmail(Student.Email)).Returns(Student);

            // Act
            ServiceResponse message = _ss.MealBox.Reserve(2, Student.Email);

            // Assert
            Assert.Equal("You have already reserved a mealbox for this date", message.Message);

        }

this is my validator

        public ServiceResponse Reserve(int id, string email)
        {
            var response = new ServiceResponse();

            var student = _repositoryManager.Student.GetByEmail(email);
            if (student == null)
            {
                response.Success = false;
                response.Message = "Student not found";
                return response;
            }

            var mealBox = _repositoryManager.MealBox.GetById(id);
            if (mealBox == null)
            {
                response.Success = false;
                response.Message = "MealBox not found";
                return response;
            }

            var resultOfChecks = MealBoxReserveChecks(response, mealBox, student);
            if (!resultOfChecks.Success)
            {
                return resultOfChecks;
            }

            mealBox.ReservedById = student.Id;

            try
            {
                _repositoryManager.MealBox.Update(mealBox);
                _repositoryManager.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            response.Success = true;
            response.Message = "MealBox reserved successfully!";
            return response;
        }

        private ServiceResponse MealBoxReserveChecks(ServiceResponse response, MealBox mealBox, Student student)
        {
            if (mealBox.ReservedBy != null)
            {
                response.Success = false;
                response.Message = "MealBox already reserved";
                return response;
            }

            if (mealBox.IndicationalIs18Plus)
            {
                int hasToBePickedUp = Int32.Parse(mealBox.PickupDateTime.ToString("yyyyMMdd"));
                int dateOfBirth = Int32.Parse(student.DateOfBirth.ToString("yyyyMMdd"));

                if (((hasToBePickedUp - dateOfBirth) / 10000) < 18)
                {
                    response.Success = false;
                    response.Message = "You are not 18+ and cannot reserve this mealbox";
                    return response;
                }
            }

            var reservedMealBoxes = _repositoryManager.MealBox.GetAll().Where(mb => mb.ReservedById == student.Id).ToList();

            if (reservedMealBoxes.Any(mb => mb.PickupDateTime.Day == mealBox.PickupDateTime.Day))
            {
                response.Success = false;
                response.Message = "You have already reserved a mealbox for this date";
                return response;
            }

            response.Success = true;
            return response;
        }

in Xunit with this code my mealbox will still be reserved succesfully, which is so weird

someone know the answer to my problem?

I tried many things such as changing the way the mealbox is added to the user, but nothing worked.

the goal is to get the error that you already have a mealbox reserved for this date


问:
expo-image-picker pinch in/out to crop image doesn't work on Android
I'm trying to use expo-image-picker in my React Native application for a user to choose the image and crop it by zooming in or out. All works well on iOS simulator, but same feature doesn't work on Android simulation as well as on Android device.

I couldn't find any place in the documentation that says explicitly that this feature doesn't work on Android, so I'm assuming that I've omitted something. To test the feature I'm using the example from Expo docs (as below, link: https://docs.expo.dev/versions/latest/sdk/imagepicker/?redirected)

If this is not possible using expo-image-picker, are there any alternatives for Expo that would work on Android?

```<code>import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>
  );
}```
```

Body:
I'm trying to use expo-image-picker in my React Native application for a user to choose the image and crop it by zooming in or out. All works well on iOS simulator, but same feature doesn't work on Android simulation as well as on Android device.

I couldn't find any place in the documentation that says explicitly that this feature doesn't work on Android, so I'm assuming that I've omitted something. To test the feature I'm using the example from Expo docs (as below, link: https://docs.expo.dev/versions/latest/sdk/imagepicker/?redirected)

If this is not possible using expo-image-picker, are there any alternatives for Expo that would work on Android?

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>
  );
}```


问:
Unhandled Exception: PlatformException(Failed to run model, Interpreter busy,
why im getting this error, im trying to run a object detection app in flutter
while running im getting this error in run time, and the object text also not appear

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, java.lang.RuntimeException: Interpreter busy

My code,

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_tflite/flutter_tflite.dart';
//import 'package:tflite/tflite.dart';

String result = "";

class CameraScreen extends StatefulWidget {
  final CameraDescription camera;

  CameraScreen(this.camera);

  @override
  _CameraScreenState createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  loadModel() async {
    await Tflite.loadModel(
        model: "assets/mobilenet_v1_1.0_224.tflite",
        labels: "assets/mobilenet_v1_1.0_224.txt");
  }

  late CameraController _controller;
  late CameraImage imgCam;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    _controller = CameraController(widget.camera, ResolutionPreset.medium);
    _initializeControllerFuture = _controller.initialize().then((value) => {
          setState((() {
            _controller.startImageStream((imageFromStream) => {
                  imgCam = imageFromStream,
                  runModel(),
                });
          }))
        });
    loadModel();
  }

  runModel() async {
    if (imgCam != null) {
      var recognition = await Tflite.runModelOnFrame(
        bytesList: imgCam.planes.map((plane) {
          return plane.bytes;
        }).toList(),
        imageHeight: imgCam.height,
        imageWidth: imgCam.width,
        imageMean: 127.5,
        imageStd: 127.5,
        rotation: 90,
        numResults: 1,
        threshold: 0.1,
        asynch: true,
      );
      result = "yes";
      recognition?.forEach((response) {
        result += response["label"] +
            " " +
            (response["confidence"] as double).toStringAsFixed(2) +
            "\n\n";
        print(result);
        print("\n\n\n\n\n\n\n\n\n\n");
      });
      setState(() {
        result;
      });
    }
  }

  @override
  void dispose() async {
    _controller.dispose();
    await Tflite.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    return Scaffold(
        body: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the Future is complete, display the preview
                return AspectRatio(
                  aspectRatio: deviceRatio,
                  child: CameraPreview(
                      child: Center(
                        child: Text(result),
                      ),
                      _controller),
                );
              } else {
                // Otherwise, display a loading indicator
                return Center(child: CircularProgressIndicator());
              }
            }));
  }
}
</code>```

Body:
why im getting this error, im trying to run a object detection app in flutter
while running im getting this error in run time, and the object text also not appear

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, java.lang.RuntimeException: Interpreter busy

My code,

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_tflite/flutter_tflite.dart';
//import 'package:tflite/tflite.dart';

String result = "";

class CameraScreen extends StatefulWidget {
  final CameraDescription camera;

  CameraScreen(this.camera);

  @override
  _CameraScreenState createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  loadModel() async {
    await Tflite.loadModel(
        model: "assets/mobilenet_v1_1.0_224.tflite",
        labels: "assets/mobilenet_v1_1.0_224.txt");
  }

  late CameraController _controller;
  late CameraImage imgCam;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    _controller = CameraController(widget.camera, ResolutionPreset.medium);
    _initializeControllerFuture = _controller.initialize().then((value) => {
          setState((() {
            _controller.startImageStream((imageFromStream) => {
                  imgCam = imageFromStream,
                  runModel(),
                });
          }))
        });
    loadModel();
  }

  runModel() async {
    if (imgCam != null) {
      var recognition = await Tflite.runModelOnFrame(
        bytesList: imgCam.planes.map((plane) {
          return plane.bytes;
        }).toList(),
        imageHeight: imgCam.height,
        imageWidth: imgCam.width,
        imageMean: 127.5,
        imageStd: 127.5,
        rotation: 90,
        numResults: 1,
        threshold: 0.1,
        asynch: true,
      );
      result = "yes";
      recognition?.forEach((response) {
        result += response["label"] +
            " " +
            (response["confidence"] as double).toStringAsFixed(2) +
            "\n\n";
        print(result);
        print("\n\n\n\n\n\n\n\n\n\n");
      });
      setState(() {
        result;
      });
    }
  }

  @override
  void dispose() async {
    _controller.dispose();
    await Tflite.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    return Scaffold(
        body: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the Future is complete, display the preview
                return AspectRatio(
                  aspectRatio: deviceRatio,
                  child: CameraPreview(
                      child: Center(
                        child: Text(result),
                      ),
                      _controller),
                );
              } else {
                // Otherwise, display a loading indicator
                return Center(child: CircularProgressIndicator());
              }
            }));
  }
}


问:
how to execute this transaction in python?
I have this transaction in MySQL, but when I execute it in my python code it does nothing, but if I execute the transaction in MySQL it works

```<code>llamada = (
    "CALL PA_INSERTAR_NO_TRANSACCIONAL(%s,%s,%s)"
)
def NoTransaccional():
    con = mysql.connect(host="localhost", user="root", password="", database="gestion")
    cursor = con.cursor()
    try:
        datos1= (m6_Entry.get(), m8_Entry.get(), m7_Entry.get())
        cursor.execute(llamada,datos1)
        row = cursor.fetchone()
        print(row);
        con.close();
        MessageBox.showinfo(message="Transaccion Exitosa",title="Felicidades!")
    except:
        MessageBox.showwarning("ADVERTENCIA","Ocurrió un error al actualizar el registro")
        pass
</code>```
```<code>DELIMITER $$
CREATE PROCEDURE PA_INSERTAR_NO_TRANSACCIONAL (PIDCUENTAORIGEN INT, PIDCUENTADESTINO INT,  PVALOR NUMERIC(10,2))
BEGIN
SELECT "Error";
BEGIN
START TRANSACTION;
insert into TRANSFERENCIA values(PIDCUENTAORIGEN,PIDCUENTADESTINO,PVALOR);
insert into MOVIMIENTO(IDCUENTA,TIPOMOVIMIENTO,VALOR) values(PIDCUENTADESTINO,'A',PVALOR);
update CUENTA set SALDO=saldo+PVALOR where IDCUENTA=PIDCUENTADESTINO;
insert into MOVIMIENTO(IDCUENTA,TIPOMOVIMIENTO,VALOR) values(PIDCUENTAORIGEN,'D',PVALOR);
update CUENTA set SALDO=saldo-PVALOR where IDCUENTA=PIDCUENTAORIGEN;
COMMIT;
END ;
END;
$$
DELIMITER ;
</code>```

the transaction does not have to work, it has to transfer the values so it fails, it is for an exercise, but what I want is to execute it in python

Body:
I have this transaction in MySQL, but when I execute it in my python code it does nothing, but if I execute the transaction in MySQL it works

llamada = (
    "CALL PA_INSERTAR_NO_TRANSACCIONAL(%s,%s,%s)"
)
def NoTransaccional():
    con = mysql.connect(host="localhost", user="root", password="", database="gestion")
    cursor = con.cursor()
    try:
        datos1= (m6_Entry.get(), m8_Entry.get(), m7_Entry.get())
        cursor.execute(llamada,datos1)
        row = cursor.fetchone()
        print(row);
        con.close();
        MessageBox.showinfo(message="Transaccion Exitosa",title="Felicidades!")
    except:
        MessageBox.showwarning("ADVERTENCIA","Ocurrió un error al actualizar el registro")
        pass

DELIMITER $$
CREATE PROCEDURE PA_INSERTAR_NO_TRANSACCIONAL (PIDCUENTAORIGEN INT, PIDCUENTADESTINO INT,  PVALOR NUMERIC(10,2))
BEGIN
SELECT "Error";
BEGIN
START TRANSACTION;
insert into TRANSFERENCIA values(PIDCUENTAORIGEN,PIDCUENTADESTINO,PVALOR);
insert into MOVIMIENTO(IDCUENTA,TIPOMOVIMIENTO,VALOR) values(PIDCUENTADESTINO,'A',PVALOR);
update CUENTA set SALDO=saldo+PVALOR where IDCUENTA=PIDCUENTADESTINO;
insert into MOVIMIENTO(IDCUENTA,TIPOMOVIMIENTO,VALOR) values(PIDCUENTAORIGEN,'D',PVALOR);
update CUENTA set SALDO=saldo-PVALOR where IDCUENTA=PIDCUENTAORIGEN;
COMMIT;
END ;
END;
$$
DELIMITER ;

the transaction does not have to work, it has to transfer the values so it fails, it is for an exercise, but what I want is to execute it in python


问:
No overload matches this call on useReducer function
I am getting the error on my useReducer function.

No overload matches this call.
Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
Argument of type '(state: any, action: any) => { value: any; isValid: boolean; }' is not assignable to parameter of type 'ReducerWithoutAction'.
Overload 2 of 5, '(reducer: (state: any, action: any) => { value: any; isValid: boolean; }, initialState: { value: any; isValid: boolean; }, initializer?: undefined): [{ value: any; isValid: boolean; }, Dispatch]', gave the following error.
Type 'null' is not assignable to type 'boolean'.ts(2769)
Search.tsx(15, 35): The expected type comes from property 'isValid' which is declared here on type '{ value: any; isValid: boolean; }'

This is my code. Strangely if I change the return statement for the reducer

```<code>return { value: action.value, isValid: action.value.length === 13 };
</code>```

to

```<code>return { value: action.value, isValid: action.value.includes('@')};
</code>```

Then it the errors go away.

```<code>import React, { useState, useEffect, useReducer } from "react";

import Card from "../UI/Card/Card";
import classes from "./Login.module.css";
import Button from "../UI/Button/Button";

interface searchInputState {
    value: string,
    isValid: boolean | null
}

const mprnInputReducer = (state: any, action: any) => {
  console.log("emailReducer runs");
  if (action.type === "MPRN_INPUT") {
    return { value: action.value, isValid: action.value.length === 13};
  }
  if (action.type === "MPRN_BLUR") {
    return { value: state.value, isValid: state.value.length === 13 };
  }
  return { value: "", isValid: false };
};

 const Search = (props: any) => {
  const [formIsValid, setFormIsValid] = useState(false);

  const [mprnInputState, dispatchMPRN] = useReducer(mprnInputReducer, {
    value: "",
    isValid: null,
  });

  const mprnChangeHandler = (event: any) => {
    console.log("emailChangeHandler runs");
    dispatchMPRN({ type: "MPRN_INPUT", val: event.target.value });

    setFormIsValid(event.target.value.trim().length == 13);
  };

  const validateMPRNHandler = () => {
    console.log("validatePasswordHandler runs");
    dispatchMPRN({ type: "MPRN_BLUR" });
  };

  const submitHandler = (event: any) => {
    console.log("submitHandler runs");
    event.preventDefault();
    props.onSearch(mprnInputState.value);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            mprnInputState.isValid === false ? classes.invalid : ""
          }`}
        >
          <label htmlFor="search">E-Mail</label>
          <input
            type="searchInput"
            id="searchInput"
            value={mprnInputState.value}
            onChange={mprnChangeHandler}
            onBlur={validateMPRNHandler}
          />
        </div>
        <div className={classes.actions}>
          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>
        </div>
      </form>
    </Card>
  );
};

export default Search;
</code>```

Could someone help me resolve this?

Body:
I am getting the error on my useReducer function.

No overload matches this call.
Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
Argument of type '(state: any, action: any) => { value: any; isValid: boolean; }' is not assignable to parameter of type 'ReducerWithoutAction'.
Overload 2 of 5, '(reducer: (state: any, action: any) => { value: any; isValid: boolean; }, initialState: { value: any; isValid: boolean; }, initializer?: undefined): [{ value: any; isValid: boolean; }, Dispatch]', gave the following error.
Type 'null' is not assignable to type 'boolean'.ts(2769)
Search.tsx(15, 35): The expected type comes from property 'isValid' which is declared here on type '{ value: any; isValid: boolean; }'

This is my code. Strangely if I change the return statement for the reducer

return { value: action.value, isValid: action.value.length === 13 };

to

return { value: action.value, isValid: action.value.includes('@')};

Then it the errors go away.

import React, { useState, useEffect, useReducer } from "react";

import Card from "../UI/Card/Card";
import classes from "./Login.module.css";
import Button from "../UI/Button/Button";

interface searchInputState {
    value: string,
    isValid: boolean | null
}

const mprnInputReducer = (state: any, action: any) => {
  console.log("emailReducer runs");
  if (action.type === "MPRN_INPUT") {
    return { value: action.value, isValid: action.value.length === 13};
  }
  if (action.type === "MPRN_BLUR") {
    return { value: state.value, isValid: state.value.length === 13 };
  }
  return { value: "", isValid: false };
};

 const Search = (props: any) => {
  const [formIsValid, setFormIsValid] = useState(false);

  const [mprnInputState, dispatchMPRN] = useReducer(mprnInputReducer, {
    value: "",
    isValid: null,
  });

  const mprnChangeHandler = (event: any) => {
    console.log("emailChangeHandler runs");
    dispatchMPRN({ type: "MPRN_INPUT", val: event.target.value });

    setFormIsValid(event.target.value.trim().length == 13);
  };

  const validateMPRNHandler = () => {
    console.log("validatePasswordHandler runs");
    dispatchMPRN({ type: "MPRN_BLUR" });
  };

  const submitHandler = (event: any) => {
    console.log("submitHandler runs");
    event.preventDefault();
    props.onSearch(mprnInputState.value);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>

          E-Mail
          <input
            type="searchInput"
            id="searchInput"
            value={mprnInputState.value}
            onChange={mprnChangeHandler}
            onBlur={validateMPRNHandler}
          />

          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>

      </form>
    </Card>
  );
};

export default Search;

Could someone help me resolve this?


问:
Typescript ssh2-sftp-client module's get and fastGet downloading 0 byte zip files
I am using ssh2-sftp-client to connect to an sftp server and download files. I know the connection is working as I can download the files but I am getting 0 byte zip files.

this._connection is a ssh2-sftp-client object. file is the name of the file.

```<code>async download(_sourcePath: String, _basePath: String, file: String): Promise<void> {
    await this._connection.get(_sourcePath + '/' + file, _basePath + '/' + file)
}
</code>```

Above is the code I am using. The files are getting dropped off but they are 0 bytes. Not sure what I am doing wrong here. I am using await expecting the promise to be fufilled.

When I try this code outside of my project with this code it works:

```<code>sftp.connect(options)
.then(() => {
 return sftp.list('/some path')
})
.then(data => {
 console.log(data)
for (let i = 0; i < data.length; i++) {
 sftp.get(_sourcePath + '/' + data[i]['name'], _basePath + '/' + data[i]['name'])}
}).catch(err => {
 console.error(err.message);
});
</code>```

Body:
I am using ssh2-sftp-client to connect to an sftp server and download files. I know the connection is working as I can download the files but I am getting 0 byte zip files.

this._connection is a ssh2-sftp-client object. file is the name of the file.

async download(_sourcePath: String, _basePath: String, file: String): Promise<void> {
    await this._connection.get(_sourcePath + '/' + file, _basePath + '/' + file)
}

Above is the code I am using. The files are getting dropped off but they are 0 bytes. Not sure what I am doing wrong here. I am using await expecting the promise to be fufilled.

When I try this code outside of my project with this code it works:

sftp.connect(options)
.then(() => {
 return sftp.list('/some path')
})
.then(data => {
 console.log(data)
for (let i = 0; i < data.length; i++) {
 sftp.get(_sourcePath + '/' + data[i]['name'], _basePath + '/' + data[i]['name'])}
}).catch(err => {
 console.error(err.message);
});


问:
Track changes in the stack of the executed program
Is it possible to react to a change in the function call stack of an executed program on unix-like systems? Specifically, Linux. For example, to track the call of the assembly function "call". The goal is to get a stack trace of the executed program without changing the source code of the program itself
Please provide a tip, but not an answer. If possible, I will post the project in open source. Thanks</p>


问:
How to use descending order in Medoo?
I have this table:

Given a patient name, I want to fetch a row with the highest id, which is:

Agus Maryono - 10 - F - 11 - 2023-01-13 17:08:07

The SQL query to do that is:

```<code>SELECT nama_pasien, uid_pasien, kode, id, estimasi_dilayani FROM poli_fisioterapi WHERE nama_pasien="Agus Maryono" ORDER BY id DESC LIMIT 1;
</code>```

Now I'm trying to do that with Medoo, ideally without manually writing SQL query manually. I used this:

```<code>$data_poli_fisioterapi = $database->select("poli_fisioterapi", ["nama_pasien", "uid_pasien", "kode", "id", "estimasi_dilayani"], ["nama_pasien" => "Agus Maryono"], ["ORDER" => ["id" => "DESC"], ["LIMIT" => 1]]);
</code>```

Instead, it returns all rows which "nama_pasien" = "Agus Maryono":

```<code>[
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 9,
estimasi_dilayani: "2023-01-13 17:02:03"
},
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 10,
estimasi_dilayani: "2023-01-13 17:09:05"
},
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 11,
estimasi_dilayani: "2023-01-13 17:08:07"
}
]
</code>```

What's wrong here?

Title: How to use descending order in Medoo?

Body:
I have this table:

Given a patient name, I want to fetch a row with the highest id, which is:

Agus Maryono - 10 - F - 11 - 2023-01-13 17:08:07

The SQL query to do that is:

SELECT nama_pasien, uid_pasien, kode, id, estimasi_dilayani FROM poli_fisioterapi WHERE nama_pasien="Agus Maryono" ORDER BY id DESC LIMIT 1;

Now I'm trying to do that with Medoo, ideally without manually writing SQL query manually. I used this:

$data_poli_fisioterapi = $database->select("poli_fisioterapi", ["nama_pasien", "uid_pasien", "kode", "id", "estimasi_dilayani"], ["nama_pasien" => "Agus Maryono"], ["ORDER" => ["id" => "DESC"], ["LIMIT" => 1]]);

Instead, it returns all rows which "nama_pasien" = "Agus Maryono":

[
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 9,
estimasi_dilayani: "2023-01-13 17:02:03"
},
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 10,
estimasi_dilayani: "2023-01-13 17:09:05"
},
{
nama_pasien: "Agus Maryono",
uid_pasien: 10,
kode: "F",
id: 11,
estimasi_dilayani: "2023-01-13 17:08:07"
}
]

What's wrong here?


问:
How to trigger rabbit mq shutdown signal for testing?
Faced an issue on prod system where 1 message was left unacked for 30 mins which lead to consumer being shutdown. Now I have added shutdownlisteners as described in rabbit mq docs -
https://rabbitmq.github.io/rabbitmq-java-client/api/4.x.x/com/rabbitmq/client/ShutdownListener.html

```<code>                if (cause.isHardError()) {
                    log.error("Connection error with cause : {}", cause);
                    Connection conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        log.error("Rabbit Mq Consumer Connection Shutdown : {} {}", reason, cause);
                    }
                } else{
                    Channel ch = (Channel)cause.getReference();
                    log.error("Channel error details : {}", ch);
                }
            });
</code>```

The issue is it's not getting invoked at all in testing. I tried triggering it through 2 ways-

Through unacked delivery timeout. Basically threw a general excption and never acked it(these were the original conditions of the bug). However, this didn't work.

I used channel.close() to shutdown the consumer but still didn't receive an event.

Looking for any way to replicate the issue I faced and test/trigger the shutdownlisteners. Thanks

Body:
Faced an issue on prod system where 1 message was left unacked for 30 mins which lead to consumer being shutdown. Now I have added shutdownlisteners as described in rabbit mq docs -
https://rabbitmq.github.io/rabbitmq-java-client/api/4.x.x/com/rabbitmq/client/ShutdownListener.html

                if (cause.isHardError()) {
                    log.error("Connection error with cause : {}", cause);
                    Connection conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        log.error("Rabbit Mq Consumer Connection Shutdown : {} {}", reason, cause);
                    }
                } else{
                    Channel ch = (Channel)cause.getReference();
                    log.error("Channel error details : {}", ch);
                }
            });

The issue is it's not getting invoked at all in testing. I tried triggering it through 2 ways-

Through unacked delivery timeout. Basically threw a general excption and never acked it(these were the original conditions of the bug). However, this didn't work.

I used channel.close() to shutdown the consumer but still didn't receive an event.

Looking for any way to replicate the issue I faced and test/trigger the shutdownlisteners. Thanks


问:
Getting error: Error in map(ID=8): Image.select: Pattern 'B5' did not match any bands in Google Earth Engine
Trying to modify a code in Google Earth Engine I found in the internet which I need for performing time series analysis. I need Landsat images from 1984-2022, that’s why I merged two Image Collection (L5 and L8).
But I am getting an error: ImageCollection (Error)
Error in map(ID=28):
Image.select: Pattern 'B5' did not match any bands.

```<code>var collectionL5 = ee.ImageCollection('LANDSAT/LT05/C02/T1_TOA')
  .filterBounds(studyArea);

var collectionL8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(studyArea);

function maskL8sr(collectionL5) {
  var cloudShadowBitMask = 1 << 3;
  var cloudsBitMask = 1 << 5;

  var qa = collectionL5.select('QA_PIXEL');

  var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
      .and(qa.bitwiseAnd(cloudsBitMask).eq(0));

  return collectionL5.updateMask(mask).divide(10000)
      .select("B[0-9]*")
      .copyProperties(collectionL5, ["system:time_start"]);
}

function maskL8sr(collectionL8) {
  var cloudShadowBitMask = 1 << 3;
  var cloudsBitMask = 1 << 5;

  var qa1 = collectionL8.select('QA_PIXEL');

  var mask = qa1.bitwiseAnd(cloudShadowBitMask).eq(0)
      .and(qa1.bitwiseAnd(cloudsBitMask).eq(0));

  return collectionL8.updateMask(mask).divide(10000)
      .select("B[0-9]*")
      .copyProperties(collectionL8, ["system:time_start"]);
}

var imageCollection = collectionL5.merge(collectionL8).filterBounds(studyArea);

var stepList = ee.List.sequence(1984,2021);

var filterCollection = stepList.map(function(year){
  var startDate = ee.Date.fromYMD(year,5,1);
  var endDate = ee.Date.fromYMD(year,9,15);
  var composite_i = imageCollection.filterDate(startDate, endDate)
                        .map(maskL8sr)
                        .median()
                        .set('system:time_start',startDate);
  return composite_i;
});

var yearlyComposites = ee.ImageCollection(filterCollection);
print(yearlyComposites, 'Masked and Filtered Composites');

// // Add Enhanced Vegetation Index to a function and apply it.
// // EVI = 2.5 * ((NIR - Red) / (NIR + 6 * Red – 7.5 * Blue + 1))
function evi(img){
  var eviImg = img.select(['B5','B4','B2','B6','B3'],['nir','red','blue','swir1','green']);
  eviImg = eviImg.expression(
    '(2.5 * ((NIR - RED)) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
      'NIR': eviImg.select('nir'),
      'RED': eviImg.select('red'),
      'BLUE': eviImg.select('blue'),
      'SWIR1': eviImg.select('swir1'),
      'GREEN': eviImg.select('green')
    }).rename('EVI');
  return img.addBands(eviImg);
}

yearlyComposites = yearlyComposites.map(function(image){
  return evi(image);
});

print(yearlyComposites, 'With EVI as Band');

// Create image collection of yearly composites, selecting the EVI band.
var eviCollection = yearlyComposites.select('EVI');
</code>```

But I am getting error: ImageCollection (Error)
Error in map(ID=28):
Image.select: Pattern 'B5' did not match any bands.

I know that the problem is in Image 28. While checking the bands I noticed that image 28 is empty.I also noticed that 28 image is a "transitional" image between the L5 and L8 collections.
Image28
Can it be possible that somehow while merging two image collections they overlap each other ending up with empty image inside.

Body:
Trying to modify a code in Google Earth Engine I found in the internet which I need for performing time series analysis. I need Landsat images from 1984-2022, that’s why I merged two Image Collection (L5 and L8).
But I am getting an error: ImageCollection (Error)
Error in map(ID=28):
Image.select: Pattern 'B5' did not match any bands.

var collectionL5 = ee.ImageCollection('LANDSAT/LT05/C02/T1_TOA')
  .filterBounds(studyArea);

var collectionL8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(studyArea);

function maskL8sr(collectionL5) {
  var cloudShadowBitMask = 1 << 3;
  var cloudsBitMask = 1 << 5;

  var qa = collectionL5.select('QA_PIXEL');

  var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
      .and(qa.bitwiseAnd(cloudsBitMask).eq(0));

  return collectionL5.updateMask(mask).divide(10000)
      .select("B[0-9]*")
      .copyProperties(collectionL5, ["system:time_start"]);
}

function maskL8sr(collectionL8) {
  var cloudShadowBitMask = 1 << 3;
  var cloudsBitMask = 1 << 5;

  var qa1 = collectionL8.select('QA_PIXEL');

  var mask = qa1.bitwiseAnd(cloudShadowBitMask).eq(0)
      .and(qa1.bitwiseAnd(cloudsBitMask).eq(0));

  return collectionL8.updateMask(mask).divide(10000)
      .select("B[0-9]*")
      .copyProperties(collectionL8, ["system:time_start"]);
}

var imageCollection = collectionL5.merge(collectionL8).filterBounds(studyArea);

var stepList = ee.List.sequence(1984,2021);

var filterCollection = stepList.map(function(year){
  var startDate = ee.Date.fromYMD(year,5,1);
  var endDate = ee.Date.fromYMD(year,9,15);
  var composite_i = imageCollection.filterDate(startDate, endDate)
                        .map(maskL8sr)
                        .median()
                        .set('system:time_start',startDate);
  return composite_i;
});

var yearlyComposites = ee.ImageCollection(filterCollection);
print(yearlyComposites, 'Masked and Filtered Composites');

// // Add Enhanced Vegetation Index to a function and apply it.
// // EVI = 2.5 * ((NIR - Red) / (NIR + 6 * Red – 7.5 * Blue + 1))
function evi(img){
  var eviImg = img.select(['B5','B4','B2','B6','B3'],['nir','red','blue','swir1','green']);
  eviImg = eviImg.expression(
    '(2.5 * ((NIR - RED)) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
      'NIR': eviImg.select('nir'),
      'RED': eviImg.select('red'),
      'BLUE': eviImg.select('blue'),
      'SWIR1': eviImg.select('swir1'),
      'GREEN': eviImg.select('green')
    }).rename('EVI');
  return img.addBands(eviImg);
}

yearlyComposites = yearlyComposites.map(function(image){
  return evi(image);
});

print(yearlyComposites, 'With EVI as Band');

// Create image collection of yearly composites, selecting the EVI band.
var eviCollection = yearlyComposites.select('EVI');

But I am getting error: ImageCollection (Error)
Error in map(ID=28):
Image.select: Pattern 'B5' did not match any bands.

I know that the problem is in Image 28. While checking the bands I noticed that image 28 is empty.I also noticed that 28 image is a "transitional" image between the L5 and L8 collections.
Image28
Can it be possible that somehow while merging two image collections they overlap each other ending up with empty image inside.


问:
Rstudio freezes or computer crashes when knitting to html
I am trying to knit my rmarkdown file to .html, however rstudio freezes when I reach certain computation-heavy commands like difftime a distHaverstine.

```<code>trips_2 <- trips_1 %>%
   mutate(
     weekday = wday(started_at, label = T, abbr = F),
     month = month(started_at, label = T, abbr =F),
     week = strftime(started_at, format = "%V"),
     day = day(started_at),
     start_hour = hour(started_at),
     trip_length = as.numeric(difftime(ended_at, started_at,units = "secs"))
</code>```

or

```<code>may_to_october_behavior <- trips_w_stations %>%
  filter(month == 'May'|
           month == 'June'|
           month == 'July'|
           month == 'August'|
           month == 'September'|
           month == 'October') %>%
  rowwise() %>%
  mutate(trip_distance = distHaversine(c(start_lng, start_lat), c(end_lng, end_lat),
                                       r=6378137)) %>%
  filter(trip_distance > 0) %>%
  group_by(customer_type, bike_type) %>%
  summarize(mean_trip_length = mean(trip_length),
            mean_distance_travelled_m = mean(trip_distance),
            ride_count = n_distinct(ride_id)) %>%
  mutate(avg_mph = (mean_distance_travelled_m/mean_trip_length)*2.2369)
</code>```

Does anyone have any tips on how to solve this problem? My computer runs on Win10 and remains pretty beefy, which leads me to believe the issue may have to do with rstudio specifically.

In an attempt to lower the demand on the program, I have gone back and removed any dataframes that might clutter the environment, but even with the bare minimum data in my environment, I'm getting the same freeze issue.

Many thanks for any advice.

Body:
I am trying to knit my rmarkdown file to .html, however rstudio freezes when I reach certain computation-heavy commands like difftime a distHaverstine.

trips_2 <- trips_1 %>%
   mutate(
     weekday = wday(started_at, label = T, abbr = F),
     month = month(started_at, label = T, abbr =F),
     week = strftime(started_at, format = "%V"),
     day = day(started_at),
     start_hour = hour(started_at),
     trip_length = as.numeric(difftime(ended_at, started_at,units = "secs"))

or

may_to_october_behavior <- trips_w_stations %>%
  filter(month == 'May'|
           month == 'June'|
           month == 'July'|
           month == 'August'|
           month == 'September'|
           month == 'October') %>%
  rowwise() %>%
  mutate(trip_distance = distHaversine(c(start_lng, start_lat), c(end_lng, end_lat),
                                       r=6378137)) %>%
  filter(trip_distance > 0) %>%
  group_by(customer_type, bike_type) %>%
  summarize(mean_trip_length = mean(trip_length),
            mean_distance_travelled_m = mean(trip_distance),
            ride_count = n_distinct(ride_id)) %>%
  mutate(avg_mph = (mean_distance_travelled_m/mean_trip_length)*2.2369)

Does anyone have any tips on how to solve this problem? My computer runs on Win10 and remains pretty beefy, which leads me to believe the issue may have to do with rstudio specifically.

In an attempt to lower the demand on the program, I have gone back and removed any dataframes that might clutter the environment, but even with the bare minimum data in my environment, I'm getting the same freeze issue.

Many thanks for any advice.


问:
How do I configure 2nd site on Bitnami Lightsail Wordpress to host a second web site?
How do I configure 2nd site on Bitnami Lightsail  Wordpress to host a second web site?

I just started with AWS Lightsail and I have a wordpress site running on it without an issues.. I site does not have alot of users so I would like to add my 2nd workpress site to it.

The first thing I am trying is to point my apache to a 2nd folder using vhost.  I want into

```<code>/home/bitnami/stack/apache/conf/vhosts
</code>```

and copied the following two files and edited the pathed on the new sites

```<code>-rw-r--r-- 1 root    root    1830 Jan 11 17:19 wordpress-https-vhost.conf
-rw-r--r-- 1 root    root    1998 Jan 11 17:19 wordpress-vhost.conf
</code>```

I then restarted apache

```<code>sudo /opt/bitnami/ctlscript.sh restart apache
</code>```

both domain names are still going to the same location.. what am I missing

Body:
How do I configure 2nd site on Bitnami Lightsail  Wordpress to host a second web site?

I just started with AWS Lightsail and I have a wordpress site running on it without an issues.. I site does not have alot of users so I would like to add my 2nd workpress site to it.

The first thing I am trying is to point my apache to a 2nd folder using vhost.  I want into

/home/bitnami/stack/apache/conf/vhosts

and copied the following two files and edited the pathed on the new sites

-rw-r--r-- 1 root    root    1830 Jan 11 17:19 wordpress-https-vhost.conf
-rw-r--r-- 1 root    root    1998 Jan 11 17:19 wordpress-vhost.conf

I then restarted apache

sudo /opt/bitnami/ctlscript.sh restart apache

both domain names are still going to the same location.. what am I missing


问:
useEffect executes on every render even after passing empty array as dependency
I have a landing page and some about, faq, tnc, etc pages.
When I navigate (using react-router v6) from landing page to another and come back, the useEffect executes even though I have given empty dependency array.

useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, []);
```
<p>I also tried passing a dependency which do not change like this..</p>
<pre class="lang-js prettyprint-override"><code>const doNotLoadLandingAnimation = true;
    useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, [doNotLoadLandingAnimation]);
</code>```

But still.. useEffect executes everytime the page is visited.

Body:
I have a landing page and some about, faq, tnc, etc pages.
When I navigate (using react-router v6) from landing page to another and come back, the useEffect executes even though I have given empty dependency array.

useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, []);

I also tried passing a dependency which do not change like this..

const doNotLoadLandingAnimation = true;
    useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, [doNotLoadLandingAnimation]);

But still.. useEffect executes everytime the page is visited.


问:
Angular: Dynamically Changing Click Events and Handlers
I have a component that will have a set of states, in which each state has a set of UI events and response methods. Some of the UI events may not be included in all the states.

My current idea is to create a controller interface including methods for each possible UI event that the component can then call in response to each event. Each state will then have a corresponding implementation of the interface. The main issue here is that many of the concrete controllers will have empty methods being called.

To avoid this issue, the only solution I can think of is to not even use Angular directives and have each concrete controller create its own event listeners. While this would avoid the previous issue, I am wondering whether there's a better approach relying on Angular features.


问:
I am waiting a output after Conv3x3 in this shape : (112,112,32) but I took a output inthis shape(111,111,32). What can I do?
x = model.add(Conv2D(32,3, input_shape = (224,224,1),strides=2))</p>


问:
Kafka topic creation: Timed out waiting for node assignment
I am trying to set up the following on a single remote AWS EC2 machine.

1 Kafka Zookeeper
3 Kafka brokers
1 Kafka topic

I have done the following:

I have created two copies of the server.properties file and named them server_1.properties and server_2.properties, where I changed the following values:

broker.id=0 to broker.id=1 and broker.id=2 respectively

advertised.listeners=PLAINTEXT://your.host.name:9092 to  advertised.listeners=PLAINTEXT://3.72.250.103:9092

advertised.listeners=PLAINTEXT://3.72.250.103:9093

advertised.listeners=PLAINTEXT://3.72.250.103:9094  in the three config files

changed log.dirs=/tmp/kafka-logs to

log.dirs=/tmp/kafka-logs_1 and log.dirs=/tmp/kafka-logs_2  in the respective files

All three brokers start up fine, and

```<code>
bin/zookeeper.sh localhost:2181 ls /brokers/ids
</code>```

shows all three brokers

But when I try to create a topic like:

```<code>bin/kafka-topics.sh --bootstrap-server localhost:9092,localhost:9093,localhost:9094 --create --   partitions 5 --replication-factor 1 --topic cars
</code>```

the command times out with the error message: Timed out waiting for node assignment

What have I tried:

I tried creating only one broker - that worked fine

I tried creating the topic with --bootstrap-server localhost:9092 only - that did not work

I tried changing listeners=PLAINTEXT://:9092 to listeners=PLAINTEXT://3.72.250.103:9092 and for the 2nd and 3rd broker respectively - I was not even able to start the brokers with this configuration.

I am not sure what to try next

Body:
I am trying to set up the following on a single remote AWS EC2 machine.

1 Kafka Zookeeper
3 Kafka brokers
1 Kafka topic

I have done the following:

I have created two copies of the server.properties file and named them server_1.properties and server_2.properties, where I changed the following values:

broker.id=0 to broker.id=1 and broker.id=2 respectively

advertised.listeners=PLAINTEXT://your.host.name:9092 to  advertised.listeners=PLAINTEXT://3.72.250.103:9092

advertised.listeners=PLAINTEXT://3.72.250.103:9093

advertised.listeners=PLAINTEXT://3.72.250.103:9094  in the three config files

changed log.dirs=/tmp/kafka-logs to

log.dirs=/tmp/kafka-logs_1 and log.dirs=/tmp/kafka-logs_2  in the respective files

All three brokers start up fine, and

bin/zookeeper.sh localhost:2181 ls /brokers/ids

shows all three brokers

But when I try to create a topic like:

bin/kafka-topics.sh --bootstrap-server localhost:9092,localhost:9093,localhost:9094 --create --   partitions 5 --replication-factor 1 --topic cars

the command times out with the error message: Timed out waiting for node assignment

What have I tried:

I tried creating only one broker - that worked fine

I tried creating the topic with --bootstrap-server localhost:9092 only - that did not work

I tried changing listeners=PLAINTEXT://:9092 to listeners=PLAINTEXT://3.72.250.103:9092 and for the 2nd and 3rd broker respectively - I was not even able to start the brokers with this configuration.

I am not sure what to try next


问:
Don't serialize part of POJO if user defined default values exists
I have a POJO:

```<code>public class Quux {
    private String name = "";
    private String foobar = "a-default-value";

    public String getName() {
        return name;
    }

    public void setName(String value) {
        name = value;
    }

    public String getFoobar() {
        return foobar;
    }

    public void setFoobar(String value) {
        foobar = value;
    }
}
</code>```

I want to serialize this using Jackson ObjectMapper.

Example:

```<code>Quux quux = new Quux();
quux.name = "guybrush"

ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.setSerializationInclusion(Include.NON_NULL);
objMapper.setSerializationInclusion(Include.NON_EMPTY);
objMapper.setSerializationInclusion(Include.NON_DEFAULT);
System.out.println(writer.writeValueAsString(quux));
</code>```

Question:

I would like the resulting JSON to be

```<code>{ "name": "guybrush" }
</code>```

i.e. the value foobar ("a-default-value") should not be included in the resulting JSON.

Also, if I create an object like

```<code>Quux quux = new Quux();
quux.name = "guybrush";
quux.foobar = "a-default-value";  // set, but same as default value
</code>```

the serialized output should be the same:

```<code>{ "name": "guybrush" }
</code>```

Is this possible?

as it is now the result is as follows:

```<code>{ "name": "guybrush", "foobar": "a-default-value" }
</code>```

how come?

Body:
I have a POJO:

public class Quux {
    private String name = "";
    private String foobar = "a-default-value";

    public String getName() {
        return name;
    }

    public void setName(String value) {
        name = value;
    }

    public String getFoobar() {
        return foobar;
    }

    public void setFoobar(String value) {
        foobar = value;
    }
}

I want to serialize this using Jackson ObjectMapper.

Example:

Quux quux = new Quux();
quux.name = "guybrush"

ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.setSerializationInclusion(Include.NON_NULL);
objMapper.setSerializationInclusion(Include.NON_EMPTY);
objMapper.setSerializationInclusion(Include.NON_DEFAULT);
System.out.println(writer.writeValueAsString(quux));

Question:

I would like the resulting JSON to be

{ "name": "guybrush" }

i.e. the value foobar ("a-default-value") should not be included in the resulting JSON.

Also, if I create an object like

Quux quux = new Quux();
quux.name = "guybrush";
quux.foobar = "a-default-value";  // set, but same as default value

the serialized output should be the same:

{ "name": "guybrush" }

Is this possible?

as it is now the result is as follows:

{ "name": "guybrush", "foobar": "a-default-value" }

how come?


问:
VS Code - Text Editor behaving like terminal on click
Rather then acting like a word document (for lack of a better way of putting it)

When I am using VS code, when I click into a new html document for example, it behaves as if I am I am typing in the termainal.

This used to happen to me when I would copy/paste something into the document.
I checked my shortcuts and could not see anything, thought it might be a problem with an exentsion or vs code itself. Uninstalled vs code and all my extensions and it did resolve the problem but it is back now, but as I said only occurs when I click into another file.


问:
Extract firstname and lastname, but firstname max length
I need to get the first and last name, but the maximum in the first name is 30 characters

```<code>declare @name nvarchar(250)='David Judith and Holofernes Equestrian of Gattamelata'

SELECT LEFT(rtrim(@name), LEN(rtrim(@name)) - CHARINDEX(' ',REVERSE(rtrim(@name)))) 'firstName'

SELECT RIGHT(rtrim(@name), CHARINDEX(' ',REVERSE(rtrim(@name)))-1) 'lastName'
</code>```

result of my attempt:

Firstname=David Judith and Holofernes Equestrian of

Lastname=Gattamelata

the end result I want:

Firstname=David Judith and Holofernes

Lastname=Equestrian of Gattamelata

That is, it must be placed after 30 characters in the last name.

try again, now i need to optimize this code below:

```<code>    declare @name nvarchar(250)='David Judith and Holofernes Equestrian of Gattamelata'
    SELECT value FROM STRING_SPLIT(@name, ' ');
    DECLARE @firstName as NVARCHAR(50)='';
    DECLARE @lastName  as NVARCHAR(50)='';
    DECLARE @value     as NVARCHAR(50);
    DECLARE @NamesCursor as CURSOR;
    SET @NamesCursor = CURSOR FORWARD_ONLY FOR

SELECT value
    FROM STRING_SPLIT(@name, ' ');

    OPEN @NamesCursor;
    FETCH NEXT FROM @NamesCursor INTO @value;
     WHILE @@FETCH_STATUS = 0
    BEGIN
        print @value
        print  len(@firstname)
 if (len(@firstname) < 30 and len(isnull(@firstname,'') + @value) < 30)
            set @firstname=isnull(@firstname,'') + @value + ' '
        else
            set @lastName=isnull(@lastName,'') + @value + ' '

        print @firstname
         FETCH NEXT FROM @NamesCursor INTO @value;
    END
    CLOSE @NamesCursor;
    DEALLOCATE @NamesCursor;
    select rtrim(ltrim(@firstname)) 'First Name', rtrim(ltrim(@lastName)) 'Last Name'
</code>```

thanks

Body:
I need to get the first and last name, but the maximum in the first name is 30 characters

declare @name nvarchar(250)='David Judith and Holofernes Equestrian of Gattamelata'

SELECT LEFT(rtrim(@name), LEN(rtrim(@name)) - CHARINDEX(' ',REVERSE(rtrim(@name)))) 'firstName'

SELECT RIGHT(rtrim(@name), CHARINDEX(' ',REVERSE(rtrim(@name)))-1) 'lastName'

result of my attempt:

Firstname=David Judith and Holofernes Equestrian of

Lastname=Gattamelata

the end result I want:

Firstname=David Judith and Holofernes

Lastname=Equestrian of Gattamelata

That is, it must be placed after 30 characters in the last name.

try again, now i need to optimize this code below:

    declare @name nvarchar(250)='David Judith and Holofernes Equestrian of Gattamelata'
    SELECT value FROM STRING_SPLIT(@name, ' ');
    DECLARE @firstName as NVARCHAR(50)='';
    DECLARE @lastName  as NVARCHAR(50)='';
    DECLARE @value     as NVARCHAR(50);
    DECLARE @NamesCursor as CURSOR;
    SET @NamesCursor = CURSOR FORWARD_ONLY FOR

SELECT value
    FROM STRING_SPLIT(@name, ' ');

    OPEN @NamesCursor;
    FETCH NEXT FROM @NamesCursor INTO @value;
     WHILE @@FETCH_STATUS = 0
    BEGIN
        print @value
        print  len(@firstname)
 if (len(@firstname) < 30 and len(isnull(@firstname,'') + @value) < 30)
            set @firstname=isnull(@firstname,'') + @value + ' '
        else
            set @lastName=isnull(@lastName,'') + @value + ' '

        print @firstname
         FETCH NEXT FROM @NamesCursor INTO @value;
    END
    CLOSE @NamesCursor;
    DEALLOCATE @NamesCursor;
    select rtrim(ltrim(@firstname)) 'First Name', rtrim(ltrim(@lastName)) 'Last Name'

thanks