Saturday, 9 November 2013

IP, TCP and Computer Stacks

Here's a piece of ComSci homework we had to complete about protocols, networks and the Internet.

IP, TCP and Computer Stacks

By Minghua Yin, 10W

What is a typical Internet packet made up of?

An Internet packet contains control information and user data (also known as the payload). The control information is usually found in the header and trailer of the packet, with the payload in between. An IP packet, for example, contains an IP header and a payload. The header, a bit like in emails and letters, contains data about the packet itself, including the type of IP packet (IPv4 or IPv6), the IP address of the destination machine and the length of the packet. The payload is like the “message” and contains data such as part of the content of a website.

How does an Internet packet move through the Internet?

The Internet is essentially a network of routers all sending and receiving bytes of information. An IP packet may be sent by a local router and travel through the network to a router that covers a wider area. The router then does a longest-prefix lookup on the IP address of the packet’s destination, where the bits of the IP address are compared with a table of IP addresses to determine which way – through which interface – the packet should travel.

What is a server?

A server is a computer or computer program which manages access to a centralized resource or service in a network.

What is a client?

A client is a desktop computer or workstation that is capable of obtaining information and applications from a server, or a program that is capable of obtaining a service provided by another program.

What is a dynamic IP address?

A dynamic IP address is one that changes every time a user logs on to his or her computer. The IP address is assigned each time by the user’s ISP (Internet Service Provider) using the DHCP (Dynamic Host Configuration Protocol) protocol.

Why are IP addresses dynamic?

IP addresses are usually dynamic for security reasons. Dynamic IP addresses are also more cost effective than static ones, and there is no human intervention, so there is less risk of a conflict or network problem. Static IP addresses are better for VOIP (Voice Over Internet Protocol), online gaming, game hosting and VPN (Virtual Private Network), as there is less chance of the service disconnecting, since your IP address is always the same; however, the benefits of dynamic addresses usually outweigh the negatives.

What is the difference between UDP and TCP?

The UDP (User Datagram Protocol) and TCP (Transmission Control Protocol) protocols both work at the transport layer of the OSI model, but have different uses. TCP is more reliable than UDP – it is connection-oriented, and so guarantees that the packets sent are all received in the correct order, whereas UDP is connectionless, so some data may be lost. This means that UDP is more lightweight than TCP, as in TCP resend requests may have to be sent if a packet goes missing, and the packets received need to be ordered if not already, which takes time; UDP, on the other hand, is “fire and forget”! In TCP, the data is read as a stream, with no indication as to when one packet ends and another begins, and there may be multiple packets per read call, whereas in UDP, packets are sent individually.

Therefore, TCP is better for the World Wide Web, emails and files, where all the data needs to be received completely, while UDP is better for DNS, media streaming, VOIP and online games, where complete data retrieval is not necessary and the retrieval needs to be fast.

Extra stuff

A day in the life of a packet (sent from a business computer)…

First, the data that needs to be sent is packaged and control information (headers and trailers) added. The packet then travels through the LAN via router switches, maybe passes into a broader intranet via a router, and eventually reaches a proxy, where it is blocked if it is requesting banned data as defined by the proxy, such as a blocked website. Otherwise, the packet continues on its journey and reaches the firewall, where it is blocked if it is carrying sensitive corporate information. If it makes it through the firewall, it is transferred by the Internet router onto a bandwidth, which connects to the Internet. When it arrives at its destination after travelling across the Internet, there may be a firewall, which prevents viruses and other malware from getting through, as well as packets requesting to go through a closed port. The packet travels to its destination machine, such as a server or another computer, maybe making a short journey through the intranet and LAN first. Finally, the packet is unpacked and the data it is carrying read.

PackagedàLAN (router switches and routers)àProxyàFirewallàInternet routeràBandwidthàFirewallàPortàInterfaceàUnpackaged

Difference between the intranet and LAN

A LAN (Local Area Connection) connects the router with your computer and other personal devices, usually in close or direct contact with one another. An intranet is like an expanded LAN, connecting many different devices in a certain area, such as devices in different offices at a business.

Sunday, 27 October 2013

The basics of object-oriented programming - "Supermarket"

Recently, I've been working on a small Supermarket program that demonstrates some key OO concepts. It has a very basic (primitive, even) GUI, but it's a good example of effective use of inheritance and superclass abstraction in object-oriented programming (if I do say so myself). I've also used lots of Java classes, including:

  • java.util.ArrayList (with generics!)
  • java.util.Scanner
  • java.text.NumberFormat
  • java.io.File

I've also used exception-handling code for NumberFormatExceptions and other RuntimeExceptions.

As this wasn't a very major project, I've simply copied and pasted all the code below rather than upload it to Pastebin.

Download the JAR file!

"Supermarket" consists of two files - an executable .jar file and a plain text file. Links to download both of these can be found below. Make sure you put both files in the same directory or the program will not function correctly.

Complete code with annotations:

package fruits;

// **ADDED** - import declaration for java.awt.Color
import java.awt.Color;

// **CHANGED** - made Fruit abstract
public abstract class Fruit
{
//attributes
float pricePerKG; //price per kg of this fruit
String sName; //name of this fruit
boolean bEdible; //is this fruit edible
String sTexture; //texture of this fruit
Color sColour; //colour of this fruit - should be an enum!

// **DELETED** - default constructor
//default constructor
public Fruit(String sName, float fPrice)
{
//initialise variable to blanks
this.pricePerKG = fPrice;
this.sName = sName;
this.bEdible = false;
this.sTexture = "";
this.sColour = null;
}
public float getPrice()
{
return(this.pricePerKG);
}
// **ADDED** - getter for sName
public String getName() {
return sName;
}
// **ADDED** - an abstract method that all concrete subclasses must "implement"
public abstract void eat();

}
-----------------------------------------------------------
// **ADDED** - class Apple

package fruits;

public class Apple extends Fruit {
int radiusToNearestCm;

public Apple(String sName, float fPrice, int radiusToNearestCm) {
super(sName, fPrice);
super.bEdible = true;
this.radiusToNearestCm = radiusToNearestCm;
}

@Override
public void eat() {
for (int i = 0; i < radiusToNearestCm; i++) {
System.out.println("Nom");
}
}

}
-----------------------------------------------------------
// **ADDED** - class Banana

package fruits;

public class Banana extends Fruit {

public Banana(String sName, float fPrice) {
super(sName, fPrice);
}

@Override
public void eat() {
peel();
System.out.println("Nom");
System.out.println("Nom");
System.out.println("Nom");
}

private void peel() {
System.out.println("Banana peeled!");
}

}
-----------------------------------------------------------
// **ADDED** - class Grape

package fruits;

public class Grape extends Fruit {
boolean peelSkin;

public Grape(String sName, float fPrice, boolean peelSkin) {
super(sName, fPrice);
this.peelSkin = peelSkin;
}

@Override
public void eat() {
if (peelSkin) peel();
System.out.println("Nom");
}
public void peel() {
System.out.println("Grape peeled!");
}

}
-----------------------------------------------------------


-----------------------------------------------------------

-----------------------------------------------------------
package supermarket;

import fruits.Fruit;


/*
 * This class is a holder for an item in a basket - it is not intended to be used independently of the Basket class
 */
public class BasketItem
{
// Declare Variables
private Fruit ourFruit;
private float fHowMuchFruit;

// **DELETED** - default constructor
// normal constructor for this class
public BasketItem(Fruit chosenFruit, float fThisMuchFruit)
{
this.ourFruit = chosenFruit;
this.fHowMuchFruit = fThisMuchFruit;
}
// **ADDED** - getter for ourFruit
public Fruit getFruit() {
return ourFruit;
}
// **ADDED** - getter for fHowMuchFruit
public float getAmountOfFruit() {
return fHowMuchFruit;
}
// **ADDED** - method that calculates and returns the price of the item
public float getPrice() {
return ourFruit.getPrice() * fHowMuchFruit;
}

}
-----------------------------------------------------------
package supermarket;

import java.util.ArrayList;

import fruits.Fruit;

/*
 * Holds an array of Basket Items and updates the total cost providing helper methods
 * Only accepts Fruit objects!
 */
public class Basket
{
//Declare variables
private float fBasketValue; //the gross cost of the all the basket items
// **ADDED** - generics
private ArrayList<BasketItem> basketItems; //an ArrayList of BasketItem objects to represent the fruit items
//default constructor
public Basket()
{
this.basketItems = new ArrayList<>();
this.fBasketValue = 0.0f;
}
//add a fruit to the Basket - using BasketItem as the intermediary object
public void addFruitToBasket(Fruit newChosenFruit, float thisMuchFruit)
{
//make a new BasketItem object
BasketItem newFruitItem = new BasketItem(newChosenFruit,thisMuchFruit);
this.basketItems.add(newFruitItem);
//now to update the total
this.fBasketValue += (newChosenFruit.getPrice() * thisMuchFruit);
}
public float getBasketValue()
{
return (this.fBasketValue);
}
// **ADDED** - a getter for basketItems
public ArrayList<BasketItem> getBasketItems() {
return basketItems;
}
// **ADDED** - remove a fruit from the Basket
public void removeFruitFromBasket(int index) throws IndexOutOfBoundsException {
BasketItem fruitItem = basketItems.get(index);
//now to update the total
fBasketValue -= fruitItem.getPrice();
basketItems.remove(index);
}

}
-----------------------------------------------------------
package supermarket;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.JOptionPane;

import fruits.Apple;
import fruits.Banana;
import fruits.Fruit;
import fruits.Grape;

public class SimpleShop {
private Basket ourBasket;
private ArrayList<String> discountCodes;

// **ADDED** - methods so that the code isn't all in main()
public void go() {
// Setup our Basket
ourBasket = new Basket();

// Welcome message
JOptionPane.showMessageDialog(null, "Welcome to SimpleShop!");

// **ADDED** - Options menu
boolean programExit = false;
while (!programExit) {

String optionString = JOptionPane
.showInputDialog("What would you like to do?\n1 - Add a fruit\n2 - Show the fruits in the basket\n3 - Calculate the price of the fruits in the basket\n4 - Remove an item\n5 - Pay");

if (optionString != null) {
switch (optionString) {
case "1":
addFruit();
break;
case "2":
showFruits();
break;
case "3":
calcPrice();
break;
case "4":
removeItem();
break;
case "5":
pay();
programExit = true;
break;
default:
break;
}
} else {
programExit = true;
}
}

JOptionPane.showMessageDialog(null, "Thanks for shopping. We hope to see you again soon!");

// End the program
System.exit(0);
}

private void addFruit() {
try {
Fruit f = null;
String fruitNum;
String name;
String priceString;
float price;
String weightString;
float weightInKg;

do {
fruitNum = JOptionPane
.showInputDialog("What fruit would you like to add?\n1 - Apple\n2 - Banana\n3 - Grape");
} while (fruitNum == null);

if (!fruitNum.equals("1") && !fruitNum.equals("2") && !fruitNum.equals("3")) {
throw new Exception();
}

do {
name = JOptionPane
.showInputDialog("And the name of the fruit?");
} while (name == null);

do {
priceString = JOptionPane.showInputDialog("Price per kg? (In pounds, please.)");
} while (priceString == null);
price = Float.parseFloat(priceString);

switch (fruitNum) {
case "1":
String radiusString;
int radius;

do {
radiusString = JOptionPane.showInputDialog("What's the radius of the apple? (To the nearest cm, please.)");
} while (radiusString == null);
radius = Integer.parseInt(radiusString);

f = new Apple(name, price, radius);

break;
case "2":
f = new Banana(name, price);
break;
case "3":
String peelSkinString;
boolean peelSkin;

do {
peelSkinString = JOptionPane.showInputDialog("Peel the skin of the grape(s)? y/n");
} while (peelSkinString == null);

if (peelSkinString.equals("y")) {
peelSkin = true;
} else if (peelSkinString.equals("n")) {
peelSkin = false;
} else {
throw new Exception();
}

f = new Grape(name, price, peelSkin);

break;
default:
break;
}

do {
weightString = JOptionPane.showInputDialog("How much, in kg, of the fruit do you want to add?");
} while (weightString == null);
weightInKg = Float.parseFloat(weightString);

ourBasket.addFruitToBasket(f, weightInKg);

JOptionPane.showMessageDialog(null, "Fruit successfully added!");

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "AAAARRRRGGGHHH! HORRIBLE EXPLOSION!!!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Something bad happened. Sorry.");
}
}

private void showFruits() {
// **ADDED** - check what's in the basket!
// Create a StringBuilder object to add things to a string
// I could've just written 'String itemLister = "";', but that's boring :)
StringBuilder itemLister = new StringBuilder();
ArrayList<BasketItem> items = ourBasket.getBasketItems();

// Here, if I'd used a string ('String itemLister = "";') I would've written 'itemLister += "Name of fruit...";'
itemLister.append("Name of fruit--Weight (kg)--Price (£)\n");

for (BasketItem item : items) {
// Here, if I'd used a string ('String itemLister = "";') I would've written 'itemLister += item.getFruit()...;'
itemLister.append(item.getFruit().getName() + "--" + item.getAmountOfFruit() + "--" + String.format("%,.2f", item.getPrice()) + "\n");
}

// Here, if I'd used a string ('String itemLister = "";') I would've written '...Dialog(null, itemLister);'
JOptionPane.showMessageDialog(null, itemLister.toString());
}

private void calcPrice() {
// now to check what the cost of the basket is
NumberFormat format = NumberFormat.getCurrencyInstance();

JOptionPane.showMessageDialog(null, "Your basket is worth: " + format.format(ourBasket.getBasketValue()));
}

private void removeItem() {
// Display all the fruits in the basket and ask the user which one he/she would like to remove
StringBuilder messageBuilder = new StringBuilder();
ArrayList<BasketItem> items = ourBasket.getBasketItems();
int number = 0;
String indexString;
int indexToRemove;

messageBuilder.append("Here are the fruits currently in your basket:\n\n");

messageBuilder.append("No.--Name of fruit--Weight (kg)--Price (£)\n");

for (BasketItem item : items) {
messageBuilder.append(number + "--" + item.getFruit().getName() + "--" + item.getAmountOfFruit() + "--" + String.format("%,.2f", item.getPrice()) + "\n");
number++;
}

messageBuilder.append("\nWhich fruit would you like to remove? Type the corresponding item number.");

try {
do {
indexString = JOptionPane.showInputDialog(messageBuilder.toString());
} while (indexString == null);

indexToRemove = Integer.parseInt(indexString);

ourBasket.removeFruitFromBasket(indexToRemove);

JOptionPane.showMessageDialog(null, "Fruit successfully removed!");
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(null, "AAAARRRRGGGHHH! HORRIBLE EXPLOSION!!!!");
}
}

private void pay() {
NumberFormat format = NumberFormat.getCurrencyInstance();
float amountToPay = ourBasket.getBasketValue();

int useDiscountCode = JOptionPane.showConfirmDialog(null, "Do you have a discount code?", "Discount code?", JOptionPane.YES_NO_OPTION);

if (useDiscountCode == 0) {
discountCodes = new ArrayList<>();

try (Scanner fileScanner = new Scanner(new File("discount_codes.txt"))) {
while (fileScanner.hasNextLine()) {
discountCodes.add(fileScanner.nextLine());
}

boolean match = false;
do {
String discountCode = JOptionPane.showInputDialog("Please enter your discount code");
if (discountCode != null) {
if (discountCodes.contains(discountCode)) {
match = true;
} else {
JOptionPane.showMessageDialog(null, "Please try again.");
}
} else {
pay();
return;
}
} while (!match);
JOptionPane.showMessageDialog(null, "10% discount!");
amountToPay = ourBasket.getBasketValue() * 0.9f;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Discount codes file not found. Sorry.");
}
}
JOptionPane.showMessageDialog(null, "Please pay " + format.format(amountToPay));
JOptionPane.showMessageDialog(null, "Thank you for paying!");
}

public static void main(String[] args)
{
SimpleShop shop = new SimpleShop();
shop.go();
}

}

Friday, 11 October 2013

Blog Bulletin - "Sorting Algorithms"

I've started creating pages for "special" programs that took me a substantial amount of time to make. Recently, I've finished making a program that sorts an inputted list of numbers in ascending order. Check out the page 'Program - "Sorting Algorithms"' for the complete code for the program, as well as a link to download an executable JAR file that runs the thing!

Thursday, 10 October 2013

Blog Bulletin - Pastebin

Just a quick post to let you know that I've created Pastebin account to store my code online. From now on, all the code posted on this blog will be embedded from Pastebin.

Friday, 20 September 2013

VowelReplacer and StringRemover

Our task for the last few weeks has been to create a simple program that replaces vowels in a String input with something else (I've chosen the letter "z", because, you know, "zzzz..."). You can find my code below:


import java.util.Scanner; 

class VowelReplacer {
   
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String string = scanner.nextLine();
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (char c : vowels) {
            // System.out.println("Value of c: " + c);
            string = string.replace(c, 'z');
            // S
ystem.out.println(string);
        }
       
        System.out.println(string);
    }
}


And here's a program that removes all occurrences of a user-specified String from a String input:

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class StringRemover {
   
    public static void main(String[] args) {
     Scanner scanner = new Scanner(System.in);
     System.out.println("Please type a word or sentence:");
        String stringToChange = scanner.nextLine();
        Pattern pattern = Pattern.compile(stringToChange);
        System.out.println("Please type a String:");
        String stringToRemove = scanner.nextLine();
        Matcher matcher = pattern.matcher(stringToChange);
       
        if (matcher.find()) {
         stringToChange = stringToChange.replaceAll(stringToRemove, "");
        }
       
        System.out.println("Resulting String is \"" + stringToChange + "\"");
    }
}
Please note that the second of these two programs has one major limitation - it's case-sensitive.

Wednesday, 18 September 2013

Here we go again!

Woo! Hello everyone! After a depressing, boring, totally unsatisfying summer holiday, I'm back on the roll - and this year, we're doing JAVA!

I have to tell you, I have not been so excited in a very, very long time. Java is my all-time favourite language (well, out of the three I know, my knowledge of two of which is extremely limited). Sure, it's strict, but that's what I love about it - you simply won't let you go in completely the wrong direction and potentially make a huge coding blunder. It's object-oriented, its syntax is simple and consistent, and it pioneered portability with its "Write Once, Run Anywhere" coding philosophy.

As I said in the header thing at the top of this blog, I'm currently making a "top-secret" GUI program (except just about everyone in my class knows what it is). So far, I've incorporated various Java and OO features into the program, including class inheritance, static utility methods, abstract classes, inner classes, implementation of interfaces... Yeah, snazzy stuff!

Stay tuned for updates on the progress of Project TestMaker (you can probably guess what it does now), and maybe a few posts on various bits of Java.

Saturday, 8 June 2013

Some more lovely electronics questions!! Yay!

Two more...

7) Current through R = 12 + 35 - 40
                                  = 7 mA

8) Voltage across R = 7 * 27
                                = 189 mV

And now, for some chess notation, because I'm bored... :-)
! - good move
!! - brilliant move
? - questionable move
?? - blunder, howler
?! - risky move
!? - interesting move

(I think)

cogito, ergo sum... :)

Tuesday, 7 May 2013

Basic electronics knowledge - revision

9) Proportion Vout/Vin = 470/(120+470)
                                      = 470/590
                                      = 47/59

    Vout = 6 * 47/59
             = 4.77966101695...
             = 4.78 V (3 s.f.)


10) If Vin = 6 V, then
      Vout = 15 * 47/59
               = 11.9491525424...
               = 11.9 V (3 s.f.)
11) Proportion Vout/Vin = 470/(680 + 470)
                                         = 470/1150
                                         = 47/115

      Vout = 6 * 47/115
               = 2.45217391304...
               = 2.45 V (3 s.f.)

12) Vout = 5 V, therefore

       5 = Vin * 47/59
       Vin = 5 * 59/47
              = 6.27659574468...
              = 6.28 V (3 s.f.)

Wednesday, 1 May 2013

Basic resistor knowledge

Here are some pretty pictures to get us going...
This is basically how a rotary potentiometer (variable resistor) works - twisting the knob changes the amount of metal in the resistor that is used in the circuit, thereby changing the resistance.
Here, a variable resistor is connected in a circuit.

Important points to note:

  • Typical pots (potentiometers) are rated to run at a maximum of 0.2W to 0.5W
  • The fourth band on a resistor tells us how precise or tolerant the resistor is
  • 'Colours of Tolerance': red is +/- 2% tolerance; gold is +/- 5% tolerance; silver 10%; no band 20%
  • If there are many resistors connected in series, the total resistance of the circuit is the sum of all the resistors' resistances
  • The rate of energy conversion (basically power??) is measured in watts

Important information on voltage dividers:

Working out the total resistance in a parallel circuit:


Questions on Resistance:

  1. 3.7 A of current flows towards and through R
  2. The current flowing through R is now 0.2 A in the same direction
  3. R2 because it has the highest resistance, so the voltage/potential difference will drop the most across it
  4. V = IR
    Making I the subject:
    I = V/R
    Therefore the current (I) through the circuit is
    10/(56 + 120 + 82)
    = 10/258
    = 5/129
    = 0.0388 A (3 s.f.)
    = 38.8 mA

    V = IR
    Therefore,
    Voltage across R1 = 0.0388 * 56
                                  = 2.170542635658915...
                                  = 2.17 V (3 s.f.)
    Similarly,
    Voltage across R2 = 0.0388 * 120
                                  = 4.651162790697675...
                                  = 4.65 V (3 s.f.)
    and
    Voltage across R3 = 0.0388 * 82
                                  = 3.178294573643411...
                                  = 3.18 V (3 s.f.)
    Check: 2.17 + 4.65 + 3.18 = 10 V - YAY!!! I GOT IT RIIIIIGGGHHT!!!
  5. Voltage = 0.03 * 258 = 7.74 V
  6. Current through R1 = 3/100 = 0.03 A = 30 mA
    Current through R2 = 3/47 = 0.06382978723 = 0.0638 A (3 s.f.) = 63.8 mA
    Voltages across R1 & R2 are both 3V (obviously!)

Tuesday, 23 April 2013

Arduino Lesson 1 - The Very Basics

Please note that I still have not finished my Copter game. I think I need to ask Mr Patel or Mr Hussain for help as an important part of the game doesn't seem to work...

OK, from now on I'm going to post on my blog more frequently...

So, last lesson a few lessons ago we looked at the very basics of Arduino programming. We learnt how to make the simplest program you can write, and then we ran out of time and didn't do anything else.

Below is an incredibly basic Arduino program (mm-hmm, I did write it all from scratch...):

PLEASE CORRECT ANYTHING HIGHLIGHTED IN RED (OR NOT, FOR THAT MATTER) IF YOU KNOW IT'S INCORRECT!

Begin code:
/*
 * Basic stuff, init!
 */

int ledPin = 13; // "ledPin" is a variable that stores the number 13 - pin 13 on an Arduino Uno is connected to a built-in LED

void setup() {
/* This is the method/function which contains all the preliminary
 * setup code, e.g. defining the pins that are used in the
 * program.
 */

  digitalWrite(ledPin, OUTPUT);
  /* The "digitalWrite" method/function is used to tell the Arduino
   * that the first value in the brackets (in this case ledPin,
   * i.e. 13) is the number of a pin which is used in the program.
   * The second parameter (value in the brackets) tells the Arduino
   * whether we want to control current flow through a pin or we
   * want to test if there is current flowing through a pin.
   */

}

void loop() {
/* This is the method/function which runs over and over again -
 * it loops and loops and loops and keeps looping until the
 * program is ended/terminated.
 */

  pinMode(ledPin, HIGH);
  /* This translates to "turn pin 13 (ledPin) HIGH" - run current
   * through it. This will turn on the built-in LED, which is
   * connected to pin 13.
   */

  delay(500);
  /* Wait 500 milliseconds (half a second) before running the
   * next line of code:
   */

  pinMode(ledPin, LOW);
  /* Yep, you guessed it - this turns the LED OFF. So this
   * program will cause the LED to flash on and off once every
   * second.
   */

  delay(500);
  /* Wait 500 milliseconds before re-running loop() and thereby
   * turning the LED on.
   */

}

End code.