问:
Mathematica: branch points for real roots of polynomial
I am doing a brute force search for "gradient extremals" on the following example function

```<code>fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;
</code>```

This involves finding the following zeros

```<code>gecond = With[{g = D[fv[{x, y}], {{x, y}}], h = D[fv[{x, y}], {{x, y}, 2}]},
 g.RotationMatrix[Pi/2].h.g == 0]
</code>```

Which Reduce happily does for me:

```<code>geyvals = y /. Cases[List@ToRules@Reduce[gecond, {x, y}], {y -> _}];
</code>```

geyvals is the three roots of a cubic polynomial, but the expression is a bit large to put here.

Now to my question: For different values of x, different numbers of these roots are real, and I would like to pick out the values of x where the solutions branch in order to piece together the gradient extremals along the valley floor (of fv). In the present case, since the polynomial is only cubic, I could probably do it by hand -- but I am looking for a simple way of having Mathematica do it for me?

Edit: To clarify: The gradient extremals stuff is just background -- and a simple way to set up a hard problem. I am not so interested in the specific solution to this problem as in a general hand-off way of spotting the branch points for polynomial roots. Have added an answer below with a working approach.

Edit 2: Since it seems that the actual problem is much more fun than root branching: rcollyer suggests using ContourPlot directly on gecond to get the gradient extremals. To make this complete we need to separate valleys and ridges, which is done by looking at the eigenvalue of the Hessian perpendicular to the gradient. Putting a check for "valleynes" in as a RegionFunction we are left with only the valley line:

```<code>valleycond = With[{
    g = D[fv[{x, y}], {{x, y}}],
    h = D[fv[{x, y}], {{x, y}, 2}]},
  g.RotationMatrix[Pi/2].h.RotationMatrix[-Pi/2].g >= 0];
gbuf["gevalley"]=ContourPlot[gecond // Evaluate, {x, -2, 4}, {y, -.5, 1.2},
   RegionFunction -> Function[{x, y}, Evaluate@valleycond],
   PlotPoints -> 41];
</code>```

Which gives just the valley floor line. Including some contours and the saddle point:

```<code>fvSaddlept = {x, y} /. First@Solve[Thread[D[fv[{x, y}], {{x, y}}] == {0, 0}]]
gbuf["contours"] = ContourPlot[fv[{x, y}],
   {x, -2, 4}, {y, -.7, 1.5}, PlotRange -> {0, 1/2},
   Contours -> fv@fvSaddlept (Range[6]/3 - .01),
   PlotPoints -> 41, AspectRatio -> Automatic, ContourShading -> None];
gbuf["saddle"] = Graphics[{Red, Point[fvSaddlept]}];
Show[gbuf /@ {"contours", "saddle", "gevalley"}]
</code>```

We end up with a plot like this:

答:
Updated: see below.

I'd approach this first by visualizing the imaginary parts of the roots:

This tells you three things immediately:  1) the first root is always real, 2) the second two are the conjugate pairs, and 3) there is a small region near zero in which all three are real.  Additionally, note that the exclusions only got rid of the singular point at x=0, and we can see why when we zoom in:

We can then use the EvalutionMonitor to generate the list of roots directly:

```<code>Map[Module[{f, fcn = #1},
            f[x_] := Im[fcn];
            Reap[Plot[f[x], {x, 0, 1.5},
                  Exclusions -> {True, f[x] == 1, f[x] == -1},
                  EvaluationMonitor :> Sow[{x, f[x]}][[2, 1]] //
            SortBy[#, First] &];]
   ]&, geyvals]
</code>```

(Note, the Part specification is a little odd, Reap returns a List of what is sown as the second item in a List, so this results in a nested list.  Also, Plot doesn't sample the points in a straightforward manner, so SortBy is needed.) There may be a more elegant route to determine where the last two roots become complex, but since their imaginary parts are piecewise continuous, it just seemed easier to brute force it.

Edit: Since you've mentioned that you want an automatic method for generating where some of the roots become complex, I've been exploring what happens when you substitute in y -> p + I q.  Now this assumes that x is real, but you've already done that in your solution.  Specifically, I do the following

```<code>In[1] := poly = g.RotationMatrix[Pi/2].h.g /. {y -> p + I q} // ComplexExpand;
In[2] := {pr,pi} = poly /. Complex[a_, b_] :> a + z b & // CoefficientList[#, z] & //
         Simplify[#, {x, p, q} \[Element] Reals]&;
</code>```

where the second step allows me to isolate the real and imaginary parts of the equation and simplify them independent of each other.  Doing this same thing with the generic 2D polynomial, f + d x + a x^2 + e y + 2 c x y + b y^2, but making both x and y complex; I noted that Im[poly] = Im[x] D[poly, Im[x]] + Im[y] D[poly,[y]], and this may hold for your equation, also.  By making x real, the imaginary part of poly becomes q times some function of x, p, and q.  So, setting q=0 always gives Im[poly] == 0.  But, that does not tell us anything new.  However, if we

```<code>In[3] := qvals = Cases[List@ToRules@RReduce[ pi == 0 && q != 0, {x,p,q}],
          {q -> a_}:> a];
</code>```

we get several formulas for q involving x and p.  For some values of x and p, those formulas may be imaginary, and we can use Reduce to determine where Re[qvals] == 0.  In other words, we want the "imaginary" part of y to be real and this can be accomplished by allowing q to be zero or purely imaginary.  Plotting the region where Re[q]==0 and overlaying the gradient extremal lines via

```<code>With[{rngs = Sequence[{x,-2,2},{y,-10,10}]},
Show@{
 RegionPlot[Evaluate[Thread[Re[qvals]==0]/.p-> y], rngs],
 ContourPlot[g.RotationMatrix[Pi/2].h.g==0,rngs
      ContourStyle -> {Darker@Red,Dashed}]}]
</code>```

gives

which confirms the regions in the first two plots showing the 3 real roots.

Body:
I am doing a brute force search for "gradient extremals" on the following example function

fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;

This involves finding the following zeros

gecond = With[{g = D[fv[{x, y}], {{x, y}}], h = D[fv[{x, y}], {{x, y}, 2}]},
 g.RotationMatrix[Pi/2].h.g == 0]

Which Reduce happily does for me:

geyvals = y /. Cases[List@ToRules@Reduce[gecond, {x, y}], {y -> _}];

geyvals is the three roots of a cubic polynomial, but the expression is a bit large to put here.

Now to my question: For different values of x, different numbers of these roots are real, and I would like to pick out the values of x where the solutions branch in order to piece together the gradient extremals along the valley floor (of fv). In the present case, since the polynomial is only cubic, I could probably do it by hand -- but I am looking for a simple way of having Mathematica do it for me?

Edit: To clarify: The gradient extremals stuff is just background -- and a simple way to set up a hard problem. I am not so interested in the specific solution to this problem as in a general hand-off way of spotting the branch points for polynomial roots. Have added an answer below with a working approach.

Edit 2: Since it seems that the actual problem is much more fun than root branching: rcollyer suggests using ContourPlot directly on gecond to get the gradient extremals. To make this complete we need to separate valleys and ridges, which is done by looking at the eigenvalue of the Hessian perpendicular to the gradient. Putting a check for "valleynes" in as a RegionFunction we are left with only the valley line:

valleycond = With[{
    g = D[fv[{x, y}], {{x, y}}],
    h = D[fv[{x, y}], {{x, y}, 2}]},
  g.RotationMatrix[Pi/2].h.RotationMatrix[-Pi/2].g >= 0];
gbuf["gevalley"]=ContourPlot[gecond // Evaluate, {x, -2, 4}, {y, -.5, 1.2},
   RegionFunction -> Function[{x, y}, Evaluate@valleycond],
   PlotPoints -> 41];

Which gives just the valley floor line. Including some contours and the saddle point:

fvSaddlept = {x, y} /. First@Solve[Thread[D[fv[{x, y}], {{x, y}}] == {0, 0}]]
gbuf["contours"] = ContourPlot[fv[{x, y}],
   {x, -2, 4}, {y, -.7, 1.5}, PlotRange -> {0, 1/2},
   Contours -> fv@fvSaddlept (Range[6]/3 - .01),
   PlotPoints -> 41, AspectRatio -> Automatic, ContourShading -> None];
gbuf["saddle"] = Graphics[{Red, Point[fvSaddlept]}];
Show[gbuf /@ {"contours", "saddle", "gevalley"}]

We end up with a plot like this:

Body:
Updated: see below.

I'd approach this first by visualizing the imaginary parts of the roots:

This tells you three things immediately:  1) the first root is always real, 2) the second two are the conjugate pairs, and 3) there is a small region near zero in which all three are real.  Additionally, note that the exclusions only got rid of the singular point at x=0, and we can see why when we zoom in:

We can then use the EvalutionMonitor to generate the list of roots directly:

Map[Module[{f, fcn = #1},
            f[x_] := Im[fcn];
            Reap[Plot[f[x], {x, 0, 1.5},
                  Exclusions -> {True, f[x] == 1, f[x] == -1},
                  EvaluationMonitor :> Sow[{x, f[x]}][[2, 1]] //
            SortBy[#, First] &];]
   ]&, geyvals]

(Note, the Part specification is a little odd, Reap returns a List of what is sown as the second item in a List, so this results in a nested list.  Also, Plot doesn't sample the points in a straightforward manner, so SortBy is needed.) There may be a more elegant route to determine where the last two roots become complex, but since their imaginary parts are piecewise continuous, it just seemed easier to brute force it.

Edit: Since you've mentioned that you want an automatic method for generating where some of the roots become complex, I've been exploring what happens when you substitute in y -> p + I q.  Now this assumes that x is real, but you've already done that in your solution.  Specifically, I do the following

In[1] := poly = g.RotationMatrix[Pi/2].h.g /. {y -> p + I q} // ComplexExpand;
In[2] := {pr,pi} = poly /. Complex[a_, b_] :> a + z b & // CoefficientList[#, z] & //
         Simplify[#, {x, p, q} \[Element] Reals]&;

where the second step allows me to isolate the real and imaginary parts of the equation and simplify them independent of each other.  Doing this same thing with the generic 2D polynomial, f + d x + a x^2 + e y + 2 c x y + b y^2, but making both x and y complex; I noted that Im[poly] = Im[x] D[poly, Im[x]] + Im[y] D[poly,[y]], and this may hold for your equation, also.  By making x real, the imaginary part of poly becomes q times some function of x, p, and q.  So, setting q=0 always gives Im[poly] == 0.  But, that does not tell us anything new.  However, if we

In[3] := qvals = Cases[List@ToRules@RReduce[ pi == 0 && q != 0, {x,p,q}],
          {q -> a_}:> a];

we get several formulas for q involving x and p.  For some values of x and p, those formulas may be imaginary, and we can use Reduce to determine where Re[qvals] == 0.  In other words, we want the "imaginary" part of y to be real and this can be accomplished by allowing q to be zero or purely imaginary.  Plotting the region where Re[q]==0 and overlaying the gradient extremal lines via

With[{rngs = Sequence[{x,-2,2},{y,-10,10}]},
Show@{
 RegionPlot[Evaluate[Thread[Re[qvals]==0]/.p-> y], rngs],
 ContourPlot[g.RotationMatrix[Pi/2].h.g==0,rngs
      ContourStyle -> {Darker@Red,Dashed}]}]

gives

which confirms the regions in the first two plots showing the 3 real roots.


来源: stackexchange

问:
Geocalization android studio
I'm designing an app with a MapsActivity that will update my location, but when I run it I only get the world map without telling me my position. I do not see the fault, I have tried many things .</p>

```<code> package com.example.dani.etakemongo.ProductionFrontends;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.dani.etakemongo.DevelopFrontends.Menu;
import com.example.dani.etakemongo.Modelo.Usuario;
import com.example.dani.etakemongo.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.Serializable;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

String tag = "MapsActivity";
private GoogleMap mMap;
private Marker marcador;
double lat = 0.0;
double ing = 0.0;
String email2, emailaMenu;
int idusuario, idusuarioaMenu;

FloatingActionButton menu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    Log.d(tag, "Event onCreate()");

    email2 = getIntent().getExtras().getString("email");
    emailaMenu = email2;

    //BOTON MENU
    menu = (FloatingActionButton) findViewById(R.id.fab_menu);
    menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                goToMenu(v);
            } catch (Exception ex) {
                String error = ex.getMessage();
                Toast.makeText(MapsActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        }
    });

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    miUbicacion();

}

//Metodo para incluir un marker, CameraUpdate para centrar la camara a la posicion del marker
private void agregarMarcador(double lat, double ing) {

    LatLng coordenadas = new LatLng(lat, ing);
    CameraUpdate miUbicacion = CameraUpdateFactory.newLatLngZoom(coordenadas, 16);
    if (marcador != null)
        marcador.remove(); //Si el marcador diferente de null le añadimos propiedades, titulo, imagen
    marcador = mMap.addMarker(new MarkerOptions()
            .position(coordenadas)
            .title("Mi posicion")
            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)));
    mMap.animateCamera(miUbicacion);
}

//Metodo para obtener latitud y longitud de nuestra posicion actual
private void actualizarUbicacion(Location location) {
    if (location != null) {  //Comrpobamos la localizacion recibida es diferente de null antes de asignar valores a las valariables
        lat = location.getLatitude();
        ing = location.getLongitude();
        agregarMarcador(lat, ing);
    }
}

//Implementamos un objeto del tipo LocationListener, su funcion es estar atento a cambio de localidad recividio por el GPS
LocationListener locListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        actualizarUbicacion(location);//Llamamos anuestro metodo para actualizar la ubicacion
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};

//Metodo para obtener servicio de posicionamiento, nos da la ultima posicion obtenida y se actualiza cada 15 segundos

private void miUbicacion() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    actualizarUbicacion(location);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,0,locListener);
}
@Override
protected void onStart() {
    super.onStart();
    Log.d(tag, "Event onStart()");
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(tag, "Event onResume()");

}

@Override
protected void onPause() {
    super.onPause();
    Log.d(tag, "Event onPause()");

}

@Override
protected void onStop() {
    super.onStop();
    Log.d(tag, "Event onStop()");

}

@Override
protected void onRestart() {
    super.onRestart();
    Log.d(tag, "Event onRestart()");

}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d(tag, "Event onDestroy()");

}

public void goToMenu(View view){
    Intent intent = new Intent(MapsActivity.this, Menu.class);
    intent.putExtra("email2",emailaMenu);
    startActivityForResult(intent, 800);
}
}
</code>```

答:
Add this line of code in onMapReady </p>

```<code>mGoogleMap.setMyLocationEnabled(true);
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    miUbicacion();
    if (PermissionUtils.checkPermission(HomeActivity_.this,
                  PermissionConstant.LOCATION_PERMISSION)
                    == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Geocalization android studio

Body:
I'm designing an app with a MapsActivity that will update my location, but when I run it I only get the world map without telling me my position. I do not see the fault, I have tried many things .

 package com.example.dani.etakemongo.ProductionFrontends;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.dani.etakemongo.DevelopFrontends.Menu;
import com.example.dani.etakemongo.Modelo.Usuario;
import com.example.dani.etakemongo.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.Serializable;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

String tag = "MapsActivity";
private GoogleMap mMap;
private Marker marcador;
double lat = 0.0;
double ing = 0.0;
String email2, emailaMenu;
int idusuario, idusuarioaMenu;

FloatingActionButton menu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    Log.d(tag, "Event onCreate()");

    email2 = getIntent().getExtras().getString("email");
    emailaMenu = email2;

    //BOTON MENU
    menu = (FloatingActionButton) findViewById(R.id.fab_menu);
    menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                goToMenu(v);
            } catch (Exception ex) {
                String error = ex.getMessage();
                Toast.makeText(MapsActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        }
    });

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    miUbicacion();

}

//Metodo para incluir un marker, CameraUpdate para centrar la camara a la posicion del marker
private void agregarMarcador(double lat, double ing) {

    LatLng coordenadas = new LatLng(lat, ing);
    CameraUpdate miUbicacion = CameraUpdateFactory.newLatLngZoom(coordenadas, 16);
    if (marcador != null)
        marcador.remove(); //Si el marcador diferente de null le añadimos propiedades, titulo, imagen
    marcador = mMap.addMarker(new MarkerOptions()
            .position(coordenadas)
            .title("Mi posicion")
            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)));
    mMap.animateCamera(miUbicacion);
}

//Metodo para obtener latitud y longitud de nuestra posicion actual
private void actualizarUbicacion(Location location) {
    if (location != null) {  //Comrpobamos la localizacion recibida es diferente de null antes de asignar valores a las valariables
        lat = location.getLatitude();
        ing = location.getLongitude();
        agregarMarcador(lat, ing);
    }
}

//Implementamos un objeto del tipo LocationListener, su funcion es estar atento a cambio de localidad recividio por el GPS
LocationListener locListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        actualizarUbicacion(location);//Llamamos anuestro metodo para actualizar la ubicacion
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};

//Metodo para obtener servicio de posicionamiento, nos da la ultima posicion obtenida y se actualiza cada 15 segundos

private void miUbicacion() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    actualizarUbicacion(location);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,0,locListener);
}
@Override
protected void onStart() {
    super.onStart();
    Log.d(tag, "Event onStart()");
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(tag, "Event onResume()");

}

@Override
protected void onPause() {
    super.onPause();
    Log.d(tag, "Event onPause()");

}

@Override
protected void onStop() {
    super.onStop();
    Log.d(tag, "Event onStop()");

}

@Override
protected void onRestart() {
    super.onRestart();
    Log.d(tag, "Event onRestart()");

}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d(tag, "Event onDestroy()");

}

public void goToMenu(View view){
    Intent intent = new Intent(MapsActivity.this, Menu.class);
    intent.putExtra("email2",emailaMenu);
    startActivityForResult(intent, 800);
}
}

Body:
Add this line of code in onMapReady

mGoogleMap.setMyLocationEnabled(true);
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    miUbicacion();
    if (PermissionUtils.checkPermission(HomeActivity_.this,
                  PermissionConstant.LOCATION_PERMISSION)
                    == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            }

}

ContentLicense: CC BY-SA 3.0


问:
Play/Stop button to control a loop
I'd like to start and stop a loop with play and start button but it doesn't work. I've got an infinite loop when I press test button.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Vibration } from '@ionic-native/vibration';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  isPlayed: boolean = false;

  constructor(public navCtrl: NavController, private vibration: Vibration) {

  }

  play(){
    this.isPlayed = true;
    this.test();
    console.log(this.isPlayed);
  }

  stop(){
    this.isPlayed = false;
    this.test();
    console.log(this.isPlayed);
  }

  test(){
    while (this.isPlayed == true) {
      console.log("test")
  }
}
}
</code>```

And the HTML :

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Pulse
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="play()">
    Play
  </button>
  <button ion-button (click)="stop()">
    Stop
  </button>
  <button ion-button (click)="test()">
    Test
  </button>
  {{counter}}
</ion-content>
</code>```

答:
You have to set this.isPlayed to false (or a falsy value) for the while loop to stop. But you can't run stop() because console.log is constantly executing.

Maybe you can test it with setInterval:

```<code>  private interval;

  test(){
      if (this.interval) {
          return;
      }

      this.interval = setInterval(() => {
          if (this.isPlayed) {
              console.log('playing');
          } else {
              console.log('stopped');
          }
      }, 1000);
  }
</code>```

Title: Play/Stop button to control a loop

Body:
I'd like to start and stop a loop with play and start button but it doesn't work. I've got an infinite loop when I press test button.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Vibration } from '@ionic-native/vibration';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  isPlayed: boolean = false;

  constructor(public navCtrl: NavController, private vibration: Vibration) {

  }

  play(){
    this.isPlayed = true;
    this.test();
    console.log(this.isPlayed);
  }

  stop(){
    this.isPlayed = false;
    this.test();
    console.log(this.isPlayed);
  }

  test(){
    while (this.isPlayed == true) {
      console.log("test")
  }
}
}

And the HTML :

<ion-header>
  <ion-navbar>
    <ion-title>
      Pulse
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="play()">
    Play
  </button>
  <button ion-button (click)="stop()">
    Stop
  </button>
  <button ion-button (click)="test()">
    Test
  </button>
  {{counter}}
</ion-content>

Body:
You have to set this.isPlayed to false (or a falsy value) for the while loop to stop. But you can't run stop() because console.log is constantly executing.

Maybe you can test it with setInterval:

  private interval;

  test(){
      if (this.interval) {
          return;
      }

      this.interval = setInterval(() => {
          if (this.isPlayed) {
              console.log('playing');
          } else {
              console.log('stopped');
          }
      }, 1000);
  }


问:
Adding "Play WS Standalone" dependency to SBT build
```<code>name := "pta-accuracy-ocean"
version := "0.0.1"
scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  // Spark dependencies
  "org.apache.spark" % "spark-hive_2.11" % "2.1.1",
  "org.apache.spark" % "spark-mllib_2.11" % "2.1.1",
  // Third-party libraries
  "net.sf.jopt-simple" % "jopt-simple" % "4.3",
  "com.amazonaws" % "aws-java-sdk" % "1.3.11",
  "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M10"
)
</code>```

This "sbt assembly" builds just fine.  Now I want to use Play WS Standalone.

So I add the following library dependency:

```<code>  "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M10"
</code>```

But I get the following errors:

```<code>[error] Modules were resolved with conflicting cross-version suffixes in {file:/Users/paulreiners/dev/tv-insight-spark-scala/tv-pta-accuracy-ocean/}tv-pta-accuracy-ocean:
[error]    org.apache.spark:spark-launcher _2.11, _2.10
[error]    org.json4s:json4s-ast _2.11, _2.10
[error]    org.apache.spark:spark-catalyst _2.11, _2.10
[error]    org.apache.spark:spark-network-shuffle _2.11, _2.10
[error]    com.typesafe.akka:akka-actor _2.10, _2.11
[error]    com.twitter:chill _2.11, _2.10
[error]    org.apache.spark:spark-sql _2.11, _2.10
[error]    org.json4s:json4s-jackson _2.11, _2.10
[error]    com.fasterxml.jackson.module:jackson-module-scala _2.11, _2.10
[error]    org.json4s:json4s-core _2.11, _2.10
[error]    org.apache.spark:spark-unsafe _2.11, _2.10
[error]    org.apache.spark:spark-core _2.11, _2.10
[error]    org.apache.spark:spark-network-common _2.11, _2.10
java.lang.RuntimeException: Conflicting cross-version suffixes in: org.apache.spark:spark-launcher, org.json4s:json4s-ast, org.apache.spark:spark-catalyst, org.apache.spark:spark-network-shuffle, com.typesafe.akka:akka-actor, com.twitter:chill, org.apache.spark:spark-sql, org.json4s:json4s-jackson, com.fasterxml.jackson.module:jackson-module-scala, org.json4s:json4s-core, org.apache.spark:spark-unsafe, org.apache.spark:spark-core, org.apache.spark:spark-network-common
    at scala.sys.package$.error(package.scala:27)
    at sbt.ConflictWarning$.processCrossVersioned(ConflictWarning.scala:46)
    at sbt.ConflictWarning$.apply(ConflictWarning.scala:32)
    at sbt.Classpaths$$anonfun$69.apply(Defaults.scala:1219)
    at sbt.Classpaths$$anonfun$69.apply(Defaults.scala:1216)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
    at sbt.std.Transform$$anon$4.work(System.scala:63)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
    at sbt.Execute.work(Execute.scala:237)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[error] (*:update) Conflicting cross-version suffixes in: org.apache.spark:spark-launcher, org.json4s:json4s-ast, org.apache.spark:spark-catalyst, org.apache.spark:spark-network-shuffle, com.typesafe.akka:akka-actor, com.twitter:chill, org.apache.spark:spark-sql, org.json4s:json4s-jackson, com.fasterxml.jackson.module:jackson-module-scala, org.json4s:json4s-core, org.apache.spark:spark-unsafe, org.apache.spark:spark-core, org.apache.spark:spark-network-common
</code>```

How do I fix this?  I've tried too many combinations of scalaVersion and libraryDependencies to list.  Is there some methodical way to find compatible JARs?

Note that I don't need to use any particularly Scala version nor any particular library version, although I would like to use the most up-to-date combination possible.

答:
```<code>name := "ds-exactearth-pta-evaluation"
version := "1.0"
scalaVersion := "2.11.11"

javacOptions ++= Seq("-source", "1.7", "-target", "1.7")

// additional libraries
libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "1.3.1" % "provided",
  "org.apache.spark" % "spark-sql_2.11" % "2.1.0",
  "org.apache.spark" %% "spark-hive" % "1.3.1",
  "org.apache.spark" %% "spark-streaming" % "1.3.1",
  "org.apache.spark" %% "spark-streaming-flume" % "1.3.1",
  "org.apache.spark" %% "spark-mllib" % "1.3.1",
  "org.apache.commons" % "commons-lang3" % "3.0",
  "org.eclipse.jetty"  % "jetty-client" % "8.1.14.v20131031",
  "com.fasterxml.jackson.core" % "jackson-databind" % "2.3.3",
  "org.elasticsearch" % "elasticsearch-hadoop-mr" % "2.0.0.RC1",
  "net.sf.opencsv" % "opencsv" % "2.0",
  "com.twitter.elephantbird" % "elephant-bird" % "4.5",
  "com.twitter.elephantbird" % "elephant-bird-core" % "4.5",
  "mysql" % "mysql-connector-java" % "5.1.31",
  "com.github.scopt" %% "scopt" % "3.2.0",
  "org.scalatest" %% "scalatest" % "2.2.1" % "test",
  "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M9"
)
</code>```

Body:
name := "pta-accuracy-ocean"
version := "0.0.1"
scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  // Spark dependencies
  "org.apache.spark" % "spark-hive_2.11" % "2.1.1",
  "org.apache.spark" % "spark-mllib_2.11" % "2.1.1",
  // Third-party libraries
  "net.sf.jopt-simple" % "jopt-simple" % "4.3",
  "com.amazonaws" % "aws-java-sdk" % "1.3.11",
  "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M10"
)

This "sbt assembly" builds just fine.  Now I want to use Play WS Standalone.

So I add the following library dependency:

  "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M10"

But I get the following errors:

[error] Modules were resolved with conflicting cross-version suffixes in {file:/Users/paulreiners/dev/tv-insight-spark-scala/tv-pta-accuracy-ocean/}tv-pta-accuracy-ocean:
[error]    org.apache.spark:spark-launcher _2.11, _2.10
[error]    org.json4s:json4s-ast _2.11, _2.10
[error]    org.apache.spark:spark-catalyst _2.11, _2.10
[error]    org.apache.spark:spark-network-shuffle _2.11, _2.10
[error]    com.typesafe.akka:akka-actor _2.10, _2.11
[error]    com.twitter:chill _2.11, _2.10
[error]    org.apache.spark:spark-sql _2.11, _2.10
[error]    org.json4s:json4s-jackson _2.11, _2.10
[error]    com.fasterxml.jackson.module:jackson-module-scala _2.11, _2.10
[error]    org.json4s:json4s-core _2.11, _2.10
[error]    org.apache.spark:spark-unsafe _2.11, _2.10
[error]    org.apache.spark:spark-core _2.11, _2.10
[error]    org.apache.spark:spark-network-common _2.11, _2.10
java.lang.RuntimeException: Conflicting cross-version suffixes in: org.apache.spark:spark-launcher, org.json4s:json4s-ast, org.apache.spark:spark-catalyst, org.apache.spark:spark-network-shuffle, com.typesafe.akka:akka-actor, com.twitter:chill, org.apache.spark:spark-sql, org.json4s:json4s-jackson, com.fasterxml.jackson.module:jackson-module-scala, org.json4s:json4s-core, org.apache.spark:spark-unsafe, org.apache.spark:spark-core, org.apache.spark:spark-network-common
    at scala.sys.package$.error(package.scala:27)
    at sbt.ConflictWarning$.processCrossVersioned(ConflictWarning.scala:46)
    at sbt.ConflictWarning$.apply(ConflictWarning.scala:32)
    at sbt.Classpaths$$anonfun$69.apply(Defaults.scala:1219)
    at sbt.Classpaths$$anonfun$69.apply(Defaults.scala:1216)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
    at sbt.std.Transform$$anon$4.work(System.scala:63)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
    at sbt.Execute.work(Execute.scala:237)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[error] (*:update) Conflicting cross-version suffixes in: org.apache.spark:spark-launcher, org.json4s:json4s-ast, org.apache.spark:spark-catalyst, org.apache.spark:spark-network-shuffle, com.typesafe.akka:akka-actor, com.twitter:chill, org.apache.spark:spark-sql, org.json4s:json4s-jackson, com.fasterxml.jackson.module:jackson-module-scala, org.json4s:json4s-core, org.apache.spark:spark-unsafe, org.apache.spark:spark-core, org.apache.spark:spark-network-common

How do I fix this?  I've tried too many combinations of scalaVersion and libraryDependencies to list.  Is there some methodical way to find compatible JARs?

Note that I don't need to use any particularly Scala version nor any particular library version, although I would like to use the most up-to-date combination possible.


问:
boolean example in Schildt book
I'm really new to Java, but it sucks all my free time, it's very interesting to study, but I need a little help.

Here's an example of Boolean test from Schildt's book:

```<code>public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}
</code>```

This code shows me result:

Expression b false

Expression b true

This code is ok.

10 > 9 true

First line is ok, second is ok, third too, but why the fourth doesn't show me "The code is not ok.", 'cause there is "b=false" and it should say that? Why it jumps to the last System.out.println?

Can someone add commentaries to this example? Thanks a lot!

答:
```<code>if (b) System.out.println("b was true");
</code>```

that line says: only if b is true do what comes after the closing ). Since b is false, the rest of the line is not executed. More verbose example:

```<code>if (b) {
    System.out.println("b was true");
} else {
    System.out.println("b was false");
}
</code>```

Title: boolean example in Schildt book

Body:
I'm really new to Java, but it sucks all my free time, it's very interesting to study, but I need a little help.

Here's an example of Boolean test from Schildt's book:

public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}

This code shows me result:

Expression b false

Expression b true

This code is ok.

10 > 9 true

First line is ok, second is ok, third too, but why the fourth doesn't show me "The code is not ok.", 'cause there is "b=false" and it should say that? Why it jumps to the last System.out.println?

Can someone add commentaries to this example? Thanks a lot!

Body:
if (b) System.out.println("b was true");

that line says: only if b is true do what comes after the closing ). Since b is false, the rest of the line is not executed. More verbose example:

if (b) {
    System.out.println("b was true");
} else {
    System.out.println("b was false");
}


问:
Simulated chatbot that switches input methods?
I have a chatbot I created that asks for a user's username, then stores it as a variable. However, in one of my dialog trees, I have to ask the user for them to type another answer, I have it working so that user's can navigate via button clicks.

On username capture, the "input bar" is removed from controls and I append buttons with each message function. I tried to do the inverse of this (remove buttons and add an input) which does work, however I can't get my input to do anything. It won't submit on enter, it won't save a variable and in my trial and error, I found that if I try to set a var off that msg value, it updates the username's.

Here is my function to retrieve name

```<code>function get_username() {
  send_msg("Hello I'm Mumbles, the Help Bot", function(){
    send_msg("Who am I speaking with today?")
  });
}

function ai(msg) {
  if (username.length < 3) {
    username = msg;
          send_msg("Nice to meet you"+username+". What are you working on today?" , function() {
            $("#controls").append(
              '<button class="options one" value="my_certifications" type="button">My Certifications</button>' +
                '<button class="options one" value="videos"type="button">Videos</butto/>' +
                '<button class="options one" value="login"type="button">Login</butto/>' +
                '<button class="options one" value="other"type="button">Other</butto/>'
            );
          });
        }
      // Remove text bar
      $("#controls").empty();

};
</code>```

Here is my function to try and capture email

```<code>    } else if (b_val == "my_practicum") {
      send_msg("What is the email address you submitted your practicum with? By having this we can give you a status update!" , function() {
            $("#controls").append(
                      '<textarea id="message" class="practicum-bar" placeholder="Type Your Name - Then Hit Enter"></textarea><button style="display:none;" id="sendMsg">Send</button>'                  );
                 email = msg;
        console.log(email);
      });
    }
}
</code>```

If you want to see this in action, here my JSFiddle. You can see it by going through this user path

Enter name > Certifications > My Practicum > Enter email

Any help on this is appreciated! Thanks!

答:
It looks like you remove controls  by doing $("#controls").empty(); and you want to add an event to a dynamically created element so you have to add the context to the second parameter of the .on.  look now you can see the console.log in the fiddle the second time you clicked enter because jquery can detect the item now.

```<code>$("#controls").on("keypress", "#message", function(event){

 if (event.which == 13) {
      console.log("my test");
      if ($("#slideThree").prop("checked")) {
         $("#sendMsg").click();
         event.preventDefault();
         //*edit you can now change variables outside of scope*
      }
  }
});
</code>```

now you can do your event handling.

Body:
I have a chatbot I created that asks for a user's username, then stores it as a variable. However, in one of my dialog trees, I have to ask the user for them to type another answer, I have it working so that user's can navigate via button clicks.

On username capture, the "input bar" is removed from controls and I append buttons with each message function. I tried to do the inverse of this (remove buttons and add an input) which does work, however I can't get my input to do anything. It won't submit on enter, it won't save a variable and in my trial and error, I found that if I try to set a var off that msg value, it updates the username's.

Here is my function to retrieve name

function get_username() {
  send_msg("Hello I'm Mumbles, the Help Bot", function(){
    send_msg("Who am I speaking with today?")
  });
}

function ai(msg) {
  if (username.length < 3) {
    username = msg;
          send_msg("Nice to meet you"+username+". What are you working on today?" , function() {
            $("#controls").append(
              '<button class="options one" value="my_certifications" type="button">My Certifications</button>' +
                '<button class="options one" value="videos"type="button">Videos</butto/>' +
                '<button class="options one" value="login"type="button">Login</butto/>' +
                '<button class="options one" value="other"type="button">Other</butto/>'
            );
          });
        }
      // Remove text bar
      $("#controls").empty();

};

Here is my function to try and capture email

    } else if (b_val == "my_practicum") {
      send_msg("What is the email address you submitted your practicum with? By having this we can give you a status update!" , function() {
            $("#controls").append(
                      '<textarea id="message" class="practicum-bar" placeholder="Type Your Name - Then Hit Enter"></textarea><button style="display:none;" id="sendMsg">Send</button>'                  );
                 email = msg;
        console.log(email);
      });
    }
}

If you want to see this in action, here my JSFiddle. You can see it by going through this user path

Enter name > Certifications > My Practicum > Enter email

Any help on this is appreciated! Thanks!

Body:
It looks like you remove controls  by doing $("#controls").empty(); and you want to add an event to a dynamically created element so you have to add the context to the second parameter of the .on.  look now you can see the console.log in the fiddle the second time you clicked enter because jquery can detect the item now.

$("#controls").on("keypress", "#message", function(event){

 if (event.which == 13) {
      console.log("my test");
      if ($("#slideThree").prop("checked")) {
         $("#sendMsg").click();
         event.preventDefault();
         //*edit you can now change variables outside of scope*
      }
  }
});

now you can do your event handling.


问:
Getting error when browse the website in IIS
I have website on IIS and when I browse I get this error-
HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Someone told me register asp.net but I get this error when I run this below command in cmd.

```<code>c:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -i

This option is not supported on this version of the operating system.  Administr
ators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Win
dows Features On/Off" dialog,  the Server Manager management tool, or the dism.e
xe command line tool.  For more details please see http://go.microsoft.com/fwlin
k/?LinkID=216771.
</code>```

Can anyone help me to solve this?

答: You are missing the 4.5 version of the .NET Framework. Try this solution: https://support.microsoft.com/pt-br/help/2736284/how-to-install-asp.net-4.5-on-windows-8-and-windows-server-2012</p>

Body:
I have website on IIS and when I browse I get this error-
HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Someone told me register asp.net but I get this error when I run this below command in cmd.

c:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -i

This option is not supported on this version of the operating system.  Administr
ators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Win
dows Features On/Off" dialog,  the Server Manager management tool, or the dism.e
xe command line tool.  For more details please see http://go.microsoft.com/fwlin
k/?LinkID=216771.

Can anyone help me to solve this?


问:
OWASP ESAPI SecurityWrapper filter not loading on webapp deployed in Tomcat - Throws ClassNotFound Exception
I'm integrating ESAPI to my java web application. I added the following to my web.xml according to the ESAPI documentation

```<code><filter>
    <filter-name>SecurityWrapperDefault</filter-name>
    <filter-class>org.owasp.filters.SecurityWrapper</filter-class>
 </filter>
</code>```

I have also added the ESAPI dependency in my pom.xml. When I build and deploy the .war file, I can see the esapi .jar file inside the /WEB-INF/lib/. But when tomcat is being started, it throws a ClassNotFoundException on the SecurityWrapper class.

```<code>org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter SecurityWrapperDefault
java.lang.ClassNotFoundException: org.owasp.filters.SecurityWrapper
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
</code>```

Things I tried to recover from this issue:

Add the esapi-2.1.0.1.jar to the /lib folder directly just to see if the class could be found - no luck

Write a new dummy Filter extending the ESAPI SecurityWrapper class, hoping the class would be forced to load and added the dummy filter entry in the web.xml. - This results in the application not being able to find the dummy filter class.

public class XSSFilter extends SecurityWrapper{
}

If someone has an idea what's going on pls let me know! Thanks.

答: I checked the jar you are using. SecurityWrapper is in package org.owasp.esapi.filters

Body:
I'm integrating ESAPI to my java web application. I added the following to my web.xml according to the ESAPI documentation

<filter>
    <filter-name>SecurityWrapperDefault</filter-name>
    <filter-class>org.owasp.filters.SecurityWrapper</filter-class>
 </filter>

I have also added the ESAPI dependency in my pom.xml. When I build and deploy the .war file, I can see the esapi .jar file inside the /WEB-INF/lib/. But when tomcat is being started, it throws a ClassNotFoundException on the SecurityWrapper class.

org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter SecurityWrapperDefault
java.lang.ClassNotFoundException: org.owasp.filters.SecurityWrapper
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)

Things I tried to recover from this issue:

Add the esapi-2.1.0.1.jar to the /lib folder directly just to see if the class could be found - no luck

Write a new dummy Filter extending the ESAPI SecurityWrapper class, hoping the class would be forced to load and added the dummy filter entry in the web.xml. - This results in the application not being able to find the dummy filter class.

public class XSSFilter extends SecurityWrapper{
}

If someone has an idea what's going on pls let me know! Thanks.


问:
Why my variable is Nil? - Ruby on Rails
i have a controller called Produto and a model called Produto. I want to pass all the Produto objects to a variable as the same the Produto controller does, but to another controller. So, the controller Produto take @Produto = Produto.all in her Index def and the view of this controller uses that variable. But i want to do this in other controller.
Look what i have :

Produto controller:

```<code>class ProdutosController < ApplicationController
  before_action :set_produto, only: [:show, :edit, :update, :destroy]

  # GET /produtos
  # GET /produtos.json
  def index
    @produtos = Produto.all
  end

  def show
  end

  def new
    @produto = Produto.new
  end

  def edit
  end

  def create
    @produto = Produto.new(produto_params)
    respond_to do |format|
      if @produto.save
        format.html { redirect_to @produto, notice: 'Produto was successfully created.' }
        format.json { render :show, status: :created, location: @produto }
      else
        format.html { render :new }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @produto.update(produto_params)
        format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }
        format.json { render :show, status: :ok, location: @produto }
      else
        format.html { render :edit }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @produto.destroy
    respond_to do |format|
      format.html { redirect_to produtos_url, notice: 'Produto was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_produto
      @produto = Produto.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def produto_params
      params.require(:produto).permit(:nome, :preco, :fornecedor_id)
    end
end
</code>```

Home controller (this is the controller i want to take those Produto objects too, as the same the Produto controller):

```<code>    class HomeController < ApplicationController

  def index
    @produtos = Produto.all
    render "index"
  end

  def show
    if session[:user]
      @user = User.find(session[:user])
    end
  end

end
</code>```

the view of Home has this part on the code:

```<code>  <table>
    <thead>
    <tr>
      <th>Nome</th>
      <th>Preco</th>
      <th>Fornecedor</th>
      <th colspan="3"></th>
    </tr>
    </thead>

    <tbody>
    <% @produtos.each do |produto| %>
        <tr>
          <td><%= produto.nome %></td>
          <td><%= produto.preco %></td>
          <td><%= produto.fornecedor %></td>
          <td><%= link_to 'Show', produto %></td>
          <td><%= link_to 'Edit', edit_produto_path(produto) %></td>
          <td><%= link_to 'Destroy', produto, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
    <% end %>
    </tbody>
  </table>
</code>```

and i'm getting this error:

undefined method `each' for nil:NilClass in <% @produtos.each do
  |produto| %>

My routes:

```<code>Rails.application.routes.draw do

  root 'login#new'
  get 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end
</code>```

Login controller (which is the root route):

```<code>class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/index", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end

  end
  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end
</code>```

答:
Make your routes, methods, views match:

```<code># config/routes.rb
get '/home/inicio', to: 'home#index'

# app/controllers/home_controller.rb
def index
  @produtos = Produto.all
end

# app/views/home/index.html.erb
<% @produtos.each do |produto| %>
</code>```

As you see it changes just the URI but you must make reference to your index method in both controller method and view name.

If you use render 'inicio' then you must use the inicio.html.erb view instead index.html.erb.

Title: Why my variable is Nil? - Ruby on Rails

Body:
i have a controller called Produto and a model called Produto. I want to pass all the Produto objects to a variable as the same the Produto controller does, but to another controller. So, the controller Produto take @Produto = Produto.all in her Index def and the view of this controller uses that variable. But i want to do this in other controller.
Look what i have :

Produto controller:

class ProdutosController < ApplicationController
  before_action :set_produto, only: [:show, :edit, :update, :destroy]

  # GET /produtos
  # GET /produtos.json
  def index
    @produtos = Produto.all
  end

  def show
  end

  def new
    @produto = Produto.new
  end

  def edit
  end

  def create
    @produto = Produto.new(produto_params)
    respond_to do |format|
      if @produto.save
        format.html { redirect_to @produto, notice: 'Produto was successfully created.' }
        format.json { render :show, status: :created, location: @produto }
      else
        format.html { render :new }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @produto.update(produto_params)
        format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }
        format.json { render :show, status: :ok, location: @produto }
      else
        format.html { render :edit }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @produto.destroy
    respond_to do |format|
      format.html { redirect_to produtos_url, notice: 'Produto was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_produto
      @produto = Produto.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def produto_params
      params.require(:produto).permit(:nome, :preco, :fornecedor_id)
    end
end

Home controller (this is the controller i want to take those Produto objects too, as the same the Produto controller):

    class HomeController < ApplicationController

  def index
    @produtos = Produto.all
    render "index"
  end

  def show
    if session[:user]
      @user = User.find(session[:user])
    end
  end

end

the view of Home has this part on the code:

      Nome
      Preco
      Fornecedor

    <% @produtos.each do |produto| %>

          <%= produto.nome %>
          <%= produto.preco %>
          <%= produto.fornecedor %>
          <%= link_to 'Show', produto %>
          <%= link_to 'Edit', edit_produto_path(produto) %>
          <%= link_to 'Destroy', produto, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

and i'm getting this error:

undefined method `each' for nil:NilClass in <% @produtos.each do
  |produto| %>

My routes:

Rails.application.routes.draw do

  root 'login#new'
  get 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end

Login controller (which is the root route):

class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/index", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end

  end
  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end

Body:
Make your routes, methods, views match:

# config/routes.rb
get '/home/inicio', to: 'home#index'

# app/controllers/home_controller.rb
def index
  @produtos = Produto.all
end

# app/views/home/index.html.erb
<% @produtos.each do |produto| %>

As you see it changes just the URI but you must make reference to your index method in both controller method and view name.

If you use render 'inicio' then you must use the inicio.html.erb view instead index.html.erb.


问:
Linux c++ error: undefined reference to 'dlopen'
I work in Linux with C++ (Eclipse), and want to use a library.
Eclipse shows me an error:

```<code>undefined reference to 'dlopen'
</code>```

Do you know a solution?

Here is my code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char **argv) {
    void *handle;
    double (*desk)(char*);
    char *error;

    handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    desk= dlsym(handle, "Apply");

    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    dlclose(handle);
}
</code>```

答:
```<code> $gcc -o program program.c -l <library_to_resolve_program.c's_unresolved_symbols>
</code>```

A good description of why the placement of -l dl matters

But there's also a pretty succinct explanation in the docs
From $man gcc

```<code>   -llibrary
   -l library
       Search the library named library when linking.  (The second
       alternative with the library as a separate argument is only for POSIX
       compliance and is not recommended.)
</code>```

```<code>       It makes a difference where in the command you write this option; the
       linker searches and processes libraries and object files in the order
       they are specified.  Thus, foo.o -lz bar.o searches library z after
       file foo.o but before bar.o.  If bar.o refers to functions in z,
       those functions may not be loaded.
</code>```

Body:
I work in Linux with C++ (Eclipse), and want to use a library.
Eclipse shows me an error:

undefined reference to 'dlopen'

Do you know a solution?

Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char **argv) {
    void *handle;
    double (*desk)(char*);
    char *error;

    handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    desk= dlsym(handle, "Apply");

    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    dlclose(handle);
}

Body:
 $gcc -o program program.c -l <library_to_resolve_program.c's_unresolved_symbols>

A good description of why the placement of -l dl matters

But there's also a pretty succinct explanation in the docs
From $man gcc

   -llibrary
   -l library
       Search the library named library when linking.  (The second
       alternative with the library as a separate argument is only for POSIX
       compliance and is not recommended.)

       It makes a difference where in the command you write this option; the
       linker searches and processes libraries and object files in the order
       they are specified.  Thus, foo.o -lz bar.o searches library z after
       file foo.o but before bar.o.  If bar.o refers to functions in z,
       those functions may not be loaded.


问:
How to parse rss-feeds / xml in a shell script
I'd like to parse rss feeds and download podcasts on my ReadyNas which is running 24/7 anyway.

So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files.

What is the best way to do the parsing?

Thanks!

答:
I read about XMLStartlet here and there

But is there a port to ReadyNas NV+ available?

OwnerDisplayName: Oli

ContentLicense: CC BY-SA 2.5


答:
At this line :

```<code>b = false;
if (b) System.out.println("This code is not ok.");
</code>```

b is false. So the if statement is false and the instruction in the if block is not executed, no matter the content of the String !

Title: boolean example in Schildt book

Body:
At this line :

b = false;
if (b) System.out.println("This code is not ok.");

b is false. So the if statement is false and the instruction in the if block is not executed, no matter the content of the String !


问:
Terraform - resource repeated multiple times
I have a terraform plan which consists of multiple aws_sqs_queue resources which more of less share the same config. Before I remove any repeating configs and use variables I wanted to run terraform plan to see if it works. However I keep running into -

```<code>module root: 1 error(s) occurred:

* data.template_file.ep_match_result_queues: resource repeated multiple times
</code>```

Ive tried googling but there is not much information available. Any help will be much appreciated. My plan looks like this: (ignore extra braces, typos as this is just a skeleton to give you a general idea how the plan is sturctured):

```<code>data "template_file" "ep_match_result_queues" {
  template = "${var.namespace}-sm-ep"
}

resource "aws_sns_topic" "sns_topic_name" {
  name            = "ep_sm_match_result_topic${var.environment}"
  display_name    = ""
  policy          = <<POLICY
{
 #policy
}

resource "aws_sqs_queue" "queue1" {
 #config
}

resource "aws_sqs_queue" "queue2" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue3" {
#config
}

resource "aws_sqs_queue" "queue4" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue5" {
 #config
}

resource "aws_sqs_queue" "queue6" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue7" {
 #config
}

resource "aws_sqs_queue" "queue8" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue_policy" "queue_policy" {
  queue_url = [ ... ]
  policy    = "${data.aws_iam_policy_document.match_result_queues_policy.json}"
}

data "aws_iam_policy_document" "match_result_queues_policy" {
 #policy
}
</code>```

答: I think that error means you have declared the resource with the same name more than once, that's in the same tf file or in another tf file in the same directory where you are running terraform.</p>

Body:
I have a terraform plan which consists of multiple aws_sqs_queue resources which more of less share the same config. Before I remove any repeating configs and use variables I wanted to run terraform plan to see if it works. However I keep running into -

module root: 1 error(s) occurred:

* data.template_file.ep_match_result_queues: resource repeated multiple times

Ive tried googling but there is not much information available. Any help will be much appreciated. My plan looks like this: (ignore extra braces, typos as this is just a skeleton to give you a general idea how the plan is sturctured):

data "template_file" "ep_match_result_queues" {
  template = "${var.namespace}-sm-ep"
}

resource "aws_sns_topic" "sns_topic_name" {
  name            = "ep_sm_match_result_topic${var.environment}"
  display_name    = ""
  policy          = <<POLICY
{
 #policy
}

resource "aws_sqs_queue" "queue1" {
 #config
}

resource "aws_sqs_queue" "queue2" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue3" {
#config
}

resource "aws_sqs_queue" "queue4" {
 #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue5" {
 #config
}

resource "aws_sqs_queue" "queue6" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue" "queue7" {
 #config
}

resource "aws_sqs_queue" "queue8" {
  #config

    redrive_policy             = <<POLICY
{
 #policy
}
POLICY
}

resource "aws_sqs_queue_policy" "queue_policy" {
  queue_url = [ ... ]
  policy    = "${data.aws_iam_policy_document.match_result_queues_policy.json}"
}

data "aws_iam_policy_document" "match_result_queues_policy" {
 #policy
}


问:
UWP Compilation in Release fails
I've updated Visual Studio 2015 to Update 2. And now .NET Native compiler stops working every time I compile the project. (It works just great for the blank app).

STARTPROCESSTASK : error : Internal compiler Error

error : Method 'A(object)' will always throw an exception due to the missing method 'B'. There may have been a missing assembly.

error : ILT0005: 'C:\Program Files (x86)\MSBuild\Microsoft.NetNative\x86\ilc\Tools\nutc_driver.exe @"C:\Projects\x86\Release\ilc\intermediate\MDIL\App5.rsp"' returned exit code -1073741819

That's actually true that some assemblies are missing but I have a lot of some legacy stuff and I will not get those assemblies. Before Update 2 compiler gave me a warning instead of error and the app ran without any issues.

答:
I had the same problem in Visual Studio 2017. (our project was originally created in Visual Studio 2015).

This is how I resolved it:

Right Click on UWP project -> Properties -> Build.

Uncheck Compile with .Net Native tool chain.

Title: UWP Compilation in Release fails


问:
How do you inject named field parameters in Kotlin with Dagger 2?
I have a named parameter in Java that I inject in the following way:

```<code>@Inject @Named("io")
Scheduler ioScheduler;
</code>```

How do I do this in Kotlin?

答:
The following is the form for Dagger2 & Kotlin for named fields.

```<code> @field:[Inject Named("io")]
 lateinit var ioScheduler: Scheduler
</code>```

see also:

Late initialized properties

Kotlin annotation syntax

Annotation use-site targets

Body:
I have a named parameter in Java that I inject in the following way:

@Inject @Named("io")
Scheduler ioScheduler;

How do I do this in Kotlin?

Body:
The following is the form for Dagger2 & Kotlin for named fields.

 @field:[Inject Named("io")]
 lateinit var ioScheduler: Scheduler

see also:

Late initialized properties

Kotlin annotation syntax

Annotation use-site targets


问:
DNS name from IP address
I need to create a list of IP addresses and DNS names. I
   am trying to get DNS names from IP addresses. I have tried two ways:

try/catch but it ends afterwards.

Without and it just outputs DNS names that I can't relate to the IP addresses.

Here's what I have so far:

```<code>#try {
 Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object
{([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt}
# }
 # catch {
 if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt }
# }
</code>```

答:
You might want to try the other solutions offered here, but here are some things you might want to think about.

First, I'd recommend not putting the try{}catch{} around the whole of the first command. If you are looping through data and just one of them causes an exception, you risk not completing the task. Put the try{}catch{} around just the "risky" line of code:

```<code>Get-Content C:\Users\pintose\Documents\IP_Address.txt | Foreach-Object {
  try {
    ([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt
  }
  catch {
    if ($_.Exception.Message -like "*The requested name is valid*") {
      Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt
    }
  }
}
</code>```

When you catch the exception, you only write to the text file in the case that "the requested name is valid" (do you mean invalid?). You never write anything to the file otherwise. Thus, going back to your original code:

IF there is an exception caused by ANY of the IP addresses

AND the exception is NOT "the requested name is valid" (which I think might be a typo?)

THEN no error gets written to the file and the script ends without necessarily completing all the IP addresses.

Other things:

You use two methods to write to the file: >> and Out-File. Probably better to use the PowerShell cmdlet but with the -Append switch to ensure you append to the end of the file:

```<code>([system.net.dns]::GetHostByAddress($_)).hostname | Out-File C:\Users\user\Documents\hostname.txt -Append

Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt -Append
</code>```

@restless1987 has suggested a way to ensure you write both the IP address and the hostname (if determined) to the output file. I'd have a look at that to work out what is going on.

My final tip would be to be wary of reading in from .txt files with Get-Content. They often have trailing (blank) lines and you might want to try to ignore such blanks. Probably not a big issue in this case as it will just mean a failed DNS attempt, but I have seen such things wreak havoc on every mailbox in a (very) large company when used with other commands.

Title: DNS name from IP address

Body:
I need to create a list of IP addresses and DNS names. I
   am trying to get DNS names from IP addresses. I have tried two ways:

try/catch but it ends afterwards.

Without and it just outputs DNS names that I can't relate to the IP addresses.

Here's what I have so far:

#try {
 Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object
{([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt}
# }
 # catch {
 if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt }
# }

Body:
You might want to try the other solutions offered here, but here are some things you might want to think about.

First, I'd recommend not putting the try{}catch{} around the whole of the first command. If you are looping through data and just one of them causes an exception, you risk not completing the task. Put the try{}catch{} around just the "risky" line of code:

Get-Content C:\Users\pintose\Documents\IP_Address.txt | Foreach-Object {
  try {
    ([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt
  }
  catch {
    if ($_.Exception.Message -like "*The requested name is valid*") {
      Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt
    }
  }
}

When you catch the exception, you only write to the text file in the case that "the requested name is valid" (do you mean invalid?). You never write anything to the file otherwise. Thus, going back to your original code:

IF there is an exception caused by ANY of the IP addresses

AND the exception is NOT "the requested name is valid" (which I think might be a typo?)

THEN no error gets written to the file and the script ends without necessarily completing all the IP addresses.

Other things:

You use two methods to write to the file: >> and Out-File. Probably better to use the PowerShell cmdlet but with the -Append switch to ensure you append to the end of the file:

([system.net.dns]::GetHostByAddress($_)).hostname | Out-File C:\Users\user\Documents\hostname.txt -Append

Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt -Append

@restless1987 has suggested a way to ensure you write both the IP address and the hostname (if determined) to the output file. I'd have a look at that to work out what is going on.

My final tip would be to be wary of reading in from .txt files with Get-Content. They often have trailing (blank) lines and you might want to try to ignore such blanks. Probably not a big issue in this case as it will just mean a failed DNS attempt, but I have seen such things wreak havoc on every mailbox in a (very) large company when used with other commands.


问:
How to csv-import cyrillic text into latin1-swedish-ci encoded table in PhpMyAdmin?
How to csv-import cyrillic text into latin1-swedish-ci encoded table in PhpMyAdmin?

My problem:

Everything works fine with front-end. But now I need to import ~1000 rows in a table. I'd prefer UTF-8, but the table is in latin1-swedish-ci. When I even prepare my CSV in latin1-swedish-ci, there is no such option in the PhpMyAdmin import settings.

答:
First, keep in mind that the encoding of the file and the CHARACTER SET of the column/table do not need to be the same.

Second, latin1 cannot represent Cyrillic.  Perhaps cp1251 has what you need.  Caution:  I think it can handle only English and Russian, not the rest of Europe.

UTF-8 (MySQL's utf8mb4) is the way to go.  This will involve 2 bytes per Cyrillic character.

Before mangling things worse, find out what the encoding of your data is.  The HEX for Д (Capital DE):

```<code>C4 -- in cp1251 aka ISO/IEC 8859-5
D094 -- in utf8 or utf8mb4
</code>```

Body:
First, keep in mind that the encoding of the file and the CHARACTER SET of the column/table do not need to be the same.

Second, latin1 cannot represent Cyrillic.  Perhaps cp1251 has what you need.  Caution:  I think it can handle only English and Russian, not the rest of Europe.

UTF-8 (MySQL's utf8mb4) is the way to go.  This will involve 2 bytes per Cyrillic character.

Before mangling things worse, find out what the encoding of your data is.  The HEX for Д (Capital DE):

C4 -- in cp1251 aka ISO/IEC 8859-5
D094 -- in utf8 or utf8mb4


问:
Is there any way to use ctags with ruby namespacing?
When I have classes ModuleA::Class1 with method test_method and ModuleB::Class2 with test_method as well, and somewhere in code I have ModuleB::Class2.test_method and click Ctrl-] on test_method it jumps to wrong test_method definition from ModuleA::Class1.

Is there any way to make ctags work with Ruby namespaces?

答:
Maybe you could give ripper-tags a try, but I don't have any experience with it.

What I do usually is, if Ctrl+] doesn't open the correct tag, I just repeat :tnext until I reach the correct one.

In case you find that tiring, you could use vim-unimpaired to have the convenient [t and ]t or manually map

```<code>nnoremap ]t :tnext<cr>
nnoremap [t :tprevious<cr>
</code>```

Body:
Maybe you could give ripper-tags a try, but I don't have any experience with it.

What I do usually is, if Ctrl+] doesn't open the correct tag, I just repeat :tnext until I reach the correct one.

In case you find that tiring, you could use vim-unimpaired to have the convenient [t and ]t or manually map

nnoremap ]t :tnext<cr>
nnoremap [t :tprevious<cr>


问:
How do i show an attribute of an object, rather than the object itself, in an accessor field in django-tables2?
I have a table of Compounds with a name field, which is linked to another table called Names.

When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object.

models.py:

```<code>class Compound(models.Model):

    drug_id = models.AutoField(primary_key=True)

    drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT)
    # for flagging problematic data
    flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT)
    # is a cocktail
    is_combination = models.BooleanField()

    class Meta:
        db_table = 'compounds'
</code>```

tables.py:

```<code>import django_tables2 as tables
from .models import Compound

class FimTable(tables.Table):

    drug_name = tables.Column(accessor='name.name')

    class Meta:
        model = Compound
        attrs = {'class': 'paleblue table table-condensed table-vertical-center'}
        fields = ('drug_id', 'drug_name')
        sequence = ('drug_id', 'drug_name')
        order_by = ('drug_id')
</code>```

views.py:

```<code>@csrf_protect
@login_required  # redirects to login page if user.is_active is false
def render_fim_table(request):

    table = FimTable(Compound.objects.all())

    table.paginate(page=request.GET.get('page', 1), per_page=20)

    response = render(request, 'fim_table.html', {'table': table})
    return response
</code>```

Result:

答:
you can also use...</p>

```<code>class Name(model.Model):
      ...
      def __unicode__(self):
          return self.name
</code>```

Body:
I have a table of Compounds with a name field, which is linked to another table called Names.

When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object.

models.py:

class Compound(models.Model):

    drug_id = models.AutoField(primary_key=True)

    drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT)
    # for flagging problematic data
    flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT)
    # is a cocktail
    is_combination = models.BooleanField()

    class Meta:
        db_table = 'compounds'

tables.py:

import django_tables2 as tables
from .models import Compound

class FimTable(tables.Table):

    drug_name = tables.Column(accessor='name.name')

    class Meta:
        model = Compound
        attrs = {'class': 'paleblue table table-condensed table-vertical-center'}
        fields = ('drug_id', 'drug_name')
        sequence = ('drug_id', 'drug_name')
        order_by = ('drug_id')

views.py:

@csrf_protect
@login_required  # redirects to login page if user.is_active is false
def render_fim_table(request):

    table = FimTable(Compound.objects.all())

    table.paginate(page=request.GET.get('page', 1), per_page=20)

    response = render(request, 'fim_table.html', {'table': table})
    return response

Result:

Body:
you can also use...

class Name(model.Model):
      ...
      def __unicode__(self):
          return self.name


问:
Fatal Error Unable to attach to base address
When I try to do a composer update, it appears the following message: "Fatal Error Unable to attach to base address"
I'm using symfony 3

I hope you could help me. Thanks

Error image

答:
for example, in your appBundle/Controler/DefaultController

just remove arguments passed in array

from:

```<code>namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {

        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
        ]);
    }
}
</code>```

to:

```<code>namespace AppBundle\Controller;
</code>```

...all use statements

```<code>class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {

        return $this->render('default/index.html.twig', [

        ]);
    }
}
</code>```

Body:
for example, in your appBundle/Controler/DefaultController

just remove arguments passed in array

from:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {

        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
        ]);
    }
}

to:

namespace AppBundle\Controller;

...all use statements

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {

        return $this->render('default/index.html.twig', [

        ]);
    }
}


问:
How to thru char into TextBox?
I have some TextBox on focus ( cursor is blinking on him ).
Now, from other usercontrol ( that contain buttons ) i want to send event that will insert char into the TextBox when pressing any of the buttons that are on the usercontrol.

This need to be without lose the focus from the TextBox ... ( blinking cursor on the TextBox )

How can i do it ?
( i try to raise key down event - but its does not work )

答:
```<code>        <StackPanel>
            <TextBox Name="MainTextBox" />
            <Button Content="A"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="B"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="C"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="D"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="E"
                    Focusable="False"
                    Click="Button_Click" />
        </StackPanel>
</code>```

Code:

```<code>    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MainTextBox.Text += (sender as Button).Content.ToString();
    }
</code>```

Title: How to thru char into TextBox?

Body:
        <StackPanel>
            <TextBox Name="MainTextBox" />
            <Button Content="A"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="B"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="C"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="D"
                    Focusable="False"
                    Click="Button_Click" />
            <Button Content="E"
                    Focusable="False"
                    Click="Button_Click" />
        </StackPanel>

Code:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MainTextBox.Text += (sender as Button).Content.ToString();
    }


问:
Implement OnClickListener on FastAdapter implementing IItem
I am learning to use FastAdapter with Realm. Here is my model and this is how I implement OnClick in a Fragment:

```<code>fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<ProductsModel>() {
    @Override
    public boolean onClick(View v, IAdapter<ProductsModel> adapter, ProductsModel item, int position) {
        Toast.makeText(getActivity(), "got it", Toast.LENGTH_SHORT).show();
        return false;
    }
});
</code>```

But I don't get the Toast appearing. Can anybody please tell me what am I missing?

Update: Here is my model

```<code>public class ProductsModel extends RealmObject implements IItem<ProductsModel, ProductsModel.ViewHolder>{
    @PrimaryKey
    private String code;

    private String name, generic, packSize;
    private int quantity, status;

    //variables needed for adapter
    protected boolean isSelected = false; // defines if the item is selected

    @Ignore
    protected Object tag;// defines if this item is isSelectable

    @Ignore
    protected boolean isSelectable = true;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPackSize() {
        return packSize;
    }

    public void setPackSize(String packSize) {
        this.packSize = packSize;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getGeneric() {
        return generic;
    }

    public void setGeneric(String generic) {
        this.generic = generic;
    }

    @Override
    public Object getTag() {
        return tag;
    }

    @Override
    public ProductsModel withTag(Object tag) {
        this.tag = tag;
        return this;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }

    @Override
    public ProductsModel withEnabled(boolean enabled) {
        return null;
    }

    @Override
    public boolean isSelected() {
        return isSelected;
    }

    @Override
    public ProductsModel withSetSelected(boolean selected) {
        return null;
    }

    @Override
    public boolean isSelectable() {
        return isSelectable;
    }

    @Override
    public ProductsModel withSelectable(boolean selectable) {
        this.isSelectable = selectable;
        return this;
    }

    @Override
    public int getType() {
        return R.id.pwdsList;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.item_product;
    }

    @Override
    public View generateView(Context ctx) {
        ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), null, false));
        bindView(viewHolder, Collections.EMPTY_LIST);
        return viewHolder.itemView;
    }

    @Override
    public View generateView(Context ctx, ViewGroup parent) {
        ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false));
        bindView(viewHolder, Collections.EMPTY_LIST);
        return null;
    }

    private ViewHolder getViewHolder(View view) {
        return new ViewHolder(view);
    }

    @Override
    public ViewHolder getViewHolder(ViewGroup parent) {
        return getViewHolder(LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false));
    }

    @Override
    public void bindView(ViewHolder holder, List<Object> payloads) {
        holder.name.setText(name + " " + packSize + " (" + quantity + ")");
        holder.generic.setText(generic);
        holder.itemView.setSelected(isSelected());
    }

    @Override
    public void unbindView(ViewHolder holder) {
        holder.name.setText(null);
        holder.generic.setText(null);
    }

    @Override
    public boolean equals(int id) {
        return false;
    }

    @Override
    public ProductsModel withIdentifier(long identifier) {
        return null;
    }

    @Override
    public long getIdentifier() {
        return 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{

        ATextView name, generic;

        public ViewHolder(View itemView) {
            super(itemView);

            name = (ATextView) itemView.findViewById(R.id.name);
            generic = (ATextView) itemView.findViewById(R.id.generic);
        }
    }
}
</code>```

答:
Your item is not enabled which results in the click event not being forwarded. Just change your code to return isEnabled=true

```<code>@Override
public boolean isEnabled() {
    return true;
}
</code>```

Body:
I am learning to use FastAdapter with Realm. Here is my model and this is how I implement OnClick in a Fragment:

fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<ProductsModel>() {
    @Override
    public boolean onClick(View v, IAdapter<ProductsModel> adapter, ProductsModel item, int position) {
        Toast.makeText(getActivity(), "got it", Toast.LENGTH_SHORT).show();
        return false;
    }
});

But I don't get the Toast appearing. Can anybody please tell me what am I missing?

Update: Here is my model

public class ProductsModel extends RealmObject implements IItem<ProductsModel, ProductsModel.ViewHolder>{
    @PrimaryKey
    private String code;

    private String name, generic, packSize;
    private int quantity, status;

    //variables needed for adapter
    protected boolean isSelected = false; // defines if the item is selected

    @Ignore
    protected Object tag;// defines if this item is isSelectable

    @Ignore
    protected boolean isSelectable = true;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPackSize() {
        return packSize;
    }

    public void setPackSize(String packSize) {
        this.packSize = packSize;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getGeneric() {
        return generic;
    }

    public void setGeneric(String generic) {
        this.generic = generic;
    }

    @Override
    public Object getTag() {
        return tag;
    }

    @Override
    public ProductsModel withTag(Object tag) {
        this.tag = tag;
        return this;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }

    @Override
    public ProductsModel withEnabled(boolean enabled) {
        return null;
    }

    @Override
    public boolean isSelected() {
        return isSelected;
    }

    @Override
    public ProductsModel withSetSelected(boolean selected) {
        return null;
    }

    @Override
    public boolean isSelectable() {
        return isSelectable;
    }

    @Override
    public ProductsModel withSelectable(boolean selectable) {
        this.isSelectable = selectable;
        return this;
    }

    @Override
    public int getType() {
        return R.id.pwdsList;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.item_product;
    }

    @Override
    public View generateView(Context ctx) {
        ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), null, false));
        bindView(viewHolder, Collections.EMPTY_LIST);
        return viewHolder.itemView;
    }

    @Override
    public View generateView(Context ctx, ViewGroup parent) {
        ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false));
        bindView(viewHolder, Collections.EMPTY_LIST);
        return null;
    }

    private ViewHolder getViewHolder(View view) {
        return new ViewHolder(view);
    }

    @Override
    public ViewHolder getViewHolder(ViewGroup parent) {
        return getViewHolder(LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false));
    }

    @Override
    public void bindView(ViewHolder holder, List<Object> payloads) {
        holder.name.setText(name + " " + packSize + " (" + quantity + ")");
        holder.generic.setText(generic);
        holder.itemView.setSelected(isSelected());
    }

    @Override
    public void unbindView(ViewHolder holder) {
        holder.name.setText(null);
        holder.generic.setText(null);
    }

    @Override
    public boolean equals(int id) {
        return false;
    }

    @Override
    public ProductsModel withIdentifier(long identifier) {
        return null;
    }

    @Override
    public long getIdentifier() {
        return 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{

        ATextView name, generic;

        public ViewHolder(View itemView) {
            super(itemView);

            name = (ATextView) itemView.findViewById(R.id.name);
            generic = (ATextView) itemView.findViewById(R.id.generic);
        }
    }
}

Body:
Your item is not enabled which results in the click event not being forwarded. Just change your code to return isEnabled=true

@Override
public boolean isEnabled() {
    return true;
}