The document discusses arrays in JavaScript, including how to declare and initialize arrays, reference array elements, process arrays using loops, combine arrays, and find the maximum value in an array. It also covers functions, including defining functions, passing arguments to functions, and functions that return values. Finally, it demonstrates creating form elements and buttons in HTML and assigning onclick events to buttons.
This document discusses top-k string similarity search and proposes a clustered trie-based approach. Previous work used tries or q-grams with edit distance metrics. The proposed method clusters similar strings and constructs a primary trie of cluster centers and secondary tries of cluster contents. It finds pivot entries between tries to iteratively expand the search. Evaluation shows the clustered approach outperforms others with higher k values and is more robust to prefix/suffix additions. Challenges include scaling to large datasets and skewed clustering.
The document discusses heaps and heapsort. It defines max heaps and min heaps as complete binary trees where each node's key is greater than or less than its children's keys. It describes operations on heaps like insertion, deletion of the max/min element, and creation of an empty heap. Algorithms for insertion and deletion into max heaps are provided. Heapsort is described as building a max heap of the input array and then repeatedly extracting the max element to sort the array.
Many people ask about how to develop a functional mindset. It’s difficult if you’ve learned another paradigm and don’t know where to start. Functional thinking is a set of habits that you can train that will serve you well while programming in any language.
This document describes several web scraping functions:
1. A web scraper function that extracts data from an HTML document as a character object based on CSS selectors.
2. A function to check if an object is a valid HTML element.
3. A tag counter function that counts the number of tags in a string.
4. Closing tag locator functions that find the closing tags for given opening tags.
5. A content extractor function that extracts HTML elements based on tag positions and can remove tags or construct a data frame.
6. A table constructor function that creates a data frame from an HTML table.
7. A content remover function that removes unwanted content from extractor
The document discusses priority queues and binary heaps. It explains that priority queues store tasks based on priority level and ensure the highest priority task is at the head of the queue. Binary heaps are the underlying data structure used to implement priority queues. The key operations on a binary heap are insert and deleteMin. Insert involves adding an element and percolating it up the heap, while deleteMin removes the minimum element and percolates the replacement down. Both operations have O(log n) time complexity. The document provides examples and pseudocode for building a heap from a list of elements in O(n) time using a buildHeap method.
This document provides an overview of basic usage of the Apache Spark framework for data analysis. It describes what Spark is, how to install it, and how to use it from Scala, Python, and R. It also explains the key concepts of RDDs (Resilient Distributed Datasets), transformations, and actions. Transformations like filter, map, join, and reduce return new RDDs, while actions like collect, count, and first return results to the driver program. The document provides examples of common transformations and actions in Spark.
Slides from my "Purely functional data structures" talk at Boiling Frogs 2016 conference. It covered some concepts from Chris Okasaki's thesis as well as Git internals as an example of legendary implementation.
This document discusses top-k string similarity search and proposes a clustered trie-based approach. Previous work used tries or q-grams with edit distance metrics. The proposed method clusters similar strings and constructs a primary trie of cluster centers and secondary tries of cluster contents. It finds pivot entries between tries to iteratively expand the search. Evaluation shows the clustered approach outperforms others with higher k values and is more robust to prefix/suffix additions. Challenges include scaling to large datasets and skewed clustering.
The document discusses heaps and heapsort. It defines max heaps and min heaps as complete binary trees where each node's key is greater than or less than its children's keys. It describes operations on heaps like insertion, deletion of the max/min element, and creation of an empty heap. Algorithms for insertion and deletion into max heaps are provided. Heapsort is described as building a max heap of the input array and then repeatedly extracting the max element to sort the array.
Many people ask about how to develop a functional mindset. It’s difficult if you’ve learned another paradigm and don’t know where to start. Functional thinking is a set of habits that you can train that will serve you well while programming in any language.
This document describes several web scraping functions:
1. A web scraper function that extracts data from an HTML document as a character object based on CSS selectors.
2. A function to check if an object is a valid HTML element.
3. A tag counter function that counts the number of tags in a string.
4. Closing tag locator functions that find the closing tags for given opening tags.
5. A content extractor function that extracts HTML elements based on tag positions and can remove tags or construct a data frame.
6. A table constructor function that creates a data frame from an HTML table.
7. A content remover function that removes unwanted content from extractor
The document discusses priority queues and binary heaps. It explains that priority queues store tasks based on priority level and ensure the highest priority task is at the head of the queue. Binary heaps are the underlying data structure used to implement priority queues. The key operations on a binary heap are insert and deleteMin. Insert involves adding an element and percolating it up the heap, while deleteMin removes the minimum element and percolates the replacement down. Both operations have O(log n) time complexity. The document provides examples and pseudocode for building a heap from a list of elements in O(n) time using a buildHeap method.
This document provides an overview of basic usage of the Apache Spark framework for data analysis. It describes what Spark is, how to install it, and how to use it from Scala, Python, and R. It also explains the key concepts of RDDs (Resilient Distributed Datasets), transformations, and actions. Transformations like filter, map, join, and reduce return new RDDs, while actions like collect, count, and first return results to the driver program. The document provides examples of common transformations and actions in Spark.
Slides from my "Purely functional data structures" talk at Boiling Frogs 2016 conference. It covered some concepts from Chris Okasaki's thesis as well as Git internals as an example of legendary implementation.
The document discusses heap sort, which is a sorting algorithm that uses a heap data structure. It works in two phases: first, it transforms the input array into a max heap using the insert heap procedure; second, it repeatedly extracts the maximum element from the heap and places it at the end of the sorted array, reheapifying the remaining elements. The key steps are building the heap, processing the heap by removing the root element and allowing the heap to reorder, and doing this repeatedly until the array is fully sorted.
The Ring programming language version 1.6 book - Part 38 of 189Mahmoud Samir Fayed
This document summarizes the key classes in the Ring programming language including the String, List, Stack, Queue, HashTable, Tree, and Math classes. For each class, it provides an overview of the parent class and core methods, followed by examples of using each method on instances of the classes. It demonstrates initializing class instances, accessing and modifying values, and performing common operations like adding/removing items, sorting, and mathematical functions.
The document provides a list of regular expression patterns that could be used to scan protein sequences for prosite patterns. It begins by showing example consensus patterns for protein domains and motifs. It then lists 20 regular expression patterns translated from prosite consensus patterns that could be used to scan protein sequences and look for matches. The document concludes by providing an example Python code snippet to scan sequences for the given prosite patterns using regular expressions.
The document contains code for a C# program that merges employee wage and tip data from multiple text files into a single output file. It reads configuration settings from an XML file to determine the input and output file paths. It then reads the input files, merges the data based on employee identifiers, handles null values, and writes the results to the output file. It also writes log information to another output file. The key steps are: 1) reading the configuration, 2) reading and parsing the input files, 3) merging and formatting the data, and 4) writing the merged data and log to output files.
The document discusses Python lists, tuples, and dictionaries. It covers accessing and updating values in lists and tuples, deleting lists and tuples, and various built-in functions for lists, tuples, and dictionaries such as len(), max(), min(), etc. Methods for lists, tuples, and dictionaries are also explained, such as list.append(), tuple.count(), dict.clear(), etc. The key differences between lists, tuples, and dictionaries are that lists are mutable, tuples are immutable but can be concatenated, and dictionaries have unique keys.
The Ring programming language version 1.8 book - Part 41 of 202Mahmoud Samir Fayed
This document provides summaries of key classes in the Ring programming language standard library (stdlib), including classes for strings, lists, stacks, queues, hash tables, trees, and mathematical functions. It describes the purpose and basic usage of methods in each class.
Paco van der Linden, werkzaam als Senior ADF Ontwikkelaar bij AMIS, heeft met Groovy een aantal interessante oplossingen ontwikkeld. De kennis en ervaring die hij daarbij met Groovy in combinatie met Java (en ADF) heeft opgedaan, heeft hij op maandag 26 november gedeeld in een kennissessie.
Implementing pseudo-keywords through Functional ProgramingVincent Pradeilles
The document discusses implementing asynchronous code in a more functional way using pseudo-keywords. It introduces a weakify function that takes a function and returns a function that wraps it to avoid retain cycles when referencing self. This approach is expanded to other common patterns like debouncing. The document then shows how property wrappers can be used to implement these pseudo-keywords more declaratively. This allows patterns like asynchronous code and debouncing to be written in a cleaner way without extra boilerplate.
This document provides information about priority queues and binary heaps. It defines a binary heap as a nearly complete binary tree where the root node has the maximum/minimum value. It describes heap operations like insertion, deletion of max/min, and increasing/decreasing keys. The time complexity of these operations is O(log n). Heapsort, which uses a heap data structure, is also covered and has overall time complexity of O(n log n). Binary heaps are often used to implement priority queues and for algorithms like Dijkstra's and Prim's.
In this set of Python Lecture slides I demonstrate Numpy arrays and functions with appropriate applications. Demo on Data structures are done with Pandas.
The document discusses different types of heaps and heap algorithms. It describes binary min-heaps and max-heaps, including their properties and implementations using arrays. Basic heap operations like insert, delete, and build heap are explained along with their time complexities. Applications of heaps like priority queues and selection algorithms are covered. More advanced heap types like leftist heaps, skew heaps and binomial queues are also mentioned.
The Ring programming language version 1.5.2 book - Part 44 of 181Mahmoud Samir Fayed
The Page class contains methods for generating HTML elements and adding them to a page. It includes methods for common elements like headings, paragraphs, links, images, forms, tables, and more. Parameters allow setting attributes like IDs, classes, and styles. The class supports generating entire pages or parts of pages to be rendered on the server or client.
The document discusses different collection types in C#, including arrays, ArrayList, List, LinkedList, Dictionary, Queue and Stack. It provides code examples to demonstrate how to create and use each collection type, and describes their key properties and methods. Generic collections like List provide stronger typing and are preferred over non-generic collections like ArrayList. Collections like Dictionary provide fast retrieval based on keys, while Queue and Stack access elements based on FIFO and LIFO principles respectively.
This document contains the code for 13 programs written in C# .NET as part of a lab manual for a DOTNET Technology course. The programs cover basic concepts like arithmetic calculations, array operations, classes, inheritance, functions, and Windows forms applications including a calculator and basic notepad. For each program, the code is provided along with sample input/output.
The Ring programming language version 1.9 book - Part 44 of 210Mahmoud Samir Fayed
This document provides documentation on Ring's standard library classes. It describes several commonly used classes, including String, List, Stack, Queue, HashTable, Tree, and Math. For each class, it lists parent classes, attributes, methods, and examples of how to use the class methods.
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...BAINIDA
Introduction to financial time series analysis, getting financial time series data through yahoo finance API with R, time series visualization, risk and return calculation for financial time series data, autoregressive integrated moving average models with R code and applications in financial time series.
This document discusses concurrency features in Groovy and GPars. It highlights useful Groovy features for concurrency like closures, immutable collections, and annotation support. It also discusses common concurrency libraries and tools that can be used with Groovy like GPars, Google Collections, and Actors. The document provides examples of how Groovy improves on Java for concurrency tasks through features like closures, immutable types, and domain specific languages.
This document discusses building Windows applications using tree view and file compare controls to copy and delete files between directories. It also discusses building a web application in ASP.NET and accessing data using ADO.NET. Key aspects covered include filling a tree view with directories and files, getting checked files, comparing files, and handling copy and delete button clicks by getting file lists and performing the operations. Building a web form and adding a data source to select from a database table are also summarized.
Arrays in JavaScript can be used to store multiple values in a single variable. Arrays are objects with numeric indexes and various methods that can be used to modify arrays. Some key array methods include concat(), join(), push(), pop(), unshift(), shift(), sort(), reverse(), slice(), splice(), indexOf(), lastIndexOf(), and length. Arrays are dynamically typed and sparse, allowing elements to contain values of any type.
Java has a reputation for boilerplate code: ubiquitous getters and setters, a verbose anonymous class syntax, and redundant declarations to name a few. It doesn't have to be this way! There are many ways to bust the boilerplate and this session provides a solid understanding of the most modern techniques. Come learn about inversion of control idioms, Proxy objects, code generation tools, and the latest libraries that both create and manage boilerplate code so you don't have to. A leaner, meaner codebase is yours for the taking.
The document discusses various techniques for reducing boilerplate code in Java, including libraries like Google Guava, Apache Commons Lang, and features in Java 7 and later. It provides examples of using these libraries and features to simplify tasks like error handling, resource management, string processing, collections, and object representation.
The document discusses heap sort, which is a sorting algorithm that uses a heap data structure. It works in two phases: first, it transforms the input array into a max heap using the insert heap procedure; second, it repeatedly extracts the maximum element from the heap and places it at the end of the sorted array, reheapifying the remaining elements. The key steps are building the heap, processing the heap by removing the root element and allowing the heap to reorder, and doing this repeatedly until the array is fully sorted.
The Ring programming language version 1.6 book - Part 38 of 189Mahmoud Samir Fayed
This document summarizes the key classes in the Ring programming language including the String, List, Stack, Queue, HashTable, Tree, and Math classes. For each class, it provides an overview of the parent class and core methods, followed by examples of using each method on instances of the classes. It demonstrates initializing class instances, accessing and modifying values, and performing common operations like adding/removing items, sorting, and mathematical functions.
The document provides a list of regular expression patterns that could be used to scan protein sequences for prosite patterns. It begins by showing example consensus patterns for protein domains and motifs. It then lists 20 regular expression patterns translated from prosite consensus patterns that could be used to scan protein sequences and look for matches. The document concludes by providing an example Python code snippet to scan sequences for the given prosite patterns using regular expressions.
The document contains code for a C# program that merges employee wage and tip data from multiple text files into a single output file. It reads configuration settings from an XML file to determine the input and output file paths. It then reads the input files, merges the data based on employee identifiers, handles null values, and writes the results to the output file. It also writes log information to another output file. The key steps are: 1) reading the configuration, 2) reading and parsing the input files, 3) merging and formatting the data, and 4) writing the merged data and log to output files.
The document discusses Python lists, tuples, and dictionaries. It covers accessing and updating values in lists and tuples, deleting lists and tuples, and various built-in functions for lists, tuples, and dictionaries such as len(), max(), min(), etc. Methods for lists, tuples, and dictionaries are also explained, such as list.append(), tuple.count(), dict.clear(), etc. The key differences between lists, tuples, and dictionaries are that lists are mutable, tuples are immutable but can be concatenated, and dictionaries have unique keys.
The Ring programming language version 1.8 book - Part 41 of 202Mahmoud Samir Fayed
This document provides summaries of key classes in the Ring programming language standard library (stdlib), including classes for strings, lists, stacks, queues, hash tables, trees, and mathematical functions. It describes the purpose and basic usage of methods in each class.
Paco van der Linden, werkzaam als Senior ADF Ontwikkelaar bij AMIS, heeft met Groovy een aantal interessante oplossingen ontwikkeld. De kennis en ervaring die hij daarbij met Groovy in combinatie met Java (en ADF) heeft opgedaan, heeft hij op maandag 26 november gedeeld in een kennissessie.
Implementing pseudo-keywords through Functional ProgramingVincent Pradeilles
The document discusses implementing asynchronous code in a more functional way using pseudo-keywords. It introduces a weakify function that takes a function and returns a function that wraps it to avoid retain cycles when referencing self. This approach is expanded to other common patterns like debouncing. The document then shows how property wrappers can be used to implement these pseudo-keywords more declaratively. This allows patterns like asynchronous code and debouncing to be written in a cleaner way without extra boilerplate.
This document provides information about priority queues and binary heaps. It defines a binary heap as a nearly complete binary tree where the root node has the maximum/minimum value. It describes heap operations like insertion, deletion of max/min, and increasing/decreasing keys. The time complexity of these operations is O(log n). Heapsort, which uses a heap data structure, is also covered and has overall time complexity of O(n log n). Binary heaps are often used to implement priority queues and for algorithms like Dijkstra's and Prim's.
In this set of Python Lecture slides I demonstrate Numpy arrays and functions with appropriate applications. Demo on Data structures are done with Pandas.
The document discusses different types of heaps and heap algorithms. It describes binary min-heaps and max-heaps, including their properties and implementations using arrays. Basic heap operations like insert, delete, and build heap are explained along with their time complexities. Applications of heaps like priority queues and selection algorithms are covered. More advanced heap types like leftist heaps, skew heaps and binomial queues are also mentioned.
The Ring programming language version 1.5.2 book - Part 44 of 181Mahmoud Samir Fayed
The Page class contains methods for generating HTML elements and adding them to a page. It includes methods for common elements like headings, paragraphs, links, images, forms, tables, and more. Parameters allow setting attributes like IDs, classes, and styles. The class supports generating entire pages or parts of pages to be rendered on the server or client.
The document discusses different collection types in C#, including arrays, ArrayList, List, LinkedList, Dictionary, Queue and Stack. It provides code examples to demonstrate how to create and use each collection type, and describes their key properties and methods. Generic collections like List provide stronger typing and are preferred over non-generic collections like ArrayList. Collections like Dictionary provide fast retrieval based on keys, while Queue and Stack access elements based on FIFO and LIFO principles respectively.
This document contains the code for 13 programs written in C# .NET as part of a lab manual for a DOTNET Technology course. The programs cover basic concepts like arithmetic calculations, array operations, classes, inheritance, functions, and Windows forms applications including a calculator and basic notepad. For each program, the code is provided along with sample input/output.
The Ring programming language version 1.9 book - Part 44 of 210Mahmoud Samir Fayed
This document provides documentation on Ring's standard library classes. It describes several commonly used classes, including String, List, Stack, Queue, HashTable, Tree, and Math. For each class, it lists parent classes, attributes, methods, and examples of how to use the class methods.
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...BAINIDA
Introduction to financial time series analysis, getting financial time series data through yahoo finance API with R, time series visualization, risk and return calculation for financial time series data, autoregressive integrated moving average models with R code and applications in financial time series.
This document discusses concurrency features in Groovy and GPars. It highlights useful Groovy features for concurrency like closures, immutable collections, and annotation support. It also discusses common concurrency libraries and tools that can be used with Groovy like GPars, Google Collections, and Actors. The document provides examples of how Groovy improves on Java for concurrency tasks through features like closures, immutable types, and domain specific languages.
This document discusses building Windows applications using tree view and file compare controls to copy and delete files between directories. It also discusses building a web application in ASP.NET and accessing data using ADO.NET. Key aspects covered include filling a tree view with directories and files, getting checked files, comparing files, and handling copy and delete button clicks by getting file lists and performing the operations. Building a web form and adding a data source to select from a database table are also summarized.
Arrays in JavaScript can be used to store multiple values in a single variable. Arrays are objects with numeric indexes and various methods that can be used to modify arrays. Some key array methods include concat(), join(), push(), pop(), unshift(), shift(), sort(), reverse(), slice(), splice(), indexOf(), lastIndexOf(), and length. Arrays are dynamically typed and sparse, allowing elements to contain values of any type.
Java has a reputation for boilerplate code: ubiquitous getters and setters, a verbose anonymous class syntax, and redundant declarations to name a few. It doesn't have to be this way! There are many ways to bust the boilerplate and this session provides a solid understanding of the most modern techniques. Come learn about inversion of control idioms, Proxy objects, code generation tools, and the latest libraries that both create and manage boilerplate code so you don't have to. A leaner, meaner codebase is yours for the taking.
The document discusses various techniques for reducing boilerplate code in Java, including libraries like Google Guava, Apache Commons Lang, and features in Java 7 and later. It provides examples of using these libraries and features to simplify tasks like error handling, resource management, string processing, collections, and object representation.
The document contains code examples demonstrating various Scala programming concepts such as functions, pattern matching, traits, actors and more. It also includes links to online resources for learning Scala.
The document discusses Simple API for XML (SAX), an event-based model for parsing XML documents. SAX involves defining handler methods that are called when XML parsing events occur, like start elements or character data. This allows applications to process XML documents as they are parsed without loading the entire document into memory. The example shows a SAX parser that outputs a tree structure of an XML document by overriding handler methods.
This document summarizes a talk given at YAPC Tokyo 2010 about calling C code from Perl using various techniques. It discusses Ctypes, a module for directly calling C functions without XS; Libperl++, a C++ library for embedding and extending Perl; and XS++, which allows writing C++ classes that integrate seamlessly with Perl using a special syntax.
The document discusses behavior driven development (BDD) and test-driven development (TDD). It shows an example of incrementally developing a FizzBuzz program using TDD and JUnit tests. First, a single test is written to verify the output for the number 1. Then tests are added and code is modified to pass each new test, building up the full FizzBuzz logic over multiple test/code iterations. The document also discusses differences between traditional TDD testing and BDD-style testing, where test method names are written as sentences describing expected behavior.
This document discusses arrays and pointers in C++. It begins by explaining that arrays allow storing multiple values of the same type, and that arrays have a fixed size and type after declaration. It then covers how to declare, initialize, access elements of, and iterate through arrays using indexes and loops. Multidimensional arrays are also explained, including how they can be thought of as tables with rows and columns. The document concludes by introducing pointers as variables that store the memory addresses of other variables.
The document describes an advanced Perl techniques training course that covers new features in Perl 5.10, dates and times using the DateTime module, testing and benchmarking code, and accessing databases. The one-day course will move quickly and cover dates/times, testing, databases, profiling, object-oriented programming with Moose, templates, and MVC frameworks. Resources from the training will be available online.
When I left Frogtrade, I was asked to provide a presentation on Javascript basics to act as reference material for the PHP developers I left behind. This is that presentation.
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
Control flow statements determine the order in which program instructions are executed. They include conditional branches (if/else), loops (while, for, do-while), and jumps. Arrays allow storing multiple values of the same type together in contiguous memory locations that can be individually referenced using an index. Multi-dimensional arrays generalize this by storing arrays inside other arrays, allowing modeling of matrices. They require nested loops for processing all elements.
The document provides information about arrays and pointers in C++. It discusses how to declare, initialize, access elements of arrays including multi-dimensional arrays. It also covers pointers, how they store memory addresses rather than values, and how to declare and assign addresses to pointers. Key topics include declaring arrays with syntax like dataType arrayName[size]; initializing arrays; accessing elements using indices; multi-dimensional arrays of different sizes; declaring pointers with syntax like int* pointer; and assigning addresses to pointers using &operator.
This document discusses ES6 features and best practices for using them. It covers new features like let and const, arrow functions, classes, modules, destructuring, default parameters, and promises. It emphasizes keeping code simple, using context appropriately, and favoring powerful yet simple features. Tools like Babel, Gulp and Karma are recommended for compiling, building workflows and testing ES6 code.
The document discusses the basics of JavaFX including variables, functions, sequences, control structures, classes, inheritance, and charts. It provides an overview of key JavaFX concepts and features from the perspective of a Java developer. Resources for learning more about JavaFX are also listed, including books, tutorials, and API documentation.
- Arrays allow storing multiple values of the same type sequentially in memory. They have a fixed size or dimension.
- To declare an integer array of size 4, we write "int arr[4]". Individual elements can be accessed using indexes from 0 to dimension-1.
- Strings in C++ are arrays of characters that end with a null character. Common string functions like strcpy(), strcat(), strlen() allow manipulating strings.
The document discusses arrays in C++. It explains one-dimensional and two-dimensional arrays, how to declare, initialize, and access elements of arrays. Key points include arrays storing a collection of like-typed data, being indexed starting from 0, initializing during declaration, and accessing two-dimensional array elements requiring row and column indices. Examples are provided to demonstrate array concepts.
4. Array Declaration and Initialisation var tmaScoreArray = new Array(6); // value of all array elements will be undefined until initialised // initialisation of array elements tmaScoreArray[0] = 92; tmaScoreArray[1] = 87; tmaScoreArray[2] = 85; tmaScoreArray[3] = 78; tmaScoreArray[4] = 89; tmaScoreArray[5] = 82; var tmaScoreArray = [92,87,85,78,89,82]; 1 2
6. Accessing Array Elements var tmaScoreArray = [92,87,85,78,89,82]; var tma1; tma1 = tmaScoreArray[0]; document.write('Your score for TMA01 was: ' + tma1]); Your score for TMA01 was: 92 The output is the same for both methods var tmaScoreArray = [92,87,85,78,89,82]; document.write( ' Your score for TMA01 was: ' + tmaScoreArray[0]); 1. Assigning value in array element to a variable 2. Accessing value in array element directly
7. The length Property var studentArray = [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; index 0 to 5 The length of the array is 6 (one more than the index of the last element). ‘ Eda’ 4 ‘ Carl’ 3 ‘ Ian’ 5 ‘ Mike’ 2 ‘ Nicky’ 1 ‘ David’ 0
8. More on the length property var studentArray = [‘David’,’Nicky’,’Mike’,’Carl’,’Eda’,’Ian’]; var studentArray = [,,,,,]; var studentArray = new Array(6); Whether you: declare and initialise an array with six elements, or declare an array with six empty elements, or declare a new array with six elements not yet initialised, they all have length 6. If this array was half full it would still have length 6.
9. Using the length Property var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; document.write('Array length is: ' + studentArray.length); document.write('<br>The last element is: ' + studentArray[studentArray.length - 1]); Array length is: 6 The last element is: Ian Output
11. Processing Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; //Write out list of students for ( var i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + '<br>') } David Nicky Mike Carl Eda Ian Output
12. Joining Output from Two Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; //Write a list of first names and surnames of students for ( var i = 0; i < studentArray.length; i = i + 1) { document.write(studentArray[i] + ' ' + surnameArray[i] + '<br>'); }
13. Output David Gates Nicky Lovelace Mike Pascal Carl Babbage Eda Hopper Ian von Neumann
14. Combining Two Arrays var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var fullNameArray = new Array(6); //Join first names and surnames in third array and write out for ( var i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] = studentArray[i] + ' ' + surnameArray[i]; document.write(fullNameArray[i] + '<br>') }
15. Don't know the number of students? Prompt for input! var numberOfStudents; var markArray; numberOfStudents = parseFloat(window.prompt('How many students do you have?', '')); markArray = new Array(numberOfStudents); for ( var student = 0; student < numberOfStudents; student = student + 1) { markArray[student] = window.prompt('Enter student mark', '') }
16. Making it more informative var studentArray = ['David','Nicky','Mike','Carl','Eda','Ian']; var surnameArray = ['Gates','Lovelace','Pascal','Babbage','Hopper','von Neumann']; var fullNameArray = new Array(6); document.write ('Array program to display numbered students<br><br>'); //Join first names and surnames in third array and write out for ( var i = 0; i < fullNameArray.length; i = i + 1) { fullNameArray[i] = studentArray[i] + ' ' + surnameArray[i]; document.write( 'Student ' + (i + 1) + ': ' + fullNameArray[i] + '<br>') } document.write('<br>End of display');
17. Output Array program to display numbered students Student 1: David Gates Student 2: Nicky Lovelace Student 3: Mike Pascal Student 4: Carl Babbage Student 5: Eda Hopper Student 6: Ian von Neumann End of display
18. Finding the Maximum Value initialise array of TV hours watched for 7 days initialise maximum TV hours watched to hours in day 1 for each day of the week except the first compare the hours with the current maximum if it is bigger replace current maximum with that days hours end for write out the final maximum number of hours
19. Finding the Maximum Value var tvHoursArray = [5,3,4,2,6,1]; var maxTvHours = tvHoursArray[0]; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] } } document.write('Maximun hours of TV watched was: ' + maxTvHours); Maximun hours of TV watched was: 6 Output
20. Improving the Output var tvHoursArray = [5,3,4,2,6,1]; var maxIndex = 0; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > tvHoursArray[maxIndex] ) { maxIndex = day } } document.write('Maximun hours of TV watched was: ' + tvHoursArray[maxIndex] + ' on day ' + (maxIndex + 1)); Maximun hours of TV watched was: 6 on day 5 Output
21. Improving the Output var tvHoursArray = [5,3,4,2,6,1]; var maxTvHours = tvHoursArray[0]; //Initialise to 1st element in array var maxIndex = 0; for ( var day = 1; day < tvHoursArray.length; day = day + 1) { if(tvHoursArray[day] > maxTvHours) { maxTvHours = tvHoursArray[day] ; maxIndex = day } } document.write('Maximun hours of TV watched was: ' + maxTvHours + ' on day ' + (maxIndex + 1) ); Maximun hours of TV watched was: 6 on day 5 Output
23. Functions function doSomething() { //some statements } Syntax function sayHello() { document.write('Hello!') } Example Header Body
24. Functions function sayHello() { document.write('Hello!') } // Call or invoke the funtion sayHello() sayHello(); /* Call or invoke the function sayHelloSomebody(name) */ sayHelloSomebody('Rita') function sayHelloSomebody(name) { document.write('Hello! ' + name) } Hello! Output Hello! Rita Output
25. <HTML> <HEAD> <TITLE> Greeting Program </TITLE> <SCRIPT> //Greeting function function sayHelloSomebody(name) { document.write('Hello! ' + name) }; var myName; //Prompt for name and assign to variable myName = window.prompt('Please input your name','Put your name here'); //Call function sayHelloSomebody(myName); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Hello! Rita Output
26. Functions That Return a Value function total(numberA, numberB) { return numberA + numberB } document.write( total(2,3) ); //function call function total(numberA, numberB) { return numberA + numberB } var sum; sum = total(2,3) ; //function call document.write(sum); Output 5 Output 5 1 2
27. Formal and Actual Arguments function sayHelloSomebody(name) { document.write('Hello! ' + name) } sayHelloSomebody('Rita') formal argument Actual argument
30. Creating Elements <BODY> <!-- Create the form --> <FORM NAME = "form1"> <!-- Create the helloButton --> <INPUT TYPE = "button" VALUE = "Try me" ONCLICK = "document.form.helloBox.value = 'Hello!'"> <!-- Create the textBox --> <INPUT TYPE = "text" NAME = "helloBox" VALUE = ''> </FORM> </BODY>
31. <BODY> <!-- Create the form --> <FORM NAME = "form1"> <!-- Create the helloButton --> <INPUT TYPE = "button" VALUE = "Try me" ONCLICK = "window.alert(What a great tutorial!)'"> </FORM> </BODY>
32. <BODY> <!-- Create the form --> <FORM NAME = "form1"> <!-- Create the helloButton --> <INPUT TYPE = "button" VALUE = "Try me" ONCLICK = "window.confirm('Do you still love me?')"> </FORM> </BODY>
33. <BODY> <!-- Create the form --> <FORM NAME = "form1"> <!-- Create the helloButton --> <INPUT TYPE = "button" VALUE = "Try me" ONCLICK = "document.write(window.confirm('Do you still love me?'))"> </FORM> </BODY> true Output
34. More About Strings myString myString.length is ? mystring.charAt(5) is ? myString.indexOf('d') is ? index 11 10 9 8 7 6 5 4 3 2 1 0 ! d l r o w o l l e H
35. /* function to check whether a character is 'a', 'b' or 'c' */ function isabORc(aChar) { return (aChar >= 'a') && (aChar <= 'c') }; var inputChar; inputChar = window.prompt('Please input a character'); if { document.write('The character was ' + inputChar) } else { document.write('The character was not a, b or c') } (isabORc(inputChar)) //evaluate function call
Editor's Notes
Don’t forget to do truth tables and precedence from Unit 6 and tracing a program and programming tips: Comments Skeleton and test line by line – ish Insert write lines at points In Unit 8 we are going to look at arrays as an example of a data structure holding a collection of data that has something in common. The Block 2 Glossary defines a data structure as: a collection of simple data items, e.g. numbers, characters or strings, combined together in a specified way so that they can be manipulated as a single entity. We are also going to introduce functions as a way of dealing with complexity. and as a way of reusing useful bits of code. We’ll introduce event-driven programming and some of the facilities that JavaScript has for building a graphical user interface.
Arrays feature in most programming languages but might have slightly different rules or syntax in different languages. So far we have looked at single-valued data but now we are going to look at collections of values in the form of arrays as an example of a data structure and how when we find a pattern or program that works well we can reuse it for something else. These data are all of the same type – numbers - and are related to each other. They are TMA scores, and, as an array, can be manipulated as a single item or the individual elements can be referred to separately. It is structured data. The indexing of an array is similar to that for strings – starting at zero, so the index of the first element is zero. An array must have a named variable – here it's tmaScoreArray. Q What is the value of the element in the third position? – 85. Q And what is its index? – 2. An array is an object the Array object (with a capital A – all objects begin with a capital letter) that is built into JavaScript and it has its own properties and methods for processing arrays.
You can access or reference an individual element by using the variable name and the index in square brackets. So the first element will be tmaScoreArray square brackets 0 (tmaScoreArray[0]) and the fourth element will be tmaScoreArray square brackets 3 (tmaScoreArray[3]).
There are two ways to declare and initialise an array. If you know what data is going to go into it you can initialise the array at the same time as you declare it as in 1. You declare a variable such as tmaScoreArray and assign to it the values of the elements separated by commas and enclosed in square brackets. If you don’t know what data is going into the array but you know how many elements you want it to have you create a new array to hold that number of elements as in 2. To do this you use the keyword new and a method of the Array object Array followed by the number of elements in parentheses. So you create a new array to hold 6 elements and assign it to the variable tmaScoreArray. All the elements of that array will be undefined. They will have nothing in them until we add some numbers to initialise the array. Suppose we now know the numbers – the scores – we can add them to the array by accessing the array elements as we saw in the last slide. For the first element we say tmaScoreArray[0] is assigned 92; for the second, tmaScoreArray[1] is assigned 87, etc. You don’t have to initialise all the elements if you don’t know the scores yet. Elements don’t have to be numbers, they can be characters or strings even other arrays!
So you declare an array that is empty and assign values to its elements.
For example you can assign the value in an element of an array to another variable. Here we have declared and initialised the array tmaScoreArray and declared a variable tma1. Into that variable we have assigned the value that is at index 0 in the array. You can also access an array element directly and, for example, write it out. The output is the same for both methods.
In JavaScript the Array object has a length property. The length of an array is one more than the index of the last element because the index starts at zero.
Whether you: declare and initialise an array with six elements explicitly, or declare an array with six empty elements, or declare a new array with six elements not yet initialised, they all have length 6. If this array was half full it would still have length 6.
Having declared and initialised the array we write out the length of the array. studentArray.length gives us the length and that is concatenated to the string ‘Array length is:’. We can also use the length property to access the last element in the array. You remember we access an array element by using the array name followed by the index in square brackets. studentArray.length is 6 so studentArray.length – 1 is 5, so we are accessing the element at index 5 – the last element in the array.
Structured English is used in planning an algorithm. Some of the same keywords are used that are used in the program and the layout of the algorithm is similar to the layout of the program. This structured English is sometimes called pseudo code. To go through our student array and write out a list of names the algorithm in structured English would be: for each student name in the array write out the name end for
You can use the for loop to process the array elements one by one. This program fragment writes out the list of names in the array and is translated into JavaScript from the structured English on the previous slide. We have to declare a variable for the loop counter (i in this case), specify a starting value (0 because it matches the start of the array), decide on a condition (i < studentArray.length) … Q In the condition why don't we say i <= studentArray.length? Because the length is 6 but we want to leave the loop after the element at index 5 so we say as long is i less than 6 execute the loop. We started at element 0. Also this is useful if you don't know how many elements there are in the array. ... and finally state a rule for incrementing the loop counter – increment it by 1. i is often used as a loop counter in programming, and if you need a second one for some reason j is used. Also it's short and doesn't take so much room up on the slide! The unit has used month in its rainfall examples because month is meaningful in that context. Q What more meaningful variable name for our loop counter could we have here?
We can join the output from two arrays or parallel arrays. We have the studentArray we had before and we have a another array called surnameArray, both initialised. We got through the loop again writing out an element from studentArray, then a space, then the corresponding element from sturnameArray at the same index.
Output from previous slide
We can combine the two arrays into a third array – fullNameArray. We have the same two arrays again and we declare a new array, fullNameArray, that is not yet initialised. Then we loop though a for loop concatenating the names from studentArray to the names from surnameArray, each in turn, and assigning them to elements of fullNameArray. Then we write out the new values in fullNameArray. This has the same output as the previous program.
This is the example on page 19 of Unit 8. The structured English algorithm for the program is near the top of the page. It is an array of students' marks where you don't know the number of students to start with or what the marks are, so you have to prompt for the number of students first. You have declared a variable, numberOfStudents, to hold the number of students so you read it into that. At the same time as you are reading that in you parseFloat it because you need it to be a number. You've already declared a variable markArray to hold the array but now you know how many students you're going to have you can initialise markArray by creating a new array of size numberOfStudents and assigning it to markArray. Once your array has been created you can then loop through it prompting for the mark for each index in turn.
Previously we wrote out a list of student names which didn't mean anyhting on it's own so now we are going write out a bit of explanation and the position in the array as well, using the index. The bits we've added are in shocking pink! In the write statement in the for loop we want to write out the position in the array (not the index) so we put (i + 1) and it must be in parentheses or else the interpreter will regard it as a concatenation. Also whatever is in the inner parentheses will be evalutaed before the outer parentheses.
Output from previous slide.
In this program we want to find the maximum number of hours of TV watched per day, over a week. This is our algorithm in natural English: First we initialise array of TV hours watched for 7 days (that may already have been done somewhere else in the program) Then we initialise maximum TV hours watched to hours in day 1 (index 0). Then for each day of the week except the first we compare the hours of TV watched with the current maximum hours and if it is bigger replace current maximum with that days hours and end the for loop. Then we write out the final maximum number of hours
This is the program to find the maximum number of hours of TV watched per day, over a week. We have a variable to hold an array containing number of hours of TV watched every day for a week starting on Sunday. We also have a variable to hold the maximum number of hours of TV watched which we initialise to first element in array – the element at index 0. Then we are going to work our way through the array starting at the second element (index 1) and see if each in turn is bigger than the maximum, which is held in maxTvHours. If it is bigger then that number is assigned to maxTvHours. When the loop is exited maxTvHours will hold the maximum number of hours of TV watched for that week. We can then write it out. Q Why do we start the loop at index 1? Because we have already looked at the first element and we are going to compare it with the second. This is OK but it doesn't tell us which day of the week has the maximum number of hours of TV watched. Activity 2.6 and Exercise 2.3 show you how to do it using two for loops.
To improve the output, and write out what day most hours of TV were watched, we need to keep track of the index of the element with the biggest number of hours. So we will need a variable to to store that index. Here I've declared maxIndex to store the index of the element with the biggest number of hours. We initially set it to zero and it will be updated each time a higher number of hours is found as it goes through the loop. This time we write out, after exiting the loop, the string, 'Maximun hours of TV watched was: ' concatenated to tvHoursArray[maxIndex], i.e. the element of the array at the index where the maximum value is, concatenated to the string ' on day ' concatenated to (maxIndex + 1), the position in the array of the element with the biggest value. Don't forget the parentheses round (maxIndex + 1) and don't forget the spaces. Q Has anybody any idea how we could improve that further? We could have seven if statements saying if maxIndex = 0 write out Sunday, if maxIndex = 1 write out Monday … etc. Later you'll learn a programming construct where you execute a different bit of code depending on a number of different choices, it's called a switch statement.
[Omit if time short.] Another way to do it is to go through a loop updateing maxTvHours and maxIndex in one loop. First we need a variable to hold the index of the day that has the maximum number of hours. I've called that maxIndex and initialised it to 0. Then in the if statement if we find a that the hours of TV watched for a particular day is greater than maxTvHours we assign the index of that day to maxIndex. At the end we write out what we wrote out before concatenated to ' on day ' concatenated to (maxIndex + 1) because the index starts at 0 and we want the position in the array. Don't forget the parentheses round (maxIndex + 1) and don't forget the spaces.
We've briefly mentioned Objects and Math is another object (don't forget objects start with capital letters). One method of the Math object is round(). It rounds a decimal, or real, number up or down to the nearest whole number. So 12.2-something will be rounded down to 12 and 12.7-something will be rounded up to 13.
A complicated program can be broken down into smaller subtasks and in JavaScript these subtasks are called functions. The course style is to put the code for the functions before the main program. The keyword function comes first followed by the function name, doSomething, and the name is followed by a pair of parentheses. Sometimes we want to pass some information to the function that the function is going to use and this goes in the parentheses. It is called an argument. You must have the parentheses whether you are passing any information to the function or not. The first line of the function is called the header and statements are in the body. The beauty of a function is that you can use it as many times as you want within a program, or in different programs, and you only have to write the code once. Also, if at some future date you decide to change the function slightly, you only have to change the one bit of code and not go searching through hundreds or thousands of lines of code to find bits you want to change.
In the first example we have a function that just does something – write out Hello – we don't have to pass it an argument. To use the function we have to call or invoke it and then it writes out Hello. The second one has an argument. In the function definition it is called name and name stands in for the actual argument we are going to pass it. So we invoke the function as before but we pass it the string 'Rita' by putting it in the parentheses. The string 'Rita' replaces name in the function body. It then writes out Hello! Rita. You don't have to pass the actual string (a string literal) or number or whatever, you can declare a variable and perhaps prompt the user for a name then assign it to the variable, then pass the variable to the function. The argument, name, is only meaningful inside the function. It is not available outside the function.
A simple program might look something like this. We have the usual HTML tags. The function is declared first inside the <script> tag at line 7. We declare a variable myName at line 12, then we prompt for the name and assign it to the variable myName at line 14. We then call or invoke the function, sayHelloSomebody(name), passing myName as an argument in the parentheses, at line 16. myName then replaces name inside the function. The main program may be in the main body between the body tags. It doesn't have to be in the head. Don't forget a suitable title and don't forget some comments. Q What does the second argument do in the window.prompt statement on line 14 - 'Put your name here'? Puts that text in the prompt dialogue box by default. Q What is line 7 called? The function header.
The functions we've just looked at just did something useless – sorry!– trivial, but you can have functions that return a value to you that you can do something with. Functions can also have more than one argument. We use the keyword return to tell the function to return whatever comes after it, then what is returned is available to the program that called the function. In example 1 we have declared a variable called sum. We then call or evoke the function total() with the arguments 2 and 3, separated by commas. The value that is returned is assigned to the variable sum. In example 2 we have included the function call directly in the write statement. The function call will be evaluated first and return the total then document.write will write it out.
The arguments you use when you call a function, not surprisingly, are called the actual arguments . The arguments in the function definition are called the formal arguments . When you call a function the actual arguments replace the formal arguments.
In olden days you had to use a command line interface and you had to remember exactly all the commands and type them into DOS or Unix, and it wasn't very pretty. You didn't even get a screen at first, the output went to a printer. Now we have graphical user interfaces, or GUIs, where we can just hold the mouse over an item and get a drop-down menu or click on a button to do something. The buttons, menus and text boxes etc are generally called widgets but in JavaScript they're known as elements in the HTML pages.
To use widgets you have to create a form to put them on and the form has to have a name. The form is in the Document object (the page on the screen) and the Document object is in the Window object. If the top button is called helloButton, what it says on it is its value and the form we'll called form1 we would refer to the vlue on the helloButton as: document.form1.helloButton.value
First create the form in the body of the HTML document using opening and closing HTML form tags. Look at the text box first. You create it with the INPUT tag and then set its attributes. We give it the type &quot;text&quot;, the name &quot;helloBox&quot; and the value '' an empty string. We want to click the button and have some text appear in the text box but before we click the button we want nothing in the text box so we set its value attribute to an empty string. Now look at the button. Its type attribute is &quot;button&quot;, its value (that's what it says on the button) is &quot;Try me&quot; and its ONCLICK event is to write in the text box Hello! What's in its value attribute appears in the text box, helloBox. To start with there's nothing in helloBox so to tell the helloBox what we want it to display we say (reading from right to left) the value of helloBox in form1 in the document object is Hello! – when we click it. This bit of code that says what's to happen when the button is clicked is called the event handler. You can use functions as event handlers. You can define a function and make afunction call as the ONCLICK event.
Another ONCLICK event could be to produce an Alert dialog box. alert() is a method of the Window object and what you put in the argument is what appears in the alert box.
We also have a confirm dialog box. When you click the button this confirm box appears. If you click OK it returns the Boolean value true, if you click Cancel it returns false. So in a program where you were using a confirm box you could write an if/else statement depending on whether the confirm box returned true or false. To demonstrate this …
Here I've asked it to write the value returned by the confirm box after OK or Cancel has been clicked. I clicked OK and it wrote out true – the value that was returned. If OK is clicked then (window.confirm('Do you still love me?')) evaluates to true so document.write writes out true. That value could be used elswhere in the program.
Figure 5.1 on page 68 of Unit gives us a reminder of what we've done so far on strings and introduces another method of String objects - indexOf(). myString.length is 12 mystring.charAt(5) is space myString.indexOf('d') is 10
In the function we need to test whether a character is 'a', 'b', or 'c'? Q How do we do that? We could say: if (aChar == 'a') || (aChar == 'b') || (aChar == 'c') { return true }; But the way shown on the slide is more elegant. However this way is not wrong and it's more explicit and less mysterious and if you want to do it that way while you're learning, because you understand it better, that's OK. We've declared a variable – inputChar - and prompted for input that we've assigned to it. If inputChar is lower case a, b or c we write it out, if not we tell the user the character wasn't a, b or c. Q So what condition do we want in the if statement, bearing in mind we've just created a function that returns true or false? if(isabORc(inputChar)) It is a call to the function isabORc(inputChar) and if it is the condition in the if statement it's like saying 'if true …. else …. '