问:
Xamarin MasterDetailPage button
How would I reference the Master Detail Page (MenuNavigation) by a clickable button inside of Homepage.xaml.cs and Homepage.xaml?

I want the side menu to appear whenever I click the "menu" button. (see below)
I have tried MasterDetail.isPresentedProperty inside the clicked button event handler in Homepage.xaml.cs and cannot figure it out.

Please help!

MenuNavigation.xaml:

```<code><MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              x:Class="App2.MenuNavigation"
              xmlns:local="clr-namespace:App2">

<!--this is the Menu Hamburger sidebar -->
<MasterDetailPage.Master>
    <ContentPage Title="Menu" Padding="20" BackgroundColor="#4B1388" >
        <StackLayout Orientation="Vertical">
            <Label Text="Menu" TextColor="White" FontSize="Large" FontAttributes="Bold"  HorizontalOptions="Center"/>

            <Button Text="Home"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_Home"/> <!-- event handler points to MenuNavigation C# file when button is clicked-->
            <Button Text="About"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_About"/>
            <Button Text="Help"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_Help"/>
        </StackLayout>
    </ContentPage>
</MasterDetailPage.Master>

<!--links to the detail pages from the hamburger sidebar -->
<MasterDetailPage.Detail>

</MasterDetailPage.Detail>
</code>```

MenuNavigation.xaml.cs:

```<code>namespace App2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MenuNavigation : MasterDetailPage
{
    public MenuNavigation()
    {
        InitializeComponent();

        //this is for no nav bar at top
        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false);
        Detail = new NavigationPage(Homepage);
        IsPresented = false; //this will make the side menu disappear when you select a page

    }

    private void Button_Clicked_Home(object sender, EventArgs e)
    {
        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false);
        Detail = new NavigationPage(Homepage);
        IsPresented = false; //this will make the side menu disappear when you select a page
    }

    private void Button_Clicked_About(object sender, EventArgs e)
    {
        Detail = new NavigationPage(new About());
        IsPresented = false;
    }

    private void Button_Clicked_Help(object sender, EventArgs e)
    {
        Detail = new NavigationPage(new Help());
        IsPresented = false;
    }
}
</code>```

}

Homepage.xaml:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Homepage"
         Title="Homepage">

            <Button Text="Menu" Clicked="MasterDetailButton_Pressed"/>
</ContentPage>
</code>```

Hompage.xaml.cs:

```<code>namespace App2
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Homepage : ContentPage
    {

        public Homepage()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos; //allows for binding
    }
    private void MasterDetailButton_Pressed(object sender, EventArgs e)
        {
            MasterDetailPage.IsPresentedProperty.Equals(true);
            //open the master detail page when button is clicked.
            //MasterDetailPage.IsPresentedProperty.Equals(true);
            //MenuNavigation.IsPresentedProperty.Equals(true);
        }
    }
}
</code>```

答:
You should get a reference of your MasterDetailPage and change the IsPresented property of the reference. As the MasterDetailPage has to be the root of the app, something like this should work: (App.Current.MainPage as MasterDetailPage).IsPresented = true;.

Hope it helps! :)

Title: Xamarin MasterDetailPage button

Body:
How would I reference the Master Detail Page (MenuNavigation) by a clickable button inside of Homepage.xaml.cs and Homepage.xaml?

I want the side menu to appear whenever I click the "menu" button. (see below)
I have tried MasterDetail.isPresentedProperty inside the clicked button event handler in Homepage.xaml.cs and cannot figure it out.

Please help!

MenuNavigation.xaml:

<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              x:Class="App2.MenuNavigation"
              xmlns:local="clr-namespace:App2">

<MasterDetailPage.Master>
    <ContentPage Title="Menu" Padding="20" BackgroundColor="#4B1388" >
        <StackLayout Orientation="Vertical">

            <Button Text="Home"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_Home"/>
            <Button Text="About"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_About"/>
            <Button Text="Help"
                    TextColor="White" BackgroundColor="#4B1388"
                    Clicked="Button_Clicked_Help"/>
        </StackLayout>
    </ContentPage>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>

</MasterDetailPage.Detail>

MenuNavigation.xaml.cs:

namespace App2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MenuNavigation : MasterDetailPage
{
    public MenuNavigation()
    {
        InitializeComponent();

        //this is for no nav bar at top
        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false);
        Detail = new NavigationPage(Homepage);
        IsPresented = false; //this will make the side menu disappear when you select a page

    }

    private void Button_Clicked_Home(object sender, EventArgs e)
    {
        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false);
        Detail = new NavigationPage(Homepage);
        IsPresented = false; //this will make the side menu disappear when you select a page
    }

    private void Button_Clicked_About(object sender, EventArgs e)
    {
        Detail = new NavigationPage(new About());
        IsPresented = false;
    }

    private void Button_Clicked_Help(object sender, EventArgs e)
    {
        Detail = new NavigationPage(new Help());
        IsPresented = false;
    }
}

}

Homepage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Homepage"
         Title="Homepage">

            <Button Text="Menu" Clicked="MasterDetailButton_Pressed"/>
</ContentPage>

Hompage.xaml.cs:

namespace App2
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Homepage : ContentPage
    {

        public Homepage()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos; //allows for binding
    }
    private void MasterDetailButton_Pressed(object sender, EventArgs e)
        {
            MasterDetailPage.IsPresentedProperty.Equals(true);
            //open the master detail page when button is clicked.
            //MasterDetailPage.IsPresentedProperty.Equals(true);
            //MenuNavigation.IsPresentedProperty.Equals(true);
        }
    }
}


来源: stackexchange

问:
Getting onFailure Response in Callback Android Studio
I'm trying to get a List from my server as I've done in other classes and it works.
But now I'm getting an error in this Callback. Always goes to onFailure
I test with postman and the server returns the list well.

```<code>         RetrofitOwn retro = new RetrofitOwn();
        Retrofit retrofit = retro.getObjectRetrofit();

        GitHubClient etakemonsusuario = retrofit.create(GitHubClient.class);

        Call<List<Captura>> call = etakemonsusuario.getCapturasUsuario(idloged);

        call.enqueue(new Callback<List<Captura>>() {
            @Override
            public void onResponse(Call<List<Captura>> call, Response<List<Captura>> response) {
                if (response.isSuccessful()){

                    listView = (ListView) findViewById(R.id.listEtakemons);
                    listarecibida = (List<Captura>) response.body();
                    listacapturas = new ArrayList<String>();

                    for (int i = 0; i < listarecibida.size(); i++) {
                        Captura captura = listarecibida.get(i);
                        listacapturas.add(captura.getNombreetakemon());
                    }

                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>
                            (EtakemonsUsuario.this, android.R.layout.simple_list_item_1, listacapturas);
                    listView.setAdapter(arrayAdapter);
                }
                else{
                    Toast.makeText(EtakemonsUsuario.this, "Peticion erronea!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Captura>> call, Throwable t) {
                Toast.makeText(EtakemonsUsuario.this, "No hay conexión!", Toast.LENGTH_SHORT).show();
                 Log.d(tag, "ERROR al conectar!");
            }
        });
</code>```

The API call in the interface is declared as following:

```<code>@GET ("usuario/{id}/get_capturas")
        Call<List<Captura>> getCapturasUsuario(@Path("id") int id);
</code>```

Also the code from the server Controller is:

```<code>        @GET
    @Path("/{id}/get_capturas")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getCapturasUsuario(@PathParam("id") int idUsuario){

        Usuario usuario = new Usuario();
        if (idUsuario != 0){
            Usuario usuario2 = new Usuario();
            List<Captura> capturaList =  usuario2.getCapturasUsuario(idUsuario);
//            for (int i = 0; i < capturaList.size(); i++){
//                System.out.println(capturaList.get(i).getNombreetakemon());
//            }
            GenericEntity<List<Captura>> entity = new GenericEntity<List<Captura>>(capturaList) {};
            return Response.status(201).entity(entity).build();
        }
        else
        {
            String noResult = "No tiene capturas.";
            return Response.status(404).entity(noResult).build();
        }
    }
</code>```

And the function the controller calls is:

```<code>public List<Captura> getCapturasUsuario(int id) {
List<Captura> listaCapturaUsuario = new ArrayList<Captura>();
try {
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM Captura WHERE captura.idusuariosss = " + id);
    while (rs.next()) {
        Captura capturaUsuario = new Captura();
        capturaUsuario.setId(rs.getInt("id"));
        capturaUsuario.setIdusuariosss(rs.getInt("idusuariosss"));
        capturaUsuario.setIdetakemon(rs.getInt("idetakemon"));
        capturaUsuario.setNivel(rs.getInt("nivel"));
        capturaUsuario.setExperiencia(rs.getInt("experiencia"));
        capturaUsuario.setVida(rs.getInt("vida"));
        capturaUsuario.setAtaque(rs.getInt("ataque"));
        capturaUsuario.setDefensa(rs.getInt("defensa"));
        capturaUsuario.setEstado(rs.getInt("estado"));
        capturaUsuario.setFecha(rs.getDate("fecha"));
        capturaUsuario.setNombreetakemon(rs.getString("nombreetakemon"));
        capturaUsuario.setHabilidadetakemon(rs.getString("habilidadetakemon"));
        capturaUsuario.setTipoetakemon(rs.getInt("tipoetakemon"));
        capturaUsuario.setImagen(rs.getString("imagen"));
        listaCapturaUsuario.add(capturaUsuario);
    }
} catch (SQLException e) {
    e.printStackTrace();
    logger.error("getCapturasUsuario: "+e.getMessage());
}

return listaCapturaUsuario;
</code>```

}

Anyone knows where could be the problem?

I thought the response from the server is successful but android studio says it's unsuccessful

Thanks a lot!

I've just found this error

答:
You need to define a Date format to parse the date. In your retrofit instance use a gson builder. Try this:

```<code>Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
}
</code>```

Hope it helps

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a List from my server as I've done in other classes and it works.
But now I'm getting an error in this Callback. Always goes to onFailure
I test with postman and the server returns the list well.

         RetrofitOwn retro = new RetrofitOwn();
        Retrofit retrofit = retro.getObjectRetrofit();

        GitHubClient etakemonsusuario = retrofit.create(GitHubClient.class);

        Call<List<Captura>> call = etakemonsusuario.getCapturasUsuario(idloged);

        call.enqueue(new Callback<List<Captura>>() {
            @Override
            public void onResponse(Call<List<Captura>> call, Response<List<Captura>> response) {
                if (response.isSuccessful()){

                    listView = (ListView) findViewById(R.id.listEtakemons);
                    listarecibida = (List<Captura>) response.body();
                    listacapturas = new ArrayList<String>();

                    for (int i = 0; i < listarecibida.size(); i++) {
                        Captura captura = listarecibida.get(i);
                        listacapturas.add(captura.getNombreetakemon());
                    }

                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>
                            (EtakemonsUsuario.this, android.R.layout.simple_list_item_1, listacapturas);
                    listView.setAdapter(arrayAdapter);
                }
                else{
                    Toast.makeText(EtakemonsUsuario.this, "Peticion erronea!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Captura>> call, Throwable t) {
                Toast.makeText(EtakemonsUsuario.this, "No hay conexión!", Toast.LENGTH_SHORT).show();
                 Log.d(tag, "ERROR al conectar!");
            }
        });

The API call in the interface is declared as following:

@GET ("usuario/{id}/get_capturas")
        Call<List<Captura>> getCapturasUsuario(@Path("id") int id);

Also the code from the server Controller is:

        @GET
    @Path("/{id}/get_capturas")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getCapturasUsuario(@PathParam("id") int idUsuario){

        Usuario usuario = new Usuario();
        if (idUsuario != 0){
            Usuario usuario2 = new Usuario();
            List<Captura> capturaList =  usuario2.getCapturasUsuario(idUsuario);
//            for (int i = 0; i < capturaList.size(); i++){
//                System.out.println(capturaList.get(i).getNombreetakemon());
//            }
            GenericEntity<List<Captura>> entity = new GenericEntity<List<Captura>>(capturaList) {};
            return Response.status(201).entity(entity).build();
        }
        else
        {
            String noResult = "No tiene capturas.";
            return Response.status(404).entity(noResult).build();
        }
    }

And the function the controller calls is:

public List<Captura> getCapturasUsuario(int id) {
List<Captura> listaCapturaUsuario = new ArrayList<Captura>();
try {
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM Captura WHERE captura.idusuariosss = " + id);
    while (rs.next()) {
        Captura capturaUsuario = new Captura();
        capturaUsuario.setId(rs.getInt("id"));
        capturaUsuario.setIdusuariosss(rs.getInt("idusuariosss"));
        capturaUsuario.setIdetakemon(rs.getInt("idetakemon"));
        capturaUsuario.setNivel(rs.getInt("nivel"));
        capturaUsuario.setExperiencia(rs.getInt("experiencia"));
        capturaUsuario.setVida(rs.getInt("vida"));
        capturaUsuario.setAtaque(rs.getInt("ataque"));
        capturaUsuario.setDefensa(rs.getInt("defensa"));
        capturaUsuario.setEstado(rs.getInt("estado"));
        capturaUsuario.setFecha(rs.getDate("fecha"));
        capturaUsuario.setNombreetakemon(rs.getString("nombreetakemon"));
        capturaUsuario.setHabilidadetakemon(rs.getString("habilidadetakemon"));
        capturaUsuario.setTipoetakemon(rs.getInt("tipoetakemon"));
        capturaUsuario.setImagen(rs.getString("imagen"));
        listaCapturaUsuario.add(capturaUsuario);
    }
} catch (SQLException e) {
    e.printStackTrace();
    logger.error("getCapturasUsuario: "+e.getMessage());
}

return listaCapturaUsuario;

}

Anyone knows where could be the problem?

I thought the response from the server is successful but android studio says it's unsuccessful

Thanks a lot!

I've just found this error

Body:
You need to define a Date format to parse the date. In your retrofit instance use a gson builder. Try this:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
}

Hope it helps


答:
AFAICT, you need to change:

```<code>SHPR_TOT_NRG_FCAST_QRY//GAS_DAY
</code>```

to:

```<code>../../SHPR_TOT_NRG_FCAST_QRY/GAS_DAY
</code>```

Not sure what other changes you want to make. If you need to reformat the dates, then you'll want have a named template you can call for that.

Title: XML to CSV using XSLT help required

Body:
I am trying to convert xml to csv. Please help me to get correct XSL file

Output I am looking as (csv)==>

GAS_DAY     CRT_DT      CRT_TM     TOT_FCAST    CNG_SNCE_LST_NM  NA_RNM_UPDTD
10/02/2017  09/02/2017  11:01:21    13847690    99                 Y
10/02/2017  09/02/2017  13:01:59    13780670    -0.5               Y
10/02/2017  09/02/2017  16:01:03    13889719    0.8                Y
10/02/2017  10/02/2017  00:01:07    13862376    -0.2               Y
10/02/2017  10/02/2017  10:01:01    13679133    -1.3               Y
11/02/2017  10/02/2017  11:01:21    338473240   99                 Y
11/02/2017  10/02/2017  13:01:59    13780670    10.5               Y
11/02/2017  10/02/2017  16:01:03    23889719    3.8                Y
11/02/2017  11/02/2017  00:01:07    13432376    10.2               Y
11/02/2017  11/02/2017  10:01:01    13432133    -1.3               Y

Sample XML ==>

<root>
    <SHPR_TOT_NRG_FCAST_OUT>
        <METADATA>
            <TMSTMP>2017-02-10T10:15:44</TMSTMP>
        </METADATA>
        <SHPR_TOT_NRG_FCAST_QRY>
            <GAS_DAY>2017-02-10</GAS_DAY>
        </SHPR_TOT_NRG_FCAST_QRY>
        <DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>11:01:21</CRT_TM>
                <TOT_FCAST>13847690</TOT_FCAST>
                <CNG_SNCE_LST_NM>99.0</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>13:01:59</CRT_TM>
                <TOT_FCAST>13780670</TOT_FCAST>
                <CNG_SNCE_LST_NM>-0.5</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>16:01:03</CRT_TM>
                <TOT_FCAST>13889719</TOT_FCAST>
                <CNG_SNCE_LST_NM>0.8</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>00:01:07</CRT_TM>
                <TOT_FCAST>13862376</TOT_FCAST>
                <CNG_SNCE_LST_NM>-0.2</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>10:01:01</CRT_TM>
                <TOT_FCAST>13679133</TOT_FCAST>
                <CNG_SNCE_LST_NM>-1.3</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
        </DTL>
    </SHPR_TOT_NRG_FCAST_OUT>
    <SHPR_TOT_NRG_FCAST_OUT>
        <METADATA>
            <TMSTMP>2017-02-10T10:15:44</TMSTMP>
        </METADATA>
        <SHPR_TOT_NRG_FCAST_QRY>
            <GAS_DAY>2017-02-11</GAS_DAY>
        </SHPR_TOT_NRG_FCAST_QRY>
        <DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>11:01:21</CRT_TM>
                <TOT_FCAST>338473240</TOT_FCAST>
                <CNG_SNCE_LST_NM>99.0</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>13:01:59</CRT_TM>
                <TOT_FCAST>13780670</TOT_FCAST>
                <CNG_SNCE_LST_NM>10.5</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>16:01:03</CRT_TM>
                <TOT_FCAST>23889719</TOT_FCAST>
                <CNG_SNCE_LST_NM>3.8</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-11</CRT_DT>
                <CRT_TM>00:01:07</CRT_TM>
                <TOT_FCAST>13432376</TOT_FCAST>
                <CNG_SNCE_LST_NM>10.2</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-11</CRT_DT>
                <CRT_TM>10:01:01</CRT_TM>
                <TOT_FCAST>13432133</TOT_FCAST>
                <CNG_SNCE_LST_NM>-1.3</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
        </DTL>
    </SHPR_TOT_NRG_FCAST_OUT>
</root>

XSL I could progress is ==

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:fo="http://www.w3.org/1999/XSL/Format" >
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">GAS_DAY,CRT_DT,CRT_TM,TOT_FCAST,CNG_SNCE_LST_NM,NA_RNM_UPDTD
<xsl:for-each select="//DTL//NRG_FCAST_DTL">
     <xsl:value-of select="concat(SHPR_TOT_NRG_FCAST_QRY//GAS_DAY,',',CRT_DT, ',' ,CRT_TM,',' ,TOT_FCAST,',' ,CNG_SNCE_LST_NM,',' ,NA_RNM_UPDTD,'
     ')"/>
        <xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Body:
AFAICT, you need to change:

SHPR_TOT_NRG_FCAST_QRY//GAS_DAY

to:

../../SHPR_TOT_NRG_FCAST_QRY/GAS_DAY

Not sure what other changes you want to make. If you need to reformat the dates, then you'll want have a named template you can call for that.


问:
Unable to change RadioButtonFor selection via JQuery
I am working on code to determine whether or not to show a contact information section.  To do this I am implementing the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor.

When the page is loaded I need to change from the default, not to show it, to show it if the HasConflicts model value is true.  I am attempting to use JQuery to do this at the page load, but the chosen option will not change.

Here is the Razor section

```<code> <div class="left-col" id="noConflict">
    @Html.RadioButtonFor(m => m.HasConflicts, "false") <strong><em>No Conflict of Interest exists at this time</em></strong>
 </div>
 <div class="right-col" id="yesConflict">
    @Html.RadioButtonFor(m => m.HasConflicts, "true") <strong><em>A Conflict of Interest exists at this time</em></strong>
 </div>
</code>```

And here is JQuery that I tried to put into the page load, following another answer from the site, and removing the conditional just to see if I even can get the "yesConflict" button to be chosen.

```<code>$(function () {
    $('#yesConflict').prop('checked', true).change();
};
</code>```

The strangest thing is that the change event DOES take place, so this should be the correct ID, but the button selected on the screen does not change.

I appreciate any input, thanks!

EDIT:  I had a request for the HTML output of those RadioButtonFor lines - here it is.

```<code>    <div class="left-col" id="noConflict">
        <input checked="checked" data-val="true" data-val-required="The HasConflicts field is required." id="HasConflicts" name="HasConflicts" type="radio" value="false" /> <strong><em>No Conflict of Interest exists at this time</em></strong>
    </div>
    <div class="right-col" id="yesConflict">
        <input id="HasConflicts" name="HasConflicts" type="radio" value="true" /> <strong><em>A Conflict of Interest exists at this time</em></strong>
    </div>
</code>```

When inspected via IE Developer Tools while running here are the two inputs:

```<code><input name="HasConflicts" id="HasConflicts" type="radio" checked="checked" value="false" data-val-required="The HasConflicts field is required." data-val="true" data-dpmaxz-eid="6">
<input name="HasConflicts" id="HasConflicts" type="radio" value="true" data-dpmaxz-eid="7">
</code>```

Please let me know if I can be of any further assistance in getting an answer.  Everything I've researched says that the JQuery line I put in there should do what I want from JQuery 1.6 and up, using 1.10 - but it's simply not working.

答:
First of all, ID are unique

For id="HasConflicts" you should not use it more than once, try to change it to class="HasConflicts" etc, because when you call #HasConflicts it will only target the first one.

Solution to your jQuery code:

You are targeting the parent element, use $('#yesConflict > input') to target the input radio (direct child of #yesConflict), check the following:

Note:

$('#yesConflict input') use space it will find all input inside #yesConflict

$('#yesConflict > input') use > it will only target the direct child of #yesConflict

$(function() {
  $('#yesConflict > input').prop('checked', true).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-col" id="noConflict">
  <input checked="checked" data-val="true" data-val-required="The HasConflicts field is required." id="HasConflicts" name="HasConflicts" type="radio" value="false" /> <strong><em>No Conflict of Interest exists at this time</em></strong>
</div>
<div class="right-col" id="yesConflict">
  <input id="HasConflicts" name="HasConflicts" type="radio" value="true" /> <strong><em>A Conflict of Interest exists at this time</em></strong>
</div></code>```

Body:
I am working on code to determine whether or not to show a contact information section.  To do this I am implementing the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor.

When the page is loaded I need to change from the default, not to show it, to show it if the HasConflicts model value is true.  I am attempting to use JQuery to do this at the page load, but the chosen option will not change.

Here is the Razor section

    @Html.RadioButtonFor(m => m.HasConflicts, "false") No Conflict of Interest exists at this time

    @Html.RadioButtonFor(m => m.HasConflicts, "true") A Conflict of Interest exists at this time

And here is JQuery that I tried to put into the page load, following another answer from the site, and removing the conditional just to see if I even can get the "yesConflict" button to be chosen.

$(function () {
    $('#yesConflict').prop('checked', true).change();
};

The strangest thing is that the change event DOES take place, so this should be the correct ID, but the button selected on the screen does not change.

I appreciate any input, thanks!

EDIT:  I had a request for the HTML output of those RadioButtonFor lines - here it is.

        <input checked="checked" data-val="true" data-val-required="The HasConflicts field is required." id="HasConflicts" name="HasConflicts" type="radio" value="false" /> No Conflict of Interest exists at this time

        <input id="HasConflicts" name="HasConflicts" type="radio" value="true" /> A Conflict of Interest exists at this time

When inspected via IE Developer Tools while running here are the two inputs:

<input name="HasConflicts" id="HasConflicts" type="radio" checked="checked" value="false" data-val-required="The HasConflicts field is required." data-val="true" data-dpmaxz-eid="6">
<input name="HasConflicts" id="HasConflicts" type="radio" value="true" data-dpmaxz-eid="7">

Please let me know if I can be of any further assistance in getting an answer.  Everything I've researched says that the JQuery line I put in there should do what I want from JQuery 1.6 and up, using 1.10 - but it's simply not working.

Body:
First of all, ID are unique

For id="HasConflicts" you should not use it more than once, try to change it to class="HasConflicts" etc, because when you call #HasConflicts it will only target the first one.

Solution to your jQuery code:

You are targeting the parent element, use $('#yesConflict > input') to target the input radio (direct child of #yesConflict), check the following:

Note:

$('#yesConflict input') use space it will find all input inside #yesConflict

$('#yesConflict > input') use > it will only target the direct child of #yesConflict

$(function() {
  $('#yesConflict > input').prop('checked', true).change();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-col" id="noConflict">
  <input checked="checked" data-val="true" data-val-required="The HasConflicts field is required." id="HasConflicts" name="HasConflicts" type="radio" value="false" /> <strong><em>No Conflict of Interest exists at this time</em></strong>
</div>
<div class="right-col" id="yesConflict">
  <input id="HasConflicts" name="HasConflicts" type="radio" value="true" /> <strong><em>A Conflict of Interest exists at this time</em></strong>
</div>


问:
Dependency Properties on Controls
In WPF some properties of controls are dependency properties, others are normal properties.

Eg TextBox.SelectedText is a normal property and not a dependency property. I use MVVM and it happens often to me that I want to bind to some property, but I cant, because it is a normal property.

Can someone explain to me, what logic stands behind the decision whether a property is normal or a dependency property.

Also, can I work around this and somehow bind to the normal properties as if they were dependency properties?

答:
Go through these links

When to use a WPF Dependency Property versus INotifyPropertyChanged

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/65bf126f-e706-4d3e-8cc3-e0130a0ee6de

http://joshsmithonwpf.wordpress.com/2007/06/22/overview-of-dependency-properties-in-wpf/

WPF: What distinguishes a Dependency Property from a regular CLR Property?

How to set bindings on CLR Properties using DataResource

You will get better idea about what you are looking to find out

ContentLicense: CC BY-SA 2.5

Title: Dependency Properties on Controls


问:
NodeJs - How to render EJS in a rendered EJS?
that's my idea: I want to load a rendered ejs file as the body of my main template ejs file. Is it possible?

My app.js:

```<code>router.get('/', function(req, res) {
  res.render('layout', {title: "Example title", body: _____________});
});
</code>```

I tried the following but it did not work:

```<code>body: res.render('page1_body_content')
</code>```

That would be my main-template-file (layout.ejs)

<!doctype html>

  <title>
   <% (title) ? title : '' %>
  </title>
  <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/style.css" />

  <%= body %>

```
</div>
</div>
</p>

<p>My 2nd file (page1_body_content.ejs) looks like this:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>hallo</b></code>```

The result should look like this:

<!doctype html>

  <title>
   Expample title
  </title>
  <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/style.css" />

  Hallo

```

答:
Try this code:-

```<code>var ejs = require('ejs');
var compiled = ejs.compile(fs.readFileSync(__dirname + '/page1_body_content.ejs', 'utf8'));
var html = compiled();

res.render('layout', {title: "Example title", body: html });
</code>```

Update the body tag code to:-

```<code><body>
    <%- body %>
</body>
</code>```

Body:
that's my idea: I want to load a rendered ejs file as the body of my main template ejs file. Is it possible?

My app.js:

router.get('/', function(req, res) {
  res.render('layout', {title: "Example title", body: _____________});
});

I tried the following but it did not work:

body: res.render('page1_body_content')

That would be my main-template-file (layout.ejs)

<!doctype html>

  <title>
   <% (title) ? title : '' %>
  </title>
  <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/style.css" />

  <%= body %>

My 2nd file (page1_body_content.ejs) looks like this:

hallo

The result should look like this:

<!doctype html>

  <title>
   Expample title
  </title>
  <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/style.css" />

  Hallo

Body:
Try this code:-

var ejs = require('ejs');
var compiled = ejs.compile(fs.readFileSync(__dirname + '/page1_body_content.ejs', 'utf8'));
var html = compiled();

res.render('layout', {title: "Example title", body: html });

Update the body tag code to:-

<body>
    <%- body %>
</body>


问:
Show the value of a geom_point using geom_text
Using this nice code from here:

```<code>countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

library(ggplot2)
library(maps)
base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend
</code>```

I would like to show next to the geom_point the value. So I tried the geom_text using the following:

```<code>p+geom_text(aes(label=countries$Value,x=Longitude, y=Latitude),hjust=0, vjust=0)
</code>```

but I receive this error:

```<code>Error in eval(expr, envir, enclos) : object 'Longitude' not found
</code>```

答:
You're missing the data parameter in your geom_text:

```<code>p + geom_text(data = countries, aes(label=Value, x=Longitude, y=Latitude), hjust=0, vjust=0)
</code>```

Body:
Using this nice code from here:

countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

library(ggplot2)
library(maps)
base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend

I would like to show next to the geom_point the value. So I tried the geom_text using the following:

p+geom_text(aes(label=countries$Value,x=Longitude, y=Latitude),hjust=0, vjust=0)

but I receive this error:

Error in eval(expr, envir, enclos) : object 'Longitude' not found

Body:
You're missing the data parameter in your geom_text:

p + geom_text(data = countries, aes(label=Value, x=Longitude, y=Latitude), hjust=0, vjust=0)


问:
AWS Device Farm- Appium Python - Order of tests
I'm using Appium-Python with AWS Device farm. And I noticed that AWS run my tests in a random order.
Since my tests are part dependent I need to find a way to tell AWS to run my tests in a specific order.
Any ideas about how can I accomplish that?

Thanks

答:
I work for the AWS Device Farm team.
This seems like an old thread but I will answer so that it is helpful to everyone in future.

Device Farm parses the test in a random order. In case of Appium Python it will be the order what is received from pytest --collect-only.
This order may change across executions.

The only way to guarantee an order right now is to wrap all the test calls in a new test which will be the only test called. Although not the prettiest solution this is the only way to achieve this today.

We are working on bringing more parity between your local environment and Device Farm in the coming weeks.

ContentLicense: CC BY-SA 4.0


问:
Running a Chef guard block as a different user
I want to have a Chef guard block, and I want to run that block as a specific user.

I know how to run a shell command in a guard as a user, since that's covered in the documentation:

```<code>not_if 'grep adam /etc/passwd', :user => 'adam'
</code>```

I want to use a guard block instead so I can do some more complex operations, and I want to run the code as the postgres user. For example:

```<code>only_if do
  c = PGconn.connect(user: 'postgres', dbname: 'postgres')
  # do some other stuff with the postgres connection
end
</code>```

How do I assign the user or other attributes here?

答: Code blocks aren't run as a user per se, they are just run by Ruby as whatever user Ruby happens to be running as. In this case case you probably want to shell out to psql and change the user as per normal for a subprocess.

Body:
I want to have a Chef guard block, and I want to run that block as a specific user.

I know how to run a shell command in a guard as a user, since that's covered in the documentation:

not_if 'grep adam /etc/passwd', :user => 'adam'

I want to use a guard block instead so I can do some more complex operations, and I want to run the code as the postgres user. For example:

only_if do
  c = PGconn.connect(user: 'postgres', dbname: 'postgres')
  # do some other stuff with the postgres connection
end

How do I assign the user or other attributes here?


问:
Object is not being created with info from JSONP API
I'm relatively new to jQuery and Javascript, I'm trying to create an object with information received from an API. The object is supposed to hold an object of basic info, for each of the users from the array users. To do so I make an API call for each user and then pass the json to a constructor that is supposed to create its properties. However, when I run the code the object only has a name property. And only for the first user, not all.

Could someone tell me what am I doing wrong?

Here's the code:

$(document).ready(function () {
    var url = "https://wind-bow.gomix.me/twitch-api/streams/";

    var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

    var streamersObj = {};

    for(var i = 0; i < users.length; i++) {
        console.log(users[i]);
        connectToApi(users[i]);
    }

    function StreamerObjCreate (jsonObj, name) {
       streamersObj[name] = name;
       streamersObj[name].onStream = jsonObj.stream;
       streamersObj[name].channel = jsonObj._links.channel;
       streamersObj[name].stream = jsonObj._links.self;
       console.log(streamersObj);
    }
  function connectToApi (target) {
      url = url + target + "?" + "callback=?";
    $.getJSON(url, function (json) {
        StreamerObjCreate(json, target);
    });
  }
    console.log(streamersObj);
});```

I just started to learn, so if you have any feedback related or unrelated it will be much appreciated.

答:
It seems you're overriding the url variable each time in your connectToApi function. Try this one instead</p>

```<code>function connectToApi (target) {
    var targetUrl = url + target + "?" + "callback=?";
    $.getJSON(targetUrl, function (json) {
        StreamerObjCreate(json, target);
    });
}
</code>```

Body:
I'm relatively new to jQuery and Javascript, I'm trying to create an object with information received from an API. The object is supposed to hold an object of basic info, for each of the users from the array users. To do so I make an API call for each user and then pass the json to a constructor that is supposed to create its properties. However, when I run the code the object only has a name property. And only for the first user, not all.

Could someone tell me what am I doing wrong?

Here's the code:

$(document).ready(function () {
    var url = "https://wind-bow.gomix.me/twitch-api/streams/";

    var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

    var streamersObj = {};

    for(var i = 0; i < users.length; i++) {
        console.log(users[i]);
        connectToApi(users[i]);
    }

    function StreamerObjCreate (jsonObj, name) {
       streamersObj[name] = name;
       streamersObj[name].onStream = jsonObj.stream;
       streamersObj[name].channel = jsonObj._links.channel;
       streamersObj[name].stream = jsonObj._links.self;
       console.log(streamersObj);
    }
  function connectToApi (target) {
      url = url + target + "?" + "callback=?";
    $.getJSON(url, function (json) {
        StreamerObjCreate(json, target);
    });
  }
    console.log(streamersObj);
});

I just started to learn, so if you have any feedback related or unrelated it will be much appreciated.

Body:
It seems you're overriding the url variable each time in your connectToApi function. Try this one instead

function connectToApi (target) {
    var targetUrl = url + target + "?" + "callback=?";
    $.getJSON(targetUrl, function (json) {
        StreamerObjCreate(json, target);
    });
}


问:
Can I make this script even faster?
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

```<code>function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}
</code>```

Here is an example of a call of the function:

```<code>delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5
</code>```

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

答:
Many of the PowerShell cmdlets are slower than their .NET equivalents. You could, for example, make a call to [System.IO.File]::Delete($_.FullName) instead, and see if there is a performance difference. Same goes for Get-ChildItem => [System.IO.Directory]::GetFiles(...).

To do that, I would write a small script that creates two temp folders with say, 100,000 empty test files in each. Then call each version of the function wrapped in [System.Diagnostics.StopWatch].

Some sample code:

```<code>$stopwatch = New-Object 'System.Diagnostics.StopWatch'
$stopwatch.Start()

Remove-OldItems1 ...

$stopwatch.Stop()
Write-Host $stopwatch.ElapsedMilliseconds

$stopwatch.Reset()
$stopwatch.Start()

Remove-OldItems2 ...

$stopwatch.Stop()
Write-Host $stopwatch.ElapsedMilliseconds
</code>```

Further brownie points for PowerShell: Run Get-Verb in a Powershell window and you can see the list of approved verbs. Functions in PowerShell are suggested to be Verb-Noun named, so something like Remove-OldItems would fit the bill.

Title: Can I make this script even faster?

Body:
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}

Here is an example of a call of the function:

delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

Body:
Many of the PowerShell cmdlets are slower than their .NET equivalents. You could, for example, make a call to [System.IO.File]::Delete($_.FullName) instead, and see if there is a performance difference. Same goes for Get-ChildItem => [System.IO.Directory]::GetFiles(...).

To do that, I would write a small script that creates two temp folders with say, 100,000 empty test files in each. Then call each version of the function wrapped in [System.Diagnostics.StopWatch].

Some sample code:

$stopwatch = New-Object 'System.Diagnostics.StopWatch'
$stopwatch.Start()

Remove-OldItems1 ...

$stopwatch.Stop()
Write-Host $stopwatch.ElapsedMilliseconds

$stopwatch.Reset()
$stopwatch.Start()

Remove-OldItems2 ...

$stopwatch.Stop()
Write-Host $stopwatch.ElapsedMilliseconds

Further brownie points for PowerShell: Run Get-Verb in a Powershell window and you can see the list of approved verbs. Functions in PowerShell are suggested to be Verb-Noun named, so something like Remove-OldItems would fit the bill.


问:
FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service
I am beginner in android. i create a new service and run it in android mobile API Level-23. when i press button to startservice it show me ERROR. now i Create new project but problem is same there.

```<code>**FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service com.example.uzair.servicesapp.myIntentService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference**
</code>```

MainActivity.java

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static int i =0;
    private Intent  ii;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ii = new Intent(this,myIntentService.class);
       Toast.makeText(this, "this is custom toast", Toast.LENGTH_SHORT).show();
 }

    public void clickme2(View view)
    {
        startService(ii);
        Toast.makeText(this, " Service start toast", Toast.LENGTH_SHORT).show();
    }

    public void clickme(View view) {

 stopService(ii);
Toast.makeText(this, "Service stop toast", Toast.LENGTH_SHORT).show();
        i++;
    }
}
</code>```

MyIntentService.java

```<code>import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
public class myIntentService extends IntentService {

    public myIntentService()
    {
        super("myIntentService");
        Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this, "OnhandleIntent toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Destroy toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uzair.servicesapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".myIntentService"/>

    </application>

</manifest>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.uzair.servicesapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickme"
        android:text="@string/click_me"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="118dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="clickme2" />
</RelativeLayout>
</code>```

答:
Delete this line:

```<code>Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);
</code>```

First, you are not calling show() on any of your Toast objects, so none will display. Use Log.d() to log messages to LogCat instead.

Second, do not use this, or call inherited methods on a Service, from the constructor.

If that does not help, edit the question and post the entire Java stack trace, not just the error message.

Body:
I am beginner in android. i create a new service and run it in android mobile API Level-23. when i press button to startservice it show me ERROR. now i Create new project but problem is same there.

**FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service com.example.uzair.servicesapp.myIntentService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference**

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static int i =0;
    private Intent  ii;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ii = new Intent(this,myIntentService.class);
       Toast.makeText(this, "this is custom toast", Toast.LENGTH_SHORT).show();
 }

    public void clickme2(View view)
    {
        startService(ii);
        Toast.makeText(this, " Service start toast", Toast.LENGTH_SHORT).show();
    }

    public void clickme(View view) {

 stopService(ii);
Toast.makeText(this, "Service stop toast", Toast.LENGTH_SHORT).show();
        i++;
    }
}

MyIntentService.java

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
public class myIntentService extends IntentService {

    public myIntentService()
    {
        super("myIntentService");
        Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this, "OnhandleIntent toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Destroy toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uzair.servicesapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".myIntentService"/>

    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.uzair.servicesapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickme"
        android:text="@string/click_me"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="118dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="clickme2" />
</RelativeLayout>

Body:
Delete this line:

Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);

First, you are not calling show() on any of your Toast objects, so none will display. Use Log.d() to log messages to LogCat instead.

Second, do not use this, or call inherited methods on a Service, from the constructor.

If that does not help, edit the question and post the entire Java stack trace, not just the error message.


问:
Wrapper datatype to store YEAR alone
I just want to store year value( for example 2011 or 2020) in a wrapper datatype. Which is the best suggested datatype? Is Integer wrapper type enough? </p>

答:
if you want to use Integer class it can save same as int
you can see the max value by using Integer.MAX_VALUE</p>

Title: Wrapper datatype to store YEAR alone


问:
Spring 4 Java Config for MultipartResolver for Servlet 3.0
I'm taking an all-Java approach to Spring MVC configuration and cannot figure out how to associate a MultipartConfigElement with my DispatcherServlet programmatically.

Spring documentation states:

In order to use Servlet 3.0 based multipart parsing, you need to mark
  the DispatcherServlet with a "multipart-config" section in web.xml, or
  with a javax.servlet.MultipartConfigElement in programmatic Servlet
  registration...

http://docs.spring.io/spring/docs/4.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-multipart

Here is my WebApplicationInitializer code:

```<code>public class DispatcherServletInitializer implements WebApplicationInitializer {

    private static final Logger logger = LoggerFactory.getLogger(DispatcherServletInitializer.class);

    @Override
    public void onStartup(ServletContext container) {

        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(WebConfig.class);

        //HOW CAN I ASSOCIATE THIS CONFIG WITH MY DISPATCHER SERVLET?
        MultipartConfigElement config = new MultipartConfigElement("C:\\Temp", 20848820, 418018841, 1048576);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }

}
</code>```

How do I associate the MultipartConfigElement with my DispatcherServlet?  I don't see any method like setMultipartConfiguration or any constructor that accepts it.

Also note that my WebConfig declares a MultipartResolver:

```<code>@Bean
public StandardServletMultipartResolver multipartResolver(){
    return new StandardServletMultipartResolver();
}
</code>```

But the Spring documentation states:

```<code>Configuration settings such as maximum sizes or storage locations need to be applied at that Servlet registration level as Servlet 3.0 does not allow for those settings to be done from the MultipartResolver.
</code>```

Any guidance would be greatly appreciated.

答:
Here is the solution compatible with AbstractAnnotationConfigDispatcherServletInitializer way of configuring the servlet. This is a bit less invasive than WebApplicationInitializer.

It uses an override of AbstractAnnotationConfigDispatcherServletInitializer.customizeRegistration.

```<code>public class MySpringWebSetup extends AbstractAnnotationConfigDispatcherServletInitializer
{
  // Your usual obligatory configuration overrides:
  @Override protected Class<?>[] getRootConfigClasses() { ... }
  @Override protected Class<?>[] getServletConfigClasses() { ... }
  @Override protected String[] getServletMappings() { ... }

  // Optional configuration:
  @Override
  protected void customizeRegistration(Dynamic registration) {
    registration.setMultipartConfig(
      // Maybe use more sophisticated configuration than this:
      new MultipartConfigElement("")
    );
  }
}
</code>```

I found it catching the stack trace of getServletMappings and thus getting into the code of org\springframework\web\servlet\support\AbstractDispatcherServletInitializer.java:

```<code>protected void registerDispatcherServlet(ServletContext servletContext) {

    [more registration stuff was here]

    registration.setLoadOnStartup(1);
    registration.addMapping(getServletMappings());
    registration.setAsyncSupported(isAsyncSupported());

    Filter[] filters = getServletFilters();
    if (!ObjectUtils.isEmpty(filters)) {
        for (Filter filter : filters) {
            registerServletFilter(servletContext, filter);
        }
    }

    customizeRegistration(registration);
}
</code>```

Body:
I'm taking an all-Java approach to Spring MVC configuration and cannot figure out how to associate a MultipartConfigElement with my DispatcherServlet programmatically.

Spring documentation states:

In order to use Servlet 3.0 based multipart parsing, you need to mark
  the DispatcherServlet with a "multipart-config" section in web.xml, or
  with a javax.servlet.MultipartConfigElement in programmatic Servlet
  registration...

http://docs.spring.io/spring/docs/4.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-multipart

Here is my WebApplicationInitializer code:

public class DispatcherServletInitializer implements WebApplicationInitializer {

    private static final Logger logger = LoggerFactory.getLogger(DispatcherServletInitializer.class);

    @Override
    public void onStartup(ServletContext container) {

        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(WebConfig.class);

        //HOW CAN I ASSOCIATE THIS CONFIG WITH MY DISPATCHER SERVLET?
        MultipartConfigElement config = new MultipartConfigElement("C:\\Temp", 20848820, 418018841, 1048576);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }

}

How do I associate the MultipartConfigElement with my DispatcherServlet?  I don't see any method like setMultipartConfiguration or any constructor that accepts it.

Also note that my WebConfig declares a MultipartResolver:

@Bean
public StandardServletMultipartResolver multipartResolver(){
    return new StandardServletMultipartResolver();
}

But the Spring documentation states:

Configuration settings such as maximum sizes or storage locations need to be applied at that Servlet registration level as Servlet 3.0 does not allow for those settings to be done from the MultipartResolver.

Any guidance would be greatly appreciated.

Body:
Here is the solution compatible with AbstractAnnotationConfigDispatcherServletInitializer way of configuring the servlet. This is a bit less invasive than WebApplicationInitializer.

It uses an override of AbstractAnnotationConfigDispatcherServletInitializer.customizeRegistration.

public class MySpringWebSetup extends AbstractAnnotationConfigDispatcherServletInitializer
{
  // Your usual obligatory configuration overrides:
  @Override protected Class<?>[] getRootConfigClasses() { ... }
  @Override protected Class<?>[] getServletConfigClasses() { ... }
  @Override protected String[] getServletMappings() { ... }

  // Optional configuration:
  @Override
  protected void customizeRegistration(Dynamic registration) {
    registration.setMultipartConfig(
      // Maybe use more sophisticated configuration than this:
      new MultipartConfigElement("")
    );
  }
}

I found it catching the stack trace of getServletMappings and thus getting into the code of org\springframework\web\servlet\support\AbstractDispatcherServletInitializer.java:

protected void registerDispatcherServlet(ServletContext servletContext) {

    [more registration stuff was here]

    registration.setLoadOnStartup(1);
    registration.addMapping(getServletMappings());
    registration.setAsyncSupported(isAsyncSupported());

    Filter[] filters = getServletFilters();
    if (!ObjectUtils.isEmpty(filters)) {
        for (Filter filter : filters) {
            registerServletFilter(servletContext, filter);
        }
    }

    customizeRegistration(registration);
}


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
From a development viewpoint 'done' is described quite well by my friend and mentor Simon Baker, here

Alistair Cockburn, Jeff Patton and Mike Cohn also have the following collected views

Shippable quality, which has to be exercised in a go-live, forces teams to really focus on ensuring that incremental work is more carefully thought through.

'Done' is something which all the above quoted would be the first to agree is always different per team and project; however to satisfy knowing that a given piece of work is done, the team must conduct an exercise at the start to flesh out the measure of done-ness and list those criteria.

In so doing, everyone has agreed by consensus what an acceptable completion point is - whether that includes noting the Task in Excel, or writing documentation (or not) becomes an implementation detail for that team/project. The overriding thing is that everyone's understanding of Done is uniform.

Equally, assuming you reach that definition by consensus, it can also be changed as required by consensus.

OwnerDisplayName: Micah

OwnerDisplayName: j pimmel


问:
Is declaring an header file essential?
Is declaring an header file essential? This code:

```<code>main()
{
  int i=100;

  printf("%d\n",i);
}
</code>```

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

答:
How is this possible? In short: three pieces of luck.

This is possible because some compilers will make assumptions about undeclared functions. Specifically, parameters are assumed to be int, and the return type also int.  Since an int is often the same size as a char* (depending on the architecture), you can get away with passing ints and strings, as the correct size parameter will get pushed onto the stack.

In your example, since printf was not declared, it was assumed to take two int parameters, and you passed a char* and an int which is "compatible" in terms of the invocation.  So the compiler shrugged and generated some code that should have been about right.  (It really should have warned you about an undeclared function.)

So the first piece of luck was that the compiler's assumption was compatible with the real function.

Then at the linker stage, because printf is part of the C Standard Library, the compiler/linker will automatically include this in the link stage.  Since the printf symbol was indeed in the C stdlib, the linker resolved the symbol and all was well.  The linking was the second piece of luck, as a function anywhere other than the standard library will need its library linked in also.

Finally, at runtime we see your third piece of luck.  The compiler made a blind assumption, the symbol happened to be linked in by default.  But - at runtime you could have easily passed data in such a way as to crash your app.  Fortunately the parameters matched up, and the right thing ended up occurring.  This will certainly not always be the case, and I daresay the above would have probably failed on a 64-bit system.

So - to answer the original question, it really is essential to include header files, because if it works, it is only through blind luck!

Title: Is declaring an header file essential?

Body:
Is declaring an header file essential? This code:

main()
{
  int i=100;

  printf("%d\n",i);
}

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?


问:
Repeated timing of function
I have a very simple function f :: Int -> Int and I want to write a program that calls f for each n = 1,2,...,max. After each call of f the (cumulative) time that was used up to that point should be displayed (along with n and f n). How can this be implemented?

I'm still really new to input/output in Haskell, so this is what I've tried so far (using some toy example function f)

```<code>f :: Int -> Int
f n = sum [1..n]

evalAndTimeFirstN :: Int -> Int -> Int -> IO()
evalAndTimeFirstN n max time =
  if n == max
   then return () -- in the following we have to calculate the time difference from start to now
   else let str =  ("(" ++ (show n) ++  ", " ++ (show $ f n) ++ ", "++ (show time)++ ")\n")
         in putStrLn str >> evalAndTimeFirstN (n+1) max time -- here we have to calculate the time difference

main :: IO()
main = evalAndTimeFirstN 1 5 0
</code>```

I don't quite see how I have to introduce the timing here. (The Int for time probably has to be replaced with something else.)

答:
You probably want something like this. Adapt the following basic example as needed for your recursive function.

```<code>import Data.Time.Clock
import Control.Exception (evaluate)

main :: IO ()
main = do
  putStrLn "Enter a number"
  n <- readLn
  start <- getCurrentTime
  let fact = product [1..n] :: Integer
  evaluate fact  -- this is needed, otherwise laziness would postpone the evaluation
  end <- getCurrentTime
  putStrLn $ "Time elapsed: " ++ show (diffUTCTime end start)
  -- putStrLn $ "The result was " ++ show fact
</code>```

Uncomment the last line to print the result (it gets very large very quickly).

Title: Repeated timing of function

Body:
I have a very simple function f :: Int -> Int and I want to write a program that calls f for each n = 1,2,...,max. After each call of f the (cumulative) time that was used up to that point should be displayed (along with n and f n). How can this be implemented?

I'm still really new to input/output in Haskell, so this is what I've tried so far (using some toy example function f)

f :: Int -> Int
f n = sum [1..n]

evalAndTimeFirstN :: Int -> Int -> Int -> IO()
evalAndTimeFirstN n max time =
  if n == max
   then return () -- in the following we have to calculate the time difference from start to now
   else let str =  ("(" ++ (show n) ++  ", " ++ (show $ f n) ++ ", "++ (show time)++ ")\n")
         in putStrLn str >> evalAndTimeFirstN (n+1) max time -- here we have to calculate the time difference

main :: IO()
main = evalAndTimeFirstN 1 5 0

I don't quite see how I have to introduce the timing here. (The Int for time probably has to be replaced with something else.)

Body:
You probably want something like this. Adapt the following basic example as needed for your recursive function.

import Data.Time.Clock
import Control.Exception (evaluate)

main :: IO ()
main = do
  putStrLn "Enter a number"
  n <- readLn
  start <- getCurrentTime
  let fact = product [1..n] :: Integer
  evaluate fact  -- this is needed, otherwise laziness would postpone the evaluation
  end <- getCurrentTime
  putStrLn $ "Time elapsed: " ++ show (diffUTCTime end start)
  -- putStrLn $ "The result was " ++ show fact

Uncomment the last line to print the result (it gets very large very quickly).


问:
get average from while loop in C using the same variable
I have a variable total that stores the total of miles and gallons every time user enters it.

When user hits -1, the program is suppose to add all the totals together and take the average.
I can't get the variable to add the previous total value to itself for the next iteration of the loop.

I tried totals += totals; but that returns the last total value of the loop?

what am i doing wrong?

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        totals = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", totals);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += totals;
        numOfEntries++;
        avgConsumption = totals / numOfEntries;

    } // end while
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    _getch();
    return 0;

} // end main
</code>```

答:
what am i doing wrong?

Code is mis-calculating totals.

To average multiple quotients like many miles_per_gallon (MPG), usually the approach is to divide the total_miles/total_gallons.  This is not the only definition of the average MPG yet I am certain the best to use here.  @Yunnosch

```<code>// Pseudo code
total_miles = 0.0
total_gallons = 0.0
while (still_getting_input)
  miles = get_input();
  gallons = get_input();
  print miles, gallons, miles/gallon

  total_miles += miles
  total_gallons += gallons

print total_miles, total_gallons, total_miles/total_gallon
</code>```

Body:
I have a variable total that stores the total of miles and gallons every time user enters it.

When user hits -1, the program is suppose to add all the totals together and take the average.
I can't get the variable to add the previous total value to itself for the next iteration of the loop.

I tried totals += totals; but that returns the last total value of the loop?

what am i doing wrong?

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        totals = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", totals);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += totals;
        numOfEntries++;
        avgConsumption = totals / numOfEntries;

    } // end while
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    _getch();
    return 0;

} // end main

Body:
what am i doing wrong?

Code is mis-calculating totals.

To average multiple quotients like many miles_per_gallon (MPG), usually the approach is to divide the total_miles/total_gallons.  This is not the only definition of the average MPG yet I am certain the best to use here.  @Yunnosch

// Pseudo code
total_miles = 0.0
total_gallons = 0.0
while (still_getting_input)
  miles = get_input();
  gallons = get_input();
  print miles, gallons, miles/gallon

  total_miles += miles
  total_gallons += gallons

print total_miles, total_gallons, total_miles/total_gallon


问:
view how many people compelete the quiz on admin panel
I have a mysql database and I have admin panel and I have quiz on my site.

I want to add a table to count how many people complete the quiz and show it on my admin panel

I have a questions. Is the column type varchar right?

What code should I type to my admin.php to show the count?

What code should I type to my EXAMPLE_QUIZ.php to send the count to database?
and what code should i add to all quiz's php files ?
i hope someone help me :(

答:
If you are not good with programming PHP and MySQL, looks like https://stackoverflow.com/jobs is better place for this topic. Else, would be nice if you show your code and we will find a problem.

If you are going it yourself, you can use SQL query SELECT * FROM table[ WHERE col_name = value][ AND col_name = value ] [ LIMIT count_rows, from_rows_nr ]. And to visualize it in browser use HTML tables and for data get from DB use MySQL and PHP. If you connect to DB with OOP method use while($row = $result->fetch_assoc()) loop and print your data.


问:
How to Accomplish a Where on a joined table with Entity Framework
I have the following 2 tables in my database:

```<code>[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)
</code>```

and:

```<code>[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)
</code>```

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

```<code>select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()
</code>```

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

```<code>var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );
</code>```

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.

答:
```<code>from t1 in db.Patient
join t2 in db.Schedule on
t1.PatientId equals t2.PatientId
where t2.Time<getTime
select new { t1.NameFirst, t1.NameLast, t1.DOB}
</code>```

Body:
I have the following 2 tables in my database:

[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)

and:

[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.


问:
My child component checkbox is not updating when props changed from the parent?
This is the code from my parent component TodoList:

```<code>_handleSelectedTodo(e) {
    e.preventDefault();
    this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
  }
//render() { ...
  <ul>
    {todos.map((todo,todoIndex) =>
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={(this.state.checkedIds.includes(todo.id))}
      />
    )}
  </ul>
</code>```

when the checkbox in Todo component is checked I add checkedIds on the state of TodoList Component. You can see on the checked prop on todo that I use includes to set it to true or false. But my problem is my child component doesn't update and I am using componentWillReceiveProps. This is the code:

```<code>constructor(props){
    super(props);
    this.state= { checked: false }
  }

  componentWillReceiveProps(nextProps) {
  this.setState({ checked: nextProps.checked });
}
// render() { ...
<input
   checked={this.state.checked}
   onChange={handleSelectedTodo}
   type="checkbox"
   value={id}
></input>
</code>```

It's all working and when clicked the checked is true on React debugger but it will not rerender, it only rerender if I check another box, the last one I checked will be checked and not the latest one?

答:
You need to remove the () around this.state.checkedIds.includes(todo.id).

```<code>//render() { ...
  <ul>
    {todos.map((todo,todoIndex) =>
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={this.state.checkedIds.includes(todo.id)}
      />
    )}
  </ul>
</code>```

Body:
This is the code from my parent component TodoList:

_handleSelectedTodo(e) {
    e.preventDefault();
    this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
  }
//render() { ...

    {todos.map((todo,todoIndex) =>
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={(this.state.checkedIds.includes(todo.id))}
      />
    )}

when the checkbox in Todo component is checked I add checkedIds on the state of TodoList Component. You can see on the checked prop on todo that I use includes to set it to true or false. But my problem is my child component doesn't update and I am using componentWillReceiveProps. This is the code:

constructor(props){
    super(props);
    this.state= { checked: false }
  }

  componentWillReceiveProps(nextProps) {
  this.setState({ checked: nextProps.checked });
}
// render() { ...
<input
   checked={this.state.checked}
   onChange={handleSelectedTodo}
   type="checkbox"
   value={id}
></input>

It's all working and when clicked the checked is true on React debugger but it will not rerender, it only rerender if I check another box, the last one I checked will be checked and not the latest one?

Body:
You need to remove the () around this.state.checkedIds.includes(todo.id).

//render() { ...
  <ul>
    {todos.map((todo,todoIndex) =>
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={this.state.checkedIds.includes(todo.id)}
      />
    )}
  </ul>


问:
How to run Django's test database only in memory?
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an SSD, but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a single test is slow since the database needs to be rebuilt / south migrated every time. So here's my idea...

Since I know the test database will always be quite small, why can't I just configure the system to always keep the entire test database in RAM? Never touch the disk at all. How do I configure this in Django?  I'd prefer to keep using MySQL since that's what I use in production, but if SQLite 3 or something else makes this easy, I'd go that way.

Does SQLite or MySQL have an option to run entirely in memory? It should be possible to configure a RAM disk and then configure the test database to store its data there, but I'm not sure how to tell Django / MySQL to use a different data directory for a certain database, especially since it keeps getting erased and recreated each run. (I'm on a Mac FWIW.)

答:
You can do double tweaking:

use transactional tables: initial fixtures state will be set using database rollback after every TestCase.

put your database data dir on ramdisk: you will gain much as far as database creation is concerned and also running test will be faster.

I'm using both tricks and I'm quite happy.

How to set up it for MySQL on Ubuntu:

```<code>$ sudo service mysql stop
$ sudo cp -pRL /var/lib/mysql /dev/shm/mysql

$ vim /etc/mysql/my.cnf
# datadir = /dev/shm/mysql
$ sudo service mysql start
</code>```

Beware, it's just for testing, after reboot your database from memory is lost!

Body:
You can do double tweaking:

use transactional tables: initial fixtures state will be set using database rollback after every TestCase.

put your database data dir on ramdisk: you will gain much as far as database creation is concerned and also running test will be faster.

I'm using both tricks and I'm quite happy.

How to set up it for MySQL on Ubuntu:

$ sudo service mysql stop
$ sudo cp -pRL /var/lib/mysql /dev/shm/mysql

$ vim /etc/mysql/my.cnf
# datadir = /dev/shm/mysql
$ sudo service mysql start

Beware, it's just for testing, after reboot your database from memory is lost!


问:
check if there are two or more equal values in Json
How I should process this Json, to extract the cat1 value once in a Spinner, and in the second Spinner based on the first spinner selection I display book1 and book2.

Json:

```<code>{
 "library":
[
{
   "Cat": "cat1",
   "Book": "book1",
   "authur": "authur1"
 },
 {
   "Cat": "cat1",
   "Book": "book2",
   "authur": "authur2"
 },
 {
   "Cat": "cat2",
   "Book": "book3",
   "authur": "authur3"
 }
]
}
</code>```

答:
You can simply use a library like Gson or Jackson for creating domain objects (you need to define them before) out of the Json. Afterwards you can easily extract whatever values you like.

This is an example:
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Body:
How I should process this Json, to extract the cat1 value once in a Spinner, and in the second Spinner based on the first spinner selection I display book1 and book2.

Json:

{
 "library":
[
{
   "Cat": "cat1",
   "Book": "book1",
   "authur": "authur1"
 },
 {
   "Cat": "cat1",
   "Book": "book2",
   "authur": "authur2"
 },
 {
   "Cat": "cat2",
   "Book": "book3",
   "authur": "authur3"
 }
]
}


问:
Nsis service removing
Hello I have problem with NSIS uninstaller.

I instaled software and create a service. Service name is named by user( for example troll)

Soo I have service troll it is running and working everything is all right.

If I want uninstall software I must remove this service; I've tried several way with plugins simpleSC and nsSCM, nothing helped me.

If I wrote for ex:

nsSCM::Remove "troll" service is removed

but when I write nsSCM::Remove "$0" ->nothing happen

Where is my mistake? In getting service name from stack? I don't know the name of the service since it is custom any help will be helpfull :D

答:
I don't have any reputation, otherwise this would have been in a comment. Anyway, you say the services' name is "named by user"

Are you saying the end-user designates the service name or is it simply the end-user's username?

If it's the latter you could use this without any plugins, excluding ExecDos:

```<code>Var User

!define SVC `$User`
!define SC  `$SYSDIR\sc.exe`

System::Call "advapi32::GetUserName(t.r0,*i${NSIS_MAX_STRLEN})i"
StrCpy $User $0
ClearErrors
ExecDos::Exec /TOSTACK `"${SC}" stop "${SVC}"`
Sleep 50
ExecDos::Exec /TOSTACK `"${SC}" delete "${SVC}"`
</code>```

If it's the first option then you'll need to do something like this in your installer whenever the user specifies the service's name. Hope this isn't too complicated.

```<code>;= VARIABLES
;= ################
Var Bit
Var UserService

;= DEFINES
;= ################
!define SVC         `$UserService`
!define SCKEY       SYSTEM\CurrentControlSet\services\${SVC}
!define HKLM        HKLM\${SCKEY}
!define SC          `$SYSDIR\sc.exe`
!define GETCURRPROC `kernel32::GetCurrentProcess()i.s`
!define WOW         `kernel32::IsWow64Process(is,*i.r0)`

;= MACROS
;= ################
;=#
;= Service::Example
; ${Service::CMD} "ServiceName" /DISABLEFSR $0 $1
;       ::CMD       = Either QueryConfig, Stop, or Remove.
;       ServiceName = The service name to be handled
;       /DISABLEFSR = Disables file-system redirection if running on x64. Use "" to skip.
;       $0          = Return after call
;       $1          =  ''     ''    ''
!define Service::QueryConfig `!insertmacro _Service::QueryConfig`
!macro _Service::QueryConfig _SVC _FSR _ERR1 _ERR2
    ReadEnvStr $R0 COMSPEC
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"$R0" /c "${SC} qc "${_SVC}" | FIND "BINARY_PATH_NAME""`
    Goto +2
    ExecDos::Exec /TOSTACK `"$R0" /c "${SC} qc "${_SVC}" | FIND "BINARY_PATH_NAME""`
    Pop ${_ERR1}
    Pop ${_ERR2}
    StrCmpS ${_ERR1} 0 0 +4
    StrCpy $R1 ${_ERR2} "" 29
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Path "$R1"
    ReadRegStr $R1 HKLM `${SVCKEY}` ImagePath
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Path "$R1"
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Name "${_SVC}"
!macroend
!define Service::Stop `!insertmacro _Service::Stop`
!macro _Service::Stop _SVC _FSR _ERR1 _ERR2
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"${SC}" stop "${_SVC}"`
    Goto +2
    ExecDos::Exec /TOSTACK `"${SC}" stop "${_SVC}"`
    Pop ${_ERR1}
    Pop ${_ERR2}
!macroend
!define Service::Remove `!insertmacro _Service::Remove`
!macro _Service::Remove _SVC _FSR _ERR1 _ERR2
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"${SC}" delete "${_SVC}"`
    Goto +2
    ExecDos::Exec /TOSTACK `"${SC}" delete "${_SVC}"`
    Pop ${_ERR1}
    Pop ${_ERR2}
!macroend

Function ".onInit"
    System::Call `${GETCURRPROC}`
    System::Call `${WOW}`
    StrCmpS $0 0 +3
    StrCpy $Bit 64
    Goto +2
    StrCpy $Bit 32
FunctionEnd

;=#
;= I don't know the code you're using but let's assume
;= after the end-user specifies the service's name you
;= copy the name to the variable $UserService. This is
;= somewhere in the install process.

StrCpy $UserService $0
;#=#
;# This will write to an INI file | $EXEDIR\InstallData.ini
;#      [Service]
;#      Path=X:\Path\to\service\exe
;#      Name=ServiceName
;#=#
${Service::QueryConfig} ${SVC} /DISABLEFSR $0 $1

;=#
;= Then in your uninstaller you could simply implement
;= this into your code for easy removal. I usually use
;= this method in my projects and it works pretty good
;= without the need for any extra plugins.
ReadINIStr $0 "$EXEDIR\InstallData.ini" "Service" Name
${Service::Stop} "$0" /DISABLEFSR $0 $1
Sleep 50
${Service::Remove} "$0" /DISABLEFSR $0 $1
</code>```

The /DISABLEFSR parameter should only be used on x64 machines. However, if you mess up there's a failsafe in the macros that will dodge this bullet for you. Boy, that was a lot, huh? And to my luck this will help you by no means. Lol. Hope this helps someone though.

Title: Nsis service removing

Body:
I don't have any reputation, otherwise this would have been in a comment. Anyway, you say the services' name is "named by user"

Are you saying the end-user designates the service name or is it simply the end-user's username?

If it's the latter you could use this without any plugins, excluding ExecDos:

Var User

!define SVC `$User`
!define SC  `$SYSDIR\sc.exe`

System::Call "advapi32::GetUserName(t.r0,*i${NSIS_MAX_STRLEN})i"
StrCpy $User $0
ClearErrors
ExecDos::Exec /TOSTACK `"${SC}" stop "${SVC}"`
Sleep 50
ExecDos::Exec /TOSTACK `"${SC}" delete "${SVC}"`

If it's the first option then you'll need to do something like this in your installer whenever the user specifies the service's name. Hope this isn't too complicated.

;= VARIABLES
;= ################
Var Bit
Var UserService

;= DEFINES
;= ################
!define SVC         `$UserService`
!define SCKEY       SYSTEM\CurrentControlSet\services\${SVC}
!define HKLM        HKLM\${SCKEY}
!define SC          `$SYSDIR\sc.exe`
!define GETCURRPROC `kernel32::GetCurrentProcess()i.s`
!define WOW         `kernel32::IsWow64Process(is,*i.r0)`

;= MACROS
;= ################
;=#
;= Service::Example
; ${Service::CMD} "ServiceName" /DISABLEFSR $0 $1
;       ::CMD       = Either QueryConfig, Stop, or Remove.
;       ServiceName = The service name to be handled
;       /DISABLEFSR = Disables file-system redirection if running on x64. Use "" to skip.
;       $0          = Return after call
;       $1          =  ''     ''    ''
!define Service::QueryConfig `!insertmacro _Service::QueryConfig`
!macro _Service::QueryConfig _SVC _FSR _ERR1 _ERR2
    ReadEnvStr $R0 COMSPEC
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"$R0" /c "${SC} qc "${_SVC}" | FIND "BINARY_PATH_NAME""`
    Goto +2
    ExecDos::Exec /TOSTACK `"$R0" /c "${SC} qc "${_SVC}" | FIND "BINARY_PATH_NAME""`
    Pop ${_ERR1}
    Pop ${_ERR2}
    StrCmpS ${_ERR1} 0 0 +4
    StrCpy $R1 ${_ERR2} "" 29
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Path "$R1"
    ReadRegStr $R1 HKLM `${SVCKEY}` ImagePath
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Path "$R1"
    WriteINIStr "$EXEDIR\InstallData.ini" "Service" Name "${_SVC}"
!macroend
!define Service::Stop `!insertmacro _Service::Stop`
!macro _Service::Stop _SVC _FSR _ERR1 _ERR2
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"${SC}" stop "${_SVC}"`
    Goto +2
    ExecDos::Exec /TOSTACK `"${SC}" stop "${_SVC}"`
    Pop ${_ERR1}
    Pop ${_ERR2}
!macroend
!define Service::Remove `!insertmacro _Service::Remove`
!macro _Service::Remove _SVC _FSR _ERR1 _ERR2
    StrCmpS $Bit 64 0 +4
    StrCmp "${_FSR}" /DISABLEFSR 0 +3
    ExecDos::Exec /TOSTACK /DISABLEFSR `"${SC}" delete "${_SVC}"`
    Goto +2
    ExecDos::Exec /TOSTACK `"${SC}" delete "${_SVC}"`
    Pop ${_ERR1}
    Pop ${_ERR2}
!macroend

Function ".onInit"
    System::Call `${GETCURRPROC}`
    System::Call `${WOW}`
    StrCmpS $0 0 +3
    StrCpy $Bit 64
    Goto +2
    StrCpy $Bit 32
FunctionEnd

;=#
;= I don't know the code you're using but let's assume
;= after the end-user specifies the service's name you
;= copy the name to the variable $UserService. This is
;= somewhere in the install process.

StrCpy $UserService $0
;#=#
;# This will write to an INI file | $EXEDIR\InstallData.ini
;#      [Service]
;#      Path=X:\Path\to\service\exe
;#      Name=ServiceName
;#=#
${Service::QueryConfig} ${SVC} /DISABLEFSR $0 $1

;=#
;= Then in your uninstaller you could simply implement
;= this into your code for easy removal. I usually use
;= this method in my projects and it works pretty good
;= without the need for any extra plugins.
ReadINIStr $0 "$EXEDIR\InstallData.ini" "Service" Name
${Service::Stop} "$0" /DISABLEFSR $0 $1
Sleep 50
${Service::Remove} "$0" /DISABLEFSR $0 $1

The /DISABLEFSR parameter should only be used on x64 machines. However, if you mess up there's a failsafe in the macros that will dodge this bullet for you. Boy, that was a lot, huh? And to my luck this will help you by no means. Lol. Hope this helps someone though.