问:
Reorganize/reshape data frame
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

```<code>df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0
</code>```

I want a data frame showing for each number the system and status. The Result would look like this:

```<code>sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0
</code>```

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

```<code>a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")
</code>```

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

答:
Here is a tidyverse approach:

It is part of the tidyr package, included in the tidyverse

```<code>library(tidyverse)
out <- gather(df, key = 'week', value = 'number', -sys, -sta)
</code>```

The output:

```<code>   sys sta week number
1    a   L  w01      0
2    a   T  w01      2
3    a   P  w01      5
4    b   L  w01      2
5    b   T  w01      2
6    b   P  w01      5
7    a   L  w02      3
8    a   T  w02      2
9    a   P  w02      2
10   b   L  w02      4
11   b   T  w02      6
12   b   P  w02      1
13   a   L  w03      4
14   a   T  w03      1
15   a   P  w03      0
16   b   L  w03      5
17   b   T  w03      3
18   b   P  w03      0
</code>```

How it works:

gather takes all columns that are not excluded. Exclusion is handled by passing on select statements to the ... argument. In this case, I am excluding sys and sta. As a result, the only column we are gathering our values from is all_w.

Furthermore we give gather a name for the key and a name for the value field. The key field will contain the column name that each element (row) of the output was taken from. The value will have the content of the row in that column.

I would recommend to keep week as you might later on want to know the exposure time that generated one of your numbers. If not, you can drop it with df %>% select(-week).

You can undo this transformation doing spread(out, key = week, value = number). Voila, your old df!

Title: Reorganize/reshape data frame

Body:
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0

I want a data frame showing for each number the system and status. The Result would look like this:

sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

Body:
Here is a tidyverse approach:

It is part of the tidyr package, included in the tidyverse

library(tidyverse)
out <- gather(df, key = 'week', value = 'number', -sys, -sta)

The output:

   sys sta week number
1    a   L  w01      0
2    a   T  w01      2
3    a   P  w01      5
4    b   L  w01      2
5    b   T  w01      2
6    b   P  w01      5
7    a   L  w02      3
8    a   T  w02      2
9    a   P  w02      2
10   b   L  w02      4
11   b   T  w02      6
12   b   P  w02      1
13   a   L  w03      4
14   a   T  w03      1
15   a   P  w03      0
16   b   L  w03      5
17   b   T  w03      3
18   b   P  w03      0

How it works:

gather takes all columns that are not excluded. Exclusion is handled by passing on select statements to the ... argument. In this case, I am excluding sys and sta. As a result, the only column we are gathering our values from is all_w.

Furthermore we give gather a name for the key and a name for the value field. The key field will contain the column name that each element (row) of the output was taken from. The value will have the content of the row in that column.

I would recommend to keep week as you might later on want to know the exposure time that generated one of your numbers. If not, you can drop it with df %>% select(-week).

You can undo this transformation doing spread(out, key = week, value = number). Voila, your old df!


来源: stackexchange

问:
double android.location.Location.getLatitude()' on a null object reference
the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code : </p>

```<code>package com.example.nefissa.androidtest;

 import android.*;
 import android.Manifest;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.support.annotation.Nullable;
 import android.support.v4.content.ContextCompat;

public class GPSTracker extends Service implements LocationListener{

private final Context context;

boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;

Location location;
protected LocationManager locationManager;

  public GPSTracker(Context context){
   this.context=context;
  }

// create a GetLocation Method //

public Location getLocation(){

    try{
        locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){

            if(isGPSEnabled){
                if(location==null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
                    if(locationManager!=null){
                          location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                  }
            }
               // if location is not found from GPS then it will found from network //
            if(location==null){
                if(isNetworkEnabled){
                           locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
                        if(locationManager!=null){
                              location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

            }
        }

    }catch(Exception e){

    }
    return location;
}

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

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}
</code>```

<p>and My Main Activity code : </p>

```<code>package com.example.nefissa.androidtest;

 import android.location.Location;
 import android.support.v4.app.FragmentActivity;
  import android.os.Bundle;

 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.SupportMapFragment;
   import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements     OnMapReadyCallback {

private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    gpsTracker= new GPSTracker(getApplicationContext());
    mLocation=gpsTracker.getLocation();
    latitude= mLocation.getLatitude();
    longitude= mLocation.getLongitude();

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

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

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
 }
</code>```

答:
Try using

GPS Tracker

```<code>public GPSTracker(Activity activity) {
    this.mActivity = activity;
    getLocation();
}

public void getLocation() {
    try {
        locationManager = (LocationManager) mActivity
                .getSystemService(LOCATION_SERVICE);

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

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

        if (!isGPSEnabled || !isNetworkEnabled) {
            showSettingsAlert();
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                } else {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

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

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to ic_check GPS/wifi enabled
 *
 * @return boolean
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}
</code>```

also from Activity call as

onCreate

```<code>//
gps = new GPSTracker(SignUpActivity.this);
        if (gps.canGetLocation) {
            lat = String.valueOf(gps.getLatitude());
            lng = String.valueOf(gps.getLongitude());
        }
</code>```

Comment below if you still got issue

ContentLicense: CC BY-SA 3.0

Body:
the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code :

package com.example.nefissa.androidtest;

 import android.*;
 import android.Manifest;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.support.annotation.Nullable;
 import android.support.v4.content.ContextCompat;

public class GPSTracker extends Service implements LocationListener{

private final Context context;

boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;

Location location;
protected LocationManager locationManager;

  public GPSTracker(Context context){
   this.context=context;
  }

// create a GetLocation Method //

public Location getLocation(){

    try{
        locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){

            if(isGPSEnabled){
                if(location==null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
                    if(locationManager!=null){
                          location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                  }
            }
               // if location is not found from GPS then it will found from network //
            if(location==null){
                if(isNetworkEnabled){
                           locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
                        if(locationManager!=null){
                              location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

            }
        }

    }catch(Exception e){

    }
    return location;
}

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

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

and My Main Activity code :

package com.example.nefissa.androidtest;

 import android.location.Location;
 import android.support.v4.app.FragmentActivity;
  import android.os.Bundle;

 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.SupportMapFragment;
   import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements     OnMapReadyCallback {

private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    gpsTracker= new GPSTracker(getApplicationContext());
    mLocation=gpsTracker.getLocation();
    latitude= mLocation.getLatitude();
    longitude= mLocation.getLongitude();

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

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

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
 }

Body:
Try using

GPS Tracker

public GPSTracker(Activity activity) {
    this.mActivity = activity;
    getLocation();
}

public void getLocation() {
    try {
        locationManager = (LocationManager) mActivity
                .getSystemService(LOCATION_SERVICE);

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

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

        if (!isGPSEnabled || !isNetworkEnabled) {
            showSettingsAlert();
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                } else {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

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

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to ic_check GPS/wifi enabled
 *
 * @return boolean
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}

also from Activity call as

onCreate

//
gps = new GPSTracker(SignUpActivity.this);
        if (gps.canGetLocation) {
            lat = String.valueOf(gps.getLatitude());
            lng = String.valueOf(gps.getLongitude());
        }

Comment below if you still got issue


问:
C# XMLSerializer is deserializing the wrong type into a List
The program below is a contrived example of a problem I found when deserializing XML in C#. I have two separate assemblies which declare a type with the same name, 'Country' in the example below. The types are differentiated by XML namespace. When I deserialize a configuration file containing a single 'Country' element then the correct 'Country' type is resolved. However if I deserialize a 'List' of 'Country' elements then the wrong 'Country' type is deserialized.

```<code>class Program
{
    static void Main(string[] args)
    {
        XDocument gbConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                                 <GreatBritain>
                                                   <Country/>
                                                   <Countries>
                                                      <Country/>
                                                      <Country/>
                                                    </Countries>
                                                  </GreatBritain>                                                                     </TradingBlocConfiguration>");

        XDocument euConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                                 <EuropeanUnion>
                                                   <Country/>
                                                   <Countries>
                                                      <Country/>
                                                      <Country/>
                                                    </Countries>
                                                  </EuropeanUnion>                                                                     </TradingBlocConfiguration>");

        var greatBritainConfiguration = BuildConfig<TradingBlocConfiguration>(gbConfig);

        // A single 'Country' is always deserialized correctly..
        Console.WriteLine("Great Britain Country Type   " + greatBritainConfiguration.TradingBlocConfig.MemberCountry.GetType());

        // A List of 'Country' is deserialized to the wrong type, depending on what '[XmlElement]' tag is listed first.
        Console.WriteLine("Great Britain Countries Type " + greatBritainConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        var euConfiguration = BuildConfig<TradingBlocConfiguration>(euConfig);
        Console.WriteLine("EU Country Type              " + euConfiguration.TradingBlocConfig.MemberCountry.GetType());
        Console.WriteLine("EU Countries Type            " + euConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        Console.ReadLine();
    }

    private static T BuildConfig<T>(XDocument doc) where T : class
    {
        var stream = new MemoryStream();
        doc.Save(stream);

        T result;
        using (var reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var xs = new XmlSerializer(typeof(T));
            result = (T)xs.Deserialize(reader);
        }

        return result;
    }
}

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("GreatBritain", typeof(GB.GreatBritain))]
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion))]
    public TradingBloc TradingBlocConfig { get; set; }
}

[XmlRoot]
[XmlInclude(typeof(GB.GreatBritain))]
[XmlInclude(typeof(EU.EuropeanUnion))]
public class BaseCountry { }

public abstract class TradingBloc
{
    [XmlIgnore]
    public abstract List<BaseCountry> MemberCountries { get; set; }

    [XmlIgnore]
    public abstract BaseCountry MemberCountry { get; set; }
}

namespace GB
{
    [XmlRoot("GreatBritain")]
    public class GreatBritain : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "GB")]
        public class Country : BaseCountry { }
    }
}

namespace EU
{
    [XmlRoot("EuropeanUnion")]
    public class EuropeanUnion : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "EU")]
        public class Country : BaseCountry { }
    }
}
</code>```

If you run the example above the output is:

```<code>Great Britain Country Type   XmlSerializationTests.GB.GreatBritain+Country
Great Britain Countries Type XmlSerializationTests.EU.EuropeanUnion+Country
EU Country Type              XmlSerializationTests.EU.EuropeanUnion+Country
EU Countries Type            XmlSerializationTests.EU.EuropeanUnion+Country
</code>```

The 'Great Britain Countries Type' is incorrect. If you change the order of [XmlElement] attributes in the TradingBlocConfiguration class like:

```<code>[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion))]
    [XmlElement("GreatBritain", typeof(GB.GreatBritain))]
    public TradingBloc TradingBlocConfig { get; set; }
}
</code>```

Then the results changes to:

```<code>Great Britain Country Type   XmlSerializationTests.GB.GreatBritain+Country
Great Britain Countries Type XmlSerializationTests.GB.GreatBritain+Country
EU Country Type              XmlSerializationTests.EU.EuropeanUnion+Country
EU Countries Type            XmlSerializationTests.GB.GreatBritain+Country
</code>```

In this case Britain looks good but the EU is wrong :). Can anyone explain why the List is deserialized to the wrong type?

答:
Solution was to add xmlns tags. The updated code below works correctly:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        XDocument gbConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <GreatBritain xmlns=""GB"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>
                                                </Countries>
                                              </GreatBritain>                                                                     </TradingBlocConfiguration>");

        XDocument euConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <EuropeanUnion xmlns=""EU"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>
                                                </Countries>
                                              </EuropeanUnion>                                                                     </TradingBlocConfiguration>");

        var greatBritainConfiguration = BuildConfig<TradingBlocConfiguration>(gbConfig);

        // A single 'Country' is always deserialized correctly..
        Console.WriteLine("Great Britain Country Type   " + greatBritainConfiguration.TradingBlocConfig.MemberCountry.GetType());

        // A List of 'Country' is deserialized to the wrong type, depending on what '[XmlElement]' tag is listed first.
        Console.WriteLine("Great Britain Countries Type " + greatBritainConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        var euConfiguration = BuildConfig<TradingBlocConfiguration>(euConfig);
        Console.WriteLine("EU Country Type              " + euConfiguration.TradingBlocConfig.MemberCountry.GetType());
        Console.WriteLine("EU Countries Type            " + euConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        Console.ReadLine();
    }

    private static T BuildConfig<T>(XDocument doc) where T : class
    {
        var stream = new MemoryStream();
        doc.Save(stream);

        T result;
        using (var reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var xs = new XmlSerializer(typeof(T), new Type[] { typeof(GB.GreatBritain.Country) });
            result = (T)xs.Deserialize(reader);
        }

        return result;
    }
}

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("GreatBritain", typeof(GB.GreatBritain), Namespace = "GB")]
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion), Namespace = "EU")]
    public TradingBloc TradingBlocConfig { get; set; }
}

[XmlRoot]
[XmlInclude(typeof(GB.GreatBritain))]
[XmlInclude(typeof(EU.EuropeanUnion))]
public class BaseCountry { }

public abstract class TradingBloc
{
    [XmlIgnore]
    public abstract List<BaseCountry> MemberCountries { get; set; }

    [XmlIgnore]
    public abstract BaseCountry MemberCountry { get; set; }
}

namespace GB
{
    [XmlRoot("GreatBritain")]
    public class GreatBritain : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]

        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "GB")]
        public class Country : BaseCountry { }
    }
}

namespace EU
{
    [XmlRoot("EuropeanUnion")]
    public class EuropeanUnion : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "EU")]
        public class Country : BaseCountry { }
    }
}
</code>```

Body:
The program below is a contrived example of a problem I found when deserializing XML in C#. I have two separate assemblies which declare a type with the same name, 'Country' in the example below. The types are differentiated by XML namespace. When I deserialize a configuration file containing a single 'Country' element then the correct 'Country' type is resolved. However if I deserialize a 'List' of 'Country' elements then the wrong 'Country' type is deserialized.

class Program
{
    static void Main(string[] args)
    {
        XDocument gbConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                                 <GreatBritain>
                                                   <Country/>
                                                   <Countries>
                                                      <Country/>
                                                      <Country/>
                                                    </Countries>
                                                  </GreatBritain>                                                                     </TradingBlocConfiguration>");

        XDocument euConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                                 <EuropeanUnion>
                                                   <Country/>
                                                   <Countries>
                                                      <Country/>
                                                      <Country/>
                                                    </Countries>
                                                  </EuropeanUnion>                                                                     </TradingBlocConfiguration>");

        var greatBritainConfiguration = BuildConfig<TradingBlocConfiguration>(gbConfig);

        // A single 'Country' is always deserialized correctly..
        Console.WriteLine("Great Britain Country Type   " + greatBritainConfiguration.TradingBlocConfig.MemberCountry.GetType());

        // A List of 'Country' is deserialized to the wrong type, depending on what '[XmlElement]' tag is listed first.
        Console.WriteLine("Great Britain Countries Type " + greatBritainConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        var euConfiguration = BuildConfig<TradingBlocConfiguration>(euConfig);
        Console.WriteLine("EU Country Type              " + euConfiguration.TradingBlocConfig.MemberCountry.GetType());
        Console.WriteLine("EU Countries Type            " + euConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        Console.ReadLine();
    }

    private static T BuildConfig<T>(XDocument doc) where T : class
    {
        var stream = new MemoryStream();
        doc.Save(stream);

        T result;
        using (var reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var xs = new XmlSerializer(typeof(T));
            result = (T)xs.Deserialize(reader);
        }

        return result;
    }
}

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("GreatBritain", typeof(GB.GreatBritain))]
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion))]
    public TradingBloc TradingBlocConfig { get; set; }
}

[XmlRoot]
[XmlInclude(typeof(GB.GreatBritain))]
[XmlInclude(typeof(EU.EuropeanUnion))]
public class BaseCountry { }

public abstract class TradingBloc
{
    [XmlIgnore]
    public abstract List<BaseCountry> MemberCountries { get; set; }

    [XmlIgnore]
    public abstract BaseCountry MemberCountry { get; set; }
}

namespace GB
{
    [XmlRoot("GreatBritain")]
    public class GreatBritain : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "GB")]
        public class Country : BaseCountry { }
    }
}

namespace EU
{
    [XmlRoot("EuropeanUnion")]
    public class EuropeanUnion : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "EU")]
        public class Country : BaseCountry { }
    }
}

If you run the example above the output is:

Great Britain Country Type   XmlSerializationTests.GB.GreatBritain+Country
Great Britain Countries Type XmlSerializationTests.EU.EuropeanUnion+Country
EU Country Type              XmlSerializationTests.EU.EuropeanUnion+Country
EU Countries Type            XmlSerializationTests.EU.EuropeanUnion+Country

The 'Great Britain Countries Type' is incorrect. If you change the order of [XmlElement] attributes in the TradingBlocConfiguration class like:

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion))]
    [XmlElement("GreatBritain", typeof(GB.GreatBritain))]
    public TradingBloc TradingBlocConfig { get; set; }
}

Then the results changes to:

Great Britain Country Type   XmlSerializationTests.GB.GreatBritain+Country
Great Britain Countries Type XmlSerializationTests.GB.GreatBritain+Country
EU Country Type              XmlSerializationTests.EU.EuropeanUnion+Country
EU Countries Type            XmlSerializationTests.GB.GreatBritain+Country

In this case Britain looks good but the EU is wrong :). Can anyone explain why the List is deserialized to the wrong type?

Body:
Solution was to add xmlns tags. The updated code below works correctly:

class Program
{
    static void Main(string[] args)
    {
        XDocument gbConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <GreatBritain xmlns=""GB"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>
                                                </Countries>
                                              </GreatBritain>                                                                     </TradingBlocConfiguration>");

        XDocument euConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <EuropeanUnion xmlns=""EU"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>
                                                </Countries>
                                              </EuropeanUnion>                                                                     </TradingBlocConfiguration>");

        var greatBritainConfiguration = BuildConfig<TradingBlocConfiguration>(gbConfig);

        // A single 'Country' is always deserialized correctly..
        Console.WriteLine("Great Britain Country Type   " + greatBritainConfiguration.TradingBlocConfig.MemberCountry.GetType());

        // A List of 'Country' is deserialized to the wrong type, depending on what '[XmlElement]' tag is listed first.
        Console.WriteLine("Great Britain Countries Type " + greatBritainConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        var euConfiguration = BuildConfig<TradingBlocConfiguration>(euConfig);
        Console.WriteLine("EU Country Type              " + euConfiguration.TradingBlocConfig.MemberCountry.GetType());
        Console.WriteLine("EU Countries Type            " + euConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        Console.ReadLine();
    }

    private static T BuildConfig<T>(XDocument doc) where T : class
    {
        var stream = new MemoryStream();
        doc.Save(stream);

        T result;
        using (var reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var xs = new XmlSerializer(typeof(T), new Type[] { typeof(GB.GreatBritain.Country) });
            result = (T)xs.Deserialize(reader);
        }

        return result;
    }
}

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("GreatBritain", typeof(GB.GreatBritain), Namespace = "GB")]
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion), Namespace = "EU")]
    public TradingBloc TradingBlocConfig { get; set; }
}

[XmlRoot]
[XmlInclude(typeof(GB.GreatBritain))]
[XmlInclude(typeof(EU.EuropeanUnion))]
public class BaseCountry { }

public abstract class TradingBloc
{
    [XmlIgnore]
    public abstract List<BaseCountry> MemberCountries { get; set; }

    [XmlIgnore]
    public abstract BaseCountry MemberCountry { get; set; }
}

namespace GB
{
    [XmlRoot("GreatBritain")]
    public class GreatBritain : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]

        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "GB")]
        public class Country : BaseCountry { }
    }
}

namespace EU
{
    [XmlRoot("EuropeanUnion")]
    public class EuropeanUnion : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "EU")]
        public class Country : BaseCountry { }
    }
}


问:
Write UTF-8 files from R
Whereas R seems to handle Unicode characters well internally, I'm not able to output a data frame in R with such UTF-8 Unicode characters. Is there any way to force this?

```<code>data.frame(c("hīersumian","ǣmettigan"))->test
write.table(test,"test.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
</code>```

The output text file reads:

hiersumian mettigan

I am using R version 3.0.2 in a Windows environment (Windows 7).

EDIT

It's been suggested in the answers that R is writing the file correctly in UTF-8, and that the problem lies with the software I'm using to view the file. Here's some code where I'm doing everything in R. I'm reading in a text file encoded in UTF-8, and R reads it correctly. Then R writes the file out in UTF-8 and reads it back in again, and now the correct Unicode characters are gone.

```<code>read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
myinputfile[1,1]
write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
myoutputfile[1,1]
</code>```

Console output:

```<code>> read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
> myinputfile[1,1]
[1] hīersumian
Levels: hīersumian ǣmettigan
> write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
> read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
> myoutputfile[1,1]
[1] <U+FEFF>hiersumian
Levels: <U+01E3>mettigan <U+FEFF>hiersumian
>
</code>```

答:
I may be missing something OS-specific, but data.table appears to have no problem with this (or perhaps more likely it's an update to R internals since this question was originally posed):

```<code>t1 = data.table(a = c("hīersumian", "ǣmettigan"))
tmp = tempfile()
fwrite(t1, tmp)
system(paste('cat', tmp))
# a
# hīersumian
# ǣmettigan
fread(tmp)
#             a
# 1: hīersumian
# 2:  ǣmettigan
</code>```

Title: Write UTF-8 files from R

Body:
Whereas R seems to handle Unicode characters well internally, I'm not able to output a data frame in R with such UTF-8 Unicode characters. Is there any way to force this?

data.frame(c("hīersumian","ǣmettigan"))->test
write.table(test,"test.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")

The output text file reads:

hiersumian mettigan

I am using R version 3.0.2 in a Windows environment (Windows 7).

EDIT

It's been suggested in the answers that R is writing the file correctly in UTF-8, and that the problem lies with the software I'm using to view the file. Here's some code where I'm doing everything in R. I'm reading in a text file encoded in UTF-8, and R reads it correctly. Then R writes the file out in UTF-8 and reads it back in again, and now the correct Unicode characters are gone.

read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
myinputfile[1,1]
write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
myoutputfile[1,1]

Console output:

> read.table("myinputfile.txt",encoding="UTF-8")->myinputfile
> myinputfile[1,1]
[1] hīersumian
Levels: hīersumian ǣmettigan
> write.table(myinputfile,"myoutputfile.txt",row.names=F,col.names=F,quote=F,fileEncoding="UTF-8")
> read.table("myoutputfile.txt",encoding="UTF-8")->myoutputfile
> myoutputfile[1,1]
[1] hiersumian
Levels: mettigan hiersumian
>

Body:
I may be missing something OS-specific, but data.table appears to have no problem with this (or perhaps more likely it's an update to R internals since this question was originally posed):

t1 = data.table(a = c("hīersumian", "ǣmettigan"))
tmp = tempfile()
fwrite(t1, tmp)
system(paste('cat', tmp))
# a
# hīersumian
# ǣmettigan
fread(tmp)
#             a
# 1: hīersumian
# 2:  ǣmettigan


问:
How to setup documents share URLs across multiple domains and cultures
i have a kentico site that has two culture specific domains (.co.nz and .com.au) and i want to setup multiple cultures so that the site has different versions of the some document in a sites tree.

I have all this working, however my problem is that i want the URL's to be the same on both domains and kentico doesn't allow you to have the same path for the two documents (it places a -1 on the end of your path name if you enter them the same)

i am looking to have:

```<code>[domain name].com.au/products
[domain name].co.nz/products
</code>```

point to the same document (in its respective culture version)

how have others achieved this?

答:
You simply can't have two different documents with the same URL in the same site, otherwise how would Kentico know which page to route to.

Either have a seperate url for the NZ version like

audomain/products

nzdomain/products-nz

Or consider separating them into two different sites in the same Kentico instance. Then you can share content across the sites by creating linked documents. This also allow you to have separate content on each site if required.

ContentLicense: CC BY-SA 2.5

Body:
i have a kentico site that has two culture specific domains (.co.nz and .com.au) and i want to setup multiple cultures so that the site has different versions of the some document in a sites tree.

I have all this working, however my problem is that i want the URL's to be the same on both domains and kentico doesn't allow you to have the same path for the two documents (it places a -1 on the end of your path name if you enter them the same)

i am looking to have:

[domain name].com.au/products
[domain name].co.nz/products

point to the same document (in its respective culture version)

how have others achieved this?


问:
if initialState will have an array of object responses, should it be initialized as null or empty array?
I'm building a small photo sharing app and I have the following initialState in my photos reducer:

```<code>{
  photos: null
  category: null
}
</code>```

From my API, I will be receiving a response like this:

```<code>{
  category: 'Animals & Nature',
  photos: [{ id: 1001, url: 'cdn.url.com/img1001', title: 'dog' }, { id: 1002, url: 'cdn.url.com/img1002', title: 'cat' }
}
</code>```

Since photos will be an array of objects, should my initial state have it as null or []?

Also, if I get more photos, I will need to concat them to the state.photos..

How to best handle in this case?

答:
It is better to initialize an array to [] instead of null. There are many advantages to this approach. At least one of the advantages is - "You cannot invoke the methods of null object For(e.g.), you will not able to check length of a Array whose value is null. But, you sure can check the value of an empty array.

var arr = [];
console.log("Array Length - " + arr.length); //Length - 0```
</div>
</div>
</p>

<p>and now try this snippet below</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = null;
console.log("Array Length - " + arr.length); //Uncaught TypeError: Cannot read property 'length' of null</code>```

Body:
I'm building a small photo sharing app and I have the following initialState in my photos reducer:

{
  photos: null
  category: null
}

From my API, I will be receiving a response like this:

{
  category: 'Animals & Nature',
  photos: [{ id: 1001, url: 'cdn.url.com/img1001', title: 'dog' }, { id: 1002, url: 'cdn.url.com/img1002', title: 'cat' }
}

Since photos will be an array of objects, should my initial state have it as null or []?

Also, if I get more photos, I will need to concat them to the state.photos..

How to best handle in this case?

Body:
It is better to initialize an array to [] instead of null. There are many advantages to this approach. At least one of the advantages is - "You cannot invoke the methods of null object For(e.g.), you will not able to check length of a Array whose value is null. But, you sure can check the value of an empty array.

var arr = [];
console.log("Array Length - " + arr.length); //Length - 0

and now try this snippet below

var arr = null;
console.log("Array Length - " + arr.length); //Uncaught TypeError: Cannot read property 'length' of null


问:
Default routing in web api
When I was working with Web API 2, I found that there is slight change in routing of web api.

```<code>config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
</code>```

I understand the working of routing. Also I found that, by default there is no method name in routing although we can modify the routing and can add add pattern for action/method. But my question is what was the idea behind creating such routing.

Thank you
Susheel

答:
There are no actions because the idea is that you can have a method for each HTTP verb. e.g.

```<code>public IHttpActionResult Get()

public IHttpActionResult Get(int id)

public IHttpActionResult Post()

public IHttpActionResult Put(int id)
</code>```

The verb used determines which method is called.

The idea is that controllers are supposed to be very specific about what they relate to.

So you may have a "PersonController" which deals with adding and updating people, and an "OrdersController" which deals with orders.

Obviously this doesn't work out quite as straightforward in practice because controllers end up being more wide ranging than CRUD operations for an entity type.

Title: Default routing in web api

Body:
When I was working with Web API 2, I found that there is slight change in routing of web api.

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

I understand the working of routing. Also I found that, by default there is no method name in routing although we can modify the routing and can add add pattern for action/method. But my question is what was the idea behind creating such routing.

Thank you
Susheel

Body:
There are no actions because the idea is that you can have a method for each HTTP verb. e.g.

public IHttpActionResult Get()

public IHttpActionResult Get(int id)

public IHttpActionResult Post()

public IHttpActionResult Put(int id)

The verb used determines which method is called.

The idea is that controllers are supposed to be very specific about what they relate to.

So you may have a "PersonController" which deals with adding and updating people, and an "OrdersController" which deals with orders.

Obviously this doesn't work out quite as straightforward in practice because controllers end up being more wide ranging than CRUD operations for an entity type.


问:
Name a view or table as todays date YYYY-MM-DD or similar
How can I do a simple:

```<code>Select * into    XXXXXX     from dbo.BSAK
</code>```

with the XXXXXX table name is in the format  FILE_2017-03-29 (todays date)

Basically I will be using either this select into or a 'create view as' to store the data for tables in a job and name it as that date... If I can do it for the simple select into I will apply it to the others.

答:
You can use dynamic sql...

```<code>declare @sql varchar(max)
select @sql = concat('Select * into ' , '[File_',convert(date,getdate()), '] from dbo.bsak ')
Exec (@sql)
</code>```

But its bad design to create table daily...

Body:
How can I do a simple:

Select * into    XXXXXX     from dbo.BSAK

with the XXXXXX table name is in the format  FILE_2017-03-29 (todays date)

Basically I will be using either this select into or a 'create view as' to store the data for tables in a job and name it as that date... If I can do it for the simple select into I will apply it to the others.

Body:
You can use dynamic sql...

declare @sql varchar(max)
select @sql = concat('Select * into ' , '[File_',convert(date,getdate()), '] from dbo.bsak ')
Exec (@sql)

But its bad design to create table daily...


问:
Grails list view not working
I am trying out tutorials from this youtube link by Mike Kelly.

I completed all installations successfully. Now trying out dynamic scaffolding, but its list is not working.

This is how the show page looks like when I added a new EndUser:

Now when I try to see list of EndUsers, (see the pointing link at bottom-left corner of above image), the link actually points to index page. And when I click on it, it opens up index page with NO rows listed in table (see below image).

I also tried to access list by using url: http://localhost:9000/ProjectTracker/endUser/list, but then it resulted into 404 error:

When I saw the database console, i found the data got inserted in it:

(All files (controllers, domain files, etc.) are same as mentioned in the video tutorials)

答:
try this in EndUserController, for grails 2.4.4</p>

```<code>def index() {
    [endUserInstanceList: EndUser.list(params), endUserInstanceTotal: EndUser.count()]
}
</code>```

Title: Grails list view not working

Body:
try this in EndUserController, for grails 2.4.4

def index() {
    [endUserInstanceList: EndUser.list(params), endUserInstanceTotal: EndUser.count()]
}


问:
Python: I want to execute shell commands using python script
I want to execute shell command "objdump" using python for my research work
I have used subprocess.call("command") to execute linux command but its not working.

Sample code which i have tried is

```<code>import subprocess
subprocess.call("date")
</code>```

after the execution

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 168, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code>```

答:
You must do this:

```<code>subprocess.call('date', shell=True)
</code>```

Actually, Shell does allow you to access to global variable and programs that are in $PATH and your shell.

Body:
I want to execute shell command "objdump" using python for my research work
I have used subprocess.call("command") to execute linux command but its not working.

Sample code which i have tried is

import subprocess
subprocess.call("date")

after the execution

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 168, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

Body:
You must do this:

subprocess.call('date', shell=True)

Actually, Shell does allow you to access to global variable and programs that are in $PATH and your shell.


问:
Actual JFrame size does not match with declared
Im using Java on MacOS. Actual screen resolution is 2560x1600. But JFrame with size 1200x900 or more doesnt fit into the screen.

```<code>JFrame frame = new JFrame();
frame.setBounds(0,0,1200,900);
frame.setLayout(null);
frame.setVisible(true);
</code>```

Furthermore this:

```<code>JFrame frame = new JFrame();
frame.setBounds(0,0,3000,3000);
frame.setLayout(null);
frame.setVisible(true);
System.out.println(frame.getWidth() + "x" + frame.getHeight());
</code>```

outputs 1280x773. Why does this happen and how to deal with it?

EDIT: There is x2 scale. Might be because of retina and OS configurations. Looking for the way to change that scale.

答:
```<code>    JFrame frame = new JFrame();
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setLocationRelativeTo(null);
    frame.setLayout(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //============ or   set Location to (0, 0) for this approach

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();

    frame.setSize(width, height);
</code>```

Body:
Im using Java on MacOS. Actual screen resolution is 2560x1600. But JFrame with size 1200x900 or more doesnt fit into the screen.

JFrame frame = new JFrame();
frame.setBounds(0,0,1200,900);
frame.setLayout(null);
frame.setVisible(true);

Furthermore this:

JFrame frame = new JFrame();
frame.setBounds(0,0,3000,3000);
frame.setLayout(null);
frame.setVisible(true);
System.out.println(frame.getWidth() + "x" + frame.getHeight());

outputs 1280x773. Why does this happen and how to deal with it?

EDIT: There is x2 scale. Might be because of retina and OS configurations. Looking for the way to change that scale.


问:
Python how to define a function that only accepts an integer input that can be used for multiple lines
I am trying to make a program that has a user input numbers into multiple different lines of code and I am trying to make it so that if the user inputs something other than a number the program will ask the user again to input the number correctly. I was trying to define a function that I could use for all of them but every time I run the program, it crashes. Any help would be much appreciated, thank you.

My code:

```<code>def error():
    global m1
    global m2
    global w1
    global w2
    while True:
        try:
            int(m1 or m2 or w1 or w2)
        except ValueError:
            try:
                float(m1 or m2 or w1 or w2)
            except ValueError:
                m1 or m2 or w1 or w2=input("please input your response correctly...")
                break

m1=input("\nWhat was your first marking period percentage?")
error()
w1=input("\nWhat is the weighting of the first marking period? (in decimal)")
error()
m2=input("\nWhat was your second marking period percentage?")
error()
w2=input("\nWhat is the weighting of the second marking period? (in decimal)")
error()
</code>```

答:
You should write your function to get one number at a time. If at exception is triggered somewhere, it should be handled. Note how the get_number function shown below will keep asking for a number but also shows the prompt specified by its caller. If you are not running Python 3.6 or higher, you will need to comment out the call to print in the main function.

```<code>#! /usr/bin/env python3
def main():
    p1 = get_number('What is your 1st marking period percentage? ')
    w1 = get_number('What is the weighting of the 1st marking period? ')
    p2 = get_number('What is your 2nd marking period percentage? ')
    w2 = get_number('What is the weighting of the 2nd marking period? ')
    score = calculate_score((p1, p2), (w1, w2))
    print(f'Your score is {score:.2f}%.')

def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print('Please enter a number.')
            else:
                break
    return number

def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError('percentages and weights must have same length')
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)

if __name__ == '__main__':
    main()
</code>```

Body:
I am trying to make a program that has a user input numbers into multiple different lines of code and I am trying to make it so that if the user inputs something other than a number the program will ask the user again to input the number correctly. I was trying to define a function that I could use for all of them but every time I run the program, it crashes. Any help would be much appreciated, thank you.

My code:

def error():
    global m1
    global m2
    global w1
    global w2
    while True:
        try:
            int(m1 or m2 or w1 or w2)
        except ValueError:
            try:
                float(m1 or m2 or w1 or w2)
            except ValueError:
                m1 or m2 or w1 or w2=input("please input your response correctly...")
                break

m1=input("\nWhat was your first marking period percentage?")
error()
w1=input("\nWhat is the weighting of the first marking period? (in decimal)")
error()
m2=input("\nWhat was your second marking period percentage?")
error()
w2=input("\nWhat is the weighting of the second marking period? (in decimal)")
error()

Body:
You should write your function to get one number at a time. If at exception is triggered somewhere, it should be handled. Note how the get_number function shown below will keep asking for a number but also shows the prompt specified by its caller. If you are not running Python 3.6 or higher, you will need to comment out the call to print in the main function.

#! /usr/bin/env python3
def main():
    p1 = get_number('What is your 1st marking period percentage? ')
    w1 = get_number('What is the weighting of the 1st marking period? ')
    p2 = get_number('What is your 2nd marking period percentage? ')
    w2 = get_number('What is the weighting of the 2nd marking period? ')
    score = calculate_score((p1, p2), (w1, w2))
    print(f'Your score is {score:.2f}%.')

def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print('Please enter a number.')
            else:
                break
    return number

def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError('percentages and weights must have same length')
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)

if __name__ == '__main__':
    main()


问:
Placing an image on a canvas JS
I have the following in html:

```<code><img id="MarkingImage"></img>
<canvas id="MarkingCanvas"></canvas>
</code>```

And on css:

```<code>#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }
</code>```

And on js:

```<code>function LoadImage()
{
   var markingImage = new Image();

   markingImage.addEventListener('load', function()
   {
       m_imageWidth = this.naturalWidth;
       m_imageHeight = this.naturalHeight;

       m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth,  m_imageHeight);
   });
   markingImage.src = 'PICT0001.JPG';
}
</code>```

The thing is that this output stretches the image and it's quality gets really poor (see attached "Original" and "Result").

When I debug, I can see that the sizes if my canvas are:

width - 1410
height - 775

The sizes if my image are:

width - 551
height - 335

So my question is: why isn't the image placed in it's original size? I mean, there's enough space on the canvas. Also, why does the image gets stretched, and as a result gets in pretty low quality. Appears like it stretches beyond the size of the canvas.

What am I missing here?

答:
You need to set the canvas width and height dynamically according to the browser window's width and height. also, there is no need to use the image's naturalWidth / naturalHeight.

var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');

// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;

function LoadImage() {
    var markingImage = new Image();
    markingImage.addEventListener('load', function() {
        m_markingCanvasContext.drawImage(this, 0, 0);
    });
    markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="MarkingCanvas"></canvas></code>```

Title: Placing an image on a canvas JS

Body:
I have the following in html:

<canvas id="MarkingCanvas"></canvas>

And on css:

#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }

And on js:

function LoadImage()
{
   var markingImage = new Image();

   markingImage.addEventListener('load', function()
   {
       m_imageWidth = this.naturalWidth;
       m_imageHeight = this.naturalHeight;

       m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth,  m_imageHeight);
   });
   markingImage.src = 'PICT0001.JPG';
}

The thing is that this output stretches the image and it's quality gets really poor (see attached "Original" and "Result").

When I debug, I can see that the sizes if my canvas are:

width - 1410
height - 775

The sizes if my image are:

width - 551
height - 335

So my question is: why isn't the image placed in it's original size? I mean, there's enough space on the canvas. Also, why does the image gets stretched, and as a result gets in pretty low quality. Appears like it stretches beyond the size of the canvas.

What am I missing here?

Body:
You need to set the canvas width and height dynamically according to the browser window's width and height. also, there is no need to use the image's naturalWidth / naturalHeight.

var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');

// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;

function LoadImage() {
    var markingImage = new Image();
    markingImage.addEventListener('load', function() {
        m_markingCanvasContext.drawImage(this, 0, 0);
    });
    markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();

<canvas id="MarkingCanvas"></canvas>


问:
Cube Design Question - SQL Server
We have about 10-15 dimension tables that reflect different levels of granularity and about 15-20 metrics we want to track. Does it make more sense to build one cube at the most granular level and roll up or drill down, or to have multiple cubes at different levels of granularity?</p>

答:
Build one cube at the most granular level. This will provide you with the most flexibility in reporting.

Certain reports might run too slowly, once it's in production or once you test it with sizeable data. Only then should you consider creating more specific cubes.

Title: Cube Design Question - SQL Server


问:
How to get newly created _id from Meteor.loginWithFacebook() method?
```
    Trying to integrate social media login for my system.
    For that I have used following method
       Meteor.loginWithFacebook({}, function(err,res){
            if (err) {
                throw new Meteor.Error("Facebook login failed");
            }else{
                if(res){
                    console.log("result : " + res);
                }

                FlowRouter.go('/');
            }
        });
Above method successfully creating user and there is a successful
entry in users collection too. I want to access that newly created _id.
Is there any callback available . Thanks in advance!

```

答:
Once a user has logged in (regardless of the login method), you can use Meteor.userId() to get the id.

So in your case, as soon as the login with facebook is successful, Meteor.userId() will return that new user _id.

In case you want to full user document, you can use Meteor.user() instead.


问:
Replacing multiple special characters
I want to get rid of multiple special characters that might show up in  a specific column and replace it with a space but I keep getting this error when I try to write my file to an excel document.

```<code>Exception: Invalid Excel character '[]:*?/\' in sheetname 'AL DINTE LASA/JACKY'S'
</code>```

I have already tried the below but it is not working but I dont know why that should get rid of multiple special characters and then replace it with an underscore.

```<code> df['Name'].replace(["/''//'-[]:*?/\\/#",'_'],regex=True)
</code>```

I dont know what else to try I cant seem to get around this error, am I just not using df.replace correctly?

答: The problem is not in the spreadsheet data itself - it is in the name of the spreadsheet. Specifically, the slash is not allowed in the sheetname. You can change the name to "AL DINTE LASA-JACKY'S" and it should work fine.</p>

Title: Replacing multiple special characters

Body:
I want to get rid of multiple special characters that might show up in  a specific column and replace it with a space but I keep getting this error when I try to write my file to an excel document.

Exception: Invalid Excel character '[]:*?/\' in sheetname 'AL DINTE LASA/JACKY'S'

I have already tried the below but it is not working but I dont know why that should get rid of multiple special characters and then replace it with an underscore.

 df['Name'].replace(["/''//'-[]:*?/\\/#",'_'],regex=True)

I dont know what else to try I cant seem to get around this error, am I just not using df.replace correctly?


问:
How to fix the position of a text to follow an object plotted in R
I was wondering how I can fix a piece of text() to always appear above a bracket (or a points() etc.) in a dynamically changing plot? In other words, how should I determine the "x" and "y" for that piece of text to follow the bracket (or a points() etc.) around anywhere in the plot? (see my R code below)

Just as an example, suppose I have a bracket in the plot below whose position (xs and ys) is going to be always known regardless of how the plot will change. Here, how can I fix the position of the text() above this bracket (as currently seen in the plot) no matter where the bracket goes?

P.S. At first, I thought I can take the "y" of the bracket, and then make "y" of the text() to be: ("y" of bracket + .1* "y" of bracket). But given that the plot can dynamically change (i.e., the plot is connected to a function), + .1* "y" of bracket in any plot gives a different position for the text that doesn't guarantee the distance between he text and the bracket be always maintained.

Here is a piece of R code:

```<code>if(!require(library(pBrackets))){install.packages('pBrackets') }

library(pBrackets)

plot(1:10, ty = 'n')

brack <- brackets(x1 = 4, y1 = 6, x2 = 8, y2 = 6, h = 1, ticks = .5, curvature = .5,
              type=1, col = "blue",
              lwd = 2, xpd = T)

text(x = 6, y = 7.2, "Equivalent to ZERO", font = 2) ## How to determine "x" and "y"
                                                      # such that the "text" always
                                                      # appears above the bracket
                                                      # even if the plot changes. This helps making functions.
</code>```

答:
```<code>plot(1:10, ty = 'n')
x1 = 4
y1 = 6
x2 = 8
y2 = 6
h = 1 #Or some variation of h = sqrt( (x2-x1)^2 + (y2-y1)^2 )/4
brack <- brackets(x1 = x1, y1 = y1, x2 = x2, y2 = y2, h = h, ticks = .5, curvature = .5,
                      type=1, col = "blue",
                      lwd = 2, xpd = T)

text(x = (x1+x2)/2, y = (y1+h), "Equivalent to ZERO", font = 2, pos = 3)
#pos = 3 means the text will be on top of x and y
</code>```

Body:
I was wondering how I can fix a piece of text() to always appear above a bracket (or a points() etc.) in a dynamically changing plot? In other words, how should I determine the "x" and "y" for that piece of text to follow the bracket (or a points() etc.) around anywhere in the plot? (see my R code below)

Just as an example, suppose I have a bracket in the plot below whose position (xs and ys) is going to be always known regardless of how the plot will change. Here, how can I fix the position of the text() above this bracket (as currently seen in the plot) no matter where the bracket goes?

P.S. At first, I thought I can take the "y" of the bracket, and then make "y" of the text() to be: ("y" of bracket + .1* "y" of bracket). But given that the plot can dynamically change (i.e., the plot is connected to a function), + .1* "y" of bracket in any plot gives a different position for the text that doesn't guarantee the distance between he text and the bracket be always maintained.

Here is a piece of R code:

if(!require(library(pBrackets))){install.packages('pBrackets') }

library(pBrackets)

plot(1:10, ty = 'n')

brack <- brackets(x1 = 4, y1 = 6, x2 = 8, y2 = 6, h = 1, ticks = .5, curvature = .5,
              type=1, col = "blue",
              lwd = 2, xpd = T)

text(x = 6, y = 7.2, "Equivalent to ZERO", font = 2) ## How to determine "x" and "y"
                                                      # such that the "text" always
                                                      # appears above the bracket
                                                      # even if the plot changes. This helps making functions.


问:
cancan rules creation problem
i have rails app that contains following models - User, Blog, Post, BlogMembership.

```<code>class BlogMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog

  # Membership types:
  SUBSCRIBER = 0
  AUTHOR = 1
  MODERATOR = 2
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :memberships, :class_name => "BlogMembership"

  # Blog memberships
  def subscribers
    self.memberships.where(:membership_type => [BlogMembership::SUBSCRIBER, BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def authors
    self.memberships.where(:membership_type => [BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def moderators
    self.memberships.where(:membership_type =>  BlogMembership::MODERATOR).collect(&:user)
  end
end
</code>```

In Ability class (because i use cancan for access restriction) i try to limit access of users and moderators to the blogs, but with following rule

```<code>if user.is? :moderator
  can :manage, Post do |post|
    post.blog.moderators.include? user
  end
end
</code>```

all users can send Posts to the any blog.

Could you tell me please - how to properly configure rule in Ability class for following relations scheme?

答:
And if you try this syntax?</p>

```<code>can :manage, Post do |action, post|
    post.blog.moderators.include? user
end
</code>```

Title: cancan rules creation problem

Body:
i have rails app that contains following models - User, Blog, Post, BlogMembership.

class BlogMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog

  # Membership types:
  SUBSCRIBER = 0
  AUTHOR = 1
  MODERATOR = 2
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :memberships, :class_name => "BlogMembership"

  # Blog memberships
  def subscribers
    self.memberships.where(:membership_type => [BlogMembership::SUBSCRIBER, BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def authors
    self.memberships.where(:membership_type => [BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def moderators
    self.memberships.where(:membership_type =>  BlogMembership::MODERATOR).collect(&:user)
  end
end

In Ability class (because i use cancan for access restriction) i try to limit access of users and moderators to the blogs, but with following rule

if user.is? :moderator
  can :manage, Post do |post|
    post.blog.moderators.include? user
  end
end

all users can send Posts to the any blog.

Could you tell me please - how to properly configure rule in Ability class for following relations scheme?

Body:
And if you try this syntax?

can :manage, Post do |action, post|
    post.blog.moderators.include? user
end


问:
Error Conversion failed when converting date and/or time from character string: varchar(8000)
I have a column of type varchar(8000). We save all kinds of data in it like number, text, date etc.

I wrote a simple select query to get all "Date" values from the table all works, I can also use CAST or Convert to get my value in this format 2014-12-16 00:00:00.000.

Now I'm trying to add a where clause to filter this year's info, but I get an error:

Conversion failed when converting date and/or time from character string.

When I use TOP 10000 in my select query the error goes away. This is really strange

```<code>; WITH TempTable AS
(
    SELECT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

This throws

Conversion failed when converting date and/or time from character string.

```<code>; WITH TempTable AS
(
    SELECT TOP 100000
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

This works fine. Please note I have only 25 some rows in my result. Top 100000 is just a big number I used. This is very strange how my TOP keyword is making my query good.

Update:

Here is how I ended up resolving without using TOP keyword. I have split my query little bit as seen below. Thank you all for your time and comments.

```<code>;WITH GetAllIDs
AS (
    SELECT ID
    FROM SampleTable
    WHERE ColType = 'Date'
    )
    ,FinalTable
AS (
    SELECT ID
        ,(
            SELECT Cast([Value] AS DATETIME)
            FROM SampleTable dt
            WHERE dt.ID = tt.ID
                AND dd.ColType = 'Date'
            ) [SomeDate]
    FROM GetAllIDs tt
    )
SELECT *FROM FinalTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

答:
There is no order of execution in a SQL statement.  So, the where clause does (necessarily) filter the rows before the values are converted.  Hence, your problem.

In SQL Server 2012+, there is a simple solution using try_convert():

```<code>With TempTable AS (
      select ID, try_convert(datetime, Value) as SomeDate
      from SampleTable
      where ColType = 'Date'
     )
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';
</code>```

Microsoft considers this behavior a feature of the optimizer, not a bug (I disagree).  It provides more opportunities for optimizing the query.  In this case, simple conversions are done when the data is being read, rather than further down the processing pipeline.

Notice that I also changed the date constants to YYYY-MM-DD format.  You should always use YYYY-MM-DD or YYYYMMDD for the format.

The fact that this goes away when TOP is added is some strange artifact of the execution plan.  For some reason, that would do the filtering before evaluating the expression.  I know that TOP can have sometimes have this effect.  I'm surprised in this case because the query is simple.

EDIT:

In SQL Server 2008, you can use case.  Something like this:

```<code>With TempTable AS (
      select ID, (case when isdate(value) = 1 then convert(datetime, Value) end) as SomeDate
      from SampleTable
      where ColType = 'Date'
     )
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';
</code>```

The case expression guarantees the order of evaluation of the arguments.  The when is evaluated only after the then.

ContentLicense: CC BY-SA 4.0

Body:
I have a column of type varchar(8000). We save all kinds of data in it like number, text, date etc.

I wrote a simple select query to get all "Date" values from the table all works, I can also use CAST or Convert to get my value in this format 2014-12-16 00:00:00.000.

Now I'm trying to add a where clause to filter this year's info, but I get an error:

Conversion failed when converting date and/or time from character string.

When I use TOP 10000 in my select query the error goes away. This is really strange

; WITH TempTable AS
(
    SELECT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

This throws

Conversion failed when converting date and/or time from character string.

; WITH TempTable AS
(
    SELECT TOP 100000
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

This works fine. Please note I have only 25 some rows in my result. Top 100000 is just a big number I used. This is very strange how my TOP keyword is making my query good.

Update:

Here is how I ended up resolving without using TOP keyword. I have split my query little bit as seen below. Thank you all for your time and comments.

;WITH GetAllIDs
AS (
    SELECT ID
    FROM SampleTable
    WHERE ColType = 'Date'
    )
    ,FinalTable
AS (
    SELECT ID
        ,(
            SELECT Cast([Value] AS DATETIME)
            FROM SampleTable dt
            WHERE dt.ID = tt.ID
                AND dd.ColType = 'Date'
            ) [SomeDate]
    FROM GetAllIDs tt
    )
SELECT *FROM FinalTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

Body:
There is no order of execution in a SQL statement.  So, the where clause does (necessarily) filter the rows before the values are converted.  Hence, your problem.

In SQL Server 2012+, there is a simple solution using try_convert():

With TempTable AS (
      select ID, try_convert(datetime, Value) as SomeDate
      from SampleTable
      where ColType = 'Date'
     )
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';

Microsoft considers this behavior a feature of the optimizer, not a bug (I disagree).  It provides more opportunities for optimizing the query.  In this case, simple conversions are done when the data is being read, rather than further down the processing pipeline.

Notice that I also changed the date constants to YYYY-MM-DD format.  You should always use YYYY-MM-DD or YYYYMMDD for the format.

The fact that this goes away when TOP is added is some strange artifact of the execution plan.  For some reason, that would do the filtering before evaluating the expression.  I know that TOP can have sometimes have this effect.  I'm surprised in this case because the query is simple.

EDIT:

In SQL Server 2008, you can use case.  Something like this:

With TempTable AS (
      select ID, (case when isdate(value) = 1 then convert(datetime, Value) end) as SomeDate
      from SampleTable
      where ColType = 'Date'
     )
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';

The case expression guarantees the order of evaluation of the arguments.  The when is evaluated only after the then.


问:
webpack 2 ts-loader exclude node_modules not working
I try to use typescript 2.2.2 and babel loaders in webpack 2 and exclude node_modules, but when try webpack command still get errors from angular 4.0.0 which is in node_modules.

webpack.congfig.js:

```<code>var path = require('path');
var webpack = require('webpack');

var PROD = true;

    module.exports = {
        entry: path.join(__dirname, 'ng2', 'src','index.js'),
        output: {
            path: path.join(__dirname, 'ng2', 'dist'),
            filename: 'vendorNG2.js'
        },
        devtool: 'eval',
        resolve: {
            extensions: [".tsx", ".ts", ".js"]
        },
        watch: true,
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    loader: 'ts-loader',
                    exclude: [/node_modules/],
                },
                {
                    test: /\.js$/,
                    exclude: [/node_modules/],
                    use: {

                        loader: "babel-loader?cacheDirectory=true",
                        options: {
                            presets: ['es2015']
                        }
                    }
                },
            ]
        },
        plugins: PROD ? [
            new webpack.optimize.UglifyJsPlugin({
                 compress: { warnings: false }
            })
      ] : []
    }
</code>```

after webpack --progress command:

```<code>...
ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(13,17): error TS2693: 'Map' only refers to a type, but is being used as a value here.

ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(14,17): error TS2693: 'Set' only refers to a type, but is being used as a value here.

ERROR in ./ng2/src/app/main.ts
(19,14): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
</code>```

You can see errors come from node_modules.

tsconfig.json v1:

```<code>{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  }
}
</code>```

tsconfig.json v2:

```<code>{
  "compilerOptions": {
    "outDir": "./ng2/dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "type":[],
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

v2 errors:

```<code>ERROR in /home/user/Projects/project/front/admin/tsconfig.json
error TS5023: Unknown compiler option 'type'.
 @ ./ng2/src/index.js 8:0-21

ERROR in ./ng2/src/app/main.ts
Module build failed: error while parsing tsconfig.json
 @ ./ng2/src/index.js 8:0-21
</code>```

tsconfig.js v3 add ("experimentalDecorators": true) some errors gone:

```<code>{
  "compilerOptions": {
    "outDir": "./ng2/dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
     "experimentalDecorators": true,
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

v3 errors :

...
ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(13,17): error TS2693: 'Map' only refers to a type, but is being used as a value here.

ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
    (14,17): error TS2693: 'Set' only refers to a type, but is being used as a value here.

答:
Have you added exclude node_modules to your tsconfig?

```<code>{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

Also, you aren't specifying which versions of Typescript and Angular you are using.

Edit:
You updated your question to specify that you're using Angular 4 but your updated errors show a node_modules/angular2/ folder which doesn't seem right. Before going further, try deleting your node_modules folder and run npm install again.

Otherwise it looks like you're having a typings issue.  Do you have any @types installed?

Here is an example of how my tsconfig.json is setup:

```<code>{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "removeComments": false,
        "noImplicitAny": false,
        "types": [ "jasmine", "lodash", "core-js" ],
        "typeRoots": [
            "../node_modules/@types"
        ]
    },
    "exclude": [
        "node_modules",
        "wwwroot",
        "temp"
    ]
}
</code>```

My node_modules folder is in the parent directory, so I specify that in the typeRoots.
With that I also have the following types installed as well:

```<code>"@types/core-js": "0.9.37",
"@types/jasmine": "2.5.43",
"@types/lodash": "4.14.55",
</code>```

Body:
I try to use typescript 2.2.2 and babel loaders in webpack 2 and exclude node_modules, but when try webpack command still get errors from angular 4.0.0 which is in node_modules.

webpack.congfig.js:

var path = require('path');
var webpack = require('webpack');

var PROD = true;

    module.exports = {
        entry: path.join(__dirname, 'ng2', 'src','index.js'),
        output: {
            path: path.join(__dirname, 'ng2', 'dist'),
            filename: 'vendorNG2.js'
        },
        devtool: 'eval',
        resolve: {
            extensions: [".tsx", ".ts", ".js"]
        },
        watch: true,
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    loader: 'ts-loader',
                    exclude: [/node_modules/],
                },
                {
                    test: /\.js$/,
                    exclude: [/node_modules/],
                    use: {

                        loader: "babel-loader?cacheDirectory=true",
                        options: {
                            presets: ['es2015']
                        }
                    }
                },
            ]
        },
        plugins: PROD ? [
            new webpack.optimize.UglifyJsPlugin({
                 compress: { warnings: false }
            })
      ] : []
    }

after webpack --progress command:

...
ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(13,17): error TS2693: 'Map' only refers to a type, but is being used as a value here.

ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(14,17): error TS2693: 'Set' only refers to a type, but is being used as a value here.

ERROR in ./ng2/src/app/main.ts
(19,14): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.

You can see errors come from node_modules.

tsconfig.json v1:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  }
}

tsconfig.json v2:

{
  "compilerOptions": {
    "outDir": "./ng2/dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "type":[],
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}

v2 errors:

ERROR in /home/user/Projects/project/front/admin/tsconfig.json
error TS5023: Unknown compiler option 'type'.
 @ ./ng2/src/index.js 8:0-21

ERROR in ./ng2/src/app/main.ts
Module build failed: error while parsing tsconfig.json
 @ ./ng2/src/index.js 8:0-21

tsconfig.js v3 add ("experimentalDecorators": true) some errors gone:

{
  "compilerOptions": {
    "outDir": "./ng2/dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
     "experimentalDecorators": true,
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}

v3 errors :

...
ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
(13,17): error TS2693: 'Map' only refers to a type, but is being used as a value here.

ERROR in /home/user/Projects/project/front/node_modules/angular2/src/facade/lang.d.ts
    (14,17): error TS2693: 'Set' only refers to a type, but is being used as a value here.

Body:
Have you added exclude node_modules to your tsconfig?

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}

Also, you aren't specifying which versions of Typescript and Angular you are using.

Edit:
You updated your question to specify that you're using Angular 4 but your updated errors show a node_modules/angular2/ folder which doesn't seem right. Before going further, try deleting your node_modules folder and run npm install again.

Otherwise it looks like you're having a typings issue.  Do you have any @types installed?

Here is an example of how my tsconfig.json is setup:

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "removeComments": false,
        "noImplicitAny": false,
        "types": [ "jasmine", "lodash", "core-js" ],
        "typeRoots": [
            "../node_modules/@types"
        ]
    },
    "exclude": [
        "node_modules",
        "wwwroot",
        "temp"
    ]
}

My node_modules folder is in the parent directory, so I specify that in the typeRoots.
With that I also have the following types installed as well:

"@types/core-js": "0.9.37",
"@types/jasmine": "2.5.43",
"@types/lodash": "4.14.55",