问:
BeanCreationException: Component declared but not exist in registry
I started learning camel recently and trying out some sample application. I have encountered this error while loading application context as part of testcase run,

... 45 more Caused by: org.apache.camel.FailedToCreateRouteException:
  Failed to create route route2 at: >>>
  Bean[ref:orderItemMessageTranslator method: transformOrderItemMessage]
  <<< in route: Route(route2)[[From[sql:select id from orders."order"
  where ... because of No bean could be found in the registry for:
  orderItemMessageTranslator    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:910)
    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:175)
    at
  org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:780)
    at
  org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:2068)
    at
  org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1816)
    at
  org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1683)
    at
  org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
    at
  org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1651)
    at
  org.apache.camel.spring.SpringCamelContext.maybeStart(SpringCamelContext.java:254)
    at
  org.apache.camel.spring.SpringCamelContext.afterPropertiesSet(SpringCamelContext.java:106)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 60 more Caused by: org.apache.camel.NoSuchBeanException: No bean
  could be found in the registry for: orderItemMessageTranslator    at
  org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:87)
    at
  org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:222)
    at
  org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:499)
    at
  org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:212)
    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:907)
    ... 71 more

Tried my best by googling and looking at stack overflow to resolve but my effort went in vain. Need some help.

Here is my folder structure

Below are some related files used w.r.t to my sample application for your reference,

```<code>Application.java:
---------------------
@Configuration
@ComponentScan(basePackages = "com.pluralsight.orderfulfillment")
@PropertySource("classpath:order-fulfillment.properties")
public class Application {

}

IntegrationConfig.java:
-------------------------
@Configuration
public class IntegrationConfig extends CamelConfiguration {

    @Inject
    private Environment environment;

    @Inject
    private DataSource datasource;

    @Bean
    public SqlComponent sql() {
        SqlComponent sqlComponent = new SqlComponent();
        sqlComponent.setDataSource(datasource);
        return sqlComponent;
    }

    @Bean
    public RouteBuilder newWebsiteOrderRoute() {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("sql:"
                    + "select id from orders.\"order\" where status = '"
                    + OrderStatus.NEW.getCode()
                    + "'"
                    + "?"
                    + "consumer.onConsume=update orders.\"order\" set status = '"
                    + OrderStatus.PROCESSING.getCode()
                    + "' where id=:#id")
                .beanRef("orderItemMessageTranslator", "transformOrderItemMessage")
                .to("log:com.pluralsight.orderfulfillment.order?level=INFO");

            }

        };
    }
}

Pom.xml:
---------
..
..
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring-javaconfig</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-sql</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-spring</artifactId>
            <version>2.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <!-- SPRING FRAMEWORK -->

        <!-- Spring framework core dependency minus commons logging in favor of SLF4J -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.4.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Spring aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <!-- Spring JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <!-- Spring Data JPA -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.5.2.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-aop</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
..
..
</code>```

Thanks in advance for help.

答:
Have you decorated the OrderItemMessageTranslator with the @Component annotation?

Instead of .beanRef(..), try the .bean(..) builder method from the Java DSL(http://camel.apache.org/bean.html#Bean-JavaDSLbeansyntax):

```<code>.bean(new OrderItemMessageTranslator(), "transformOrderItemMessage")
</code>```

UPDATE:

If you would like to use the .beanRef(..) method then try to add @ComponentScan(..) to the IntegrationConfig which extends CamelConfiguration.

Like this: http://camel.apache.org/spring-java-config.html#SpringJavaConfig-Configuration

Body:
I started learning camel recently and trying out some sample application. I have encountered this error while loading application context as part of testcase run,

... 45 more Caused by: org.apache.camel.FailedToCreateRouteException:
  Failed to create route route2 at: >>>
  Bean[ref:orderItemMessageTranslator method: transformOrderItemMessage]
  <<< in route: Route(route2)[[From[sql:select id from orders."order"
  where ... because of No bean could be found in the registry for:
  orderItemMessageTranslator    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:910)
    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:175)
    at
  org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:780)
    at
  org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:2068)
    at
  org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1816)
    at
  org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1683)
    at
  org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
    at
  org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1651)
    at
  org.apache.camel.spring.SpringCamelContext.maybeStart(SpringCamelContext.java:254)
    at
  org.apache.camel.spring.SpringCamelContext.afterPropertiesSet(SpringCamelContext.java:106)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 60 more Caused by: org.apache.camel.NoSuchBeanException: No bean
  could be found in the registry for: orderItemMessageTranslator    at
  org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:87)
    at
  org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:222)
    at
  org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:499)
    at
  org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:212)
    at
  org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:907)
    ... 71 more

Tried my best by googling and looking at stack overflow to resolve but my effort went in vain. Need some help.

Here is my folder structure

Below are some related files used w.r.t to my sample application for your reference,

Application.java:
---------------------
@Configuration
@ComponentScan(basePackages = "com.pluralsight.orderfulfillment")
@PropertySource("classpath:order-fulfillment.properties")
public class Application {

}

IntegrationConfig.java:
-------------------------
@Configuration
public class IntegrationConfig extends CamelConfiguration {

    @Inject
    private Environment environment;

    @Inject
    private DataSource datasource;

    @Bean
    public SqlComponent sql() {
        SqlComponent sqlComponent = new SqlComponent();
        sqlComponent.setDataSource(datasource);
        return sqlComponent;
    }

    @Bean
    public RouteBuilder newWebsiteOrderRoute() {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("sql:"
                    + "select id from orders.\"order\" where status = '"
                    + OrderStatus.NEW.getCode()
                    + "'"
                    + "?"
                    + "consumer.onConsume=update orders.\"order\" set status = '"
                    + OrderStatus.PROCESSING.getCode()
                    + "' where id=:#id")
                .beanRef("orderItemMessageTranslator", "transformOrderItemMessage")
                .to("log:com.pluralsight.orderfulfillment.order?level=INFO");

            }

        };
    }
}

Pom.xml:
---------
..
..
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring-javaconfig</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-sql</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-spring</artifactId>
            <version>2.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.4.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.5.2.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-aop</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
..
..

Thanks in advance for help.

Body:
Have you decorated the OrderItemMessageTranslator with the @Component annotation?

Instead of .beanRef(..), try the .bean(..) builder method from the Java DSL(http://camel.apache.org/bean.html#Bean-JavaDSLbeansyntax):

.bean(new OrderItemMessageTranslator(), "transformOrderItemMessage")

UPDATE:

If you would like to use the .beanRef(..) method then try to add @ComponentScan(..) to the IntegrationConfig which extends CamelConfiguration.

Like this: http://camel.apache.org/spring-java-config.html#SpringJavaConfig-Configuration


来源: stackexchange

问:
Latitude and Longitude showing as 0 in Android
```<code>  ************* TrackGPS.java *****************************

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;

    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.widget.Toast;

    /**
     * Created by ANQ on 8/8/2016.
     */

    public class TrackGPS extends Service implements LocationListener {

        private final Context mContext;

        boolean checkGPS = false;

        boolean checkNetwork = false;

        boolean canGetLocation = false;

        Location loc;
        double latitude;
        double longitude;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
        protected LocationManager locationManager;

        public TrackGPS(Context mContext) {
            this.mContext = mContext;
            getLocation();
        }

        private Location getLocation() {

            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                checkGPS = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                checkNetwork = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!checkGPS && !checkNetwork) {
                    Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (checkNetwork) {
                        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Network", "Network");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                            }

                            if (loc != null) {
                                latitude = loc.getLatitude();
                                longitude = loc.getLongitude();
                            }
                        }
                        catch(SecurityException e){

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (checkGPS) {
                    Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
                    if (loc == null) {
                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (loc != null) {
                                    latitude = loc.getLatitude();
                                    longitude = loc.getLongitude();
                                }
                            }
                        } catch (SecurityException e) {

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return loc;
        }

        public double getLongitude() {
            if (loc != null) {
                longitude = loc.getLongitude();
            }
            return longitude;
        }

        public double getLatitude() {
            if (loc != null) {
                latitude = loc.getLatitude();
            }
            return latitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            alertDialog.setTitle("GPS Not Enabled");

            alertDialog.setMessage("Do you wants to turn On GPS");

            alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            alertDialog.show();
        }

        public void stopUsingGPS() {
            if (locationManager != null) {

                locationManager.removeUpdates(TrackGPS.this);
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

************* MainActivity.java ****************

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        private Button b_get;
        private TrackGPS gps;
        double longitude;
        double latitude;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b_get = (Button)findViewById(R.id.get);

            b_get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gps = new TrackGPS(MainActivity.this);

                    if(gps.canGetLocation()){

                        longitude = gps.getLongitude();
                        latitude = gps .getLatitude();

                        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                        gps.showSettingsAlert();
                    }

                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            gps.stopUsingGPS();
        }
    }
</code>```

When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.

答:
Here is the background service to detect current location at time interval

```<code>import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

@SuppressWarnings("MissingPermission")
public class LocationBackGroundService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationBackGroundService";
    private static final long INTERVAL = 10;
    private static final long FASTEST_INTERVAL = 10;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    Context mCOntext;

    public void LocationBackGroundService(Context mContext) {
        this.mCOntext = mContext;
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mGoogleApiClient.connect();
    }

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

        if (!isGooglePlayServicesAvailable()) {

        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }

    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            return false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @SuppressLint("LongLogTag")
    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

        Toast.makeText(this,"OnConnection Suspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"OnConnection Failed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        if (null != mCurrentLocation) {
            mCurrentLocation = location;
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());

            ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LATITUDE, lat);
            ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LONGTITUDE, lng);
            System.out.println("First Condition Hit");
            System.out.println("Lat::-- " + lat + "\n" + "LONG::--" + lng);
        }

        System.out.println("Lat::-- " + location.getLatitude() + "\n" + "LONG::--" + location.getLongitude());
    }
}
</code>```

Put this code in seperate java file named LocationBackGroundService.java and call it in your MainActivity like this startService(new Intent(this, LocationBackGroundService.class)); and don't forget to add it in menifest like this <service android:name="LocationBackGroundService"></service>

ContentLicense: CC BY-SA 3.0

Body:
  ************* TrackGPS.java *****************************

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;

    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.widget.Toast;

    /**
     * Created by ANQ on 8/8/2016.
     */

    public class TrackGPS extends Service implements LocationListener {

        private final Context mContext;

        boolean checkGPS = false;

        boolean checkNetwork = false;

        boolean canGetLocation = false;

        Location loc;
        double latitude;
        double longitude;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
        protected LocationManager locationManager;

        public TrackGPS(Context mContext) {
            this.mContext = mContext;
            getLocation();
        }

        private Location getLocation() {

            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                checkGPS = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                checkNetwork = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!checkGPS && !checkNetwork) {
                    Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (checkNetwork) {
                        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Network", "Network");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                            }

                            if (loc != null) {
                                latitude = loc.getLatitude();
                                longitude = loc.getLongitude();
                            }
                        }
                        catch(SecurityException e){

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (checkGPS) {
                    Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
                    if (loc == null) {
                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (loc != null) {
                                    latitude = loc.getLatitude();
                                    longitude = loc.getLongitude();
                                }
                            }
                        } catch (SecurityException e) {

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return loc;
        }

        public double getLongitude() {
            if (loc != null) {
                longitude = loc.getLongitude();
            }
            return longitude;
        }

        public double getLatitude() {
            if (loc != null) {
                latitude = loc.getLatitude();
            }
            return latitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            alertDialog.setTitle("GPS Not Enabled");

            alertDialog.setMessage("Do you wants to turn On GPS");

            alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            alertDialog.show();
        }

        public void stopUsingGPS() {
            if (locationManager != null) {

                locationManager.removeUpdates(TrackGPS.this);
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

************* MainActivity.java ****************

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        private Button b_get;
        private TrackGPS gps;
        double longitude;
        double latitude;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b_get = (Button)findViewById(R.id.get);

            b_get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gps = new TrackGPS(MainActivity.this);

                    if(gps.canGetLocation()){

                        longitude = gps.getLongitude();
                        latitude = gps .getLatitude();

                        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                        gps.showSettingsAlert();
                    }

                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            gps.stopUsingGPS();
        }
    }

When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.

Body:
Here is the background service to detect current location at time interval

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

@SuppressWarnings("MissingPermission")
public class LocationBackGroundService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationBackGroundService";
    private static final long INTERVAL = 10;
    private static final long FASTEST_INTERVAL = 10;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    Context mCOntext;

    public void LocationBackGroundService(Context mContext) {
        this.mCOntext = mContext;
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mGoogleApiClient.connect();
    }

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

        if (!isGooglePlayServicesAvailable()) {

        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }

    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            return false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @SuppressLint("LongLogTag")
    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

        Toast.makeText(this,"OnConnection Suspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"OnConnection Failed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        if (null != mCurrentLocation) {
            mCurrentLocation = location;
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());

            ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LATITUDE, lat);
            ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LONGTITUDE, lng);
            System.out.println("First Condition Hit");
            System.out.println("Lat::-- " + lat + "\n" + "LONG::--" + lng);
        }

        System.out.println("Lat::-- " + location.getLatitude() + "\n" + "LONG::--" + location.getLongitude());
    }
}

Put this code in seperate java file named LocationBackGroundService.java and call it in your MainActivity like this startService(new Intent(this, LocationBackGroundService.class)); and don't forget to add it in menifest like this <service android:name="LocationBackGroundService"></service>


问:
Adding a solution file to asp.net 1.1 application using Visual Studio 2010
I'm trying to migrate an old asp.net 1.1 application to target the new .net 4.0 framework. There are good guides available on this (https://learn.microsoft.com/en-us/archive/msdn-magazine/2010/september/app-migration-migrate-your-asp-net-1-1-apps-to-visual-studio-2010). However, all approaches start with the assumption that the 1.1 project contains a solution file which one has to open using VS 2010 and go through the conversion wizard.

In my case, the project does not have any solution file, giving me a sort of chicken and egg issue.

Is there a way to add a 1.1 .net soution file with or without VS 2010? Using command line tools? What is so special about a solution file anyway?

答: You might be able to just create a new solution in VS 2010 and then import the 1.1 project into the solution.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Set one ProducesResponseType typeof for several HttpStatusCodes
I am setting the ProducesResponseType so as to have it documented with Swagger.

If the response is succesful (OK => 200), then it produces a IEnumerable.

```<code>[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]
</code>```

But when I get an exception, I catch it, and then generate an object of my custom APIError class. When I populate the object, I can set different HttpStatusCodes, but in the end, what I want is to be able to set that ProducesResponseType is my APIError class for all the remaining HttpStatusCodes. I mean, I can get BadRequest, ServerInternalError, Forbidden, etc, but all are going to have the same response type (ApiError). Is there any way to set this line of code for all the error http codes? Or do I need to set it one by one?

```<code>[ProducesResponseType(typeof(ApiError), ???)]
</code>```

Final result should look like this:

```<code>[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]
[ProducesResponseType(typeof(ApiError), AllFailureHttpCodes)]
</code>```

答:
I fear that's not possible, at least not per action.

The IApiResponseMetadataProvider (see here) only has a single int StatusCode { get; } property defined and it's used for both ProducesAttribute and ProducesResponseTypeAttribute.

However, in your special case you may be able to register it as a global filter though, since the error result should be same on all actions no matter if it's GET, POST, PUT or DELETE.

```<code>services.AddMvc(options =>
{
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 400));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 401));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 409));
});
</code>```

These should then be applied to every action in your MVC/WebAPI application.

Word of warning

However, personally I find this usage wrong, because it would signal that every of your method can handle these type of errors. For example 409 is specifically for conflict, in a WebAPI you use it, when there is an error with updating an resource i.e. when using optimistic concurrency, the record was changed by another user and, hence the version of the record was changed and update failed.

Adding these to every method is just wrong. You should only add a status code if your action really handles this status code. For example, 409 is only suitable with PUT and POST Methods. Where 404 may be suitable for GET and PUT (update), but less suitable for POST (inserts).

This is especially bad, when you use tools such as Swagger to generate Api Docs, then you will just get a wrong documentation. You should look at ProducesResponseType as form of documentation and as such, shouldn't use a too generic approach for it.

Update: ASP.NET Core 2.2

With ASP.NET Core 2.2 the Swagger API support was greatly improved, this also includes convention based response type and codes.

It already comes with a good set of default conventions, but you can also override it and provide your own convention methods.

Body:
I am setting the ProducesResponseType so as to have it documented with Swagger.

If the response is succesful (OK => 200), then it produces a IEnumerable.

[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]

But when I get an exception, I catch it, and then generate an object of my custom APIError class. When I populate the object, I can set different HttpStatusCodes, but in the end, what I want is to be able to set that ProducesResponseType is my APIError class for all the remaining HttpStatusCodes. I mean, I can get BadRequest, ServerInternalError, Forbidden, etc, but all are going to have the same response type (ApiError). Is there any way to set this line of code for all the error http codes? Or do I need to set it one by one?

[ProducesResponseType(typeof(ApiError), ???)]

Final result should look like this:

[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]
[ProducesResponseType(typeof(ApiError), AllFailureHttpCodes)]

Body:
I fear that's not possible, at least not per action.

The IApiResponseMetadataProvider (see here) only has a single int StatusCode { get; } property defined and it's used for both ProducesAttribute and ProducesResponseTypeAttribute.

However, in your special case you may be able to register it as a global filter though, since the error result should be same on all actions no matter if it's GET, POST, PUT or DELETE.

services.AddMvc(options =>
{
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 400));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 401));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 409));
});

These should then be applied to every action in your MVC/WebAPI application.

Word of warning

However, personally I find this usage wrong, because it would signal that every of your method can handle these type of errors. For example 409 is specifically for conflict, in a WebAPI you use it, when there is an error with updating an resource i.e. when using optimistic concurrency, the record was changed by another user and, hence the version of the record was changed and update failed.

Adding these to every method is just wrong. You should only add a status code if your action really handles this status code. For example, 409 is only suitable with PUT and POST Methods. Where 404 may be suitable for GET and PUT (update), but less suitable for POST (inserts).

This is especially bad, when you use tools such as Swagger to generate Api Docs, then you will just get a wrong documentation. You should look at ProducesResponseType as form of documentation and as such, shouldn't use a too generic approach for it.

Update: ASP.NET Core 2.2

With ASP.NET Core 2.2 the Swagger API support was greatly improved, this also includes convention based response type and codes.

It already comes with a good set of default conventions, but you can also override it and provide your own convention methods.


问:
What's the difference between using `.catch(function(error)` and `function(errResponse)` when handing errors from AngularJS promises?
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

```<code>$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});
</code>```

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

My question is, what's the difference between the above menthod and the method shown in the book:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

What's preferred?

答:
The Difference:

If there is some error from service api then function(error) {} will catch it.

But if your success method function(data){} throws some error then only .catch() can caught it.

Example:

```<code>promise().then(function (data) {
  throw new Error('execption from success');
}).catch(function (err) {
  // execption from success caught!!
});

promise().then(function (data) {
  throw new Error('execption from success');
}, function (error) {
  // execption from success : NOT caught
});
</code>```

Read more

The Preferred one :

```<code>promise().then(function (data) {
 // handle data
}, function (error) {
  // handle error from api
}).catch(function (err) {
  // handle error from response.
});
</code>```

Body:
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

My question is, what's the difference between the above menthod and the method shown in the book:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});

What's preferred?

Body:
The Difference:

If there is some error from service api then function(error) {} will catch it.

But if your success method function(data){} throws some error then only .catch() can caught it.

Example:

promise().then(function (data) {
  throw new Error('execption from success');
}).catch(function (err) {
  // execption from success caught!!
});

promise().then(function (data) {
  throw new Error('execption from success');
}, function (error) {
  // execption from success : NOT caught
});

Read more

The Preferred one :

promise().then(function (data) {
 // handle data
}, function (error) {
  // handle error from api
}).catch(function (err) {
  // handle error from response.
});


问:
Cast context of functional interface in lambda expression
There's an example of casting a functional interface (as I understand it) in a cast context: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

```<code> // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...
</code>```

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example?
I've tried this:

```<code>// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)
</code>```

but it works without (ToIntFunction). When do I need the cast context anyway?

Also what is the purpose of mapToInt. This seems to be equivalent:

```<code>dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);
</code>```

答:
Cast context it means that Java Compiler will auto convert functional interface to the target functional interface type,

As (ToIntFunction) d -> d.intValue(), the compiler will auto convert it to: ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue()

so:

```<code>dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)
</code>```

it's equal to:

```<code>ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue();
dlist.stream().mapToInt(toIntFunction).forEach(System.out::println);
</code>```

And for:

```<code>dlist.stream().mapToInt(Double::intValue).forEach(System.out::println);
dlist.stream().map(Double::intValue).forEach(System.out::println);
</code>```

mapToInt's Double::intValue compiler will convert it to ToIntFunction<Double>.

map's Double::intValue compiler will convert it to Function<Double, Int>

Body:
There's an example of casting a functional interface (as I understand it) in a cast context: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

 // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example?
I've tried this:

// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

but it works without (ToIntFunction). When do I need the cast context anyway?

Also what is the purpose of mapToInt. This seems to be equivalent:

dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);

Body:
Cast context it means that Java Compiler will auto convert functional interface to the target functional interface type,

As (ToIntFunction) d -> d.intValue(), the compiler will auto convert it to: ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue()

so:

dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

it's equal to:

ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue();
dlist.stream().mapToInt(toIntFunction).forEach(System.out::println);

And for:

dlist.stream().mapToInt(Double::intValue).forEach(System.out::println);
dlist.stream().map(Double::intValue).forEach(System.out::println);

mapToInt's Double::intValue compiler will convert it to ToIntFunction<Double>.

map's Double::intValue compiler will convert it to Function<Double, Int>


问:
How to write latitude and longitude on image in Swift 3.0?
I followed below code and it is not at all showing the image. what would be the wrong here? I was trying to debug newimage shows nil.

I was unable to resolve it.

```<code>func textOnImage(text: NSString, atPoint: CGPoint,capturedImage:UIImage?) -> UIImage? {

    if let capturedImage = capturedImage {

        // Setup the font specific variables
        let textColor = UIColor.white
        let textFont = UIFont(name: "Helvetica", size: 14)!

        // Setup the image context using the passed image

        let scale = UIScreen.main.scale

        UIGraphicsBeginImageContextWithOptions(capturedImage.size, false, scale)

        // Setup the font attributes that will be later used to dictate how the text should be drawn
        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]

        // Create a point within the space that is as bit as the image

        let rect =  CGRect(x: atPoint.x, y: atPoint.y, width: capturedImage.size.width, height: capturedImage.size.height)

        // Draw the text into an image

        text.draw(in: rect, withAttributes: textFontAttributes)

        // Create a new image out of the images we have created
        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        // End the context now that we have the image we need
        UIGraphicsEndImageContext()
//Pass the image back up to the caller
        return newImage!
    }
    return nil
}
</code>```

答:
Include below line

```<code>capturedImage.draw(in: CGRect(x: 0, y: 0, width: capturedImage.size.width, height:capturedImage.size.height))
</code>```

so your method looks like

```<code> func textOnImage(text: NSString, atPoint: CGPoint,capturedImage:UIImage?) -> UIImage?{

        if let capturedImage = capturedImage{

            // Setup the font specific variables
            let textColor = UIColor.white
            let textFont = UIFont(name: "Helvetica", size: 14)!

            // Setup the image context using the passed image

            let scale = UIScreen.main.scale

            UIGraphicsBeginImageContextWithOptions(capturedImage.size, false, scale)

            // Setup the font attributes that will be later used to dictate how the text should be drawn
            let textFontAttributes = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
                ] as [String : Any]

            capturedImage.draw(in: CGRect(x: 0, y: 0, width: capturedImage.size.width, height:capturedImage.size.height))

            // Create a point within the space that is as bit as the image

            let rect =  CGRect(x: atPoint.x, y: atPoint.y, width: capturedImage.size.width, height: capturedImage.size.height)

            // Draw the text into an image

            text.draw(in: rect, withAttributes: textFontAttributes)

            // Create a new image out of the images we have created
            let newImage = UIGraphicsGetImageFromCurrentImageContext()

            // End the context now that we have the image we need
            UIGraphicsEndImageContext()

            //Pass the image back up to the caller
            return newImage!

        }
        return nil

    }

}
</code>```

Body:
I followed below code and it is not at all showing the image. what would be the wrong here? I was trying to debug newimage shows nil.

I was unable to resolve it.

func textOnImage(text: NSString, atPoint: CGPoint,capturedImage:UIImage?) -> UIImage? {

    if let capturedImage = capturedImage {

        // Setup the font specific variables
        let textColor = UIColor.white
        let textFont = UIFont(name: "Helvetica", size: 14)!

        // Setup the image context using the passed image

        let scale = UIScreen.main.scale

        UIGraphicsBeginImageContextWithOptions(capturedImage.size, false, scale)

        // Setup the font attributes that will be later used to dictate how the text should be drawn
        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]

        // Create a point within the space that is as bit as the image

        let rect =  CGRect(x: atPoint.x, y: atPoint.y, width: capturedImage.size.width, height: capturedImage.size.height)

        // Draw the text into an image

        text.draw(in: rect, withAttributes: textFontAttributes)

        // Create a new image out of the images we have created
        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        // End the context now that we have the image we need
        UIGraphicsEndImageContext()
//Pass the image back up to the caller
        return newImage!
    }
    return nil
}

Body:
Include below line

capturedImage.draw(in: CGRect(x: 0, y: 0, width: capturedImage.size.width, height:capturedImage.size.height))

so your method looks like

 func textOnImage(text: NSString, atPoint: CGPoint,capturedImage:UIImage?) -> UIImage?{

        if let capturedImage = capturedImage{

            // Setup the font specific variables
            let textColor = UIColor.white
            let textFont = UIFont(name: "Helvetica", size: 14)!

            // Setup the image context using the passed image

            let scale = UIScreen.main.scale

            UIGraphicsBeginImageContextWithOptions(capturedImage.size, false, scale)

            // Setup the font attributes that will be later used to dictate how the text should be drawn
            let textFontAttributes = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
                ] as [String : Any]

            capturedImage.draw(in: CGRect(x: 0, y: 0, width: capturedImage.size.width, height:capturedImage.size.height))

            // Create a point within the space that is as bit as the image

            let rect =  CGRect(x: atPoint.x, y: atPoint.y, width: capturedImage.size.width, height: capturedImage.size.height)

            // Draw the text into an image

            text.draw(in: rect, withAttributes: textFontAttributes)

            // Create a new image out of the images we have created
            let newImage = UIGraphicsGetImageFromCurrentImageContext()

            // End the context now that we have the image we need
            UIGraphicsEndImageContext()

            //Pass the image back up to the caller
            return newImage!

        }
        return nil

    }

}


问:
PHP - Get Latitude & Longitude from an address
I have used the autocomplete of geocode but when I am selecting from the drop down it is giving me the lat and long of the address

I need to check when the lat and long are empty then from the posted address I must get the latitude and longitude

答:
Using CURL

```<code><?php
$address = "Kathmandu, Nepal";
$url = "http://maps.google.com/maps/api/geocode/json?address=".urlencode($address);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$responseJson = curl_exec($ch);
curl_close($ch);

$response = json_decode($responseJson);

if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;

    echo 'Latitude: ' . $latitude;
    echo '<br />';
    echo 'Longitude: ' . $longitude;
} else {
    echo $response->status;
    var_dump($response);
}
?>
</code>```

Body:
Using CURL

<?php
$address = "Kathmandu, Nepal";
$url = "http://maps.google.com/maps/api/geocode/json?address=".urlencode($address);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$responseJson = curl_exec($ch);
curl_close($ch);

$response = json_decode($responseJson);

if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;

    echo 'Latitude: ' . $latitude;
    echo '<br />';
    echo 'Longitude: ' . $longitude;
} else {
    echo $response->status;
    var_dump($response);
}
?>


问:
How to create a multiple criteria advance filter in VBA?
I'm trying to create an advanced filter for the below table but the code below is just hiding the cells. It's working but my problem with it is if i filter something and then I drag to fill status or any other cells it will override the cells in between for example in filter mode I have 2 rows one is 1st row and the other one is at row 20 if I drag to fill status it will replace the status of all cells in between 1 and 20 and don't know how to work it out, i know this happens because I'm hiding the cells and not actually filtering them.

Any help will be much appreciated.

[Data Table][1]

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.EnableEvents = False

r1 = Target.Row
c1 = Target.Column

If r1 <> 3 Then GoTo ending:
If ActiveSheet.Cells(1, c1) = "" Then GoTo ending:

Dim LC As Long
    With ActiveSheet
        LC = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    End With

    ActiveSheet.Range("4:10000").Select
    Selection.EntireRow.Hidden = False

    LR = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

For r = 5 To LR

For c = 1 To LC
If ActiveSheet.Cells(2, c) = "" Or ActiveSheet.Cells(3, c) = "" Then GoTo nextc:
If ActiveSheet.Cells(2, c) = "exact" And UCase(ActiveSheet.Cells(r, c)) <> UCase(ActiveSheet.Cells(3, c)) Then ActiveSheet.Rows(r).EntireRow.Hidden = True: GoTo nextr:
If Cells(2, c) = "exact" Then GoTo nextc:
j = InStr(1, UCase(ActiveSheet.Cells(r, c)), UCase(ActiveSheet.Cells(3, c)))
If ActiveSheet.Cells(2, c) = "partial" And j = 0 Then ActiveSheet.Rows(r).EntireRow.Hidden = True: GoTo nextr:

nextc:
Next c

nextr:
Next r

ending:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
</code>```

答:
The below code will be the answer to the question on how to create an advanced search based on multiple criteria on what the user selects in the table.

I will need a little bit of help with how to check if the user selected by mistake an empty cell I will need to make excel ignore filtering the blank cell. Also, I will need to make excel first to check if the yellow cells A3 to T3 has data in and if it has and i press the filter button will filter by the range A3:T3 and ignore the current user selection if there is no data in range A3:T3 will filter by the user selection and in the range A3:T3, if it has data will only filter by data cell that has data in them and ignore empty ones.

```<code>Sub advancedMultipleCriteriaFilter()

 Dim cellRng As Range, tableObject As Range, subSelection As Range
 Dim filterCriteria() As String, filterFields() As Integer
 Dim i As Integer

If Selection.Rows.Count > 1 Then
 MsgBox "Cannot apply filters to multiple rows within the same column. Please make another selection and try again.", vbInformation, "Selection Error!"
 Exit Sub
 End If

Application.ScreenUpdating = False
i = 1
 ReDim filterCriteria(1 To Selection.Cells.Count) As String
 ReDim filterFields(1 To Selection.Cells.Count) As Integer
Set tableObject = Selection.CurrentRegion
 For Each subSelection In Selection.Areas
 For Each cellRng In subSelection
 filterCriteria(i) = cellRng.Text
 filterFields(i) = cellRng.Column - tableObject.Cells(1, 1).Column + 1
 i = i + 1
 Next cellRng
 Next subSelection
With tableObject
 For i = 1 To UBound(filterCriteria)
 .AutoFilter field:=filterFields(i), Criteria1:=filterCriteria(i)
 Next i
 End With
Set tableObject = Nothing
Application.ScreenUpdating = True
End Sub

Sub resetFilters()

Dim sht As Worksheet
Dim LastRow As Range

Application.ScreenUpdating = False
   On Error Resume Next
        If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
  End If

Range("A3:T3").ClearContents
Application.ScreenUpdating = True
Call GetLastRow

End Sub

Private Sub GetLastRow()

 'Step 1: Declare Your Variables.
  Dim LastRow As Long
 'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row
 'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

 End Sub
</code>```

Body:
I'm trying to create an advanced filter for the below table but the code below is just hiding the cells. It's working but my problem with it is if i filter something and then I drag to fill status or any other cells it will override the cells in between for example in filter mode I have 2 rows one is 1st row and the other one is at row 20 if I drag to fill status it will replace the status of all cells in between 1 and 20 and don't know how to work it out, i know this happens because I'm hiding the cells and not actually filtering them.

Any help will be much appreciated.

[Data Table][1]

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.EnableEvents = False

r1 = Target.Row
c1 = Target.Column

If r1 <> 3 Then GoTo ending:
If ActiveSheet.Cells(1, c1) = "" Then GoTo ending:

Dim LC As Long
    With ActiveSheet
        LC = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    End With

    ActiveSheet.Range("4:10000").Select
    Selection.EntireRow.Hidden = False

    LR = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

For r = 5 To LR

For c = 1 To LC
If ActiveSheet.Cells(2, c) = "" Or ActiveSheet.Cells(3, c) = "" Then GoTo nextc:
If ActiveSheet.Cells(2, c) = "exact" And UCase(ActiveSheet.Cells(r, c)) <> UCase(ActiveSheet.Cells(3, c)) Then ActiveSheet.Rows(r).EntireRow.Hidden = True: GoTo nextr:
If Cells(2, c) = "exact" Then GoTo nextc:
j = InStr(1, UCase(ActiveSheet.Cells(r, c)), UCase(ActiveSheet.Cells(3, c)))
If ActiveSheet.Cells(2, c) = "partial" And j = 0 Then ActiveSheet.Rows(r).EntireRow.Hidden = True: GoTo nextr:

nextc:
Next c

nextr:
Next r

ending:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Body:
The below code will be the answer to the question on how to create an advanced search based on multiple criteria on what the user selects in the table.

I will need a little bit of help with how to check if the user selected by mistake an empty cell I will need to make excel ignore filtering the blank cell. Also, I will need to make excel first to check if the yellow cells A3 to T3 has data in and if it has and i press the filter button will filter by the range A3:T3 and ignore the current user selection if there is no data in range A3:T3 will filter by the user selection and in the range A3:T3, if it has data will only filter by data cell that has data in them and ignore empty ones.

Sub advancedMultipleCriteriaFilter()

 Dim cellRng As Range, tableObject As Range, subSelection As Range
 Dim filterCriteria() As String, filterFields() As Integer
 Dim i As Integer

If Selection.Rows.Count > 1 Then
 MsgBox "Cannot apply filters to multiple rows within the same column. Please make another selection and try again.", vbInformation, "Selection Error!"
 Exit Sub
 End If

Application.ScreenUpdating = False
i = 1
 ReDim filterCriteria(1 To Selection.Cells.Count) As String
 ReDim filterFields(1 To Selection.Cells.Count) As Integer
Set tableObject = Selection.CurrentRegion
 For Each subSelection In Selection.Areas
 For Each cellRng In subSelection
 filterCriteria(i) = cellRng.Text
 filterFields(i) = cellRng.Column - tableObject.Cells(1, 1).Column + 1
 i = i + 1
 Next cellRng
 Next subSelection
With tableObject
 For i = 1 To UBound(filterCriteria)
 .AutoFilter field:=filterFields(i), Criteria1:=filterCriteria(i)
 Next i
 End With
Set tableObject = Nothing
Application.ScreenUpdating = True
End Sub

Sub resetFilters()

Dim sht As Worksheet
Dim LastRow As Range

Application.ScreenUpdating = False
   On Error Resume Next
        If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
  End If

Range("A3:T3").ClearContents
Application.ScreenUpdating = True
Call GetLastRow

End Sub

Private Sub GetLastRow()

 'Step 1: Declare Your Variables.
  Dim LastRow As Long
 'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row
 'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

 End Sub


问:
Efficiently wrapping a double
I have a number of geometric functions that only accept angles in the range 0° to 360°.  If the angle is outside that range then the angle is invalid (i.e. converting 365° to 5° is not an option) and there's no point in calling the functions.  To this end I've created the following class:

```<code>struct PositiveAngle {
    public let value: Double

    init?(value: Double) {
        guard 0.0 <= value && value <= 360.0 else {
            return nil
        }
        self.value = value
    }
}
</code>```

To be used as follows:

```<code>let angle = PositiveAngle(value: 30.0)
print(angle.value)

func foo(angle: PositiveAngle) -> PositiveAngle {
    ...
}
</code>```

This works but it feels "clunky" because I have extract the value of the angle from the struct whenever I need to use it.  Given that all I am after is a Double that has a restricted range, is there a more efficient way to achieve this?

答:
You don't want to do modulus, for reasons that aren't entirely clear to me, but I have done a lot of angle maths over the years and have always used wrap-around. In Swift,

```<code>extension Double {
    var positiveAngleInDegrees: Double {
        var x = self
        while x < 0 { x += 360 }
        while x >= 360 { x -= 360 }
        return x
    }
}

let y = 722.positiveAngleInDegrees // 2
</code>```

In mathematical terms 722º is entirely equivalent to 2º.

Title: Efficiently wrapping a double

Body:
I have a number of geometric functions that only accept angles in the range 0° to 360°.  If the angle is outside that range then the angle is invalid (i.e. converting 365° to 5° is not an option) and there's no point in calling the functions.  To this end I've created the following class:

struct PositiveAngle {
    public let value: Double

    init?(value: Double) {
        guard 0.0 <= value && value <= 360.0 else {
            return nil
        }
        self.value = value
    }
}

To be used as follows:

let angle = PositiveAngle(value: 30.0)
print(angle.value)

func foo(angle: PositiveAngle) -> PositiveAngle {
    ...
}

This works but it feels "clunky" because I have extract the value of the angle from the struct whenever I need to use it.  Given that all I am after is a Double that has a restricted range, is there a more efficient way to achieve this?

Body:
You don't want to do modulus, for reasons that aren't entirely clear to me, but I have done a lot of angle maths over the years and have always used wrap-around. In Swift,

extension Double {
    var positiveAngleInDegrees: Double {
        var x = self
        while x < 0 { x += 360 }
        while x >= 360 { x -= 360 }
        return x
    }
}

let y = 722.positiveAngleInDegrees // 2

In mathematical terms 722º is entirely equivalent to 2º.


问:
Dask reading CSV, setting partition as CSV length
I'm trying to write code that will read from a set of CSVs named my_file_*.csv into a Dask dataframe.

Then I want to set the partitions based on the length of the CSV. I'm trying to map a function on each partition and in order to do that, each partition must be the whole CSV.

I've tried to reset the index, and then set partitions based on the length of each CSV but it looks like the index of the Dask dataframe is not unique.

Is there a better way to partition based on the length of each CSV?

答:
So one partition should contain exactly one file?
You cold do:

```<code>import dask.dataframe as dd
ddf = dd.read_csv(my_file_*.csv, blocksize = None)
</code>```

Setting blocksize to None makes sure that files are not split up in several partitions. Therefore, ddf will be a dask dataframe containing one file per partition.

You might want to check out the documentation:

general instructions how to generate dask dataframes from data

details about read_csv

Body:
So one partition should contain exactly one file?
You cold do:

import dask.dataframe as dd
ddf = dd.read_csv(my_file_*.csv, blocksize = None)

Setting blocksize to None makes sure that files are not split up in several partitions. Therefore, ddf will be a dask dataframe containing one file per partition.

You might want to check out the documentation:

general instructions how to generate dask dataframes from data

details about read_csv


问:
Why does my hashset contain duplicates?
When I create a hashset for my elements, for some reason I can add duplicate elements to it. I did override the equals and hashcode methods. Underneath is a bit of my code and an example of my problem. For simplicity I named my elements "element".

```<code>set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
for (element e : set)
    System.out.println("set element : " + e.firstPoint2D.toString()
                                    + e.secondPoint2D.toString()
                                    + e.lastBoolean
                                    + " and hashcode = " + e.hashCode());
</code>```

this returns :

```<code>set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211
set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211
</code>```

We clearly see they have the same hashcode, so why are they both in the hashset? I thought a hashset's utility was in the fact that it couldn't contain duplicates? Am I missing something? Here is equals and hashcode :

```<code>public boolean equals(element e) {
    if (this.firstPoint2D.equals(e.firstPoint2D) &&
     this.secondPoint2D.equals(e.secondPoint2D) &&
     this.lastBoolean == e.lastBoolean)
        return true;
    else
        return false;
}

@Override
public int hashCode() {
    int result = (int)(firstPoint2D.getX() + 10*firstPoint2D.getY()
     + 100*secondPoint2D.getX() + 1000*secondPoint2D.getY());
    if (lastBoolean)
        return result + 1;
    else
        return result;
}
</code>```

答:
Your equals method is not correctly overridden and hence, it uses equals() method of Object class rather than the overridden version. equals() method ob Object class accepts an Object argument whereas the one you have overridden accepts element, following should work:

```<code>@Override
public boolean equals(Object e) {
    if ( e instanceof element &&
    this.firstPoint2D.equals(((element)e).firstPoint2D) &&
     this.secondPoint2D.equals(((element)e).secondPoint2D) &&
     this.lastBoolean == ((element)e).lastBoolean)
        return true;
    else
        return false;
}
</code>```

Here's javadoc for equals().

Title: Why does my hashset contain duplicates?

Body:
When I create a hashset for my elements, for some reason I can add duplicate elements to it. I did override the equals and hashcode methods. Underneath is a bit of my code and an example of my problem. For simplicity I named my elements "element".

set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
for (element e : set)
    System.out.println("set element : " + e.firstPoint2D.toString()
                                    + e.secondPoint2D.toString()
                                    + e.lastBoolean
                                    + " and hashcode = " + e.hashCode());

this returns :

set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211
set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211

We clearly see they have the same hashcode, so why are they both in the hashset? I thought a hashset's utility was in the fact that it couldn't contain duplicates? Am I missing something? Here is equals and hashcode :

public boolean equals(element e) {
    if (this.firstPoint2D.equals(e.firstPoint2D) &&
     this.secondPoint2D.equals(e.secondPoint2D) &&
     this.lastBoolean == e.lastBoolean)
        return true;
    else
        return false;
}

@Override
public int hashCode() {
    int result = (int)(firstPoint2D.getX() + 10*firstPoint2D.getY()
     + 100*secondPoint2D.getX() + 1000*secondPoint2D.getY());
    if (lastBoolean)
        return result + 1;
    else
        return result;
}

Body:
Your equals method is not correctly overridden and hence, it uses equals() method of Object class rather than the overridden version. equals() method ob Object class accepts an Object argument whereas the one you have overridden accepts element, following should work:

@Override
public boolean equals(Object e) {
    if ( e instanceof element &&
    this.firstPoint2D.equals(((element)e).firstPoint2D) &&
     this.secondPoint2D.equals(((element)e).secondPoint2D) &&
     this.lastBoolean == ((element)e).lastBoolean)
        return true;
    else
        return false;
}

Here's javadoc for equals().


问:
EntityRef adding unwanted record
I have an BookOrder object which has an EntityRef var to a Book object.  The objects are linked by book Id.  When inserting a new BookOrder record, a new Book record also gets inserted into the book table.  How do I stop this, and just insert the BookOrder record? Thanks in advance.

答:
You cannot do this, as it would create an order for a book that doesn't exist.

That's why the book gets automatically created.

You should perhaps say what technology you'r using, that would make it easier to give a more accurate answer.

And you should also accept answers to your questions, it's important for your own reputation.

Title: EntityRef adding unwanted record


问:
How to get past 7 days and next 7 days in Javascript
I'm trying to get past 7 days and next 7 days date start data and end date using javascript date function.

For example : Today 31 march 2017 , When i click previous button, it will calculate from previous date ie: start and end date , (24 March 2017 to 30 March 2017) , again click previous (17 March 2017 to 23 March 2017)etcc..

Same thing will replicate for next button ..

I have tried the below things but its not working

```<code> function getPreviousWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

 function getNextWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

function getByWeek(){

      console.log("weekpreviouscount" + ProHistoryCtrl.weekPrevcount); //-6,-12,-18,-24
      console.log("weekprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
      var d2 = new Date(); // 31.01.2017
      var d1 = new Date(d2);
      d1.setDate(d2.getDate() - 1); // 30.01.2017
      var previousWeek = '';
      var current_day = '';

      console.log("d2date" + d1.getDate());
      console.log("week2" + ProHistoryCtrl.weekPrevious)
      previousWeek = new Date(d1);
      previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

      current_day = new Date(d1); // 30.01.2017
      current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

      console.log("currentdayprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24

      var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
      var currentUTC = Math.floor(current_day.getTime() / 1000);

      console.log("previousWeekUTCTimestamp" + previousWeekUTCTimestamp);
      console.log("currentUTC" + currentUTC);

      var sinceUTC = previousWeekUTCTimestamp;
      var untilUTC = currentUTC;

}
</code>```

Its first time comes correct 24-march 2017 to 30 march 2017 , next previous its comes 24-march to 18march2017

Any ideas ?please

答:
Use this function. You don't need extra functions

var btn = document.querySelector("button")

Date.prototype.addDays = function(days) {
  this.setDate(this.getDate() + parseInt(days));
  return this;
};

function getDate(days) {
  var date = new Date().addDays(days);
  return date
}

btn.addEventListener("click", function() {
  var pastSevenDays = getDate(-7)
  var nextSevenDays = getDate(7)
  // only date
  console.log(pastSevenDays.toLocaleString().slice(0,10))
  console.log(nextSevenDays.toLocaleString().slice(0,10))
}, false)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Get Dates</button></code>```

Body:
I'm trying to get past 7 days and next 7 days date start data and end date using javascript date function.

For example : Today 31 march 2017 , When i click previous button, it will calculate from previous date ie: start and end date , (24 March 2017 to 30 March 2017) , again click previous (17 March 2017 to 23 March 2017)etcc..

Same thing will replicate for next button ..

I have tried the below things but its not working

 function getPreviousWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

 function getNextWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

function getByWeek(){

      console.log("weekpreviouscount" + ProHistoryCtrl.weekPrevcount); //-6,-12,-18,-24
      console.log("weekprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
      var d2 = new Date(); // 31.01.2017
      var d1 = new Date(d2);
      d1.setDate(d2.getDate() - 1); // 30.01.2017
      var previousWeek = '';
      var current_day = '';

      console.log("d2date" + d1.getDate());
      console.log("week2" + ProHistoryCtrl.weekPrevious)
      previousWeek = new Date(d1);
      previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

      current_day = new Date(d1); // 30.01.2017
      current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

      console.log("currentdayprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24

      var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
      var currentUTC = Math.floor(current_day.getTime() / 1000);

      console.log("previousWeekUTCTimestamp" + previousWeekUTCTimestamp);
      console.log("currentUTC" + currentUTC);

      var sinceUTC = previousWeekUTCTimestamp;
      var untilUTC = currentUTC;

}

Its first time comes correct 24-march 2017 to 30 march 2017 , next previous its comes 24-march to 18march2017

Any ideas ?please

Body:
Use this function. You don't need extra functions

var btn = document.querySelector("button")

Date.prototype.addDays = function(days) {
  this.setDate(this.getDate() + parseInt(days));
  return this;
};

function getDate(days) {
  var date = new Date().addDays(days);
  return date
}

btn.addEventListener("click", function() {
  var pastSevenDays = getDate(-7)
  var nextSevenDays = getDate(7)
  // only date
  console.log(pastSevenDays.toLocaleString().slice(0,10))
  console.log(nextSevenDays.toLocaleString().slice(0,10))
}, false)

<button>Get Dates</button>


问:
How to Log HttpRequest and HttpResponse in a file?
Can anyone explain any techniques to log HttpRequest and HttpResponse in a file.

We are using Spring MVC/Spring Rest.

What we want is to intercept the request before it is processed and log it.
Same way intercept the response before it is sent and log it.

Thanks a lot in advance.

答:
Accepted answer is already correct, adding annotation based configuration. Add following bean to your config.</p>

```<code>@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    return loggingFilter;
}
</code>```

Body:
Accepted answer is already correct, adding annotation based configuration. Add following bean to your config.

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    return loggingFilter;
}


问:
Limit Google News RSS to specific country
This may well be documented somewhere obvious, but I'm not seeing it. I'm parsing Google News results from RSS, but I'm struggling to get the RSS feed to match what I'm seeing online, with results limited to my country.

I'm in South Africa. To see SA news on a topic, I search for the topic in Google News, then select "Pages from South Africa" in the left menu. Although that option is under "The web", it does limit the news results as well.

However, the RSS link in the page footer goes to the generic (ie: not region-specific) news results as if I hadn't selected "pages from..." at all. I've been playing with the parameters in the feed URL, but I haven't found any way to get it to restrict the RSS results to my region. (Similarly: can't find an option to limit a CSE - custom search engine - the same way).

Any ideas?

答:
It can be done like so: https://news.google.com/news/feeds?country=AU?geo=2000

The above URL would limit the RSS output to news in Sydney, Australia.


问:
Javascript repeating if statements better solution?
I have 3 inputs and the code checks if they are empty and if they are then the variable values are added to the inputs.

So I have 3 variables with values:

```<code>var input1text = "something here";
var input2text = "something else here";
var input3text = "something else 2 here";
</code>```

So when the page loads, I check if the inputs are empty and if they are I add the variable values to the inputs.

Like this:

```<code>if($('#input1').val() == '') {

    //Add input1text text to it

}

if($('#input2').val() == '') {

    //Add input2text text to it

}

if($('#input3').val() == '') {

    //Add input3text text to it

}
</code>```

My question is, it having multiple ifs the most elegant way to do this? Is there a better way?

答:
How about this - the order doesn't matter, super flexible and super compact.</p>

```<code>var defaults = {
   "#input1": "something here",
   "#input2": "...",
   "#input3": "..."
};

for (var id in defaults) {
   var currVal = $(id).val();
   $(id).val(currVal.trim() || defaults[id]);
}
</code>```

Body:
I have 3 inputs and the code checks if they are empty and if they are then the variable values are added to the inputs.

So I have 3 variables with values:

var input1text = "something here";
var input2text = "something else here";
var input3text = "something else 2 here";

So when the page loads, I check if the inputs are empty and if they are I add the variable values to the inputs.

Like this:

if($('#input1').val() == '') {

    //Add input1text text to it

}

if($('#input2').val() == '') {

    //Add input2text text to it

}

if($('#input3').val() == '') {

    //Add input3text text to it

}

My question is, it having multiple ifs the most elegant way to do this? Is there a better way?

Body:
How about this - the order doesn't matter, super flexible and super compact.

var defaults = {
   "#input1": "something here",
   "#input2": "...",
   "#input3": "..."
};

for (var id in defaults) {
   var currVal = $(id).val();
   $(id).val(currVal.trim() || defaults[id]);
}


问:
Can I use html5 in my mobile website?
I must create a web site optimised for mobile devices, can I use html5 and css3?
What are the main limitations?
Which devices are compatible? (IOS, Android...)

Regards

答:
Yes - to a degree.  The website http://caniuse.com/ details HTML5 availability for the following browsers:

iOS Safari

Opera Mini

Opera Mobile

Android Browser

Title: Can I use html5 in my mobile website?


问:
PHP regex multi-line
I have the following PHP regex

```<code>preg_match('/[\/\/\*] First: (.*)\n[\/\/\*] Second: (.*)\n/i', $some_string)
</code>```

but for some reason it will not match this text:

```<code>// First: a string
// Second: another string
</code>```

I tried changing line endings between Windows and Unix style, this did nothing. I also tried splitting up the regex to match First and Second separately; this worked but when I put them both together they no longer match the sample text. It seems to have something to do with the space after the second [\/\/\*].. any ideas?

Note I can't change the regex; this is client code that I reversed because they don't provide documentation. This code looks for certain pattern in PHP files in order to load them as 'plugins' in their product. Really I'm trying to guess what header I need to add to these PHP files so they will correctly be recognized as plugins.

答:
(Posted on behalf of the OP).

Answer:

I was trying to guess what pattern this would match. It ended up being this:

```<code>/*
* First: a string
* Second: another string
*/
</code>```

Title: PHP regex multi-line

Body:
I have the following PHP regex

preg_match('/[\/\/\*] First: (.*)\n[\/\/\*] Second: (.*)\n/i', $some_string)

but for some reason it will not match this text:

// First: a string
// Second: another string

I tried changing line endings between Windows and Unix style, this did nothing. I also tried splitting up the regex to match First and Second separately; this worked but when I put them both together they no longer match the sample text. It seems to have something to do with the space after the second [\/\/\*].. any ideas?

Note I can't change the regex; this is client code that I reversed because they don't provide documentation. This code looks for certain pattern in PHP files in order to load them as 'plugins' in their product. Really I'm trying to guess what header I need to add to these PHP files so they will correctly be recognized as plugins.

Body:
(Posted on behalf of the OP).

Answer:

I was trying to guess what pattern this would match. It ended up being this:

/*
* First: a string
* Second: another string
*/


问:
Removing spaces between numbers separated by comma
I would like to remove any space between numbers separated by "." or ","

for example: 10 , 45, 3 should be: 10,45,3
and 10 . 45 . 3 should be: 10.45.3

Any help to do that in regular expressions ?

答:
Using /(\d)\s*([,.])\s*(\d)/g, "$1$2$3" you should be able to do that

var str = "Operations and maintenance $258 .277 billion , Military Personnel $153 .531 billion ,Procurement $97, 757 billion. Research, Development, Testing & Evaluation $63 . 347 billion, Military Construction $8 , 069 billion Family Housing $1. 483 billion.";
str = str.replace(/(\d)\s*([,.])\s*(\d)/g, "$1$2$3");
console.log(str)```


问:
Django filter on prefetch
I have the following query:

```<code>prefetch = Prefetch('books', queryset=Book.objects.filter(is_published=True),
                             to_attr='published_books')

profiles = Profile.objects.prefetch_related(prefetch)
</code>```

This selects all profiles and populates them with published books.
However, I want only profiles, that actually have published books (in other words len(profile.published_books) > 0).

How can I achieve it in orm?

UPDATE:

```<code>class Book(Model):
    profile = ForeignKey(Profile, related_name="books", related_query_name="book")
    name = CharField(max_length=250)
    is_published = BooleanField(default=True)

    class Meta:
        unique_together = (('profile', 'name'),)
</code>```

答:
```<code> profile_ids = Profile.objects.filter(book__is_published=True).values_list("pk", flat=True).distinct()
 profiles = Profile.objects.filter(pk__in=profile_ids).prefetch_related(prefetch)
</code>```

this will result a subquery that locate correct profile ids and then return any profile that match one of these ids.
use of distinct function has no effect on result but I am guessing it could improve performance (not really sure)

Title: Django filter on prefetch

Body:
I have the following query:

prefetch = Prefetch('books', queryset=Book.objects.filter(is_published=True),
                             to_attr='published_books')

profiles = Profile.objects.prefetch_related(prefetch)

This selects all profiles and populates them with published books.
However, I want only profiles, that actually have published books (in other words len(profile.published_books) > 0).

How can I achieve it in orm?

UPDATE:

class Book(Model):
    profile = ForeignKey(Profile, related_name="books", related_query_name="book")
    name = CharField(max_length=250)
    is_published = BooleanField(default=True)

    class Meta:
        unique_together = (('profile', 'name'),)

Body:
 profile_ids = Profile.objects.filter(book__is_published=True).values_list("pk", flat=True).distinct()
 profiles = Profile.objects.filter(pk__in=profile_ids).prefetch_related(prefetch)

this will result a subquery that locate correct profile ids and then return any profile that match one of these ids.
use of distinct function has no effect on result but I am guessing it could improve performance (not really sure)


答:
Try with simple forEach and querySelector() for pure javascript

var input1text = 'something here';
var input2text = 'something else here';
var input3text = 'something else 2 here';

document.querySelectorAll('input').forEach(function(a,b){
a.value = a.value ?  a.value :window['input'+(b+1)+'text'] ;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="1" value="dddddddd"><input id="2"><input id="3"></code>```

Title: Javascript repeating if statements better solution?

Body:
Try with simple forEach and querySelector() for pure javascript

var input1text = 'something here';
var input2text = 'something else here';
var input3text = 'something else 2 here';

document.querySelectorAll('input').forEach(function(a,b){
a.value = a.value ?  a.value :window['input'+(b+1)+'text'] ;
})

<input id="1" value="dddddddd"><input id="2"><input id="3">