Monday, 11 January 2016

The new book is good

The oracle OCA Java book is good but it does leave some gaps, more make this work which is good in some ways frustrating in others. Anyway it is filling in lots of little gaps which is what I need. I had to postpone the exam as I just wasn't ready. 

Articles and bits I liked this week,
Trying to make some tools for work although one API responds so much slower using the below instead of browser, taken URLs out. At first I thought it was because the API was first on the list, rejigged it so the problem URL not first same issue. At least it is a start. (done in my own time)

package com.company;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;

public class apiTester {

    public Map<String, String> apiURLs = new HashMap<>();

    public apiTester() {
        apiURLs.put("google",        "https://www.google.co.uk/");
        apiURLs.put("bbc",           "http://www.bbc.co.uk/");
    }

    public void runTests() {
        long startTime, stopTime = 1;
        for (String apiName : apiURLs.keySet()) {
            startTime = System.currentTimeMillis();
            HttpURLConnection connection = null;
            try {
                URL apiURL = new URL(apiURLs.get(apiName));
                connection =  

                (HttpURLConnection)apiURL.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
            } catch (MalformedURLException ex) {
                System.out.println("Bad URL");
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (connection != null)
                    connection.disconnect();
            }
            stopTime = System.currentTimeMillis();
            System.out.print(String.format("%1$-20s"  ,apiName));
            System.out.println((int) (stopTime - startTime) + "ms");
        }
    }
}

Sunday, 3 January 2016

Articles and lego picture maker getting there

Articles and news I liked, 
Been working on a lego picture maker, which has a got a bit out of hand needs a to be refactored and a lot of stuff to add just pleased it is slowly getting there (link). 

At the moment I cannot find a good up to date Java podcast however there is a podcast from early 2015, corejava: technical programming tests, the idea of a technical test done from home makes far more sense to me.

Finding the Java 8 OCA hard, worked through the Sybex Java 8 study guide and finding the tests hard going, ordered the Oracle versions at least the explanations of the topics will be different, the book is twice the size of the Sybex version.

Not seen much in the way of code camps here in the UK that do more than javascript and front end however these guys (the Iron yard) do everything and the Java Clojure course looks fun, 3 months and £8000 :O.

Thursday, 24 December 2015

Challenge 246 xmas lights

Pleased I knocked it out pretty quickly, possibly used too many variables but reads OK to me. Side note talking at work about hardest programming languages, I had brainfuck down as hard but Malbolge is another level of toughness.

package com.company;

import java.text.DecimalFormat;

public class XmasLights {
    private final int hoursLightRequired;
    private final int batteryCapacity = 1200;
    private final int ledmA = 20;
    private final double ledVoltage = 1.7;
    private final int ledsPerCiruit = 5;
    private final int batteryVoltage = 9;

    public XmasLights(int hoursLightRequired) {
        this.hoursLightRequired = hoursLightRequired;
    }

    public void go() {
        int leds = amountOfLedsForTime();
        resistanceNeeded();
        drawCircuit(leds);
    }

    //part 1, input is the max amount of leds we can have for that time
    public int amountOfLedsForTime() {
        int maxLeds = (batteryCapacity / hoursLightRequired / ledmA) * ledsPerCiruit;
        return maxLeds;
    }

    public void drawCircuit(int lights) {
        String serialCircuit = "--|>|---|>|---|>|---|>|---|>|--";
        String joiningBars = " |                             |";
        System.out.println("Scheme:");
        int ledsToDraw = lights / ledsPerCiruit;
        for (int i = 0; i < ledsToDraw; i++) {
            if (i == 0) {
                System.out.println("*" + serialCircuit + "*");
            } else  {
                System.out.println(serialCircuit);
            }
            if (i < ledsToDraw - 1) {
                System.out.println(joiningBars);
            }
        }
    }

    public double resistanceNeeded() {
        double voltageOverResister = batteryVoltage - (ledsPerCiruit * ledVoltage);
        double ohms = voltageOverResister / (batteryCapacity / 1000d);
        DecimalFormat df = new DecimalFormat("#.###");
        System.out.println("Resistance needed: " + df.format(ohms));
        return ohms;
    }
}

Tuesday, 22 December 2015

Lazyness

Fed up of writing to a text file everyday what I do in the day ready for tomorrow's scrum, from what I have read I can make a bat file put into windows start up folder and no more typing the same thing everyday.

It does need a couple of changes, keen to keep one file per year which then this program would create as needed once updated. It does seem a bit much on the try catch however I do not want to create new entries if I need to reboot during the work day.

Also seems strange to me that to add to the start of the file I need to write it all again.

package com.company;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * Created by R on 22/12/2015.
 */
public class diaryWriter {
    private String path = "";
    private LocalDate today = LocalDate.now();
    private DateTimeFormatter formatter =   

      DateTimeFormatter.ofPattern("dd-MM-yyy");
    private String message;

    public void writeMessageToDiary() {
        message = today.format(formatter)
                + "\nTested"
                + "\nTest Cases"
                + "\nRaised"
                + "\nComplete"
                + "\nNotes"
                + "\n\n";

        //Only write to file if not been written to today
        if ( !isTodayLatest() ) {
            prependMessageToFile();
        }
    }

    private boolean isTodayLatest() {
        String firstLine = "";

        try (BufferedReader bufferedReader = 

         new BufferedReader(new FileReader(path))) {
            firstLine = bufferedReader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return firstLine.equals(today.format(formatter));
    }

    private void prependMessageToFile() {
        //Read file to a string
        StringBuilder fileString = new StringBuilder();
        String line;
        try (BufferedReader bufferedReader = 

           new BufferedReader(new FileReader(path))) {
            while ( (line = bufferedReader.readLine()) != null) {
                fileString.append(line + "\n");
            }
        } catch (IOException e) {
            e.getStackTrace();
        }

        //Write complete file back to path
        try (BufferedWriter bufferedWriter = 

          new BufferedWriter(new FileWriter(path))){
            bufferedWriter

            .append(fileString.insert(0, message).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Sunday, 20 December 2015

Luhn validator

Got a bit confused whilst testing something at work as one of the luhn validation tools at work decided to change it's mind around what the check digit should be, I wrote my own:

Luhn algorithm

package com.company;

public class luhnValidator {
    public boolean isValidLuhn(String inputNumber) {
        int[] numbers = stringToIntArray(inputNumber);
        specialDoubler(numbers);
        int total = sumIntArray(numbers);

        return (total * 9) % 10 == numbers[numbers.length-1] ;
    }

    public int checkDigitCalc(String numberWithNoCheckDigit) {
        int[] numbers = stringToIntArray(numberWithNoCheckDigit);
        specialDoubler(numbers);
        int total = sumIntArray(numbers);

        return (total * 9) % 10;
    }

    private int[] stringToIntArray(String convertToNumbers) {
        char[] brokenToChars = convertToNumbers.toCharArray();
        int[] numbers = new int[brokenToChars.length];
        for (int i = 0; i < brokenToChars.length; i++) {
            numbers[i] = Character.getNumericValue(brokenToChars[i]) ;
        }

        return numbers;
    }

    /**
     * Double every second number if greater than 10 add the products together
     */
    private void specialDoubler(int[] numbers) {
        int x2;
        for (int i = numbers.length-2; i >= 0; i -= 2) {
            x2 = numbers[i] * 2;
            if (x2 < 10) {
                numbers[i] = x2;
            } else {
                numbers[i] = (x2 - 10) + 1;
            }
        }
    }

    private int sumIntArray(int[] numbers) {
        int total = 0;
        for (int i = 0; i < numbers.length-1; i++ ) {
            total += numbers[i];
        }
        return total;
    }
}





Could still be optimised but it was fun to play with the intellij tests for jUnit, as they did help pick out a simple error where I missed out the '>' in >=.

More links

https://www.ifixit.com/ actually looks handy and has my phone on there with a guide to replace the battery.

Article I liked http://allankelly.blogspot.co.uk/2015/10/software-has-diseconomies-of-scale-not.html

And a website I liked, seems simple enough and they accept bitcoin https://www.braintreepayments.com/

Wednesday, 16 December 2015

Quick challenge

Quick challenge after work, avoiding putting a front end on the lego app sigh.

package com.company;

import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String inputText = "The legend, propagated by email and message boards, purportedly demonstrates that readers can understand the "
        + "meaning of words in a sentence even when the interior letters of each word are scrambled. As long as all the necessary letters "
        + "are present, and the first and last letters remain the same, readers appear to have little trouble reading the text.";
        String aPattern = "\\w+";
        Pattern pattern = Pattern.compile(aPattern);
        Matcher matcher = pattern.matcher(inputText);
        ArrayList<String> words = new ArrayList<>();
        while (matcher.find()) {
            words.add(matcher.group());
        }

        StringBuilder outputWords = new StringBuilder(inputText.length());
        String shuffledWord, middle;
        char firstLetter, lastLetter;
        for (String word : words) {
            if(word.length() > 3) {
                //build messed up words keeping edges same
                firstLetter = word.charAt(0);
                lastLetter = word.charAt(word.length()-1);
                middle = wordShuffler(word.substring(1, word.length() - 1));
                shuffledWord = firstLetter + middle + lastLetter;
            } else {
                shuffledWord = word;
            }
            outputWords.append(shuffledWord);
        }


        String nonWord = "\\W+";
        pattern = Pattern.compile(nonWord);
        matcher = pattern.matcher(inputText);
        while (matcher.find()) {
            outputWords.insert(matcher.start(), matcher.group());
        }

        System.out.println(inputText);
        System.out.println(outputWords);
    }

    public static String wordShuffler(String wordToShuffle) {
        char[] letterArray = wordToShuffle.toCharArray();
        Random random = new Random();
        int nextValue;
        char swap;

        for (int i = 0; i < letterArray.length; i++) {
            swap = letterArray[i];
            nextValue = random.nextInt(letterArray.length);
            letterArray[i] = letterArray[nextValue];
            letterArray[nextValue] = swap;
        }
        return new String(letterArray);
    }
}