Python Web Reloader

I’m currently writing a python script to analyse web servers for connectivity. Due to various issues I have encountered whilst running this and other sites such as DDOS attacks and Mysql failing due to lack of memory. So far it probes a given site to see if it is active. If it detects connectivity it will attempt to restart the apache server.
One cool thing I learnt whilst doing this was correctly logging the output of the script using the python logging lib. The next update in this project will be to add a feature whereby it will e-mail and attach these logs for viewing by an admin should the site be down. Another idea I’m mulling  over is the ability to tail the access log of apache and detect if a site is currently under attack. Then hopefully update the IPTables to block that address.
The code so far – Note this is still in development!


import requests
import sys
import subprocess
import logging
class WebUp():
    def __init__(self):
        if(len(sys.argv) < 2) :
            print ('Usage : python webup.py http://example.com')
            sys.exit()
        self.url = sys.argv[1]

	logging.basicConfig(filename='/home/usrname/WebUp.log',format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%d/%m/%Y %I:%M:%S %p')
    def checkURL(self):
        try:
         r = requests.head(self.url)
	 if r.status_code == 200:
	         logging.info("Website OK" + str(r.status_code))
         return r.status_code == 200
        except ( requests.exceptions.RequestException) as e:
#            print("Connection Error " + str(e))
            self.handleError(e)
    def handleError(self,e):
        # Log error 
        # Get latest tail of access.log
        # Attach to e-mail?
        # Exit
        logging.warning('Website is down due to:' + str(e))
	# restart apache
	logging.info("Attempting to restart apache2 service")
	p = subprocess.Popen("sudo service apache2 restart", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        for line in p.stdout.readlines():
		print (line)
        retval = p.wait()
	self.checkURL()
if __name__ == '__main__':
    checker = WebUp()
    checker.checkURL()


A-Level Mock Assesment

A-Level Mock Assessment 2016

Based upon the WJEC A-Level specification I have put together a practical mock exam for students studying for the 2016 practical exam.
You can find it here

The exam contains similar questions to that of the exam whereby:
The first section is about their ability to demonstrate that they can read, understand and fix code.
There is a series of broken code that they should fill in.
I have also made a video tutorial on how to tackle part one which can be found here

The second part of the practical is to create a similar User interface.
They are then required to implement various algorithms such as saving information to files and then searching that file for a particular record.
A video tutorial on how to tackle part two can be found here

Raspberry PI at Techniquest

British Science Weekend @ Techniquest

Technocamps spent the weekend at Techniquest in Cardiff Bay demonstrating Computer Science.
We displayed a range of technology of which we use to deliver our workshops in schools, such as our Arduino DIY gamer’s and 3D printer.
There was lots of great interest in Computer Science and programming from both parents and children.
Interestingly there was a fair few young children, most who hadn’t even started school were having a go at creating games in Scratch and Kodu.
Another point that was quite clear was the level of knowledge of children that were in English schools.

As the Technocamps is currently a Welsh Government funded project we rarely have the opportunity to work with children from our neighbors in England, nevertheless from my experience over the weekend the critical understanding of Computer Science between English and Welsh pupils was concerning as there was clearly a divide where English pupils were leagues ahead in terms of proficiency.

All in all it was a fantastic weekend with loads of children having a go at programming.

Raspberry PI at Techniquest
Demonstrating the Raspberry Pi Camera at Techniquest
Technocamps 3D Printer
3D Printer at Techniquest

Printcraft at Llandough Primary

Today, Technocamps spend the day at Llandough primary school helping with the’re World War 2 Code breaking project.
We had great fun using Minecraft to build Anderson shelters and other WW2 era objects.
After which we fired up the 3D printer and printed out their models. This was great fun thanks to the printcraft server which we networked up so that all of the pupils were logged into the same server and worked together to complete there project.

At the end they had a model which they can see and touch that will take prime position on there display.

Connecting to Microsoft Access Database using Python

Source Code ->


import pypyodbc

# Create connection - make sure you change the file paths accordingly 
con = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/Rob/Documents/py_sql_tutorial;DBQ=C:/Users/Rob/Documents/py_sql_tutorial/Database1.mdb;')

cursor = con.cursor()

cursor.execute("SELECT customer_table.password FROM customer_table")

for row in cursor.fetchall():
    print(row)

con.close()

Technocamp for Year 8 Pupils| Llanwern High School

Technocamp for Year 8 Pupils

Many thanks to Rob Lutken and Richard Ward from The University of South Wales for coming into school today to run the Technoclub workshops for our Year 8 Pupils. Pupils learnt all about Raspberry Pi which is a low cost, credit-card sized computer that plugs into a computer monitor or TV, and uses a standard keyboard and mouse. It is a capable little device that enables people of all ages to explore computing, and to learn how to program in languages like Scratch and Python. It’s capable of doing everything you’d expect a desktop computer to do, from browsing the internet and playing high-definition video, to making spreadsheets, word-processing, and playing games. Year 8 Pupils had an awesome time today developing new skills learning how to re-programme their computers using the Raspberry Pi. Well done Year 8. – See more at: http://www.llanwernhighschool.co.uk/blog-wonder-layout/page/10/#sthash.X7KGVj8A.dpuf

Source: Latest School News | Llanwern High School

Android Application Development

I’ve just been digging around in some of my old projects and found my Hours Manager application.
The purpose of the application is to provide me with a way of logging the hours that I do, given that my schedule is so busy, trying to remember when I did what can often be challenging. Unfortunately  it never saw the light of day again due to my hectic schedule.

Given that again I am in a situation where having a log of my work schedule would be beneficial, of course you may be wondering, why don’t I just download one of the many good time management apps for the play store? The answer for me is simple, what would I learn from that?
Programming in Java is something new for me and I have various other android app’s that i have developed in the past although none of which have ever been polished enough to publish. Therefore I’m making a real effort to get this app on the market, not for profit just for the whole experience of releasing an application.

The challenge I have overcome today was adding the functionality to allow users to delete entries from the sql database.  To do so I wanted a dialog window to pop up when the user long pressed one of the entries in the list view.

The code that follows simply creates a new Alert Dialog window from within the SQL View fragment, from there two buttons are initialized (one to confirm and one to cancel). The database is also queried to ensure that the correct item is successfully removed, then the array adapter is notified that the data has changed. From there the list view adapter is updated with a new incarnation of the database.

Hopefully this snippet help’s someone else who’s struggling with creating a Alert Dialog within a Fragment. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    protected void removeRow(final long _position)
    {
        // Create a new Alert Dialog, with the fragment activity context
        AlertDialog.Builder alert = new AlertDialog.Builder(
              getActivity()
        );
        // Here we set the dialog title to that of a static string ("Delete Record?")
        alert.setTitle(R.string.dialog_title);

        // Now we open the database and query it for the current entry string - Date , Start Time, End Time etc
        openDatabase();
        alert.setMessage("Are you sure you want to remove the following entry?n" + info.getRowInfo(_position));
        closeDatabase();

        // When the confirm button is pressed
        alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Open the database again
                openDatabase();
                // Delete the entry at a specific position
                info.deleteRow(_position);
                // Tell the adapter things have changed
                adapter.notifyDataSetChanged();
                adapter.notifyDataSetInvalidated();

                // Re-populate our information in the List Adapter
                populateList();
                lv.setAdapter(adapter);

            }
        });
        // If the cancel button is pressed simply dismiss
        alert.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        // Ensure our database is closed
        closeDatabase();
        // Finally show the alert dialog
        alert.show();
    }
Alert Dialog displaying record information