The below is a simple program to add, subtract, multiply and divide integer numbers. It’s the first program I wrote in C++ as a tester and most of the basic concepts are covered so I’ll go through them here in case they’re of help to someone else! I’ll admit the explainations below are a bit patchy, but this is more aimed at someone with previous programming experience who is looking to try out C++.
To start off we have to include our basic input and output bit’s and pieces and to declare we’re using the standard namespace. To do so stick in the following in the first two lines of your program. We won’t worry about these too much for now.
#include <iostream> using namespace std;
Now we’ll get into some basic subroutine (or function) for adding and subtracting etc. We’ll start with an addition function.
int sum(int x,int y)
{
return x+y;
}
So first we declare the subroutine as an int (as our calculator is only going to deal with int’s). So we begin with an int sum. This is telling the compiler that the return value from this subroutine will be an integer value. It is also naming the subroutine as sum which is what we will use to call it later. We then tell the compiler that this subroutine will take in two parameters, both ints and call them x and y respectively.
Once the function has been called with the correct number of arguments it will add the values together and return the result. That’s it for addition. Subtraction and multiplication are exactly the same except for the obvious difference of using a – or * instead of a +. As below.
int difference(int x,int y)
{
return x - y;
}
int product(int x,int y)
{
return x * y;
}
Division is a little different. This is because if someone running the program tries to divide by zero the program will throw a big dirty error. The way to get around this is to check if the unputted value is a zero is quite simple. So we start off with the same construct as before, but mix up the inner workings a little.
int quotient(int x,int y)
{
if( x != 0 && y != 0 )
{
return x / y;
}
else{
cout << "nCannot divide by zero!n" << endl;
return false;
}
}
In the above we simply take in the x and y as normal, but this time instead of simply dividing them, we check their value first using an if statement. So inside the subrouting we will start off with:
int quotient(int x,int y)
{
if( x != 0 && y != 0 )
{
return x / y;
}
}
This means that we are saying that if x is not equal (!=) to zero, and (&&) if y is not equal (!=) to zero then go ahead and divide them. That’s all well and good, but what if one of our values is a zero? Do we just ignore it? No, we have to inform the user of the error. SO now we add in an else statement.
int quotient(int x,int y)
{
if( x != 0 && y != 0 )
{
return x / y;
}
else{
cout << "nCannot divide by zero!n" << endl;
return false;
}
}
Our else statement will now output the text “Cannot divide by zero!” if we find that one of the inputted integers is a zero, and return a value of false. That’s the main functionality of a calculator covered there now. The following two subroutines are just for printing out a semi-acceptable menu and giving the user the option of the different functions and exiting when required.
This is the menu function:
void menu(){
cout << "** Menu **" << endl;
for(int i=0;i<20;i++){
cout << "-";
}
cout << "n1. Sum" << endl;
cout << "2. Difference" << endl;
cout << "3. Product" << endl;
cout << "4. Quotient" << endl;
cout << "5. Exit" << endl;
}
This is the prompt for accepting input from the user:
void prompt(int* p_x,int* p_y){
cout << "nEnter first integer: ";
cin >> *p_x;
cout << "Enter second integer: ";
cin >> *p_y;
}
This is the main function which is called by the program when run. In it we declare our variables and get ready to accept whatever input the user enters.
int main()
{
int x;
int y;
int option;
int answer;
while(5!=option)
{
menu();
cout << "Please enter choice: ";
cin >> option;
if(1==option)
{
prompt(&x,&y);
answer = sum(x,y);
}
else if(2==option)
{
prompt(&x,&y);
answer = difference(x,y);
}
else if(3==option)
{
prompt(&x,&y);
answer = product(x,y);
}
else if(4==option)
{
prompt(&x,&y);
answer = quotient(x,y);
}
if(5!=option && answer != false){
cout << "nAnswer is: " << answer << "n" << endl;
}
}
return 0;
}
This script uses the Unix mailx program to send a pre-scripted email to someone. It will take in an email address on the command line as an argument and send the mail to this address. Just copy and paste this into a file named mailerscript and change the file permissions to 755 and then your on your way! You can see how to change the permissions here if your unsure.
In order to run the script just use the command
$ ./mailerscript user@example.com
where user@example.com is the email address you wish the mail to go to.
#!/bin/sh # Usage: mailerscript <email address> if [ $1 ]; then FILE=/tmp/mailerscript-$UID.txt echo "Emailing $1..."; echo " Hi, This script will send an email to someone taking in a single argument. You can take in as many as you want though. Killian " >$FILE mail -s "Scripted mail sent" $1 -c user@example.com < $FILE rm $FILE else echo "Usage: mailerscript <email address>" fi
In Linux is extremely easy to change your MAC address. All you need is a couple of commands. To start off you will need to take down the interface to make the change. To do so just type the following into your terminal:
$ ifconfig eth0 down
Now we can get to changing the MAC address. To do this we use the ifconfig command again along with the hw switch, we then specify the interface name (in this case eth0). Finally we will use the hw switch to set the hardware type to ethernet and give the interface the new MAC address. All in all it should look something like this.
$ ifconfig eth0 hw eth 0a:1b:2c:3d:4e:5f
Finally we can bring up the interface and this time we will see the new MAC address.
$ ifconfig eth0 up
$ ifconfig
eth0 Link encap:Ethernet HWaddr 0a:1b:2c:3d:4e:5f
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::216:36ff:fef0:cf11/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:191682 errors:0 dropped:0 overruns:0 frame:0
TX packets:120012 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:28218459 (26.9 MB) TX bytes:13230519 (12.6 MB)
Interrupt:17 Base address:0xa000
Edit (Tue Jun 16 14:41:52 IST 2009): Please note this does not work with all network cards. In some cases the drivers for a card will not support changing of a MAC address. I myself have an Eeepc 901 which has this problem with a RaLink RT2860 wireless card. I’m sure in one of the driver updates it will be included but for now I’m stuck without!
The basis for this particular article (and most of the info) came from one of the guys I work with, Gavin McCullagh, who I’m pretty sure knows more stuff than is good for him. It’s all pretty handy stuff, but can be irritating to get working
If you want to forward an X session to another machine you can use the following command to do so.
ssh -X remotepc.example.com
Now if we want to we can just start an application in the terminal session opened by the above command, and the application will run on the remote computer, but be displayed on our local machine. i.e. if you were to run nautilus on the remote server sshtest we would just type the following at the command prompt:
remotepc$ nautilus
This is the same for most applications. You will need the application installed on both machines however. Also note that firefox requires additional switches in order to run in this fashion as you can see below.
remotepc$ firefox -noshm
It is possible to string multiple ssh sessions together in order to run an application on a machine in an otherwise unreachable location. For instance if you wanted to run firefox on a machine that was behind a firewall, to access a locally restricted site, but the firewall would only allow ssh from particular machines outside the network. In this instance you could ssh to the machine which is allowed past the firewall, and then set up a second ssh session to connect to the machine inside the firewall, and run firefox through the connection. See below:
ssh -CtX outsidepc.example.com ssh -X insidepc.example.com firefox -noshm
In the above command we are using a couple of switches. These are
-C This will compress the connection
-t The -t option will instruct ssh to open a new terminal upon connection.
This is required if you want to string ssh sessions together
-X This will pass the X aapplication through the connection
You can use ssh to forward ports from a remote machine to your own. The main application I would use this for myself if for retrieving my gmail in mutt while in work as we block the required ports. To do this I would issue something like the following command:
ssh -gL 192.168.1.1:993:imap.googlemail.com:993 -gL 587:smtp.googlemail.com:587 killian@example.com
In this example the server at.example.com should be a machine on which it is possible to access these ports. i.e. either a machine with access through the firewall or in your DMZ. Once you have used this command you can just open up your email client normally and the port on the remote pc will listen for connections and they will then be passed on to your own machine.
This is just a handy script I use for renaming my music collection. It got to be too much trouble having the first letter of each word capitalised, getting new music with the names all in caps, or all in lowercase…so I decided to make everything lowercase and write a script to do it for me!
#!/usr/bin/perl -w
use strict;
# open 'find' process to list files recursively with paths
open(FIND, "find |");
while(<FIND>) {
chomp;
# don't rename ourself if script in same as executing
next if $_ eq $0;
# first move the file to $name~ and then back to the lowercase original to allow for fat32 ignoring case,
# and therefore claiming that a file with this name already exists
my $name = $_;
my $tmp = $_.'~';
rename($name, $tmp);
rename($tmp, lc($name));
}
close(FIND);
To start off the script just opens a handle on the linux find command with an output pipe and calls it…well…FIND. The while loop will then iterate through each line the find command returns and rename using the rename() function.
The rename function takes in two arguments, the old name (as returned by find) and the new name. As the current returned value we are looking at is stored in the special variable $_, we can pass this as the old file name. We can then just use the lc() function to convert the old mane to lowercase by putting $_ as the argument for lc(). Finally we close the filehandle on FIND. And voila!
NAME
Csvsql – use SQL queries to access information in CSV files
DESCRIPTION
csvsql enables you to access a CSV file as if it were a table in a database. This means you can use SQL queries, with each ’common seperated
value’ as part of a column.
Traditionally in order to access specific information from a CSV file it can take considerable use of regular expressions, awk and sed amongst
others. What if you only wanted to take out a handful of lines from a large file? It nearly becomes easier to do it manually than to figure out
the expressions needed otherwise.
SYNOPSIS
Csvsql [-h] [-v] [-c "command"] [-s seperator] [-p filename] [-l logging]
COMMAND LINE OPTIONS
-h This help message
-v Prints Csvsql version number
-c Run this command and exit. Command should be in “”
-s User defined separator (defaults to , ) if using a space please use ” ”
-p Copy output to a specified file. This option can also be specified in interactive mode.
-l Switch logging on or off. 1 = on, 0 = off (defaults to 1)
INTERACTIVE OPTIONS
SUPPORTED SQL QUERIES
At present the supported queries are:
SELECT
SELECT [ * | select_expr ]
[ FROM file_name [ WHERE where_condition ]
[ LIMIT row_count ] ]
INSERT
INSERT INTO file_name
(col_name,col_name,…)
VALUES (expr,expr,…)
UPDATE
UPDATE file_name
SET col_name=expr
[ WHERE where_condition ]
DELETE
DELETE FROM file_name
WHERE where_condition
CREATE
CREATE file_name
(col_name,col_name,…)
WITH VALUES (expr,expr…)
WHERE
The WHERE clause, if given, indicates the condition or conditions that rows must satisfy to be selected. where_condition is an expression
that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause.
The WHERE clause can be used for selections that include an AND or an OR operator, where AND requires for both conditions to be true, and OR
requires either one or the other.
NON-SQL COMMANDS
open [file_name]
Opens a file and read it’s contents into memory
close [file_name]
Closes the specified file and release all locks. If no file specified will default to the currently opened file.
describe [file_name]
Display a files column headings.
set pipe = [file_name | off]
Will copy output to a specified file. This option can also be specified as a command line option
ls [path]
List specified directory
dir [path]
Same as above
clear
Clear screen
cls Same as above
version
Print version number
dump
Dump a listing of data in memory
SPECIAL VALUES
isnull
In order to check for, or insert a null value, you should use isnull in place of ’’ Example: SELECT * FROM file_name WHERE col_name = isnull
LICENCE
Copyright (C) 2008 Killian Faughnan
CsvSQL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Soft‐
ware Foundation, either version 3 of the License, or (at your option) any later version.
You should have received a copy of the GNU General Public License along with CsvSQL. If not, see <http://www.gnu.org/licenses>
Author: Killian Faughnan <killian [at] killianfaughnan [dot] com>
<http://www.killianfaughnan.com>
SEE ALSO
For further documentation please see <http://docs.killianfaughnan.com/csvsqldocs>
Csvsql is a project I started for my BSc’s final year software project. It is written in Perl and can be used to access information in csv files in the same way you would access a table in a database. This means you can use SQL queries, with each common seperated value as a field in a column.
Traditionally in order to access specific information from a csv file it can take considerable use of regular expressions, and awk commands. What if you only wanted to take out a handful of lines from a large file? It nearly becomes easier to do it manually than to figure out the expressions needed in awk.
You can download CsvSQL here. If you have and questions, suggestions, criticisms or comments please let me know as I would be interested in hearing them. And if you do decide to use this program for something, let me know how you get on!
Printing a string in Perl couldn’t be easier, you simply use the print function. If you want to print a line in Perl you simple need to write the following:
print "Hello World!";
Output: Hello World!
Similarly you you print a variable as follows:
my $string = "Hello World!"; print $string; Output: Hello World!
eading from a file in Perl is pretty simple. After all, the language is pretty much built around dealing with text. The first step is to open the file, in which case you just need to use the following:
open(INFILE,"< myfile.txt") or die "Can't open file: $!";
In this statement we are using the open() function with a filehandle and filename as arguments. We will use this filehandle for all further actions on the file. The rest of the statement will print the error “Can’t open file: $!” where $! is the filename, should the script be unable to open the file.
To read a file which already has an open filehandleyou can use the following:
while(<INFILE>){
print $_;
}
This while loop will read through the file line by line, printing the contents, until it reaches the last line where it will terminate. In Perl $_ is a special character. It represents the “default input and pattern matching space”, which in the context above means that each line of the file is assigned to $_ in turn as the file is being read. So when we use print $_ we are printing the current line, and with each iteratation of the loop that line changed to the next.
The below will print “Hello!” 10 times:
for ($i = 0; $i < 10 ; $i++){ print "Hello!n"; }
Output: Hello!
For iterating through an array it can be handy to use a foreach loop. In the example below the foreach loop will access each variables in the array and allow you to use it as $i:
@array = ('one','two','three');
foreach $i (@array) { print "$i, "; }
Output: one, two, three,