Friday, July 31, 2015

LINQ cleanup

Just a little example of some code cleanup.. it's a-OK to break out a logic into something long to get it working and give it some thought. It's great to take your work and make it better using tools like LINQ to make it easier to read and less space. There are times it is not worth it to make it smaller if its harder to read, however. Also, it can be good to cleanup code you see in large projects to make things neater!

Here is one example with 2 pieces of code for looking up a username.. you can search it by first name, last name, or both. Likely for usability the future holds a sorting feature too!

Before lots of LINQ: After putting if/else cases into "or" inside .Where of LINQ:

Tuesday, July 28, 2015

Get; Set;

Taking a step backwards from my normal posts to some more basics.. I wanted to explain Get; Set; on properties to anyone new to software. I felt like some of the descriptions online were a little non-user friendly and wanted to help clarify it. This is done in C#, but the concepts are the same idea with other languages.

        public class Person
            public string Name { get; set; }
            // Let's investigate this one
            public string Phone { get; set; }

        // This is called an auto-implemented property. What does this really mean?
        public string Phone { get; set; }

        // This is the longhand / what really happens / the manual way to do this. 
        private string phone;
        public string Phone
            get { return phone; }
            set { phone = value; }

        // Now what is THIS doing? Example time..
        // Make a Person1 of type Person. 
        Person Person1 = new Person();

        // Add a value to the property of Person. 
        Person1.Phone = "123-4567"; // **#1 see below

        // phone field
        private string phone; 
        // phone property
        public string Phone // **#1 hits this first, causing you to enter the braces..
            get { return phone; } // #3 returns little case phone, which has been assigned to value as property Phone
            set { phone = value; } // #2 sets the magical VALUE to little case phone

        // So now if we ask for..
        // thingy will be "123-4567";
        var thingy = Person1.Phone;

        // where do we get value from????
        // "The word value references the value that client code is attempting to assign to the property." - MSDN
        // In other words.. Microsoft took care of it for you.
        // You try to access and set a property, it knows to assign that to "value"

        // With this version, you can make a new property based on other properties / customization
        // not there is only a get here. Its like a read only value
        public string PhoneString
                string phoneNumString = "";
                // null safe it! 
                if (Person.Phone == null) return string.Empty;

                // if there's an area code, add it on! 
                if (!string.IsNullOrWhiteSpace(Person.Phone.AreaCode))
                    phoneNumString = "(" + Person.Phone.AreaCode + ") " + Person.Phone.PhoneNumber;
                else phoneNumString = Person.Phone.PhoneNumber; // if not, no biggie. 

                // if there's an extension, add it on too! 
                if (!string.IsNullOrWhiteSpace(Person.Phone.Extension)) phoneNumString += "ext." + Person.Phone.Extension;
                return phoneNumString;

        // So, running with the example above... here's what you can and can't do.. 
        // NOPE. Can't set this. There is only a get. 
        Person1.Phonestring = "(813)123-4567 ext. 1000"; // This will fail and throw you an error. ANGRY RED SQUIGGLYS. 

        // But! You can do this. And then... 
        Person1.AreaCode = "813";
        Person1.Phone = "123-4567";
        Person1.Extension = "1000";

        //  result = "(813)123-4567 ext. 1000"
        var result = Person1.Phonestring;

Monday, July 27, 2015

Cool APIs

Little side applications are fun to make. Try thinking of add-ons to your favorite current apps/websites to make them even better and you can make your own project! Or these are great tools to incorporate to make something else new and cool. I love adding JS libraries and APIs from other people and places to make use of the awesome things people put out into the web to share.

Of course, Google. Google drive? Email self a document = upload to drive? Oh the million possible projects using Google..

Unfortunately, google does not have a free API for translating anymore (you have to pay..).. but Microsoft does! I used this in my AnkiTranslate project. Good for if you want to work with multiple languages or make study aids to learn another language.

Can I say wheel of lunch? Lunch picker? Thing to do picker?

Practice stock market = $$$.. if you can get good at it.

And more..

LINQ Eager and Lazy Loading

Here's a little bit on using Linq and the ways to get data out via Eager / Lazy loading and LINQ methods vs operators. The explanations are in the code comments below.

using System.Data.Entity;
using System.Linq;
using EFFundamental;

namespace ConsoleApplication1
    class Program
        // How to query against entity data model
        static void Main(string[] args)

        // using LINQ operator
        // Lazy loading = fetch only main data and have to make subsequent calls to get related data. 
        // Use when you know related data is not required at all or at the time of the call. 
        private static void LinqOperatorLazyLoading()
            var context = new CHEntities();
            var query = from c in context.council_member 
                        where c.end_dtm != null
                        select c;
            var result = query.ToList();

           // note Lazy loading is by default, on.  If you want to change this..
           // context.ContextOptions.LazyLoadingEnabled = false;

        // using LINQ operator
        // Eager loading = explicitly fetching all the data related in one call.
        // Good if all your stuff is not too large or you are unsure of what pieces of data you will need. 
        // If it is a large amount of data.. slower but more complete. 
        private static void LinqOperatorEagerLoading()
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address") // the .Include is what makes it Eager loading (these are the "extra" objects )
                                                        .Include(x => x.council_lku) // to use lambdas, make sure to add: using System.Data.Entity;
                        where c.end_dtm != null
                        select c;
            var result = query.FirstOrDefault();

        // using LINQ methods .WHERE etc.. 
        private static void LinqMethods()
            var context = new CHEntities();
            var result = context.Compliance_Notes.Where(x => x.last_updated_by == "ctenn").ToList();

        private static void ProjectionQuery()
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address")
                        where c.end_dtm != null
                        // anonymous type and 2 of its properties. new object selecting only the properties you want. 
                        select new

Thursday, July 9, 2015

Project Euler 8: Largest product in a series (C#)

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.


Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Uncomfortably large 1000 digit number is getting stored as a string to begin with.. it's just too big to fit into the regular number types. Thought was I could either iterate through all possible sets of 13 then see if 0 is part of the set. If 0 is part of the set, obviously the product will be 0 which is less than a set without 0.. so just get rid of those possibilities. If we can get a product out of it that isn't 0, we are going to parse each string into its digit using LINQ then aggregate it into a product. Then compare the product to the last highest product. If it is higher, set the current highest product to the new product.

            Stopwatch stopwatch = new Stopwatch();
            string thousandDigitNum =
                "/*insert giant number here from their website*/";

            string thirteenDigitString = null;
            long newProduct = 0;
            long currHighestProduct = 0;

            for (int i = 0; i < (thousandDigitNum.Length -13); i++)
                thirteenDigitString = thousandDigitNum.Substring(i, 13);
                if (thirteenDigitString.Contains("0")) continue;
                newProduct = thirteenDigitString.Select(digit => long
                        .Aggregate((a, b) => a*b);
                if (newProduct > currHighestProduct) currHighestProduct = newProduct;


            Console.WriteLine("The highest value is: " + currHighestProduct + ". And the time elapsed is:" + stopwatch.Elapsed);

23514624000 is the solution.

Friday, July 3, 2015

Project Euler 7: 10,001 prime number (Java)

This one is interesting, if you think about it.. question is if there is a formula?

Well.. I looked for a formula for it and according to my favies wikipedia: "In number theory, a formula for primes is a formula generating the prime numbers, exactly and without exception. No such formula which is efficiently computable is known. A number of constraints are known, showing what such a "formula" can and cannot be.".. so "efficiently" iterate it is! You could iterate yourself to death going through every possibility.. or try and find a better way to iterate, just less.

I figured.. welp. Let's say we have the number 100. It breaks down into 1 x 100, 2 x 50, 4 x 25, 5 x 20, 10 x 10.. and stops there. The first number always goes up, second one always goes down. If they meet, they reverse.. and we are repeating ourselves. BUT you can try this, no matter what .. at least one of the pair of numbers is less than half. So we will ALWAYS catch the pair of multiples if we check all the numbers up to half. So what I am doing for example 100 is seeing if any number from 1-50 will divide evenly into it. The minute its divisible by any of those numbers iterating from 1 to 50, its not prime, doesn't get added to my magic list of numbers, and the loop continues to check 101.. and so on.

1031 ms to calculate is about a second, which fits into most of your attention spans out there.. so I'll take it :).

Point to note and something that was COOL. You can use (int)Math.ceil(num/2.0) to get a rounded up version of your number (ceil = ceiling, you can do Math.floor to get it rounded down.. floor is down whee). BAD thing. Don't forget your cast depending on the type of numbers being used!!!

import java.util.ArrayList;
import java.util.List;

 * Created by Crystal on 6/29/2015.

public class Program {
    public static void main(String[] args) {
        // Project Euler #7
        // What is the 10,001st prime number if we consider 2 the first prime number?

        long start = System.nanoTime();

        int num = 2;
        int halfNum = 0;
        boolean isPrime = true;

        List primeNumbersArr = new ArrayList() {};

        while (primeNumbersArr.size() < 10001){
            isPrime = true;

            if(num % 2 == 0 || num % 3 == 0 || num % 5 == 0) {

            halfNum = (int)Math.ceil(num/2.0);

            int i = 2;
            for (; i < halfNum; i++){
                if (num % i == 0){
                    isPrime = false;

            if (isPrime == true) primeNumbersArr.add(num);

        long stop = System.nanoTime();

        System.out.println(primeNumbersArr.get(10000)  + " is the solution calculated in a time of " + (stop - start) / 1000000 + "ms");


104743 is the solution calculated in a time of 1031ms.

Project Euler 6: sums and squares (Java)

So, I've taken to trying out IntelliJ and Java for some project euler problems and then will start making small apps in there. It's been fun, these puzzles are a good way to get a quick intro into Java. There are definitely some minor differences, but for the most part navigating the IDE and not having my shortcuts be the same has been the largest challenge. There is a free 1 year subscription to IntelliJ and Resharper (for C#) if you have a student email address ending in .edu, so I recommend giving it a shot!!!

import java.util.ArrayList;
import java.util.List;

 * Created by Crystal on 6/29/2015.

public class Program {
    public static void main(String[] args) {
        // Project Euler #6: Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum
        // Starting value, set x to 100
        long start = System.nanoTime();

        int x = 100;

        int sumOfSquares = (x * (x + 1) * (2 * x + 1)) / 6;
        int sum = 0;
        for (int i = 1; i <= x; i++)sum += i;

        long stop = System.nanoTime();

        System.out.println(sum*sum - sumOfSquares + " is the solution calculated in a time of " + (stop - start) / 1000000 + "ms");

25164150 is the solution calculated in a time of 0ms.