Monday, January 30, 2023

Python workout in JavaScript

 In this post, I will convert some python code from the book "Python Workout by Reuven M. Lerner" into JavaScript (you may get a copy of the book from his website). The code used in the book are publicly available on his github page.


Lets get started...


Task 1: Generate a random integer from 1 to 100.

Ask the user repeatedly to guess the number. Until they guess correctly, tell them to guess higher or lower.


<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Random Number Generator | Guess the number...</title>

<!-- ***************** CSS ********************* -->
	<style type="text/css">
		body{
			background-color: #db20d96e;
		}

		h2, #num, #submit, #result {
			font-size: 2em;
		}

		h1{
			margin: 0;
			color: #f94711;
		}
	</style>

</head>
<body>



<!-- ***************** HTML ********************* -->
<center>
	<h2>Am thinking of a number, what is it?</h2>

	<input type="number" name="num" id="num" />
	<button id="submit">Submit</button>
	<br>
	<br>

	<label type="text" name="result" id="result" />
</center>



<!-- ***************** JS ********************* -->
<script>

// Funtion to get random number between two nums...
	function getRandomIntInclusive(min, max) {
		  min = Math.ceil(min);
		  max = Math.floor(max);
		  return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
		}
// Guessed number is...
	let guessed_num = getRandomIntInclusive(1, 100);


// Get form entry and compare to the user's guessed number....
	let btn = document.getElementById('submit');

	btn.onclick = (e) => {
		let guess_num = document.getElementById('num').value;
		let result = document.getElementById('result');

		console.log(guess_num);

		if (guessed_num == guess_num){
			// console.log('Correct Guess...');
			result.innerHTML = `Correct Guess... The number in my mind was: <h1>${guessed_num}</h1>`

		} else if (guessed_num < guess_num) {
			// console.log(`Guessed number is too HIGH; try again...`);
			result.innerHTML = `Guessed number is too HIGH; try again...`

		} else if (guessed_num > guess_num) {
			// console.log(`Guessed number is too LOW; try again...`);
			result.innerHTML = `Guessed number is too LOW; try again...`
		}

	}
	
// `${guessed_num}`
</script>

</body>
</html>


Task 2: Summing numbers

Define "mySum". Accepts any number of numeric arguments as inputs. Returns the sum of those numbers. If invoked without any arguments, returns 0.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Summing Numbers in an array....</title>


<!-- ***************** CSS ********************* -->
	<style type="text/css">
		body{
			margin: 50px;
			background-color: burlywood;
		}

		center{
			background-color: grey;
			border: solid 10px;
			border-radius: 25px;
		}

		h2, #num, #submit, #result {
			font-size: 2em;
		}

		h1{
			margin: 0;
			color: #f94711;
		}

		#num, #submit{
			border-radius: 25px;
		}		
	</style>


</head>
<body>


<!-- ***************** HTML ********************* -->

<center>
	<h2>Enter your list of numbers like this: <i>1, 2, 3, 4, 5</i></h2>

	<input type="text" name="num" id="num" />
	<button id="submit">Submit</button>
	<br>
	<br>

	<label type="text" name="result" id="result" />
</center>



<!-- ***************** JS ********************* -->

<script type="text/javascript">

// Function to sum array of numbers.... https://www.educative.io/answers/how-to-get-the-sum-of-an-array-in-javascript
	function mySum(myarray) {
		  let sum = 0;

		  for (let i = 0; i < myarray.length; i += 1) {
		    sum += (myarray[i] * 1); // multiply by 1 to convert to number: https://www.freecodecamp.org/news/how-to-convert-a-string-to-a-number-in-javascript/
		  }
		  
		  return sum;
		}

// Get form entries....
	let btn = document.getElementById('submit');
	let result = document.getElementById('result');

// Perform the magic...
	btn.onclick = (e) => {
		let list_of_num = document.getElementById('num').value;
		// console.log(typeof(list_of_num))

		// Replace spaces....
		list_of_num = list_of_num.replace(/\s+/g, '');

		// Split by ','...
		list_of_num = list_of_num.split(',');

		// Use the function above to sum the list...
		let sum_of_list_of_num = mySum(list_of_num)

		// Display result...
		if (isNaN(sum_of_list_of_num)){
			result.innerHTML = `<h1>Invalid</h1> Your entries most all be numbers.`;
		} else {
			result.innerHTML = `The Sum of ${list_of_num} is: <h1>${sum_of_list_of_num}</h1>`;
		}
		


		// console.log(`${list_of_num}`)
		// console.log(mySum(sum_of_list_of_num))
	}


</script>


</body>
</html>



Task 3: Running Time Average

Here we will use javascript to dynamically add the run time input box.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Running Time Average...</title>

<!-- ------------------------ CSS -------------------------------- -->
  <style type="text/css">
    #num{
          height: 50px;
          width: 320px;
          font-size: xx-large;
        }

    #submit, #addmore{
      font-size: x-large;
      height: 70px;
    }

    #result{
      color: green;
      font-size: xxx-large;
    }


  </style>

</head>
<body>


<!-- ------------------------ HMTL -------------------------------- -->

<center>
  <h1>Enter the time run for the 10km: </h1>

  <input type="number" name="num" id="num" class="num" />
  <button id="submit">Submit</button>
  <button id="addmore">Add More Time</button>

  <br>
  <br>

  <label type="text" name="result" id="result" />
</center>



<!-- ------------------------ JS -------------------------------- -->


<script type="text/javascript">


  // Select the button element
  const submitButton = document.querySelector('#submit');
  const addmoreButton = document.querySelector('#addmore');

  const result = document.getElementById('result');



  // Add a click event listener to the addmore button
  addmoreButton.addEventListener('click', function() {
    // Create a new element
    const elem0 = document.createElement('center');
    const elem1 = document.createElement('input');
    const elem2 = document.createElement('br');


    // Set the element's content and style
    elem1.style.color = 'red';
    elem1.style.width = '600px';
    elem1.style.height = '50px';
    elem1.style.fontSize = 'xx-large';

    elem1.type = 'number';

    // Add a class and id named 'num' to the element
    elem1.className = 'num';
    elem1.id = 'num';


    // Append the 'input' to the 'center' element
    elem0.appendChild(elem1);

    // Append the element to the DOM
    document.body.appendChild(elem0);

    // document.body.appendChild(elem1);
    document.body.appendChild(elem2);

  });




// ---------------------------------------------

 // Add a click event listener to the submit button
  submitButton.addEventListener('click', function() {


    // const all_time = document.getElementsByClassName('num');
    const all_time = document.querySelectorAll('.num');


    const averageTimeRan = Array.from(all_time).reduce((total, elem) => total + parseFloat(elem.value), 0) / all_time.length;

    result.innerHTML = `The average of total time ran is: ${averageTimeRan.toFixed(2)}`;

  });



</script>


</body>
</html>

Wednesday, January 25, 2023

Wrangling the 'Database of health facilities in Nigeria' using QGIS and Python

 A database of health facilities in Nigeria would be a valuable resource for both healthcare providers and the general public. It could provide information about the types of facilities available, their locations, and the services they offer. This information could help healthcare providers refer patients to appropriate facilities, and it could help the public find the nearest and most suitable facilities for their needs.

There are many different types of health facilities in Nigeria, including hospitals, clinics, and pharmacies. Some facilities may specialize in a particular area of healthcare, such as maternal and child health, while others may offer a range of general medical services. The availability and accessibility of these facilities can vary greatly depending on where you are in the country.

Having a comprehensive database of health facilities in Nigeria would allow for better planning and resource allocation by the government and healthcare organizations. It could also help to ensure that underserved areas are not overlooked and that there is an adequate distribution of healthcare resources throughout the country.

In addition to providing information about health facilities, such a database could also include information about the availability of healthcare professionals, including doctors, nurses, and other medical staff. This could be particularly useful for rural areas where access to healthcare professionals may be limited.

Overall, a database of health facilities in Nigeria would be a valuable tool for improving the country's healthcare system and ensuring that all citizens have access to the healthcare services they need.










Wednesday, January 18, 2023

Python for GIS data wrangling

 Python is a powerful and widely used programming language that is well-suited for GIS data wrangling tasks. There are a number of libraries and tools available in Python that can be used to perform a wide range of GIS data wrangling tasks, including reading and writing various geospatial data formats, performing spatial transformations and projections, and performing spatial analyses and visualizations.

Some of the most commonly used libraries for GIS data wrangling in Python include:

pandas: A powerful data manipulation and analysis library that is widely used for GIS data wrangling. It provides a range of functions for reading and writing geospatial data formats, including CSV, shapefile, KML, and GeoJSON.

geopandas: A library built on top of pandas that provides additional functionality for working with geospatial data. It allows you to manipulate and visualize geospatial data using familiar pandas dataframes, and includes support for geographic projections and spatial operations.

fiona: A library for reading and writing geospatial data formats, including shapefiles, GeoJSON, and KML. It can be used in combination with other libraries, such as geopandas, to perform advanced GIS data wrangling tasks.

shapely: A library for working with geometric objects such as points, lines, and polygons. It provides functions for creating, manipulating, and performing spatial operations on these objects, and can be used to clean and transform geospatial data.

Other useful libraries for GIS data wrangling in Python include rasterio, gdal, and pyproj, among others. These libraries can be used to perform a wide range of GIS data wrangling tasks, including reading and writing various geospatial data formats, performing spatial transformations and projections, and performing spatial analyses and visualizations.

Over the past few years, I have used python to wrangle different kinds of GIS data and some example can be reviewed below:-

1- Python GIS data wrangling - Harris County Appraisal District

2- GIS data wrangling with python - Gridded Street Finder

3- Geocoding and Reverse Geocoding with Python

4- Python GIS data wrangling - Mapping supper eagles head coaches since 1949

5- Python GIS Data Wrangling - U.S. Drought Monitor

6- Python Programming for GIS Data Processing in QGIS

7- GIS data wrangling with python - case study of 'African Journals Online' featured countries


If you need help with wrangling your GIS data, you may contact me via email/phone details on my website:  UmarYusuf.com

Cheers!

Tuesday, January 3, 2023

Using chatGPT (Generative Pretrained Transformer) to map first 100 regions to welcome the new year

 ChatGPT is a variant of the GPT (Generative Pretrained Transformer) language model that is specifically designed for generating human-like text in a conversational context. It is not a tool for creating maps or visual representations of data.

How do we now use it to make maps?

The answer is simple, we will use ChatGPT to generate text that lists the first 100 regions to welcome the new year by providing the model with a prompt in the form of a natural language question or statement, such as "Can you provide a list of the first 100 regions to welcome the new year?", and then allowing the model to generate the text.


We can also ask ChatGPT to geocode the places for us and that will return the geographic coordinates as seen below;-



Now, we got all we needed to map the first 100 regions to welcome the new year. Copy the chatGPT text into your GIS software of choice for the mapping, of course the text will be formatted appropriately as required be the GIS software you want to use.

As for me I use QGIS software and here is how it looks:-


The New Year is celebrated on January 1st in most countries around the world. However, different countries have different time zones, so the New Year is actually celebrated at different times in different parts of the world.

The new year is celebrated at different times around the world. celebrate the new year is typically Samoa and Christmas Island in Kiribati, which are the first to enter the new year due to their location west of the International Date Line. The last place to celebrate the new year is usually Baker Island and Howland Island, which are the last to enter the new year due to their location east of the International Date Line. However, these locations are uninhabited, so the last place where the new year is celebrated with a significant population is usually American Samoa.


Thank you for following.