Thursday, February 26, 2015

Blast from the past: C++ revisited

Ok, I'll admit that C++ doesn't appear to be as popular as some other current languages and may not draw the interest of many new developers but it was one of the first handful of languages I learned - right after CoCo Basic, 6809E assembler, Microsoft QuickC 1.0 and then Turbo C++.  I used C/C++ extensively throughout college and C++ was the primary language I used for roughly half of my career.  I have a number of fond memories from those times - fortunately the memories of corrupted memory and segfaults faded.

Anyways, I decided to check and see what has changed over the last 10 years or so.  I figured that there likely have been a number of improvements and I am pleasantly surprised.  I picked up a copy of "Effective Modern C++ by Scott Meyers; published by O'Reilly" and working my way through it. This book covers newer stuff from the C++11 and C++14 standards.  In the process, I am trying out Eclipse (initially setup for Java EE and Reports developers) with CDT installed. I had Cygwin installed already with many of the GNU tools installed (including G++ 4.8.2).

The CDK tooling doesn't seem quite as refined as the Turbo C++ or old Visual Studio tools I used years ago but it is workable.  I may just need time to adapt a bit to something new.

A quick note on accessing the most current C++ features in Eclipse; you should set the language standard to C++1y which appears to map to C++14.  If you are just working from a command line and make files; pass '-std=c++1y' on the g++ command line. 



 Here is a short example using 'auto' and 'lambda' functionality.



The output from the above is:
My Name is scott
4 + 1 =5
lambda call result:120
'auto' lambda called; result=720


Here is an extended example passing lambda defined functions to a function.



Output:
This examples produces 12.28

I do want to note that the CDK tooling indicates a problem/confusion with the return type of function "fn" in this case but the g++ compiler produces a working executable. If you simply declare the return type of "fn" as double instead of auto the error indication goes away.  Hard to say what should happen here without digging into the standards doc I am thinking.

Overall, I'm happy to see the changes made to the language so far.  Other interesting changes appear to include threading/concurrency support and "move/perfect forwarding".  I'll have to work on some examples at some point.  I have always enjoyed C++ templates and want to revisit those when time permits.



Sunday, February 22, 2015

The funny things children do - our daughter

Ok, so you find a piece of paper sitting in the kitchen which looks like it was supposed to be the start of a "to get" list.  You take a quick look and laugh because it says "Gerbowl wiper" and we just naturally expected that she was being funny and was reminding us to get both a real bowl for the gerbils that they could use for a sand bath and something it clean it out with. 

What we didn't realize until a wee bit later is that the note was sitting on a kitchen washcloth and she was saying that she had used it to clean up a makeshift sand bath container we had been using. 

We now question the meaning of any notes and don't grab washcloths which are laying around..

The little things we can tease the kids with later in life are quite funny.. Hope to never forget any of these little things.

Enjoy and God bless!
Scott


Tuesday, February 17, 2015

Java 8 lambda Example 2

Here is a slightly more interesting Java 8 example.  The larger problem being solved involves several smaller needs.
  1. Finding a users active directory group memberships that match an application specific pattern
  2. Extracting an organizational "short name" from the group definitions
  3. Returning a list of official organizational ID's associated with the short names. 
Described in a little more detail; if you had a user that belonged to the AD groups like:
    CN=HapBu-WidgetMaint-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG
    CN=ChkSk-WidgetMgr-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG

    CN=Other-App-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG
You want to select the first 2 roles because they contain: 
     App-Employee-Role,OU=Security,OU=Groups
which would be the first 2 items.  From those, you want to take the "friendly org name" which would be the values "HapBu" and "ChkSk" and map those to an organization # by using an enum of valid organizations which maintains the mapping.
In the past this would probably require some fairly specific dedicated classes/methods.  I found that I am able to do this in a simpl fashion in Java 8.  I won't say that it was especially fast for me to develop this but I think over time it will become easier and more natural.

This enumeration, OrganizationInfo, is simply showing the use of a lambda if defining an a method which uses alternative key type info to search/select an enum value.
 package test2;  
 import java.util.Arrays;  
 import java.util.function.Predicate;  
 public     enum OrganizationInfo  
 {  
      HAPPYBURGER("O123", "HapBu"),  
      TONYTORTILLA("O543", "TonTo"),  
      CHICKENSHACK("O443", "ChkSk");  
      OrganizationInfo(final String orgCode,  
                final String displayableName)  
      {  
           this.orgCode = orgCode;  
           this.displayableName = displayableName;  
      }  
      String getOrgCode()  
      {  
           return orgCode;  
      }  
      /* This is a pretty generic method to select an enum  
       * value based on some attribute. For this example,  
       * it is a bit overkill but in a more realistic context this  
       * allows a good amount of code reuse.  
      */  
      private static OrganizationInfo search(  
                final Predicate<OrganizationInfo> predicate)  
      {  
           // This filters the enum list by the provided predicate and  
           // returns the first match.  
           return Arrays.asList(  
                     OrganizationInfo.values()).  
                     stream().  
                     filter(predicate).  
                     findFirst().  
                     get();  
      }  
      public static OrganizationInfo displayableNameToEnum(  
                final String displayableName)  
      {  
           // This is example client code to the previous private method and  
           // demonstrates using a lambda to specify the filter predicate  
           return search(p -> p.displayableName.equals(displayableName));  
      }  
      private String orgCode;  
      private String displayableName;  
 }  

The getMultValAttrib method is a good example of what code looks like which receives the lambda.
 package test2;  
 import java.util.Arrays;  
 import java.util.Collections;  
 import java.util.List;  
 import java.util.function.Function;  
 import java.util.function.Predicate;  
 import java.util.stream.Collectors;  
 public class User  
 {  
      /**  
           Responsible for querying multi-valued attribute data from  
           Active Directory for attribute "attribName", only process  
           items matching the predicate and then return values  
           as processed by the provided mapper function.  
      */  
      public List<String> getMultValAttrib(final String attribName,  
        final Predicate<String> predicate,  
           final Function<String, String> mapper)  
      {  
        List<String> data = Collections.emptyList();  
        // Get the data from active directory; skipping  
        // the real details here. Using some dummy data.  
        final String [] attributeData =  
             {  
                  "CN=HapBu-WidgetMaint-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG",  
                  "CN=ChkSk-WidgetMgr-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG"  
             };  
                  //adctx.getStringAttributes(attribName);  
        if (attributeData != null)  
        {  
                // This is where all the processing is actually done but  
                // note that the processing functions are passed in so this  
                // method is pretty generic.  
          data = Arrays.asList(attributeData). // stream uses a list  
            stream().  
            filter(predicate).  // Filter out only what we want to keep  
            map(mapper). // Perform some caller specific mapping  
            collect(Collectors.toList()); // Produce a list of results  
        }  
        return data;  
      }  
 }  


Below is an example of the above in use.
 package test2;  
 import java.util.List;  
 public class Test2  
 {  
      public static void main(String args[])  
      {  
           User aUser = new User();  
           //....  
           //...  
           List<String> orgCodes =  
                aUser.getMultValAttrib(  
                     "memberOf",  
                     p -> p.matches("(.*App-Employee-Role,OU=Security,OU=Groups.*)"),  
                     g -> OrganizationInfo.displayableNameToEnum(  
                               g.substring(3, g.indexOf('-'))).  
                               getOrgCode());  
           for(String org: orgCodes)  
           {  
                System.out.println(org);  
           }  
      }  
 }  


The above code produces the following output:
O123
O443