问:
Custom AtLeastOne type not compiling as expected when used with Generic
I have defined a custom type AtLeastOne which ensures that the passed-in object contains at least one valid key. This works well when the generic is instantiated but requires casting when another generic type is passed into it. I am unable to understand why this casting is required.

Typescript playground link

```<code>// based off of https://stackoverflow.com/a/48244432/14905094
type AtLeastOne<T, U = { [K in keyof T]: Pick<Required<T>, K> }> = Partial<T> & U[keyof U];

type DbMetaData = {
  id?: number;
};

const correctlyWorks: AtLeastOne<DbMetaData> = { id: 123 };
const correctlyFails: AtLeastOne<DbMetaData> = {};

const genericsExample = <T extends DbMetaData>() => {
  // why does this not work?
  const doesNotWork: AtLeastOne<T> = { id: 123 };

  // can clear the error by using an "as"
  const requiresAsAssertion: AtLeastOne<T> = { id: 123 } as AtLeastOne<T>;
};
</code>```

The following error is generated:

```<code>Type '{ id: 123; }' is not assignable to type 'AtLeastOne<T, { [K in keyof T]: Pick<Required<T>, K>; }>'.
  Type '{ id: 123; }' is not assignable to type 'Partial<T>'
</code>```

答:
Your generic constraint says that T extends DbMetaData.  So, for example, {} would satisfy that constraint, but const correctlyWorks: AtLeastOne<{}> = { id: 123 }; would be an error.

In other words, TS is showing an error because there are some values of T for which AtLeastOne<T> is not compatible with the assigned value.

Body:
I have defined a custom type AtLeastOne which ensures that the passed-in object contains at least one valid key. This works well when the generic is instantiated but requires casting when another generic type is passed into it. I am unable to understand why this casting is required.

<a href="https://www.typescriptlang.org/play?#code/PTAECMEMGcFMBNQHsBmLnoBYBdsAdoAuEabSAYwGskA3WAJxQBskB3AOnKQFthJgALAA4ATAPEBmEcACMAgJwAGAKyL5AgFDYAnnligAgtgAysGNgDyAO1gAeACoAaUAFVQAXlABvUAG0A0qAAllaglLDaqKD2ALqEoAAKQVS2AEqwAI4ArkH0CA4AfM7%20BaAAvqWeCZD02EGQTIWgAGSuvuGR6C4xANwaWrr6ACLgALKwZEOQZB7eGqDB8AD88VZZ3OAMfWV9GlxWpKBc9Hnk2EzaAOpI9JREhiZmpNZ2I%20OT05CV3ovxMiIScp9faHY6nc7aABikCCTHuRlM5hetjeE0gUzI3y8O36IOwoAA5rAbPRktAAKIAD0g3DwTH0ngcoFglOwxPg0FAqI%20mIAFABKDylLzzUAgUCsTDaUDwJCwTnYTBBTlWJD41g3ShLUV4mVy6AAOTV11u8QRT0sNianh8QXgfwBQP6C3F5EgoXI9JqoEV%20gY9BuEGlWWgIQJoHdoAARDAozqkAd8Xlsrl5QZoOm4LUggmzY8kVb7FjfqB-oCyhHOeaC3Yi9sekA" rel="nofollow noreferrer">Typescript playground link

// based off of https://stackoverflow.com/a/48244432/14905094
type AtLeastOne<T, U = { [K in keyof T]: Pick<Required<T>, K> }> = Partial<T> & U[keyof U];

type DbMetaData = {
  id?: number;
};

const correctlyWorks: AtLeastOne<DbMetaData> = { id: 123 };
const correctlyFails: AtLeastOne<DbMetaData> = {};

const genericsExample = <T extends DbMetaData>() => {
  // why does this not work?
  const doesNotWork: AtLeastOne<T> = { id: 123 };

  // can clear the error by using an "as"
  const requiresAsAssertion: AtLeastOne<T> = { id: 123 } as AtLeastOne<T>;
};

The following error is generated:

Type '{ id: 123; }' is not assignable to type 'AtLeastOne<T, { [K in keyof T]: Pick<Required<T>, K>; }>'.
  Type '{ id: 123; }' is not assignable to type 'Partial<T>'


来源: stackexchange

问:
How to hide the "Navigate" button if the user presses the "Complete Delivery" in Xaml?
I am doing an app for the courier service. I am trying to figure out how to hide the "Navigate" button when the user presses the "Complete delivery". I tried some codes but no luck. Thanks in adv!

enter image description here

// This is the XAML Code:

```<code><ContentPage.Content>
        <StackLayout>
            <Grid Padding="10,10,4,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="50" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100*" />
                    <ColumnDefinition Width="10*" />
                </Grid.ColumnDefinitions>
                <DatePicker x:Name="dateselector" DateSelected="HandleDateSelected" Grid.Row="0" Grid.Column="0"></DatePicker>
                <Picker HeightRequest="2" IsVisible="false" Title="ORDERS"  x:Name="ordersfilterpicker" FontSize="Small" Grid.Row="1" Grid.Column="0">
                    <Picker.Items>
                        <x:String>MY DELIVERIES</x:String>
                        <x:String>FOR PICKUP</x:String>
                        <x:String>RELEASED BY WAREHOUSE</x:String>
                        <x:String>ONGOING</x:String>
                        <x:String>COMPLETED</x:String>
                    </Picker.Items>
                </Picker>
                <ImageButton Margin="-10,3,0,0" WidthRequest="32" VerticalOptions="Start" BorderColor="Transparent" BackgroundColor="Transparent" Padding="5,5,5,5" Clicked="HandleRefreshButton" Source="refresh.png" Grid.Row="0" Grid.Column="1" />
            </Grid>
            <ActivityIndicator IsRunning="False" IsVisible="False" IsEnabled="False" Color="CornflowerBlue" VerticalOptions="CenterAndExpand"
                               HorizontalOptions="FillAndExpand" HeightRequest="80" WidthRequest="80"
                               AbsoluteLayout.LayoutFlags="PositionProportional"
                               AbsoluteLayout.LayoutBounds="0.5,0.5,-1,-1" x:Name="activityind"/>
            <ListView Margin="5,20,5,20" ItemTapped="riderOrdersListView_ItemTapped"  x:Name="riderOrdersListView" ItemsSource="{Binding aorderinfo}" VerticalOptions="FillAndExpand" HasUnevenRows="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid RowSpacing="5" Padding="0,0,0,0">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="70" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="55" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="10*" />
                                    <ColumnDefinition Width="10*" />
                                </Grid.ColumnDefinitions>
                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>
                                <Label Text="REFERENCE NO." Font="Bold,Small" TextColor="Black" Grid.Row="0" Grid.Column="0"/>
                                <Label Text="SALES ORDER" Font="Bold,Small" TextColor="Black" Grid.Row="0" Grid.Column="1"/>
                                <Label Text="{Binding checkoutcode}" Font="Bold,Medium" TextColor="#777777" Grid.Row="1" Grid.Column="0"/>
                                <Label Text="{Binding salesorderno}" Font="Bold,Medium" TextColor="#777777" Grid.Row="1" Grid.Column="1"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"/>
                                <Label Text="PICKUP ADDRESS" Font="Bold,Small" TextColor="Black" Grid.Row="2" Grid.Column="0"/>
                                <Label Text="DROPOFF ADDRESS" Font="Bold,Small" TextColor="Black" Grid.Row="2" Grid.Column="1"/>
                                <Label Text="{Binding address1}" VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="#503026" Grid.Row="3" Grid.Column="0"/>
                                <Label Text="{Binding clientaddress}" VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="#503026" Grid.Row="3" Grid.Column="1"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"/>
                                <Label Text="EXPECTED DELIVERY" Font="Bold,Small" TextColor="Black" Grid.Row="4" Grid.ColumnSpan="2"/>
                                <Label Text="{Binding requested_deliverytime}" VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="#503026" Grid.Row="5" Grid.Column="0"/>
                                <Label Text="{Binding status}"  VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="Red" Grid.Row="5" Grid.Column="1"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2"/>
                                <Label Text="ORDER TOTAL" Font="Bold,Small" TextColor="Black" Grid.Row="6" Grid.Column="0"/>
                                <Label Text="REMARKS" Font="Bold,Small" TextColor="Black" Grid.Row="6" Grid.Column="1"/>
                                <Label Text="{Binding ordertotal,StringFormat='PHP {0:N}'}" VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="#503026" Grid.Row="7" Grid.Column="0"/>
                                <Label Text="{Binding confirmremarks}" VerticalOptions="Start" VerticalTextAlignment="Start" TextColor="#503026" Grid.Row="7" Grid.Column="1"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="2"/>
                                <Label Text="GRAND TOTAL" Font="Bold,Small" TextColor="#777777" Grid.Row="8" Grid.Column="0"/>
                                <Label Text="{Binding grandtotal,StringFormat='PHP {0:N}'}" VerticalOptions="Start" VerticalTextAlignment="Start" Font="Bold,Small" TextColor="#CCCCCC" Grid.Row="8" Grid.Column="1"/>

                                <Button BackgroundColor="CornflowerBlue" BorderRadius="5" Clicked="HandleNavigateButton" Text="NAVIGATE" TextColor="#503026" Grid.Row="8" Grid.Column="0"/>
                                <Button BackgroundColor="CornflowerBlue" BorderRadius="5" Clicked="HandleBookButtonAsync" Text="{Binding buttonlabel}" TextColor="#503026" Grid.Row="8" Grid.Column="1"/>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>
</code>```

//This is the Code for the buttton for the "Order Complete"

```<code>async void  HandleBookButtonAsync(object sender, EventArgs e)
        {
            bool answer = false;
            var selectedValue = ordersfilterpicker.Items[ordersfilterpicker.SelectedIndex];
            orderinfo tmp_orderinfo = (orderinfo)((Button)sender).BindingContext;
            selectedValue = tmp_orderinfo.status;
            if (selectedValue == "ALL")
            {
                answer = await popup_yesno("ACCEPT this delivery ?");
                if (answer==true)
                {
                    updateorderstatusrideraccept(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "FOR PICKUP")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "RELEASED BY LOGISTICS")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "RELEASED BY WAREHOUSE")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "ONGOING")
            {
                answer = await popup_yesno("COMPLETE this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderend(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
//I believe I should put something here for the "Nav button" to hide. but I don't know what code to use.
            }
        }
        //("Message", tmp_orderinfo.checkoutcode, "OK");
    }
</code>```

答:
At first, you should give the button a name with the x:Name. Such as

```<code><Button Text="Navigate" Clicked="Button_Clicked" x:Name="button">
</code>```

Then you can set the IsVisible = false in a clicked event. Such as

```<code>  private void Button_Clicked(object sender, EventArgs e)
    {
        button.IsVisible = false;
    }
</code>```

You can set it in the  the "Complete delivery" pressed event.

ContentLicense: CC BY-SA 4.0

Body:
I am doing an app for the courier service. I am trying to figure out how to hide the "Navigate" button when the user presses the "Complete delivery". I tried some codes but no luck. Thanks in adv!

enter image description here

// This is the XAML Code:

<ContentPage.Content>
        <StackLayout>
            <Grid Padding="10,10,4,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="50" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100*" />
                    <ColumnDefinition Width="10*" />
                </Grid.ColumnDefinitions>
                <DatePicker x:Name="dateselector" DateSelected="HandleDateSelected" Grid.Row="0" Grid.Column="0"></DatePicker>
                <Picker HeightRequest="2" IsVisible="false" Title="ORDERS"  x:Name="ordersfilterpicker" FontSize="Small" Grid.Row="1" Grid.Column="0">
                    <Picker.Items>
                        <x:String>MY DELIVERIES</x:String>
                        <x:String>FOR PICKUP</x:String>
                        <x:String>RELEASED BY WAREHOUSE</x:String>
                        <x:String>ONGOING</x:String>
                        <x:String>COMPLETED</x:String>
                    </Picker.Items>
                </Picker>
                <ImageButton Margin="-10,3,0,0" WidthRequest="32" VerticalOptions="Start" BorderColor="Transparent" BackgroundColor="Transparent" Padding="5,5,5,5" Clicked="HandleRefreshButton" Source="refresh.png" Grid.Row="0" Grid.Column="1" />
            </Grid>
            <ActivityIndicator IsRunning="False" IsVisible="False" IsEnabled="False" Color="CornflowerBlue" VerticalOptions="CenterAndExpand"
                               HorizontalOptions="FillAndExpand" HeightRequest="80" WidthRequest="80"
                               AbsoluteLayout.LayoutFlags="PositionProportional"
                               AbsoluteLayout.LayoutBounds="0.5,0.5,-1,-1" x:Name="activityind"/>
            <ListView Margin="5,20,5,20" ItemTapped="riderOrdersListView_ItemTapped"  x:Name="riderOrdersListView" ItemsSource="{Binding aorderinfo}" VerticalOptions="FillAndExpand" HasUnevenRows="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid RowSpacing="5" Padding="0,0,0,0">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="70" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="20" />
                                    <RowDefinition Height="55" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="10*" />
                                    <ColumnDefinition Width="10*" />
                                </Grid.ColumnDefinitions>
                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2"/>

                                <BoxView HeightRequest="25" Color="LightGray" Opacity="0.4" Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="2"/>

                                <Button BackgroundColor="CornflowerBlue" BorderRadius="5" Clicked="HandleNavigateButton" Text="NAVIGATE" TextColor="#503026" Grid.Row="8" Grid.Column="0"/>
                                <Button BackgroundColor="CornflowerBlue" BorderRadius="5" Clicked="HandleBookButtonAsync" Text="{Binding buttonlabel}" TextColor="#503026" Grid.Row="8" Grid.Column="1"/>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

//This is the Code for the buttton for the "Order Complete"

async void  HandleBookButtonAsync(object sender, EventArgs e)
        {
            bool answer = false;
            var selectedValue = ordersfilterpicker.Items[ordersfilterpicker.SelectedIndex];
            orderinfo tmp_orderinfo = (orderinfo)((Button)sender).BindingContext;
            selectedValue = tmp_orderinfo.status;
            if (selectedValue == "ALL")
            {
                answer = await popup_yesno("ACCEPT this delivery ?");
                if (answer==true)
                {
                    updateorderstatusrideraccept(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "FOR PICKUP")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "RELEASED BY LOGISTICS")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "RELEASED BY WAREHOUSE")
            {
                answer = await popup_yesno("START this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderstart(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
                }
            }
            else if (selectedValue == "ONGOING")
            {
                answer = await popup_yesno("COMPLETE this delivery ?");
                if (answer == true)
                {
                    updateorderstatusriderend(tmp_orderinfo.checkoutcode);
                    refreshlistviewtask();
//I believe I should put something here for the "Nav button" to hide. but I don't know what code to use.
            }
        }
        //("Message", tmp_orderinfo.checkoutcode, "OK");
    }

Body:
At first, you should give the button a name with the x:Name. Such as

<Button Text="Navigate" Clicked="Button_Clicked" x:Name="button">

Then you can set the IsVisible = false in a clicked event. Such as

  private void Button_Clicked(object sender, EventArgs e)
    {
        button.IsVisible = false;
    }

You can set it in the  the "Complete delivery" pressed event.


问:
error to set onclick event on button
i have create some xml layout and i java files, some xml file have same id of the button and i create onClick event on this,
when i click this button it's generate an error shown below</p>

```<code>08-17 01:08:12.357: ERROR/AndroidRuntime(22434): java.lang.StackOverflowError
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at java.util.HashMap.containsKey(HashMap.java:313)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$NameValueCache.getString(Settings.java:494)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$System.getString(Settings.java:575)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$System.getInt(Settings.java:624)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.media.AudioManager.querySoundEffectsEnabled(AudioManager.java:1089)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.media.AudioManager.playSoundEffect(AudioManager.java:1042)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.ViewRoot.playSoundEffect(ViewRoot.java:2478)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.playSoundEffect(View.java:8309)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2363)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(V
</code>```

答:
i have got answer :

i have used that code :

```<code>public void onClick(View v) {
    if(v.getId() == R.id.xCBApple){
            Toast.makeText(CheckBoxClass.this,"Apple is Chedked",Toast.LENGTH_SHORT);
    }
    if(jBackButton.performClick())
    {
            Intent intent = new Intent(CheckBoxClass.this,AndroidWidgetsActivity.class);
            startActivity(intent);
    }
}
</code>```

but i have to use v.getId() == R.id.backButton instead of jBackButton.performClick() and error is gone but i dont understnd about performClick() , can any one know about it ?

Thank
Rahul

ContentLicense: CC BY-SA 3.0

Title: error to set onclick event on button

Body:
i have create some xml layout and i java files, some xml file have same id of the button and i create onClick event on this,
when i click this button it's generate an error shown below

08-17 01:08:12.357: ERROR/AndroidRuntime(22434): java.lang.StackOverflowError
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at java.util.HashMap.containsKey(HashMap.java:313)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$NameValueCache.getString(Settings.java:494)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$System.getString(Settings.java:575)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.provider.Settings$System.getInt(Settings.java:624)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.media.AudioManager.querySoundEffectsEnabled(AudioManager.java:1089)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.media.AudioManager.playSoundEffect(AudioManager.java:1042)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.ViewRoot.playSoundEffect(ViewRoot.java:2478)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.playSoundEffect(View.java:8309)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2363)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(View.java:2364)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at com.widgets.CheckBoxClass.onClick(CheckBoxClass.java:44)
08-17 01:08:12.357: ERROR/AndroidRuntime(22434):     at android.view.View.performClick(V

Body:
i have got answer :

i have used that code :

public void onClick(View v) {
    if(v.getId() == R.id.xCBApple){
            Toast.makeText(CheckBoxClass.this,"Apple is Chedked",Toast.LENGTH_SHORT);
    }
    if(jBackButton.performClick())
    {
            Intent intent = new Intent(CheckBoxClass.this,AndroidWidgetsActivity.class);
            startActivity(intent);
    }
}

but i have to use v.getId() == R.id.backButton instead of jBackButton.performClick() and error is gone but i dont understnd about performClick() , can any one know about it ?

Thank
Rahul


问:
Azure Redis Cache error No connection is available to service this operation:
I'm trying to use Azure Redis cache in my MVC 4.6 app but getting connection errors. This is the error:

No connection is available to service this operation: GET
  c7fc43f3-47c4-43cb-94ff-50527b1cda0c_TokenCache; It was not possible
  to connect to the redis server(s); to create a disconnected
  multiplexer, disable AbortOnConnectFail. ConnectTimeout; IOCP:
  (Busy=3,Free=997,Min=2,Max=1000), WORKER:
  (Busy=2,Free=4093,Min=2,Max=4095), Local-CPU: 100%

My web.config has:

<add key="ida:CacheConnection" value="myCache.redis.cache.windows.net:6380,password=bpPQX6jeocNjyX1FqrvVztGMQqjekXbUXFjGkiZOyCE=,ssl=True,abortConnect=False,connectTimeout=30,syncTimeout=3000,ConnectRetry=3" />

My packages.config has:

```<code><package id="StackExchange.Redis" version="1.2.0" targetFramework="net45" />
</code>```

I followed this MSDN article to configure Aazure Redis server and client.

I tried to use client side cmd line tool to verify the connection even that is not working. Not giving me any sign of success or failure. This is my command:

```<code>C:\Program Files\Redis>redis-cli -h "myCache.redis.cache.windows.net" -a bpPQX= -p 6379
</code>```

I tried -p 6380 as well but nothing changed.

答:
Update your connection string

Set abortConnect to false

Adjust your syncTimeout and asyncTimeout as needed.

If you are using a secure TLS connection set the ssl=True,sslprotocols=tls12 in your configuration to force it to the latest version.

Upgrade your StackExchange.Redis nuget package to latest if you can.

Set the config option for ReconnectRetryPolicy in your C# code to be ExponentialRetry
https://stackexchange.github.io/StackExchange.Redis/Configuration.html#reconnectretrypolicy

```<code>private static readonly Lazy<ConfigurationOptions> configOptions  = new Lazy<ConfigurationOptions>(() =>
{
    var connections = ConfigurationManager.ConnectionStrings["redis-connection"].ConnectionString;
    var configOptions = ConfigurationOptions.Parse(connections);

    configOptions.ClientName = "MyApp-RedisCacheProvider";
    //configOptions.SyncTimeout = 100000; // don`t do this in code, set it in your connection string
    //configOptions.AbortOnConnectFail = false; // don`t do this in code, set it in your connection string

    /*
     * The default is LinearRetry which can cause congestion at virtually the same time on multiple parallel threads.
     * Use ExponentialRetry so that a degree of randomness is used in the timing across multiple threads.
     */
    configOptions.ReconnectRetryPolicy = new ExponentialRetry(5000, 10000);

    return configOptions;
});

 private static readonly Lazy<ConnectionMultiplexer> connection = new Lazy<ConnectionMultiplexer>(
         () => ConnectionMultiplexer.Connect(configOptions.Value));
</code>```

Implement IDisposable to dispose the object after its use

```<code>     public void Dispose()
     {
         try {
             if (connection.IsValueCreated)
             {
                 connection.Value.Dispose();
             }
         } catch { }
     }
</code>```

Body:
I'm trying to use Azure Redis cache in my MVC 4.6 app but getting connection errors. This is the error:

No connection is available to service this operation: GET
  c7fc43f3-47c4-43cb-94ff-50527b1cda0c_TokenCache; It was not possible
  to connect to the redis server(s); to create a disconnected
  multiplexer, disable AbortOnConnectFail. ConnectTimeout; IOCP:
  (Busy=3,Free=997,Min=2,Max=1000), WORKER:
  (Busy=2,Free=4093,Min=2,Max=4095), Local-CPU: 100%

My web.config has:

<add key="ida:CacheConnection" value="myCache.redis.cache.windows.net:6380,password=bpPQX6jeocNjyX1FqrvVztGMQqjekXbUXFjGkiZOyCE=,ssl=True,abortConnect=False,connectTimeout=30,syncTimeout=3000,ConnectRetry=3" />

My packages.config has:

<package id="StackExchange.Redis" version="1.2.0" targetFramework="net45" />

I followed this MSDN article to configure Aazure Redis server and client.

I tried to use client side cmd line tool to verify the connection even that is not working. Not giving me any sign of success or failure. This is my command:

C:\Program Files\Redis>redis-cli -h "myCache.redis.cache.windows.net" -a bpPQX= -p 6379

I tried -p 6380 as well but nothing changed.

Body:
Update your connection string

Set abortConnect to false

Adjust your syncTimeout and asyncTimeout as needed.

If you are using a secure TLS connection set the ssl=True,sslprotocols=tls12 in your configuration to force it to the latest version.

Upgrade your StackExchange.Redis nuget package to latest if you can.

Set the config option for ReconnectRetryPolicy in your C# code to be ExponentialRetry
https://stackexchange.github.io/StackExchange.Redis/Configuration.html#reconnectretrypolicy

private static readonly Lazy<ConfigurationOptions> configOptions  = new Lazy<ConfigurationOptions>(() =>
{
    var connections = ConfigurationManager.ConnectionStrings["redis-connection"].ConnectionString;
    var configOptions = ConfigurationOptions.Parse(connections);

    configOptions.ClientName = "MyApp-RedisCacheProvider";
    //configOptions.SyncTimeout = 100000; // don`t do this in code, set it in your connection string
    //configOptions.AbortOnConnectFail = false; // don`t do this in code, set it in your connection string

    /*
     * The default is LinearRetry which can cause congestion at virtually the same time on multiple parallel threads.
     * Use ExponentialRetry so that a degree of randomness is used in the timing across multiple threads.
     */
    configOptions.ReconnectRetryPolicy = new ExponentialRetry(5000, 10000);

    return configOptions;
});

 private static readonly Lazy<ConnectionMultiplexer> connection = new Lazy<ConnectionMultiplexer>(
         () => ConnectionMultiplexer.Connect(configOptions.Value));

Implement IDisposable to dispose the object after its use

     public void Dispose()
     {
         try {
             if (connection.IsValueCreated)
             {
                 connection.Value.Dispose();
             }
         } catch { }
     }


问:
Microsoft.AppCenter.Crashes not detecting crashes on Xamarin.Forms iOS project
I recently tried to implement Microsoft.AppCenter.Crashes to help track down crashes in my team's Xamarin.Forms app. However, when a crash happens on our iOS project, AppCenter never detects it. I've created the following function for setup and checking, which gets called near the start of our central project's App.xaml.cs App constructor:

```<code>private async Task CheckForPreviousCrash()
    {
        //Setup AppCenter
        await Xamarin.Forms.Device.InvokeOnMainThreadAsync(() =>
        {
            //Keys changed in StackOverflow post for security reasons.
            AppCenter.Start("ios=########-####-####-####-############;android=########-####-####-####-############;uwp=########-####-####-####-############", typeof(Crashes));
            AppCenter.IsNetworkRequestsAllowed = false; //Prevents sending user data to Microsoft. Required by company
        });

        //Make sure AppCenter is working
        bool isEnabled = await Crashes.IsEnabledAsync();
        if (!isEnabled)
        {
            _logger.LogError("AppCenter could not be started");
        }
        else
        {
            //Check for memory leak warnings
            bool memoryIssue = await Crashes.HasReceivedMemoryWarningInLastSessionAsync();
            if (memoryIssue)
            {
                _logger.LogError("AppCenter detected a memory warning in the last session");
            }

            //Check for crash info
            bool crashed = await Crashes.HasCrashedInLastSessionAsync();
            if (crashed)
            {
                var report = await Crashes.GetLastSessionCrashReportAsync();
                _logger.LogCrashReport(report);
            }

            //If AppCenter detected no issues in the last session, log an "all clear" message
            if (!memoryIssue && !crashed)
            {
                _logger.LogInformation("AppCenter did not detect a crash in the last session");
            }
        }
    }
</code>```

I've tested this code using the Crashes.GenerateTestCrash() function, one of the crashes my team is trying to resolve, and a simple recursive function that calls itself forever. When run on iOS, our logs will always show the "AppCenter did not detect a crash in the last session" message, regardless of if a crash occurred. Any help determining what could be causing this would be appreciated.

Notes:

The iOS project is always run without a debugger attached. I'm aware of the rule that crash reports will not be generated if iOS has a debugger attached

This has been seen when built using both Debug and Release mode

This code works as expected on our Android and UWP projects

The iOS project always passes the isEnabled check

This is running AppCenter and AppCenter.Crashes version 4.5.0

This is running on a 7th gen iPad on iOS 15.2.1

EDIT: Extra notes in response to a suggested answer:

The Mac used to build the iOS project is running macOS 11.6.2

Project is built using XCode 13.2.1

The Xamarin Forms project is built in Visual Studio 2019 16.11.7, and sent to the connected mac via Visual Studio's "Pair to Mac" feature

There are no other libraries used for crash reporting (the closest used is Serilog, which should only be handling logging)

We do not use CocoaPods to integrate AppCenter

答:
You can check if you meet the requirements as following shows:

-Your iOS project is set up in Xcode 11 or later on macOS version 10.14.4 or later.

-You're targeting devices running on iOS 9.0 or later.

-You're not using any other library that provides Crash Reporting functionality (only for App Center Crashes).

-If you are using CocoaPods to integrate App Center, you need CocoaPods version 1.10 or later.

App Center SDK Analytics and Crashes are compatible with Mac Catalyst via XCFramework or SwiftPM.

Here are more detail about appcenter crashed on ios https://learn.microsoft.com/en-us/appcenter/sdk/getting-started/ios

Body:
I recently tried to implement Microsoft.AppCenter.Crashes to help track down crashes in my team's Xamarin.Forms app. However, when a crash happens on our iOS project, AppCenter never detects it. I've created the following function for setup and checking, which gets called near the start of our central project's App.xaml.cs App constructor:

private async Task CheckForPreviousCrash()
    {
        //Setup AppCenter
        await Xamarin.Forms.Device.InvokeOnMainThreadAsync(() =>
        {
            //Keys changed in StackOverflow post for security reasons.
            AppCenter.Start("ios=########-####-####-####-############;android=########-####-####-####-############;uwp=########-####-####-####-############", typeof(Crashes));
            AppCenter.IsNetworkRequestsAllowed = false; //Prevents sending user data to Microsoft. Required by company
        });

        //Make sure AppCenter is working
        bool isEnabled = await Crashes.IsEnabledAsync();
        if (!isEnabled)
        {
            _logger.LogError("AppCenter could not be started");
        }
        else
        {
            //Check for memory leak warnings
            bool memoryIssue = await Crashes.HasReceivedMemoryWarningInLastSessionAsync();
            if (memoryIssue)
            {
                _logger.LogError("AppCenter detected a memory warning in the last session");
            }

            //Check for crash info
            bool crashed = await Crashes.HasCrashedInLastSessionAsync();
            if (crashed)
            {
                var report = await Crashes.GetLastSessionCrashReportAsync();
                _logger.LogCrashReport(report);
            }

            //If AppCenter detected no issues in the last session, log an "all clear" message
            if (!memoryIssue && !crashed)
            {
                _logger.LogInformation("AppCenter did not detect a crash in the last session");
            }
        }
    }

I've tested this code using the Crashes.GenerateTestCrash() function, one of the crashes my team is trying to resolve, and a simple recursive function that calls itself forever. When run on iOS, our logs will always show the "AppCenter did not detect a crash in the last session" message, regardless of if a crash occurred. Any help determining what could be causing this would be appreciated.

Notes:

The iOS project is always run without a debugger attached. I'm aware of the rule that crash reports will not be generated if iOS has a debugger attached

This has been seen when built using both Debug and Release mode

This code works as expected on our Android and UWP projects

The iOS project always passes the isEnabled check

This is running AppCenter and AppCenter.Crashes version 4.5.0

This is running on a 7th gen iPad on iOS 15.2.1

EDIT: Extra notes in response to a suggested answer:

The Mac used to build the iOS project is running macOS 11.6.2

Project is built using XCode 13.2.1

The Xamarin Forms project is built in Visual Studio 2019 16.11.7, and sent to the connected mac via Visual Studio's "Pair to Mac" feature

There are no other libraries used for crash reporting (the closest used is Serilog, which should only be handling logging)

We do not use CocoaPods to integrate AppCenter


问:
Discord JS - DiscordAPIError: Missing Access

So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error

```<code>/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
      ^

DiscordAPIError: Missing Access
    at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
  method: 'post',
  path: '/applications/901999677011005472/guilds/905266476573950023/commands',
  code: 50001,
  httpStatus: 403,
  requestData: {
    json: {
      name: 'ping',
      description: 'Bot uptime/latency checker.',
      type: undefined,
      options: undefined,
      default_permission: undefined
    },
    files: []
  }
}
</code>```

I also try looking at my code but I didn't see something wrong.

This is my code, I really think something is wrong in the code.

```<code>const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()

const client = new DiscordJS.Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES
    ]
})

client.on('ready', () => {
    console.log("The bot is online")
    // Carlos: 883425101389914152
    const guildId = '905266476573950023'
    const guild = client.guilds.cache.get(guildId)
    let commands

    if (guild) {
        commands = guild.commands
    } else {
        commands = client.application.commands
    }

    commands.create({
        name: 'ping',
        description: 'Bot uptime/latency checker.',
    })

    commands.create({
        name: 'add',
        description: 'Adds two numbers given by user.',
        options: [
            {
                name: 'number1',
                description: 'The first number',
                required: true,
                type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
            },
            {
                name: 'number2',
                description: 'The second number',
                required: true,
                type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
            },
        ]
    })
})

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) {
        return
    }

    const { commandName, Options } = interaction

    if (commandName === 'ping') {
        interaction.reply({
            content: 'Pong! **60ms**',
            // If anyone can see = True, Only command user can see = False
            ephemeral: true,
        })
    } else if (commandName === 'add') {
        interaction.reply({
            content: 'The sum is ${number1 + number2}'
        })
    }
})

client.login(process.env.KEY)
</code>```

答: For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.</p>

Body:
So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error

/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
      ^

DiscordAPIError: Missing Access
    at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
    at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
  method: 'post',
  path: '/applications/901999677011005472/guilds/905266476573950023/commands',
  code: 50001,
  httpStatus: 403,
  requestData: {
    json: {
      name: 'ping',
      description: 'Bot uptime/latency checker.',
      type: undefined,
      options: undefined,
      default_permission: undefined
    },
    files: []
  }
}

I also try looking at my code but I didn't see something wrong.

This is my code, I really think something is wrong in the code.

const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()

const client = new DiscordJS.Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES
    ]
})

client.on('ready', () => {
    console.log("The bot is online")
    // Carlos: 883425101389914152
    const guildId = '905266476573950023'
    const guild = client.guilds.cache.get(guildId)
    let commands

    if (guild) {
        commands = guild.commands
    } else {
        commands = client.application.commands
    }

    commands.create({
        name: 'ping',
        description: 'Bot uptime/latency checker.',
    })

    commands.create({
        name: 'add',
        description: 'Adds two numbers given by user.',
        options: [
            {
                name: 'number1',
                description: 'The first number',
                required: true,
                type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
            },
            {
                name: 'number2',
                description: 'The second number',
                required: true,
                type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
            },
        ]
    })
})

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) {
        return
    }

    const { commandName, Options } = interaction

    if (commandName === 'ping') {
        interaction.reply({
            content: 'Pong! **60ms**',
            // If anyone can see = True, Only command user can see = False
            ephemeral: true,
        })
    } else if (commandName === 'add') {
        interaction.reply({
            content: 'The sum is ${number1 + number2}'
        })
    }
})

client.login(process.env.KEY)


问:
How to assign result of OUTPUT DELETED to an output parameter?
I have the following query that generates the next available bill of lading numbers.

ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE Facilities
    SET NextTruckBol = NextTruckBol + @Count
    OUTPUT DELETED.NextTruckBol
    WHERE Id = @FacilityId
END
```

But now I need to modify it so that the resulting value is instead assigned to an OUTPUT parameter.

I know how to declare the OUTPUT parameter. How can I assign the value of OUTPUT DELETED.NextTruckBol to that parameter?

答:
Per the UPDATE documentation

Variable names can be used in UPDATE statements to show the old and
new values affected, but this should be used only when the UPDATE
statement affects a single record. If the UPDATE statement affects
multiple records, to return the old and new values for each record,
use the OUTPUT clause.

So if you know that the UPDATE will only affect max one row (as Id is constrained to be unique) and you don't want to mess around with table variables you can use

SET @variable = column, column = expression, which sets the variable
to the pre-update value of the column.

So that would be

```<code>CREATE OR ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1,
    @NextTruckBol INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Facilities
    SET @NextTruckBol = NextTruckBol,
        NextTruckBol = NextTruckBol + @Count
    WHERE Id = @FacilityId
END
</code>```

Body:
I have the following query that generates the next available bill of lading numbers.

ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE Facilities
    SET NextTruckBol = NextTruckBol + @Count
    OUTPUT DELETED.NextTruckBol
    WHERE Id = @FacilityId
END

But now I need to modify it so that the resulting value is instead assigned to an OUTPUT parameter.

I know how to declare the OUTPUT parameter. How can I assign the value of OUTPUT DELETED.NextTruckBol to that parameter?

Body:
Per the UPDATE documentation

Variable names can be used in UPDATE statements to show the old and
new values affected, but this should be used only when the UPDATE
statement affects a single record. If the UPDATE statement affects
multiple records, to return the old and new values for each record,
use the OUTPUT clause.

So if you know that the UPDATE will only affect max one row (as Id is constrained to be unique) and you don't want to mess around with table variables you can use

SET @variable = column, column = expression, which sets the variable
to the pre-update value of the column.

So that would be

CREATE OR ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1,
    @NextTruckBol INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Facilities
    SET @NextTruckBol = NextTruckBol,
        NextTruckBol = NextTruckBol + @Count
    WHERE Id = @FacilityId
END


问:
how to make changes to a existing column based on multiple conditions in python csv
So I am working on data processing and I want to make changes to a column called "temp_coil" based on the condition in other columns.

This is the one I made and it is giving me error.

```<code>df.temp_coil[df.outdoor_temperature < 20 & df.cooling_state == 1 & df.temp_coil == 0] = 4500
</code>```

I want the answer to be 4500 if outdoor_temperature column is less than 20, cooling_state column is 1 and temp_coil column itself is 0. All the conditions need to be met.

The error it is giving me is type and value error when I run it.
If this is already answered please let me know, I couldn't find an example that matched my problem.

答:
You must use parentheses so that the truth table is unambiguous. For your example, the correct code would be:

```<code>df.temp_coil[(df.outdoor_temperature < 20) & (df.cooling_state == 1) & (df.temp_coil == 0)] = 4500
</code>```

Or:

```<code>df.temp_coil[df.outdoor_temperature.lt(20) & df.cooling_state.eq(1) & df.temp_coil.eq(0)] = 4500
</code>```

Body:
So I am working on data processing and I want to make changes to a column called "temp_coil" based on the condition in other columns.

This is the one I made and it is giving me error.

df.temp_coil[df.outdoor_temperature < 20 & df.cooling_state == 1 & df.temp_coil == 0] = 4500

I want the answer to be 4500 if outdoor_temperature column is less than 20, cooling_state column is 1 and temp_coil column itself is 0. All the conditions need to be met.

The error it is giving me is type and value error when I run it.
If this is already answered please let me know, I couldn't find an example that matched my problem.

Body:
You must use parentheses so that the truth table is unambiguous. For your example, the correct code would be:

df.temp_coil[(df.outdoor_temperature < 20) & (df.cooling_state == 1) & (df.temp_coil == 0)] = 4500

Or:

df.temp_coil[df.outdoor_temperature.lt(20) & df.cooling_state.eq(1) & df.temp_coil.eq(0)] = 4500


问:
weka logistic regression classifier not wroking
I have a text dataset of size 15MB and it has close to 27k of rows, J48 TREE and NAÏVE BAYES classifiers work just fine, but when using logistic classifier i keep getting this error
enter image description here
I have tried reszing the heap size but it still not working, same thing goes to deep learning and random forest.
what can i do?</p>

答:
Does your data have nominal attributes with many values? If so, 2GB may not be enough.

Why? Logistic applies the NominalToBinary filter, which generates binary attributes from labels (absence or presence). That can generate a lot of additional attributes if you have many multi-valued nominal atttibutes.

Solution? Work with a sub-sample of your data or increase the heap size.


问:
Compose swipe-to-dismiss selects wrong items
I have column with items where with "swipe-to-dismiss" functionality.
The problem is: "swipe-to-delete" removes correct item only first time. Next time it sends wrong id to the "removeTask" function.
I fixed it when using lazyColumn by adding item key to the lazyLayout. But for some reason I need to use column.

```<code>Column(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            items.forEach {
                SwipeableCompletedTask(task, removeTask)
            }
        }

@Composable
private fun SwipeableCompletedTask(task: UnboxingTask, removeTask: (String) -> Unit) {
    val dismissState = rememberDismissState(
        confirmStateChange = {
            if (it == DismissValue.DismissedToEnd || it == DismissValue.DismissedToStart) {
                removeTask(task.id ?: "") // same id here every time
            }
            false
        }
    )
    SwipeToDismiss(
        state = dismissState,
 ..........
    )
}
</code>```

How can I fix this?

答:
You can use androidx.compose.runtime.key

```<code>Column(
    modifier = Modifier
        .fillMaxWidth()
) {
    items.forEach {
        key(task.id){ SwipeableCompletedTask(task, removeTask) }
    }
}
</code>```

The task.id can use other value. You should make each value is unique in this composition.

Official Document: key

Body:
I have column with items where with "swipe-to-dismiss" functionality.
The problem is: "swipe-to-delete" removes correct item only first time. Next time it sends wrong id to the "removeTask" function.
I fixed it when using lazyColumn by adding item key to the lazyLayout. But for some reason I need to use column.

Column(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            items.forEach {
                SwipeableCompletedTask(task, removeTask)
            }
        }

@Composable
private fun SwipeableCompletedTask(task: UnboxingTask, removeTask: (String) -> Unit) {
    val dismissState = rememberDismissState(
        confirmStateChange = {
            if (it == DismissValue.DismissedToEnd || it == DismissValue.DismissedToStart) {
                removeTask(task.id ?: "") // same id here every time
            }
            false
        }
    )
    SwipeToDismiss(
        state = dismissState,
 ..........
    )
}

How can I fix this?

Body:
You can use androidx.compose.runtime.key

Column(
    modifier = Modifier
        .fillMaxWidth()
) {
    items.forEach {
        key(task.id){ SwipeableCompletedTask(task, removeTask) }
    }
}

The task.id can use other value. You should make each value is unique in this composition.

Official Document: key


问:
How can I treat an array of values to be a tuple that is inferred based on what's passed to it
I have a React component like this:

```<code>interface Props<T> {
  data: {
    items: T[]
  }[]
}

const MyComponent = <T,>(props: Props<T>) => {
  return ...
}

<MyComponent data={[
  {
    items: [{ name: 'A', age: 10 }, { name: 'B', age: 20 }]
  },
  {
    items: [{ label: 'A', value: 25 }, { label: 'C', value: 50 }
  }
]} />
</code>```

In this example, I want the first data item to have T = {name: string, age: number} and the second data item to have T = { label: string, value: number }

I know that this is possible with tuples but I want to infer the tuple from the props that are passed to it.

答:
Here you go

```<code>interface Props<T1, T2> {
  data: [{ items: T1[] }, { items: T2[] }]
}

const MyComponent = <T1,T2>(props: Props<T1, T2>) => {
  return null;
}
</code>```

Which could be further optimized if needed.

Body:
I have a React component like this:

interface Props<T> {
  data: {
    items: T[]
  }[]
}

const MyComponent = <T,>(props: Props<T>) => {
  return ...
}

<MyComponent data={[
  {
    items: [{ name: 'A', age: 10 }, { name: 'B', age: 20 }]
  },
  {
    items: [{ label: 'A', value: 25 }, { label: 'C', value: 50 }
  }
]} />

In this example, I want the first data item to have T = {name: string, age: number} and the second data item to have T = { label: string, value: number }

I know that this is possible with tuples but I want to infer the tuple from the props that are passed to it.

Body:
Here you go

interface Props<T1, T2> {
  data: [{ items: T1[] }, { items: T2[] }]
}

const MyComponent = <T1,T2>(props: Props<T1, T2>) => {
  return null;
}

Which could be further optimized if needed.


问:
Android:small size image taken by camera
I have called an intent by passing action "android.media.action.IMAGE_CAPTURE"

i.e. intent.setAction("android.media.action.IMAGE_CAPTURE");and the image I get is small size.and i want to get Full Sized image of 730X1115 size.How can I get that.

答: I have scaled that image by giving the dimensions of the border in which it gets fit.</p>


问:
JWT authentication and the purpose of refresh token
I'm trying to wrap my mind around JWT authentication. I've read a lot of articles and SO questions, but some of them are getting old and I still didn't get satisfactory answers.

I've read this SO question and from José F. Romaniello's answer I understand that:

with refresh token client requests new access token before the old one has expired (it is normal, expected behavior)

on mobile apps tokens never expire

Also on auth0 it says:

You can request new access tokens until the refresh token is on the
DenyList. Applications must store refresh tokens securely because they
essentially allow a user to remain authenticated forever.

So what's the point of having time limited access token if refresh token can request for new access tokens forever?

Then I've read this SO question, which references the SO question from above. In his answer qre0ct says:

...assume that if Bob has compromised the refresh token, he would be
using it to generate an access token (because access token is the only
thing which is authorized to access resources through the APIs). As
soon as Bob (attacker) requests with the newly generated access token
because Alice's (genuine user) access token is still valid, the server
would see this as an anomaly, because for a single refresh token there
can be only one authorized access token at a time.

If we presume that it is normal for a client to request new access token at any moment (every hour, or every time the user opens the web application, as José F. Romaniello said), how will server distinguish if it's Alice or Bob who's making a request for a new access token? And why would this be anomaly?

Also, a lot of people say that the advantage of JWT authentication is that server doesn't make DB calls. But from above quotation from auth0, they mention DenyList. So I guess there must be a DB call on every request to check if the token is not blacklisted? Is the no DB calls thing a myth?

And if I have to keep record of blacklisted tokens, why not just use access tokens and blacklist them if necessary? I cannot understand the advantage of having two tokens, because if either one of them gets stolen, the thief can stay logged in forever (especially in the context of mobile apps where refresh token lasts forever)

Thanks in advance for your patience and time.

答:
Couple questions here...

Might be easiest to answer this by starting with the intent of each token type - there's actually 3 types of token that all have different uses:

Access token

ID token

Refresh token

Access tokens are uses as bearer tokens on back-end API requests and are used for auth. They're often JWTs that don't contain PII. If an access token is compromised (e.g. if it's used in unencrypted request and intercepted) it would typically only have a lifetime of 10-15 mins, so there's a limited time frame where the attacker can use it.

ID tokens are received by public client apps and shouldn't leave the app. They're often JWTs and might contain PII e.g. a users name, email, phone so that the app can just get this information from the ID token without needing to make a back-end request.

Refresh tokens are used to streamline the authentication process for subsequent auths. Instead of having to sign-in with username & password/OTP, you can just use a PIN or biometrics to unlock the refresh token and perform a refresh token exchange to the IDP to get a new access and ID token (and potentially even new refresh tokens if performing refresh token rotation). Refresh tokens are opaque and should be stored securely on the app. There needs to be a bit more security around refresh tokens as they've often got a lifetime of several months whereas a single access token might only have a lifetime of a few minutes - typically 10-15 mins. If a refresh token is compromised, it can be used to get new access tokens until it eventually expires (potentially after multiple months). Refresh tokens should be stored securely on a device - typically the device key-store/chain and not leave the device. Historically refresh tokens have only been used in native apps where they can be stored securely on the device, and NOT in browser-based SPAs, but I think there might be some changes to these guidelines with the advent of refresh token rotation.

For question about using JWT authentication and that server doesn't make DB calls. What is meant here is that JWT auth is distributed. A JWT can be validated by simply verifying the digital signature without needing to make any subsequent network request (aside from an initial lazy loaded request to get the public signing key). Alternatively with opaque tokens, you'd need to make network request every time to some kind of data store to validate the token.

WRT blacklisted tokens, once an access token is issued, we typically don't call back to the IDP to validate the token (it's all distributed auth), so there's no concept of blacklisting an access token. A refresh token on the other hand can be blocked on the IDP, so when a user/device attempts a refresh token exchange (to get new access/ID tokens) the IDP can block the request if the refresh token has been revoked. Note: there are some fine-grained authZ strategies to block access tokens before they expire on your back-end, but it can get quite complex.


问:
How can I list all table in my database and be able use the results to preform functions in Electron or NodeJs
I am trying to create an app where I will be able to list all tables in my database and then when the tables are listed. I want to be able to click each table and it should display all columns of the clicked table in electron or node js.

for example, If I have a database called 'students' and this database has about 3 tables namely 'table1' 'table2' and 'table3' and each table has its own 2 columns that have 'id' and 'name'

so say I want to list all these tables and then if I click on table1 it should take me to table1 and Select all my columns to display.

I have this code below and it helps display the tables but I have no clue of how can I make it perform based on which table I clicked.

```<code><html lang="en">
<head>

    <link rel="stylesheet" type="text/css" href="bootstrap.css">

</head>
<body>

<br>
<br>

    <div class="container">

    <table class="table table-striped " >

            <tr>
                <th>Grades </th>
            </tr>
            <tr id="grades">

            </tr>

    </table>
    </div>

<script type="text/javascript">

var mysql = require('mysql');

var con = mysql.createConnection({
        host     : "localhost",
  user     : "root",
  password : "",
  database : "students"
});

con.connect(function(err) {
  if (err) throw err;
  console.log('connected');

  var sql = "SHOW TABLES FROM students "

  con.query(sql, function (err, result, fields) {
    if (err) throw Eerr ;

        var i;
for (i = 0; i < result.length; i++) {

var cls = document.getElementById("grades");
var list ="<div>"+ result[i].Tables_in_students + "</div><br>";

cls.innerHTML += list;

}

});

});

</script>

</body>
</html>```

```

答:
I am not sure if the code is structured right but this code works exactly how I wanted it. and I believe I may have made an unnecessary second connection.

So here's how it works, the code below loops through my database and displays them in my table and I made a trick of loop-adding buttons and set values of those buttons to the name of the table. So that I can later use it to call functions.

```<code>var mysql = require('mysql');

var con = mysql.createConnection({
        host     : "localhost",
  user     : "root",
  password : "",
  database : "students"
});

con.connect(function(err) {
  if (err) throw err;
  console.log('connected');

 });

var tableContent = document.getElementById("tableContent");
tableContent.innerHTML = "";
  var sql = "SHOW TABLES  " ;

  con.query(sql, function (err, result, fields) {
    if (err) throw err;

     var i;
    for (i = 0; i < result.length; i++) {

    var num =result[i].Tables_in_students;

var list ="<tr><td><button value="+num+" onclick='deletorr(this)'></button></td></tr>";

tableContent.innerHTML += list;

}

});
</code>```

Then I have a function deletorr() which checks the value of the button.
Each button has a value of a table name that it's associated with. If that button is clicked, the function will delete the table along with the button. As shown below.

```<code>function deletorr(sel){

     var mysql = require('mysql');

var con = mysql.createConnection({
        host     : "localhost",
  user     : "root",
  password : "",
  database : "students"
});

con.connect(function(err) {
  if (err) throw err;
  console.log('connected');

 });

    var value = sel.value;
    var sql = "DROP TABLE " +value;

 con.query(sql, function (err, result, fields) {
    if (err) alert (err);

});

// refresh page and show instant result after deleting table
location.reload();

}
</code>```

Body:
I am trying to create an app where I will be able to list all tables in my database and then when the tables are listed. I want to be able to click each table and it should display all columns of the clicked table in electron or node js.

for example, If I have a database called 'students' and this database has about 3 tables namely 'table1' 'table2' and 'table3' and each table has its own 2 columns that have 'id' and 'name'

so say I want to list all these tables and then if I click on table1 it should take me to table1 and Select all my columns to display.

I have this code below and it helps display the tables but I have no clue of how can I make it perform based on which table I clicked.

    <link rel="stylesheet" type="text/css" href="bootstrap.css">

                Grades

```

Body:
I am not sure if the code is structured right but this code works exactly how I wanted it. and I believe I may have made an unnecessary second connection.

So here's how it works, the code below loops through my database and displays them in my table and I made a trick of loop-adding buttons and set values of those buttons to the name of the table. So that I can later use it to call functions.

var mysql = require('mysql');

var con = mysql.createConnection({
        host     : "localhost",
  user     : "root",
  password : "",
  database : "students"
});

con.connect(function(err) {
  if (err) throw err;
  console.log('connected');

 });

var tableContent = document.getElementById("tableContent");
tableContent.innerHTML = "";
  var sql = "SHOW TABLES  " ;

  con.query(sql, function (err, result, fields) {
    if (err) throw err;

     var i;
    for (i = 0; i < result.length; i++) {

    var num =result[i].Tables_in_students;

var list ="<tr><td><button value="+num+" onclick='deletorr(this)'></button></td></tr>";

tableContent.innerHTML += list;

}

});

Then I have a function deletorr() which checks the value of the button.
Each button has a value of a table name that it's associated with. If that button is clicked, the function will delete the table along with the button. As shown below.

function deletorr(sel){

     var mysql = require('mysql');

var con = mysql.createConnection({
        host     : "localhost",
  user     : "root",
  password : "",
  database : "students"
});

con.connect(function(err) {
  if (err) throw err;
  console.log('connected');

 });

    var value = sel.value;
    var sql = "DROP TABLE " +value;

 con.query(sql, function (err, result, fields) {
    if (err) alert (err);

});

// refresh page and show instant result after deleting table
location.reload();

}


问:
Send raw hex and strings over sockets
I'm trying to send data over sockets with Python to trigger IDS rules.

Some of the strings have to be strings i.e. Hello World

Some of the strings have to be strings with hex i.e. Hello World\xff

Some of the strings have to be only hex i.e. \xff\xff\xff\xff

I'm currently sending the data as such:

@classmethod
def send(cls, hostname: str = "8.8.8.8", srcPort: int = 0, destPort: int = 8080,
         content: str = "", buffer_size: int = 1024):
    srcPort = int(srcPort)
    destPort = int(destPort)
    content = content.encode()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Address might be in a TIME_WAIT status, ignore this
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Port might be in a TIME_WAIT status, ignore this
    # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

    # Set the source port before sending
    sock.bind(("", srcPort))
    sock.connect((hostname, destPort))
    sock.sendall(content)
    # shutdown might be redundant/unnecessary (tells connected host that we're
    #                                          done sending data)
    sock.shutdown(socket.SHUT_WR)
    while True:
        data = sock.recv(buffer_size)
        if len(data) == 0:
            break
    sock.close()
```

Assuming the value of content is the string \xff\xff\xff\xff.

I would want the data in the pcap file to read ff ff ff ff, but instead it reads:

5c 78 66 66 5c 78 66 66 5c 78 66 66 5c 78 66 66 (via wireshark)

Which is a literal translation of the string.

However, I also want a string like RemoteNC Control Password:

To read as

52 65 6d 6f 74 65 4e 43 20 43 6f 6e 74 72 6f 6c 20 50 61 73 73 77 6f 72 64 3a

which it currently does.

How can I get both of these done, without having to know if a string is just a string, a combination of a string & hex, or just hex? Is it even possible?

答:
How can I get both of these done, without having to know if a string is just a string, a combination of a string & hex, or just hex? Is it even possible?

The easiest way is standardize your inputs and outputs so that you don't need to guess or check. pack them into raw bytes and then unpack them on the other end.

Decide on a standard encoding that you'll use for the character set, for example UTF-8.

Title: Send raw hex and strings over sockets

Body:
I'm trying to send data over sockets with Python to trigger IDS rules.

Some of the strings have to be strings i.e. Hello World

Some of the strings have to be strings with hex i.e. Hello World\xff

Some of the strings have to be only hex i.e. \xff\xff\xff\xff

I'm currently sending the data as such:

@classmethod
def send(cls, hostname: str = "8.8.8.8", srcPort: int = 0, destPort: int = 8080,
         content: str = "", buffer_size: int = 1024):
    srcPort = int(srcPort)
    destPort = int(destPort)
    content = content.encode()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Address might be in a TIME_WAIT status, ignore this
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Port might be in a TIME_WAIT status, ignore this
    # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

    # Set the source port before sending
    sock.bind(("", srcPort))
    sock.connect((hostname, destPort))
    sock.sendall(content)
    # shutdown might be redundant/unnecessary (tells connected host that we're
    #                                          done sending data)
    sock.shutdown(socket.SHUT_WR)
    while True:
        data = sock.recv(buffer_size)
        if len(data) == 0:
            break
    sock.close()

Assuming the value of content is the string \xff\xff\xff\xff.

I would want the data in the pcap file to read ff ff ff ff, but instead it reads:

5c 78 66 66 5c 78 66 66 5c 78 66 66 5c 78 66 66 (via wireshark)

Which is a literal translation of the string.

However, I also want a string like RemoteNC Control Password:

To read as

52 65 6d 6f 74 65 4e 43 20 43 6f 6e 74 72 6f 6c 20 50 61 73 73 77 6f 72 64 3a

which it currently does.

How can I get both of these done, without having to know if a string is just a string, a combination of a string & hex, or just hex? Is it even possible?


问:
Update the channel name several times
What I am trying to do is have a counter that is shown in the name of a channel.

I am aware of the Discord API rate-limits and that I can change the channel name 2 times in 10 minutes. I am aware that DiscordJS handles rate-limits internally by putting them in a queue.

The problem is right here, suppose the bot executes these lines consecutively:

myChannel.setName(1);
myChannel.setName(2);
myChannel.setName(3);
myChannel.setName(4);
myChannel.setName(5);
```
<p>What happens is that the first two requests change the channel name and the other three go to queue. But after 10 minutes what happens is that the third and fourth requests are sent, while I would like to jump to the last one instead.</p>
<p>I was interested in finding out if there was a way to check the response to the request for a channel name change, in order to "intercept" the rate-limit and prevent it from going into the queue.</p>
<p>I have already thought of a solution for the problem itself:</p>
<pre class="lang-js prettyprint-override"><code>setInterval(()=>{
    myChannel.setName(varDefSomewhereElse);
},10*60*1000);
</code>```

but I want to solve the "problem" as efficiently as possible.

答:
Two ways would likely work for this:

try, catch:

```<code>try {
   myChannel.setName('asd')
}
catch (error) {
console.error(error)
// handle the error here
}
</code>```

.then

```<code>myChannel.setName(varDefSomewhereElse).then((c) => {
console.log(`Set to ${c.name}`)
})
</code>```

Title: Update the channel name several times

Body:
What I am trying to do is have a counter that is shown in the name of a channel.

I am aware of the Discord API rate-limits and that I can change the channel name 2 times in 10 minutes. I am aware that DiscordJS handles rate-limits internally by putting them in a queue.

The problem is right here, suppose the bot executes these lines consecutively:

myChannel.setName(1);
myChannel.setName(2);
myChannel.setName(3);
myChannel.setName(4);
myChannel.setName(5);

What happens is that the first two requests change the channel name and the other three go to queue. But after 10 minutes what happens is that the third and fourth requests are sent, while I would like to jump to the last one instead.

I was interested in finding out if there was a way to check the response to the request for a channel name change, in order to "intercept" the rate-limit and prevent it from going into the queue.

I have already thought of a solution for the problem itself:

setInterval(()=>{
    myChannel.setName(varDefSomewhereElse);
},10*60*1000);

but I want to solve the "problem" as efficiently as possible.

Body:
Two ways would likely work for this:

try, catch:

try {
   myChannel.setName('asd')
}
catch (error) {
console.error(error)
// handle the error here
}

.then

myChannel.setName(varDefSomewhereElse).then((c) => {
console.log(`Set to ${c.name}`)
})


问:
Replace value in stylesheet
I am trying to replace value in stylesheet from function in react native.

I have Styles.js file with created stylesheet (when I have styles for my application) and I want to change one of values in this stylesheet from screen function.

```<code>export default StyleSheet.create({
    screen: {
        flex: 1,
        backgroundColor: 'black',

    }
})
</code>```

Now, the background color is black. I want to change color from black to red. I mean something like that:

```<code>export function DisplayScreen(props) {

   . . .

   return (
       <Pressable onPress={() => styles.screen.backgroundColor.replace('red')} >
            <Text>CHANGE COLOR</Text>
       </Pressable>

}
</code>```

Of course .replace does not exist. Is there any approach on how I can change this?

答:
You can maintain a state called screenBackgroundColor and change it from black to red when the button is pressed.

For example:

```<code>export function DisplayScreen(props) {
    const [screenBackgroundColor, setScreenBackgroundColor] = useState('black');
    . . .

    return (
        <View style={{backgroundColor: screenBackgroundColor}}>
            <Pressable onPress={() => setButtonBackgroundColor('red')}>
                <Text>CHANGE COLOR</Text>
            </Pressable>
        </View>
    )
}
</code>```

Title: Replace value in stylesheet

Body:
I am trying to replace value in stylesheet from function in react native.

I have Styles.js file with created stylesheet (when I have styles for my application) and I want to change one of values in this stylesheet from screen function.

export default StyleSheet.create({
    screen: {
        flex: 1,
        backgroundColor: 'black',

    }
})

Now, the background color is black. I want to change color from black to red. I mean something like that:

export function DisplayScreen(props) {

   . . .

   return (
       <Pressable onPress={() => styles.screen.backgroundColor.replace('red')} >
            <Text>CHANGE COLOR</Text>
       </Pressable>

}

Of course .replace does not exist. Is there any approach on how I can change this?

Body:
You can maintain a state called screenBackgroundColor and change it from black to red when the button is pressed.

For example:

export function DisplayScreen(props) {
    const [screenBackgroundColor, setScreenBackgroundColor] = useState('black');
    . . .

    return (
        <View style={{backgroundColor: screenBackgroundColor}}>
            <Pressable onPress={() => setButtonBackgroundColor('red')}>
                <Text>CHANGE COLOR</Text>
            </Pressable>
        </View>
    )
}


问:
ANDROID: How to gain root access in an Android application?
I'm developing my first Android application, and I'm curious if there are any "standard" ways for executing privileged shell commands. I've only been able to find one way to do it, by executing su, and then appending my commands to stdin of the su process.

```<code>DataOutputStream pOut = new DataOutputStream(p.getOutputStream());
DataInputStream pIn = new DataInputStream(p.getInputStream());

String rv = "";

// su must exit before its output can be read
pOut.writeBytes(cmd + "\nexit\n");
pOut.flush();

p.waitFor();

while (pIn.available() > 0)
    rv += pIn.readLine() + "\n";
</code>```

I've read about wrapping privileged (superuser) calls up in JNI: is this possible? If so, how would one go about accomplishing it? Other than that, are there any other ways of calling privileged instructions from Java?

答:
As far as I know, you can only run command-line commands using root privileges. You can use this generic class I made that wraps the root access in your code:
http://muzikant-android.blogspot.com/2011/02/how-to-get-root-access-and-execute.html

All you need to do is extend this class and override the getCommandsToExecute method to return the commands you want to execute as root.

```<code>public abstract class ExecuteAsRootBase
{
   public static boolean canRunRootCommands()
   {
      boolean retval = false;
      Process suProcess;

      try
      {
         suProcess = Runtime.getRuntime().exec("su");

         DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
         DataInputStream osRes = new DataInputStream(suProcess.getInputStream());

         if (null != os && null != osRes)
         {
            // Getting the id of the current user to check if this is root
            os.writeBytes("id\n");
            os.flush();

            String currUid = osRes.readLine();
            boolean exitSu = false;
            if (null == currUid)
            {
               retval = false;
               exitSu = false;
               Log.d("ROOT", "Can't get root access or denied by user");
            }
            else if (true == currUid.contains("uid=0"))
            {
               retval = true;
               exitSu = true;
               Log.d("ROOT", "Root access granted");
            }
            else
            {
               retval = false;
               exitSu = true;
               Log.d("ROOT", "Root access rejected: " + currUid);
            }

            if (exitSu)
            {
               os.writeBytes("exit\n");
               os.flush();
            }
         }
      }
      catch (Exception e)
      {
         // Can't get root !
         // Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted

         retval = false;
         Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
      }

      return retval;
   }

   public final boolean execute()
   {
      boolean retval = false;

      try
      {
         ArrayList<String> commands = getCommandsToExecute();
         if (null != commands && commands.size() > 0)
         {
            Process suProcess = Runtime.getRuntime().exec("su");

            DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

            // Execute commands that require root access
            for (String currCommand : commands)
            {
               os.writeBytes(currCommand + "\n");
               os.flush();
            }

            os.writeBytes("exit\n");
            os.flush();

            try
            {
               int suProcessRetval = suProcess.waitFor();
               if (255 != suProcessRetval)
               {
                  // Root access granted
                  retval = true;
               }
               else
               {
                  // Root access denied
                  retval = false;
               }
            }
            catch (Exception ex)
            {
               Log.e("ROOT", "Error executing root action", ex);
            }
         }
      }
      catch (IOException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (SecurityException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (Exception ex)
      {
         Log.w("ROOT", "Error executing internal operation", ex);
      }

      return retval;
   }
   protected abstract ArrayList<String> getCommandsToExecute();
}
</code>```

Body:
I'm developing my first Android application, and I'm curious if there are any "standard" ways for executing privileged shell commands. I've only been able to find one way to do it, by executing su, and then appending my commands to stdin of the su process.

DataOutputStream pOut = new DataOutputStream(p.getOutputStream());
DataInputStream pIn = new DataInputStream(p.getInputStream());

String rv = "";

// su must exit before its output can be read
pOut.writeBytes(cmd + "\nexit\n");
pOut.flush();

p.waitFor();

while (pIn.available() > 0)
    rv += pIn.readLine() + "\n";

I've read about wrapping privileged (superuser) calls up in JNI: is this possible? If so, how would one go about accomplishing it? Other than that, are there any other ways of calling privileged instructions from Java?

Body:
As far as I know, you can only run command-line commands using root privileges. You can use this generic class I made that wraps the root access in your code:
http://muzikant-android.blogspot.com/2011/02/how-to-get-root-access-and-execute.html

All you need to do is extend this class and override the getCommandsToExecute method to return the commands you want to execute as root.

public abstract class ExecuteAsRootBase
{
   public static boolean canRunRootCommands()
   {
      boolean retval = false;
      Process suProcess;

      try
      {
         suProcess = Runtime.getRuntime().exec("su");

         DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
         DataInputStream osRes = new DataInputStream(suProcess.getInputStream());

         if (null != os && null != osRes)
         {
            // Getting the id of the current user to check if this is root
            os.writeBytes("id\n");
            os.flush();

            String currUid = osRes.readLine();
            boolean exitSu = false;
            if (null == currUid)
            {
               retval = false;
               exitSu = false;
               Log.d("ROOT", "Can't get root access or denied by user");
            }
            else if (true == currUid.contains("uid=0"))
            {
               retval = true;
               exitSu = true;
               Log.d("ROOT", "Root access granted");
            }
            else
            {
               retval = false;
               exitSu = true;
               Log.d("ROOT", "Root access rejected: " + currUid);
            }

            if (exitSu)
            {
               os.writeBytes("exit\n");
               os.flush();
            }
         }
      }
      catch (Exception e)
      {
         // Can't get root !
         // Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted

         retval = false;
         Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
      }

      return retval;
   }

   public final boolean execute()
   {
      boolean retval = false;

      try
      {
         ArrayList<String> commands = getCommandsToExecute();
         if (null != commands && commands.size() > 0)
         {
            Process suProcess = Runtime.getRuntime().exec("su");

            DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

            // Execute commands that require root access
            for (String currCommand : commands)
            {
               os.writeBytes(currCommand + "\n");
               os.flush();
            }

            os.writeBytes("exit\n");
            os.flush();

            try
            {
               int suProcessRetval = suProcess.waitFor();
               if (255 != suProcessRetval)
               {
                  // Root access granted
                  retval = true;
               }
               else
               {
                  // Root access denied
                  retval = false;
               }
            }
            catch (Exception ex)
            {
               Log.e("ROOT", "Error executing root action", ex);
            }
         }
      }
      catch (IOException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (SecurityException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (Exception ex)
      {
         Log.w("ROOT", "Error executing internal operation", ex);
      }

      return retval;
   }
   protected abstract ArrayList<String> getCommandsToExecute();
}