Monday, 26 January 2015

Can you spot the Child at risk?

Every day in the U.K. on average 2 young people commit Suicide and there are 32 attempts!

Imagine a class of school children, when you look at them they may all be smiling on the outside but what if you could see how they really feel on the inside?




 Get some SALT it could save a life!

Friday, 23 January 2015

Tidy Chop in your kitchen?


Tidy Chop

Makes preparing food tidier and quicker!

Fed up of having to stop in the middle of food preparation to clear your board of waste?
Well now there is Tidy Chop created by myself one Christmas after thinking there must be a quicker and tidier way.

Aimed at the Catering trade and made out of 304 catering grade stainless steel.  Tidy Chop sits on your workbench taking a standard size chopping board (450mm x 300 mm) and 1/3 (325mm x 176mm) Gastronome pan up to 150mm deep.

Whatever your preparing this is sure to become a valuable part of your kitchen equipment and with 2 versions available Tidy Chop can really speed up your preparation time.

Standard Tidy Chop consists of 1 Gastronome pan where as the Premium 3 pans 1 either side of the board and 1 in the middle.

Inquire now

If you can't Speak it, Write it!

Sometimes asking for help during the darkest times is very hard so if you feel you can't speak to someone try writing to them.

When i was feeling very depressed and suicidal i didn't feel i could talk to my doctor so i wrote him a letter and booked an appointment and handed him a letter.

If you can't Speak it, Write it!

Tell your doctor how your feeling, how long it's been going on for and if you know what may have triggered the thoughts.  Feeling Suicidal doesn't make you MAD or mental!  It just means you need a little bit of help and in life we all need help at sometime or other.

Keeping a diary can help, i used to mark my day out of 10 (10 being the best) and and put a little comment about anything that may have triggered my score.

Remember Suicide is a permanent solution to a temporary problem.

Helpful link http://www.metanoia.org/suicide/

Tuesday, 20 January 2015

Dynamic drop-down from XML (2 drop-downs 1 populates other)

Question
How can i use my XML file to populate two drop-downs where the 1st one defines whats displayed in the second.

Answer
 
<script type="text/javascript">
/* wait until DOM has loaded */
$(document).ready(function() {
    /* declare array to store categories in */
    var categories = [];
    /* load a remote page using an HTTP request. */
    $.ajax({
        /* type of request */
        type: "GET",
        /* url where request is sent */
        url: "pop.xml",
        /* type of data we expect back */
        dataType: "xml",
        /* function to be called if the request is a success */
        success: function(xml) {
            /* declare variable for recipe select and hide  */
            var selectCategory = $('#selectCategory');
            var listRecipe = $('#listRecipe');
            $(listRecipe).hide();
            /* parse xml file and find each recipe node */
            $(xml).find('recipe').each(function() {
                /* for each recipe node get the category */
                var category = $(this).find('category').text();
                /* put each category into our array */
                categories.push(category);
            });
            /* use our function to sort categories and remove duplicates */
            getUnique()
                /* when selectCategorys select is changed */
            $("#selectCategory").change(function() {
                /* empty recipe select then show */
                listRecipe.empty();
                $(listRecipe).show();
                /* declare variable for value of category selected */
                var selectCategory = $('#selectCategory').val();
                /* parse xml file and find each recipe node */
                $(xml).find('recipe').each(function() {
                    /* for each recipe node get the category and title */
                    var category = $(this).find('category').text();
                    var title = $(this).find('title').text();
                    /* if selected category matches category in xml file add it to listRecipe select */
                    if (category == selectCategory) {
                        listRecipe.append("<option value='" + category + "'>" + title + "</option>");
                    }
                });
            });
        },
        error: function() {
            $('#recipeFinder').hide();
            alert("Error: Something went wrong");
        }
    });

    function getUnique() {
        /* declare variables and array */
        var options = $('#selectCategory');
        var uniqueCategories = [];
        /* iterate over array categories */
        for (var i = 0; i < categories.length; i++) {
            /* if category in categories array is not in outputArray add it */
            if ((jQuery.inArray(categories[i], uniqueCategories)) == -1) {
                uniqueCategories.push(categories[i]);
            }
        }
        /* iterate over array outputArray and add each item to selectCategory select */
        for (var i = 0; i < uniqueCategories.length; i++) {
            options.append('<option value="' + uniqueCategories[i] + '">' + uniqueCategories[i] + '</option>');
        }
        /* replace 1st item in selectCategory and select it */
        options.children(":first").text("please make a selection").attr("selected", true);
    }
});
</script> 
 
Demo xml-miltiple-select.php

Wednesday, 14 January 2015

Load HTML file from Dynamically created drop-down created from XML file.

Question
How can i now load the HTML file selected from the Dynamically created drop-down.

Answer
<script type="text/javascript">
    /* check browser supports XMLHttpRequest object and create one else create ActiveXObject */
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    /* create an instance of the XMLHttpRequest object, open a URL, and send the request. */
    xhr.open("GET", 'soups/soups.xml', false); // 
    xhr.send();
    /* get the response of the request (sent as string) */
    xhrStr = xhr.responseXML;
    /* get required elements */
    var xhrTitle = xhrStr.getElementsByTagName("title");
    var xhrFilename = xhrStr.getElementsByTagName("filename");
    /* add select tag to variable */
    var str = '<select name="soups" id="soups">';
    str += '<option value="">Select a soup</option>';

    /* loop through all title tags (will get filename tags found between title tags) */
    for (i = 0; i < xhrTitle.length; i++) {
        /* with the values we get add them to option tag each time we run through the loop */
        str += '<option value=' + xhrFilename[i].childNodes[0].nodeValue + '>' + xhrTitle[i].childNodes[0].nodeValue + '</option>';
    }
    /* close select */
    str += '</select>';
    /* put select element inside createSelect */
    document.getElementById("createSelect").innerHTML = str;
    /* when dom ready and select changes run script */
    window.onload = function() {
            if (window.addEventListener) {
                document.getElementById('soups').addEventListener('change', loadRecipe, false);
            } else if (window.attachEvent) {
                document.getElementById('soups').attachEvent("onchange", loadRecipe);
            }
            /* get value of selected soup and insert it into the page using object data */
            function loadRecipe() {
                var x = document.getElementById("soups").value;
                document.getElementById("showRecipe").innerHTML = '<object data="' + x + '" type="text/html" width="500" height="700"></object>';
            }
        }
</script>
Demo xml-select-html.php

Tuesday, 13 January 2015

Populate drop-down list from XML

Question
So now i have what i want how can i put that into a select tag?

Answer
<script type="text/javascript">
    /* check browser supports XMLHttpRequest object and create one else create ActiveXObject */
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    /* create an instance of the XMLHttpRequest object, open a URL, and send the request. */
    xhr.open("GET", 'soups/soups.xml', false); // 
    xhr.send();
    /* get the response of the request (sent as string) */
    xhrStr = xhr.responseXML;
    /* get required elements */
    var xhrTitle = xhrStr.getElementsByTagName("title");
    var xhrFilename = xhrStr.getElementsByTagName("filename");
    /* add select tag to variable */
    var str = '<select name="Soups">';
    /* loop through all title tags (will get filename tags found between title tags) */
    for (i = 0; i < xhrTitle.length; i++) {
        /* with the values we get add them to option tag each time we run through the loop */
        str += '<option value=' + xhrFilename[i].childNodes[0].nodeValue + '>' + xhrTitle[i].childNodes[0].nodeValue + '</option>';
    }
    /* close select */
    str += '</select>';
    /* put select element inside createSelect */
    document.getElementById("createSelect").innerHTML = str;
</script>


Demo xml-select-tag.php

What's all this parent child thing about in XML? (Tree of recipes.xml)

Question
What's all this parent child thing about in XML?

Answer
Here is the recipe.xml Tree structure shown as a flowchart which should help explain the basics.

XML Tree

Sunday, 11 January 2015

Extract and split node by comma and save to new XML file

Question
Using Extract specific xml data and save to new xml i can extract specific nodes but what if the text node is a CSV.  As some recipes can be in more than 1 category.

Answer
<?php
/* Convert an XML file into a SimpleXMLElement object  */
$xmlDoc     = simplexml_load_file("test.xml");
/* set variable as array  */
$storeArray = array();
/* for each <recipe> node use $recipe as key (Associative array) */
foreach ($xmlDoc->recipe as $recipe) {
    /* if child is not in array add it to our array */
    if (!in_array($recipe->category, $storeArray)) {
        array_push($storeArray, $recipe->category);
    }
}
/* separate array by , (array to string) */
$arrayString  = implode(",", $storeArray);
/* break string into array separating by , (string to array) ) */
$stringArray  = explode(',', $arrayTring);
/* take each array value and trim whitespace */
$trimmedArray = array_map('trim', $stringArray);
/* remove any duplicates from array */
$result       = array_unique($trimmedArray);
/* for each item in array echo as $category */
foreach ($result as $category) {
    echo $category . "<br>";
}
?>

XML multi-category.xml
Demo split-node-xml.php

Extract specific XML data and save into new XML file

Question
Extracting text node from parent works great but how can i save it as a new XML file.

Answer
<?php
/* Convert an XML file into a SimpleXMLElement object  */
$xmlDoc     = simplexml_load_file("recipes.xml");
/* set variable as array  */
$storeArray = array();
/* for each <recipe> node use $recipe as key (Associative array) */
foreach ($xmlDoc->recipe as $recipe) {
    /* if child is not in array add it to our array */
    if (!in_array($recipe->category, $storeArray)) {
        array_push($storeArray, $recipe->category);
    }
}
/* remove any duplicates from array */
$result = array_unique($storeArray);
/* create a new SimpleXMLElement object */
$xml    = new SimpleXMLElement('<recipe></recipe>');
/* for each item in array use variable $category */
foreach ($result as $category) {
    /* add child node category with  text node $category */
    $details = $xml->addChild('category', $category);
}
/* change header type */
Header('Content-type: text/xml');
/* print to screen */
print($xml->asXML());
/* name to call our new file */
$xmlFileName = "categories.xml";
/* save our new file */
$xml->asXML($xmlFileName);
/* Open and prettify xml file */
$simplexml               = simplexml_load_file($xmlFileName);
$dom                     = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput       = true;
$dom->loadXML($simplexml->asXML());
$xml = new SimpleXMLElement($dom->saveXML());
$xml->saveXML($xmlFileName);
?> 

XML recipes.xml
Demo xml-new-xml.php

Saturday, 10 January 2015

Extract Text Node from parent ignoring duplicates

Question
Each recipe in recipes.xml is in a category and i want to print a list of the category's used without having lots of duplicates how can i do that?

Answer
<?php
/* Convert an XML file into a SimpleXMLElement object  */
$xmlDoc     = simplexml_load_file("recipes.xml");
/* set variable as array  */
$storeArray = array();
/* for each <recipe> node use $recipe as key (Associative array) */
foreach ($xmlDoc->recipe as $recipe) {
    /* if child is not in array add it to our array */
    if (!in_array($recipe->category, $storeArray)) {
        array_push($storeArray, $recipe->category);
    }
}
/* remove any duplicates from array */
$result = array_unique($storeArray);
/* for each item in array echo as $category */
foreach ($result as $category) {
    echo $category . "<br>";
}
?>

Demo xtract-node-xml.php

Sunday, 4 January 2015

I don't care if your committing suicide as longs your buying

Today i share a secret with you which i have only ever told a couple of people about.  A few years ago whilst feeling Suicidal i ordered some pills online to kill myself with, then later changed my mind but was persuaded to still get the pills which i eventually took and overdosed on spending 4 days in hospital and nearly died from.


Please wait for a site operator to respond.

You are now chatting with ‘Tanya‘

Tanya: Thank you for contacting Drugdelivery.ca, how may I help you today?

Ian: i placed an order earlier today which i’d like to cancel i should not of placed it really im suicidal and brought them to 
     kill myself with

Ian: please cancel it

Tanya: May I have your customer id “”CID Number”” or order confirmation number “JGH Number” please?

Ian: CID177866

Tanya: Thank you

Tanya: Would you provide me with your full name and your full address for security and privacy reasons please? Thank you.

Ian: Ian.*.*****

Ian: ** ****** ***

Ian: ************

Ian: **** *** ***

Ian: the 1st payment processer failed but it then took me to a second one which accepted my payment

Tanya: Please hold on while I access your account.

Ian: ok

Tanya: Thank you for holding, your patience is highly appreciated

Ian: n/p

Tanya: We can definitely cancel it as per your request but please note that there will be a $20 USD cancellation fee. Alternatively, 
       we can have the full amount credited on your account and this can be applied towards the next order with us.

Ian: ok leave it as it is then i’ll go through with the order

Tanya: Great! You would not cancel it then, right?

Ian: no leave it i’ll take the order sorry to muck you around

Tanya: No problem at all.

Tanya: Is there anything else I can help you with?

Ian: no thats it thankyou

Tanya: You’re welcome

Tanya: If you have any questions or queries, please do not hesitate to contact us at 1 877 888 3562 or email us at help@drugdelivery.ca, we will be more than happy to help you.

Tanya: Thank you for contacting Drugdelivery.ca. Have a good night. 

Extracting Allergen Information from HTML Recipes to XML before importing to Google Sheets.

Question
I use Google sheets as a daily menu system for residents in a home and it works great but now the good old EU Food Information for Consumers Regulation (1169/2011) means i have to be able to show whats in each of our dishes.

Answer
The "Top 14" allergens according to them are
  1. Celery 
  2. Gluten 
  3. Crustaceans 
  4. Eggs 
  5. Fish 
  6. Lupin 
  7. Milk 
  8. Mollusc 
  9. Mustard 
  10. Nuts 
  11. Peanuts 
  12. Sesame seeds 
  13. Soya 
  14. Sulphur Dioxide 
  15. Banana <-- Extra one i added

Make sure all your recipes (.html format) include Title, Category and Allergen information.

French Onion Soup  <-- Title

Soups  <-- Category

Allergy advice
Contains:- Celery  <-- Allergens

Ingredients
  • Butter
  • 5lb. Spanish onions (sliced)
  • 4 litres beef stock (knor)
  • Brown sugar (Sprinkle)
  • Splash of sherry
  • 2 x tbsp thyme

Method
  1. Fry onions in butter until golden brown (10-15 minutes)
  2. Add sugar and sherry
  3. Add thyme and stock and bring to boil
  4. Reduce and simmer for 45 minutes or until cooked
  5. Adjust seasoning and consistency if necessary

Now we only need to get the information in blue from the recipe above before automatically inserting it to our spreadsheet.
See the following PHP script which takes the information we need and inserts it into an XML file.

<?php
$xmlFileName  = "recipes.xml";
//  Creates a new SimpleXMLElement object 
$xml          = new SimpleXMLElement('<xml/>');
//  Path to recipe folder
$recipeFolder = "http://mental-man.com/recipes/";
//  Find all files that end with .html and use each one as recipe
foreach (glob('*.html') as $recipeName) {
    //  Set allergen variable with empty value 
    $allergenString = "";
    $doc            = new DOMDocument();
    @$doc->loadHTMLFile($recipeFolder . $recipeName);
    $xpath                = new DOMXPath($doc);
    $category             = $xpath->query("//div[@id = 'category']")->item(0)->nodeValue;
    $title                = $xpath->query("//title")->item(0)->nodeValue;
    $allergen             = $xpath->query("//h2[@id = 'allergens']")->item(0)->nodeValue;
    $capsInsensitiveNode  = strtolower($allergen);
    $allergenArray        = array(
        "Celery",
        "Gluten",
        "Crustaceans",
        "Eggs",
        "Fish",
        "Lupin",
        "Milk",
        "Mollusc",
        "Mustard",
        "Nuts",
        "Peanuts",
        "Sesame seeds",
        "Soya",
        "Sulphur Dioxide",
        "banana"
    );
    $capsInsensitiveArray = array_map('strtolower', $allergenArray);
    $stringToArrayNode    = explode(',', $capsInsensitiveNode);
    for ($i = 0; $i < count($capsInsensitiveArray); $i++) {
        if (in_array($capsInsensitiveArray[$i], $stringToArrayNode)) {
            $allergenString .= "1,";
        } //  in_array($capsInsensitiveArray[$i], $stringToArrayNode)
        else {
            $allergenString .= "0,";
        }
    } //  $i = 0; $i < count($capsInsensitiveArray); $i++
    $dropLastCharAllegens = substr($allergenString, 0, strlen($allergenString) - 1);
    $recipe               = $xml->addChild('recipe');
    $recipe->addChild('filename', $recipeFolder . $recipeName);
    $recipe->addChild('category', $category);
    $recipe->addChild('title', $title);
    $recipe->addChild('allergens', $dropLastCharAllegens);
} //  glob('*.html') as $recipeName
//  Show xml file
Header('Content-type: text/xml');
print($xml->asXML());
//  Save xml file
$xml->asXML($xmlFileName);
//  Open and format xml file
$simplexml               = simplexml_load_file($xmlFileName);
$dom                     = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput       = true;
$dom->loadXML($simplexml->asXML());
$xml = new SimpleXMLElement($dom->saveXML());
$xml->saveXML($xmlFileName);
?> 


Example XML file.

<?xml version="1.0"?>
<xml>
<recipe>
<filename>http://mental-man.com/recipes/french-onion-soup.html</filename><category>Soups</category>
<title>French Onion Soup</title>
<allergens>1,0,0,0,0,0,0,0,0,0,0,0,0,0,0</allergens>
</recipe>
</xml>

Now using IMPORTXML we can import the XML file into our spreadsheet and use it as we require.
=IMPORTXML("http://mental-man.com/recipes/recipes.xml", "//recipe")

Job done!