问:
ZooKeeper node counter?
I have a cluster of ZooKeeper with just 2 nodes, each zoo.conf has the following

```<code># Servers
server.1=10.138.0.8:2888:3888
server.2=10.138.0.9:2888:3888
</code>```

the same two lines are present in both configs

```<code>[root@zk1-prod supervisor.d]# echo mntr | nc  10.138.0.8 2181
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     5
zk_packets_sent 4
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   28
zk_max_file_descriptor_count    4096

[root@zk1-prod supervisor.d]# echo mntr | nc  10.138.0.9 2181
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     3
zk_packets_sent 2
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state leader
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   29
zk_max_file_descriptor_count    4096
zk_followers    1
zk_synced_followers     1
zk_pending_syncs        0
</code>```

so why zk_znode_count == 4 ?

答:
Znodes are not Zookeeper servers.

From Hadoop Definitive Guide:

Zookeeper doesn’t have files and directories, but a unified concept of
  a node, called a znode, which acts both as a container of data (like a
  file) and a container of other znodes (like a directory).

zk_znode_count refers to number of znodes available in that Zookeeper server. In your ZK ensemble, each server has four znodes.

Title: ZooKeeper node counter?

Body:
I have a cluster of ZooKeeper with just 2 nodes, each zoo.conf has the following

# Servers
server.1=10.138.0.8:2888:3888
server.2=10.138.0.9:2888:3888

the same two lines are present in both configs

[root@zk1-prod supervisor.d]# echo mntr | nc  10.138.0.8 2181
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     5
zk_packets_sent 4
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   28
zk_max_file_descriptor_count    4096

[root@zk1-prod supervisor.d]# echo mntr | nc  10.138.0.9 2181
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     3
zk_packets_sent 2
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state leader
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   29
zk_max_file_descriptor_count    4096
zk_followers    1
zk_synced_followers     1
zk_pending_syncs        0

so why zk_znode_count == 4 ?


来源: stackexchange

问:
Xamarin Forms Picker Item source binding in Xaml
I need to create states picker in my Xamarin Forms. I am using Xaml file for creating views.

Can any one help me to bind Picker in Xaml with item source?

答:
As JordanMazurke commented, XLabs has it.
Here is an example:

```<code><ContentPage x:Class="XLabs.Samples.Pages.Controls.ExtendedPickerPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
         Title="Picker">
<ContentPage.Content>
    <StackLayout x:Name="myStackLayout">
        <Label Text="Xaml:" />
        <controls:ExtendedPicker x:Name="myPicker"
                                 DisplayProperty="FirstName"
                                 ItemsSource="{Binding MyDataList}"
                                 SelectedItem="{Binding TheChosenOne}" />
    </StackLayout>
</ContentPage.Content>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As JordanMazurke commented, XLabs has it.
Here is an example:

<ContentPage x:Class="XLabs.Samples.Pages.Controls.ExtendedPickerPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
         Title="Picker">
<ContentPage.Content>
    <StackLayout x:Name="myStackLayout">
        <Label Text="Xaml:" />
        <controls:ExtendedPicker x:Name="myPicker"
                                 DisplayProperty="FirstName"
                                 ItemsSource="{Binding MyDataList}"
                                 SelectedItem="{Binding TheChosenOne}" />
    </StackLayout>
</ContentPage.Content>


问:
How to determine if a type implements an interface with C# reflection
Does reflection in C# offer a way to determine if some given System.Type type models some interface?

```<code>public interface IMyInterface {}

public class MyType : IMyInterface {}

// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
</code>```

答:
I just did:

```<code>public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}
</code>```

I wish I could have said where I : interface, but interface is not a generic parameter constraint option. class is as close as it gets.

Usage:

```<code>if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();
</code>```

I just said Implements because that's more intuitive. I always get IsAssignableFrom flip-flopped.

ContentLicense: CC BY-SA 2.5

Body:
Does reflection in C# offer a way to determine if some given System.Type type models some interface?

public interface IMyInterface {}

public class MyType : IMyInterface {}

// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);

Body:
I just did:

public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}

I wish I could have said where I : interface, but interface is not a generic parameter constraint option. class is as close as it gets.

Usage:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

I just said Implements because that's more intuitive. I always get IsAssignableFrom flip-flopped.


问:
search in a range of latitude and longitude from text file on server in iOS app
I am trying to search in a text file (available on a url) , there is latitude, longitude and other information separated by commas.
I need to search lat lon which is nearest to user's selected lat lon in app.
Code is done to read that file and search but it do not work perfectly.
Please let me know , how should I approach in this type of situation.
1)File get updated in real time , so I need to call url and read file every time user select location and click to get information.
2)And then search for nearest lat lon to the user's selected lat lon.

NSDICTIONARY DATA GETTING :-

```<code>(
    {
    "altitude_m" = "90.0";
    engName = “Station 1”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.058873";
    "local_time" = "16:20";
    lon = "23.976741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 2”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.048873";
    "local_time" = "16:20";
    lon = "23.876741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 3”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.059873";
    "local_time" = "16:20";
    lon = "23.986741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
</code>```

// MATCHING FUNCTION :-

```<code>-(void)matchLAtLongNow: (NSString *)latitude :(NSString *)longitude {

CLLocationCoordinate2D pinlocation;

pinlocation.latitude   = [latitude doubleValue];

pinlocation.longitude  = [longitude doubleValue];

float minLat = pinlocation.latitude - (searchDistance / 69);

float maxLat = pinlocation.latitude + (searchDistance / 69);

float minLon = pinlocation.longitude - searchDistance / fabs(cos(deg2rad(pinlocation.latitude))*69);
float maxLon = pinlocation.longitude + searchDistance / fabs(cos(deg2rad(pinlocation.longitude))*69);

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"lat <= %f AND lat >= %f AND lon <= %f AND lon >= %f",
                          maxLat, minLat, maxLon, minLon];

MatchedTxtArray = [myArray filteredArrayUsingPredicate:applePred];

}
</code>```

//GETTING ERROR
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber _fastCStringContents]: unrecognized selector sent to instance 0x175426460'
* First throw call stack:

答:
It sounds like you need a geo search, as opposed inclusion within some thresholds.  I'd reformulate to something like this:

```<code>NSArray *objects; // this is your parsed file, an array of dictionaries
CLLocation *userLocation;  // this is your user location

// sort the dictionary in order of distance to the userLocation
NSArray *sortedObjects = [objects sortedArrayUsingComparator:^(NSDictionary *objA,NSDictionary *objB) {
    CLLocationDistance distanceA = [self distanceToObject:objA from:userLocation];
    CLLocationDistance distanceB = [self distanceToObject:objB from:userLocation];
    return (NSComparisonResult)(distanceB-distanceA);
}];
</code>```

sortedObjects will contain the dictionaries sorted from nearest to farthest from the userLocation  We just need a function that produces the distance from the lat/lon values in the dictionary to the userLocation...

```<code>- (CLLocationDistance)distanceToObject:(NSDictionary *)object from:(CLLocation *)location {
    CLLocationDegrees latitude = [object[@"lat"] doubleValue];
    CLLocationDegrees longitude = [object[@"lob"] doubleValue];
    CLLocation *objectLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    return [objectLocation distanceFromLocation:location];
}
</code>```

Body:
I am trying to search in a text file (available on a url) , there is latitude, longitude and other information separated by commas.
I need to search lat lon which is nearest to user's selected lat lon in app.
Code is done to read that file and search but it do not work perfectly.
Please let me know , how should I approach in this type of situation.
1)File get updated in real time , so I need to call url and read file every time user select location and click to get information.
2)And then search for nearest lat lon to the user's selected lat lon.

NSDICTIONARY DATA GETTING :-

(
    {
    "altitude_m" = "90.0";
    engName = “Station 1”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.058873";
    "local_time" = "16:20";
    lon = "23.976741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 2”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.048873";
    "local_time" = "16:20";
    lon = "23.876741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 3”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.059873";
    "local_time" = "16:20";
    lon = "23.986741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}

// MATCHING FUNCTION :-

-(void)matchLAtLongNow: (NSString *)latitude :(NSString *)longitude {

CLLocationCoordinate2D pinlocation;

pinlocation.latitude   = [latitude doubleValue];

pinlocation.longitude  = [longitude doubleValue];

float minLat = pinlocation.latitude - (searchDistance / 69);

float maxLat = pinlocation.latitude + (searchDistance / 69);

float minLon = pinlocation.longitude - searchDistance / fabs(cos(deg2rad(pinlocation.latitude))*69);
float maxLon = pinlocation.longitude + searchDistance / fabs(cos(deg2rad(pinlocation.longitude))*69);

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"lat <= %f AND lat >= %f AND lon <= %f AND lon >= %f",
                          maxLat, minLat, maxLon, minLon];

MatchedTxtArray = [myArray filteredArrayUsingPredicate:applePred];

}

//GETTING ERROR
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber _fastCStringContents]: unrecognized selector sent to instance 0x175426460'
* First throw call stack:

Body:
It sounds like you need a geo search, as opposed inclusion within some thresholds.  I'd reformulate to something like this:

NSArray *objects; // this is your parsed file, an array of dictionaries
CLLocation *userLocation;  // this is your user location

// sort the dictionary in order of distance to the userLocation
NSArray *sortedObjects = [objects sortedArrayUsingComparator:^(NSDictionary *objA,NSDictionary *objB) {
    CLLocationDistance distanceA = [self distanceToObject:objA from:userLocation];
    CLLocationDistance distanceB = [self distanceToObject:objB from:userLocation];
    return (NSComparisonResult)(distanceB-distanceA);
}];

sortedObjects will contain the dictionaries sorted from nearest to farthest from the userLocation  We just need a function that produces the distance from the lat/lon values in the dictionary to the userLocation...

- (CLLocationDistance)distanceToObject:(NSDictionary *)object from:(CLLocation *)location {
    CLLocationDegrees latitude = [object[@"lat"] doubleValue];
    CLLocationDegrees longitude = [object[@"lob"] doubleValue];
    CLLocation *objectLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    return [objectLocation distanceFromLocation:location];
}


问:
Need to associate unique integer value with classes
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

```<code>type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;
</code>```

Testing this, I found out that I need to be super careful which class I declare. If I use this:

```<code>  var Fruit: TFruit;

  Fruit := TOrange.Create;
</code>```

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

答: If you're using Delphi 2010 you can use attributes to tag your classes with the ID.</p>

Body:
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;

Testing this, I found out that I need to be super careful which class I declare. If I use this:

  var Fruit: TFruit;

  Fruit := TOrange.Create;

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).


问:
how to get distinct column value1 from a table which does not include a particular value in column value 2 when it has multiple rows with col val1?
Probably a big Title! sorry for that.. :(

```<code>Table 1

id   col1    col2

1     10     one
2     11     two
3     10     three
</code>```

Now, i would like to write a sql query to get distinct col1 from table1 which doesn't have three in col2. I need the output col1 - 11 only.

I tried like this select distinct col1 from table1 where col2 != 'three' but this gives the result as both 10 and 11. But for 10 it has corresponding row with three as col2 value. Kindly help me to find this.

答:
Use group by and having.

```<code>select col1
from table1
group by col
having sum(case when col2='three' then 1 else 0 end)=0
</code>```

If you are using MySQL, the having condition can be shortened to

```<code>select col1
from table1
group by col
having sum(col2='three')=0
</code>```

as conditions are treated as booleans returning 1 for true and 0 for false.

Body:
Probably a big Title! sorry for that.. :(

Table 1

id   col1    col2

1     10     one
2     11     two
3     10     three

Now, i would like to write a sql query to get distinct col1 from table1 which doesn't have three in col2. I need the output col1 - 11 only.

I tried like this select distinct col1 from table1 where col2 != 'three' but this gives the result as both 10 and 11. But for 10 it has corresponding row with three as col2 value. Kindly help me to find this.

Body:
Use group by and having.

select col1
from table1
group by col
having sum(case when col2='three' then 1 else 0 end)=0

If you are using MySQL, the having condition can be shortened to

select col1
from table1
group by col
having sum(col2='three')=0

as conditions are treated as booleans returning 1 for true and 0 for false.


答:
using not in()

```<code>select distinct col1
from table1 t
where col1 not in (
  select col1
  from table1 i
  where i.col2 = 'three'
  )
</code>```

or using not exists()

```<code>select distinct col1
from table1 t
where not exists (
  select 1
  from table1 i
  where i.col1 = t.col1
    and i.col2 = 'three'
  )
</code>```

Title: how to get distinct column value1 from a table which does not include a particular value in column value 2 when it has multiple rows with col val1?

Body:
using not in()

select distinct col1
from table1 t
where col1 not in (
  select col1
  from table1 i
  where i.col2 = 'three'
  )

or using not exists()

select distinct col1
from table1 t
where not exists (
  select 1
  from table1 i
  where i.col1 = t.col1
    and i.col2 = 'three'
  )


问:
SSRS complex IIf expression
I'm stuck on an expression.  Below is programmatically what i want to do, but SSRS is not having it... How can I get this to work?  </p>

```<code>=IIf(Fields!TransTypeLabel.Value = "Hour", Fields!SalesAmount.Value, IIf(Fields!TransTypeLabel.Value = "Fee" AND Fields!CategoryId.Value = "TIME_FEE", Fields!SalesAmount.Value, 0), 0)
</code>```

答: ake the final " , 0" out (but not the end brace). You also have missed .Value (or .Label depending on what you actually want) from the end of some field references. e.g. Fields!TransTypeLabel should. be Fields!TransTypeLabel.Value . Or maybe that was a type and should have read Fields!TransType.Label ?</p>

Title: SSRS complex IIf expression

Body:
I'm stuck on an expression.  Below is programmatically what i want to do, but SSRS is not having it... How can I get this to work?

=IIf(Fields!TransTypeLabel.Value = "Hour", Fields!SalesAmount.Value, IIf(Fields!TransTypeLabel.Value = "Fee" AND Fields!CategoryId.Value = "TIME_FEE", Fields!SalesAmount.Value, 0), 0)


问:
How to display all values in a combobox by recordset (Access 2010)
I have the problem that the combobox in access 2010 displays just 1249 values of the 1278. Is there a possibility to increase the max number of values in a combobox in access?

Here is a code sample:

```<code>If not rs.EOF Then
    rs.MoveFirst
    frm.FName.RowSource = ""
    frm.FNameLux.RowSource = ""

    Do Until rs.EOF
        If rs![id] <> -1 And rs![id] <> -2 Then
            If (rs!KID <> 2 And rs!KID <> 8) Then
                If IsNull(rs![Name]) = False Then
                    frm.FName.AddItem rs![Name] & ";" & rs![id]
                    Debug.Print rs!Name 'The program writes all values in the combobox, but when I look in the form, I don't see all values
                End If
            End If

            If (rs!KID = 2 Or rs!KID = 8) Then
                If IsNull(rs![Name]) = False Then
                    frm.FNameLux.AddItem rs![Name] & ";" & rs![id]
                End If
            End If
        End If
        rs.MoveNext
        i = i + 1
    Loop
End If
</code>```

rs is the recordset. Is there any idea how to solve it or what I have to do?

答:
Apparently the RowSource property for RowSourceType = Value list is limited to 16bit integer length (2^15 = 32768) or a bit below.

Test code for a 2-column combobox:

Private Sub btValues_Click()

    Dim i As Long

    DoCmd.Hourglass True

    Me.cboValues.RowSource = ""
    For i = 1 To 5000
        Me.cboValues.AddItem "Number " & Format(i, "0000") & ";" & i
    Next i

    DoCmd.Hourglass False

    Debug.Print Len(Me.cboValues.RowSource)

End Sub
```

<p>The combobox is filled up until "Number 1991", output is <code>32739</code>.</p>

<p>So the problem is not the number of rows, but the total string length. If I shorten the text, it goes up to "Nr 2604" (32744 chars).</p>

<p>You'll have to use <code>RowSourceType = Table/query</code> to show all items.</p>

<p><strong>Edit</strong></p>

<p>Create queries as rowsource for the comboboxes. As far as I can see, there is nothing in your code that cannot be done in a WHERE clause.</p>

<p>E.g. for <code>FName</code></p>

<pre class="lang-sql prettyprint-override"><code>SELECT Name, id
FROM yourTable
WHERE id <> -1 AND id <> -2
  AND KID <> 2 AND KID <> 8
  AND Name IS NOT NULL
</code>```

If your VBA code could not be recreated in SQL, you'd have to insert the recordset rows you want into a temp table, and use this table as rowsource.

Body:
I have the problem that the combobox in access 2010 displays just 1249 values of the 1278. Is there a possibility to increase the max number of values in a combobox in access?

Here is a code sample:

If not rs.EOF Then
    rs.MoveFirst
    frm.FName.RowSource = ""
    frm.FNameLux.RowSource = ""

    Do Until rs.EOF
        If rs![id] <> -1 And rs![id] <> -2 Then
            If (rs!KID <> 2 And rs!KID <> 8) Then
                If IsNull(rs![Name]) = False Then
                    frm.FName.AddItem rs![Name] & ";" & rs![id]
                    Debug.Print rs!Name 'The program writes all values in the combobox, but when I look in the form, I don't see all values
                End If
            End If

            If (rs!KID = 2 Or rs!KID = 8) Then
                If IsNull(rs![Name]) = False Then
                    frm.FNameLux.AddItem rs![Name] & ";" & rs![id]
                End If
            End If
        End If
        rs.MoveNext
        i = i + 1
    Loop
End If

rs is the recordset. Is there any idea how to solve it or what I have to do?

Body:
Apparently the RowSource property for RowSourceType = Value list is limited to 16bit integer length (2^15 = 32768) or a bit below.

Test code for a 2-column combobox:

Private Sub btValues_Click()

    Dim i As Long

    DoCmd.Hourglass True

    Me.cboValues.RowSource = ""
    For i = 1 To 5000
        Me.cboValues.AddItem "Number " & Format(i, "0000") & ";" & i
    Next i

    DoCmd.Hourglass False

    Debug.Print Len(Me.cboValues.RowSource)

End Sub

The combobox is filled up until "Number 1991", output is 32739.

So the problem is not the number of rows, but the total string length. If I shorten the text, it goes up to "Nr 2604" (32744 chars).

You'll have to use RowSourceType = Table/query to show all items.

Edit

Create queries as rowsource for the comboboxes. As far as I can see, there is nothing in your code that cannot be done in a WHERE clause.

E.g. for FName

SELECT Name, id
FROM yourTable
WHERE id <> -1 AND id <> -2
  AND KID <> 2 AND KID <> 8
  AND Name IS NOT NULL

If your VBA code could not be recreated in SQL, you'd have to insert the recordset rows you want into a temp table, and use this table as rowsource.


问:
How to check if rufus-scheduler is already running for my Rails Application
I have a Rails application that uses rufus-scheduler to schedule some of its tasks. The scheduler get initialised in the after_fork of a unicorn script initiating the Rails application (Reference: https://gist.github.com/jkraemer/3851917).

Recently, I encountered a scenario where the unicorn scheduler thread got killed while the unicorn process hosting it was still active. This lead to the scheduler being down for a considerable time without notice.

I would like to setup an alert and monitoring system to handle such scenarios that should be capable of:
1. Throwing an alert whenever the scheduler thread is killed/aborted.
2. Restart the scheduler if the Rails process is running.

What would be a suitable way to know the running status of the scheduler, through perhaps a cron task and handle the auto-restart ?

答:
If you bring in a cron task to watch rufus-scheduler, why don't you simply drop rufus-scheduler and use Whenever for all the scheduling? You'll thus have a 100% crond solution.

Another alternative, use Foreman to manage a) your Rails application b) a separate process hosting your rufus-scheduler schedules (it could be a "schedule only" version of your Rails application) (here is a nice example in a blog post). There is also God.

If you look at Clockwork, a gem that was inspired by rufus-scheduler, they detail such one application / multiple processes scenarii.

Then you could look at the various tools out there to watch your logs and alert you in case of error.

Update:

Maybe this gist could help: https://gist.github.com/jmettraux/5f716c8568f6ab7bb016a4bc11528bc2


问:
Segmentation Fault on graph simplify
I am merging nodes in a graph using contract_vertices and then calling simplify on the graph but I am getting segmentation fault in doing so. I am not sure what I am doing wrong. Here is the code to reproduce the error:

```<code>from igraph import summary, read, Graph
g = Graph()
g.add_vertices(5)
g.vs["name"] = ["1","2","3","4","5"]
g.add_edge("1","2")
merge_vertex_list = [1,1,3,3,3]
g.contract_vertices(merge_vertex_list,"first")
g.simplify()
</code>```

The error I am getting:

```<code>Segmentation fault: 11
</code>```

Note: when I am calling contract_vertices without second argument i.e. combine_attrs parameter it is working fine.

答: I figured out the reason for it. The list I am passing for merging the array should contain contiguous integers, which will form new indexes of vertices. In above case I was passing [1,1,3,3,3] which when changed to [0,0,1,1,1] worked fine. Still I think it should have shown a meaningful error message.

Title: Segmentation Fault on graph simplify

Body:
I am merging nodes in a graph using contract_vertices and then calling simplify on the graph but I am getting segmentation fault in doing so. I am not sure what I am doing wrong. Here is the code to reproduce the error:

from igraph import summary, read, Graph
g = Graph()
g.add_vertices(5)
g.vs["name"] = ["1","2","3","4","5"]
g.add_edge("1","2")
merge_vertex_list = [1,1,3,3,3]
g.contract_vertices(merge_vertex_list,"first")
g.simplify()

The error I am getting:

Segmentation fault: 11

Note: when I am calling contract_vertices without second argument i.e. combine_attrs parameter it is working fine.


问:
Version Deprecation Facebook Graph API v2.2
our Facebook Login is not working right now. We have received a message from Facebook Developer Portal:

"Name of app" currently has access to Graph API v2.2 which will reach the end of its
  2-year lifetime on 27 March, 2017. To ensure a smooth transition,
  please migrate all calls to Graph API v2.3 or higher.

To check if your app will be affected by this upgrade you can use the
  Version Upgrade Tool. This will show you which calls, if any, are
  affected by this change as well as any replacement calls in newer
  versions. If you do not see any calls, your app may not be affected by
  this change.

You can also use our changelog to see the full list of changes in all
  Graph API versions.

We are using ASP.NET MVC 5, and we are using or authentication like this:

```<code>var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = "****",
                AppSecret = "****",
                AuthenticationType = "Facebook",
                SignInAsAuthenticationType = "ExternalCookie",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async ctx => ctx.Identity.AddClaim(new Claim(ClaimTypes.Email, ctx.User["email"].ToString()))
                }
            };

            facebookAuthenticationOptions.Scope.Add("email");
</code>```

But today, our login info object, is null in ExternalLoginCallback:

```<code>        [HttpGet]
        [AllowAnonymous]
        [RequireHttps]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
        {
            try
            {
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                {
                    return RedirectToAction("Login");
                }
... more code here...
</code>```

In Facebook Dev. Portal our API Version is 2.3

We have tested many options, with no results:

Access email address in the OAuth ExternalLoginCallback from Facebook v2.4 API in ASP.NET MVC 5

Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?

Thank you much for the help.

答:
If you cant update OWIn packages because of language packages (as my case) you can

Modify the Identity Startup class code:

```<code>var facebookOptions = new FacebookAuthenticationOptions()
{
    AppId = "your app id",
    AppSecret = "your app secret",
    BackchannelHttpHandler = new FacebookBackChannelHandler(),
    UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
    Scope = { "email" }
};

app.UseFacebookAuthentication(facebookOptions);
</code>```

This is the definition class for FacebookBackChannelHandler():

```<code>public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        var result = await base.SendAsync(request, cancellationToken);
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            return result;
        }

        var content = await result.Content.ReadAsStringAsync();
        var facebookOauthResponse = JsonConvert.DeserializeObject<FacebookOauthResponse>(content);

        var outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
        outgoingQueryString.Add(nameof(facebookOauthResponse.access_token), facebookOauthResponse.access_token);
        outgoingQueryString.Add(nameof(facebookOauthResponse.expires_in), facebookOauthResponse.expires_in + string.Empty);
        outgoingQueryString.Add(nameof(facebookOauthResponse.token_type), facebookOauthResponse.token_type);
        var postdata = outgoingQueryString.ToString();

        var modifiedResult = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(postdata)
        };

        return modifiedResult;
    }
}

private class FacebookOauthResponse
{
    public string access_token { get; set; }
    public long expires_in { get; set; }
    public string token_type { get; set; }
}
</code>```

Body:
our Facebook Login is not working right now. We have received a message from Facebook Developer Portal:

"Name of app" currently has access to Graph API v2.2 which will reach the end of its
  2-year lifetime on 27 March, 2017. To ensure a smooth transition,
  please migrate all calls to Graph API v2.3 or higher.

To check if your app will be affected by this upgrade you can use the
  Version Upgrade Tool. This will show you which calls, if any, are
  affected by this change as well as any replacement calls in newer
  versions. If you do not see any calls, your app may not be affected by
  this change.

You can also use our changelog to see the full list of changes in all
  Graph API versions.

We are using ASP.NET MVC 5, and we are using or authentication like this:

var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = "****",
                AppSecret = "****",
                AuthenticationType = "Facebook",
                SignInAsAuthenticationType = "ExternalCookie",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async ctx => ctx.Identity.AddClaim(new Claim(ClaimTypes.Email, ctx.User["email"].ToString()))
                }
            };

            facebookAuthenticationOptions.Scope.Add("email");

But today, our login info object, is null in ExternalLoginCallback:

        [HttpGet]
        [AllowAnonymous]
        [RequireHttps]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
        {
            try
            {
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                {
                    return RedirectToAction("Login");
                }
... more code here...

In Facebook Dev. Portal our API Version is 2.3

We have tested many options, with no results:

Access email address in the OAuth ExternalLoginCallback from Facebook v2.4 API in ASP.NET MVC 5

Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?

Thank you much for the help.

Body:
If you cant update OWIn packages because of language packages (as my case) you can

Modify the Identity Startup class code:

var facebookOptions = new FacebookAuthenticationOptions()
{
    AppId = "your app id",
    AppSecret = "your app secret",
    BackchannelHttpHandler = new FacebookBackChannelHandler(),
    UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
    Scope = { "email" }
};

app.UseFacebookAuthentication(facebookOptions);

This is the definition class for FacebookBackChannelHandler():

public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        var result = await base.SendAsync(request, cancellationToken);
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            return result;
        }

        var content = await result.Content.ReadAsStringAsync();
        var facebookOauthResponse = JsonConvert.DeserializeObject<FacebookOauthResponse>(content);

        var outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
        outgoingQueryString.Add(nameof(facebookOauthResponse.access_token), facebookOauthResponse.access_token);
        outgoingQueryString.Add(nameof(facebookOauthResponse.expires_in), facebookOauthResponse.expires_in + string.Empty);
        outgoingQueryString.Add(nameof(facebookOauthResponse.token_type), facebookOauthResponse.token_type);
        var postdata = outgoingQueryString.ToString();

        var modifiedResult = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(postdata)
        };

        return modifiedResult;
    }
}

private class FacebookOauthResponse
{
    public string access_token { get; set; }
    public long expires_in { get; set; }
    public string token_type { get; set; }
}


问:
How to use multiple functions, File-Out and del, in single Powershell command?
I am using Powershell v4.0 to remove some duplicate files off of our drive and generate some reports. Our hope is no one will care that we're removing duplicate files - but if they do then I can just restore the files to their location.

I create a report showing all duplicates. I create a report of all the files I'll keep. I create a report of all the files I'll erase. And finally I actually make the deletion.

The first command is to get a report of all the duplicate files that I have:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"
</code>```

The second command is to get a report of all the files I'll keep:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"
</code>```

The third command is to get a report of all the files I'll erase:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"
</code>```

The fourth command is to delete all of the duplicate files:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | del
</code>```

Can I combine multiple commands? It takes eight hours and thirty minutes per iteration of the command, so running it four times doesn't seem like a great solution.

In the least to be able to print out what I'm deleting, and to delete the files at the same step would be a good step forward.

答:
Similar to @BenH I'd suggest only getting the files and hashing once, but there's no reason to loop through the whole thing 4 times. Just put all four commands in one ForEach loop.

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % {
    $_.group | Out-File "c:\users\me\desktop\duplicatelist.txt"
    $_.group[0] | Out-File "c:\users\me\desktop\keep.txt"
    $_.group | select -skip 1 | Out-File "c:\users\me\desktop\delete.txt"
    $_.group | select -skip 1 | del
}
</code>```

Edit: Better yet, combine the last two commands with Tee-Object so it comes out to this:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % {
    $_.group | Out-File "c:\users\me\desktop\duplicatelist.txt"
    $_.group[0] | Out-File "c:\users\me\desktop\keep.txt"
    $_.group | select -skip 1 | Tee-Object -FilePath "c:\users\me\desktop\delete.txt" -Append | del
}
</code>```

Body:
I am using Powershell v4.0 to remove some duplicate files off of our drive and generate some reports. Our hope is no one will care that we're removing duplicate files - but if they do then I can just restore the files to their location.

I create a report showing all duplicates. I create a report of all the files I'll keep. I create a report of all the files I'll erase. And finally I actually make the deletion.

The first command is to get a report of all the duplicate files that I have:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"

The second command is to get a report of all the files I'll keep:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"

The third command is to get a report of all the files I'll erase:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"

The fourth command is to delete all of the duplicate files:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | del

Can I combine multiple commands? It takes eight hours and thirty minutes per iteration of the command, so running it four times doesn't seem like a great solution.

In the least to be able to print out what I'm deleting, and to delete the files at the same step would be a good step forward.

Body:
Similar to @BenH I'd suggest only getting the files and hashing once, but there's no reason to loop through the whole thing 4 times. Just put all four commands in one ForEach loop.

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % {
    $_.group | Out-File "c:\users\me\desktop\duplicatelist.txt"
    $_.group[0] | Out-File "c:\users\me\desktop\keep.txt"
    $_.group | select -skip 1 | Out-File "c:\users\me\desktop\delete.txt"
    $_.group | select -skip 1 | del
}

Edit: Better yet, combine the last two commands with Tee-Object so it comes out to this:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % {
    $_.group | Out-File "c:\users\me\desktop\duplicatelist.txt"
    $_.group[0] | Out-File "c:\users\me\desktop\keep.txt"
    $_.group | select -skip 1 | Tee-Object -FilePath "c:\users\me\desktop\delete.txt" -Append | del
}


问:
How do I make DOM/event listeners aware of newly appended nodes?
TL;DR:

I use $(..).append(node), but newly added nodes are not considered for inclusion despite them (supposedly) matching jQuery selectors.

Question

I have some code below that uses checkboxes but emulates radio button behavior.  In other words, only one checkbox can (validly) be selected at any time.  No more than one should be selected.

If you run the example below and click on the first 3 checkboxes, they will behave like radio buttons.  Only one will be selected, no matter how many you click.

However, if you Add Point, newly added points will not be considered for the JS even though in theory it should grab them too...

Specifically:  You can select the newly added checkbox, and it will be selected in addition to one already selected previously.  That is incorrect as only 1 should be selected at any time and all others should be unselected.

What is happening and how can I have newly added nodes be included into jQuery selectors?

$(function() {

  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });

  $("#addCasePoint").on("click", function() {
    var newRowIndex = $('#newRowIndex').text();
    var template = $('#casePointTemplate').data('template');
    template = template.replace(/__index__/g, newRowIndex);
    $('#casePointsFieldset').append(template);
    $('#newRowIndex').text(++newRowIndex);
    return false;
  });

  //deletes case point
  $("#selection").on("click", ".removeCase", function() {
    var caseCount = $('#selection .casePointFieldset').length
    if (caseCount === 1) return false; //keep at least one row
    $(this).closest("fieldset").remove();
    return false;
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.casePointFieldset {
  display: inline-block;
}</code>```

<form id="selection">
  <fieldset id="casePointsFieldset">
    <legend>Case Points</legend>

      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>

    <span id="casePointTemplate" data-template="<fieldset class="casePointFieldset">
Duty: <input name="point[__index__]" class="duty" value="1" type="checkbox">
<button class="removeCase">Remove</button></fieldset>">

  </fieldset>

  <button id="addCasePoint">Add Point</button>
</form>```

答:
The problem is how you're binding to them. The .click function (or .on('click')) basically works like this:

Find all of the currently existing elements which match a selector ($('.your.selector.here'))

Attach an event handler to each of those elements

Notice how I mentioned it binds to ones which already exist? That means it won't bind to newly created ones automatically. However, you can use .on to bind to the parent of those elements then listen for events on a selector. I'll show you what I mean:

$('#addItem').click(function() {
  $('.container').append('<button class="item">Item</button>');
});

// Notice that I'm binding to the parent
// then specifying which events from it's children
// I want to listen to (click events from .item elements)
$('.container').on('click', '.item', function() {
  console.log("I'm an item");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button class="item">Item</button>
</div>
<button id="addItem">Add New Item</button></code>```

If you change your on('click' to work like that then you'll have no problems.

Body:
TL;DR:

I use $(..).append(node), but newly added nodes are not considered for inclusion despite them (supposedly) matching jQuery selectors.

Question

I have some code below that uses checkboxes but emulates radio button behavior.  In other words, only one checkbox can (validly) be selected at any time.  No more than one should be selected.

If you run the example below and click on the first 3 checkboxes, they will behave like radio buttons.  Only one will be selected, no matter how many you click.

However, if you Add Point, newly added points will not be considered for the JS even though in theory it should grab them too...

Specifically:  You can select the newly added checkbox, and it will be selected in addition to one already selected previously.  That is incorrect as only 1 should be selected at any time and all others should be unselected.

What is happening and how can I have newly added nodes be included into jQuery selectors?

$(function() {

  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });

  $("#addCasePoint").on("click", function() {
    var newRowIndex = $('#newRowIndex').text();
    var template = $('#casePointTemplate').data('template');
    template = template.replace(/__index__/g, newRowIndex);
    $('#casePointsFieldset').append(template);
    $('#newRowIndex').text(++newRowIndex);
    return false;
  });

  //deletes case point
  $("#selection").on("click", ".removeCase", function() {
    var caseCount = $('#selection .casePointFieldset').length
    if (caseCount === 1) return false; //keep at least one row
    $(this).closest("fieldset").remove();
    return false;
  });
});

.casePointFieldset {
  display: inline-block;
}

<form id="selection">
  <fieldset id="casePointsFieldset">
    <legend>Case Points</legend>

      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>
      <fieldset class="casePointFieldset">

          Duty: <input name="point[1]" class="duty" value="1" type="checkbox">

        <button class="removeCase">Remove</button>
      </fieldset>

    <span id="casePointTemplate" data-template="<fieldset class="casePointFieldset">
Duty: <input name="point[__index__]" class="duty" value="1" type="checkbox">
<button class="removeCase">Remove</button></fieldset>">

  </fieldset>

  <button id="addCasePoint">Add Point</button>
</form>

Body:
The problem is how you're binding to them. The .click function (or .on('click')) basically works like this:

Find all of the currently existing elements which match a selector ($('.your.selector.here'))

Attach an event handler to each of those elements

Notice how I mentioned it binds to ones which already exist? That means it won't bind to newly created ones automatically. However, you can use .on to bind to the parent of those elements then listen for events on a selector. I'll show you what I mean:

$('#addItem').click(function() {
  $('.container').append('<button class="item">Item</button>');
});

// Notice that I'm binding to the parent
// then specifying which events from it's children
// I want to listen to (click events from .item elements)
$('.container').on('click', '.item', function() {
  console.log("I'm an item");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button class="item">Item</button>
</div>
<button id="addItem">Add New Item</button>

If you change your on('click' to work like that then you'll have no problems.


问:
If else condition in MSSQL
Suppose I have serial number, test name and few other columns, i want to write a condition if TESTNAME is null for a particular serial number then set the TESTNAME to blank else perform inner join

```<code>SELECT
    (A.PTNUMBER + '-' +A.SL_NO) AS ENUMBER,
    D.ENGINEER AS REQ, D.DATETIME as "DATE",
    (select Value
     from DROPDOWN
     where B.TEST_NAME=CONVERT(VARCHAR,DropdownID)) TESTNAME,
    TABLE_NAME AS TABLETD
FROM INSPECTION D
INNER JOIN TABLEA A ON D.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEB B ON B.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEC C ON C.ENGID = CONVERT(VARCHAR,A.EN_ID)
</code>```

答:
not sure what you mean by set testname to blank but if you meant to be using a SELECT query then you can do like

```<code>select *,
case when TESTNAME is null and serial_number = some_value then '' end as TESTNAME
from mytable
</code>```

Title: If else condition in MSSQL

Body:
Suppose I have serial number, test name and few other columns, i want to write a condition if TESTNAME is null for a particular serial number then set the TESTNAME to blank else perform inner join

SELECT
    (A.PTNUMBER + '-' +A.SL_NO) AS ENUMBER,
    D.ENGINEER AS REQ, D.DATETIME as "DATE",
    (select Value
     from DROPDOWN
     where B.TEST_NAME=CONVERT(VARCHAR,DropdownID)) TESTNAME,
    TABLE_NAME AS TABLETD
FROM INSPECTION D
INNER JOIN TABLEA A ON D.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEB B ON B.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEC C ON C.ENGID = CONVERT(VARCHAR,A.EN_ID)

Body:
not sure what you mean by set testname to blank but if you meant to be using a SELECT query then you can do like

select *,
case when TESTNAME is null and serial_number = some_value then '' end as TESTNAME
from mytable


问:
Navigation drawer on all activities
I have two activities the first one is 'Navigation drawer activity' (MainActivity) and the second activity I have created is a 'Tabbed activity' (OverView). How can I add Navigation drawer menu on Tabbed activity.

Your help and suggestion are very helpful.

Thanks
Rao

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>
</code>```

app_bar_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>
</code>```

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.raoburugula.mytable.MainActivity"
tools:showIn="@layout/app_bar_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
 </RelativeLayout>
</code>```

nav_header_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="android.studio@android.com" />

 </LinearLayout>
</code>```

MainActivity.java

```<code>package com.raoburugula.mytable;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)
     findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
     Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,
    R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView)
    findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.overview) {
        Intent overviewIntent = new Intent(getApplicationContext(),
    OverView.class);
        startActivity(overviewIntent);
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
   }
 }
</code>```

Overview activity where I want navigation menu is

activity_over_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.OverView">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>
</code>```

fragment_over_view.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.raoburugula.mytable.OverView$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

 </RelativeLayout>
</code>```

OverView.Java

```<code>package com.raoburugula.mytable;

 import android.support.design.widget.TabLayout;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;

 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
  import android.view.View;
  import android.view.ViewGroup;

  import android.widget.TextView;

 public class OverView extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
     SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton)
      findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_over_view, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_over_view,
          container, false);
        TextView textView = (TextView)
          rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format,
        getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
    below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
   }
}
</code>```

答: You are done well so far except one thing. Instead of using Intent overviewIntent = new Intent(getApplicationContext(), OverView.class); you need to create OverView class as fragment and attache it existing MainActivity. You are done.

Title: Navigation drawer on all activities

Body:
I have two activities the first one is 'Navigation drawer activity' (MainActivity) and the second activity I have created is a 'Tabbed activity' (OverView). How can I add Navigation drawer menu on Tabbed activity.

Your help and suggestion are very helpful.

Thanks
Rao

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>

app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.raoburugula.mytable.MainActivity"
tools:showIn="@layout/app_bar_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
 </RelativeLayout>

nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="android.studio@android.com" />

 </LinearLayout>

MainActivity.java

package com.raoburugula.mytable;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)
     findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
     Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,
    R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView)
    findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.overview) {
        Intent overviewIntent = new Intent(getApplicationContext(),
    OverView.class);
        startActivity(overviewIntent);
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
   }
 }

Overview activity where I want navigation menu is

activity_over_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.OverView">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>

fragment_over_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.raoburugula.mytable.OverView$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

 </RelativeLayout>

OverView.Java

package com.raoburugula.mytable;

 import android.support.design.widget.TabLayout;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;

 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
  import android.view.View;
  import android.view.ViewGroup;

  import android.widget.TextView;

 public class OverView extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
     SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton)
      findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_over_view, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_over_view,
          container, false);
        TextView textView = (TextView)
          rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format,
        getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
    below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
   }
}