JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2014.
http://www.ivanomalavolta.com
Anonymous functions allow functions to be defined and called without a name. JavaScript functions are first-class objects that can be treated like any other object. This allows functions to be defined anonymously and immediately called by wrapping the function definition in parentheses and adding another set of parentheses to call it. For example, (function(){ return "Hello World"; })(); defines and immediately calls an anonymous function without needing to assign it a name.
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
Javascript basics for automation testingVikas Thange
This document provides an overview of basic JavaScript examples and concepts. It covers topics such as writing JavaScript code, variables, conditional statements, functions, loops, events, and error handling. For each topic, it provides short code snippets to demonstrate the concept. It concludes by referencing W3Schools as a resource and thanking the reader.
Every bit of JavaScript code runs inside an Execution Context. This key principle is the base of the closures. Mastering closures is key when writing JS code and apps.
A JavaScript function is a block of code designed to perform a particular task.
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
This document discusses advanced JavaScript techniques. It covers object-oriented JavaScript concepts like references, function overloading, type checking, scopes, closures, object creation, and inheritance. It also discusses performance improvements like scope management, object caching, and optimizing DOM selection. Finally, it discusses debugging and testing JavaScript code as well as distributing JavaScript applications.
This talk was given at JSSummit 2013. Entitled "Avoiding Callback Hell with Async.js", my talk focused on common pitfalls with asynchronous functions and callbacks in JavaScript, and using the async.js library and its advanced control flows to create cleaner, more manageable code.
The document discusses Javascript Promises and the Q library for handling asynchronous code. It explains what Promises are, how they avoid callback pyramids or "Pyramids of Doom", and how the Q library can be used to generate and control Promises. The Q library allows wrapping asynchronous functions in Promises and provides methods for chaining Promises together and handling errors across asynchronous operations.
Functors, Applicatives and Monads In ScalaKnoldus Inc.
The document discusses functors, applicatives, and monads. It defines each concept and provides examples. Functors allow mapping a function over a wrapped value using map. Applicatives allow applying a function wrapped in a context to a value wrapped in a context using apply. Monads allow applying a function that returns a wrapped value to a wrapped value using flatMap. Examples of each include Option for functors, lists for applicatives, and futures for monads.
JavaScript global object, execution contexts & closuresHDR1001
The document discusses key JavaScript concepts including the global object, execution contexts, closures, and 'this'. It summarizes an article explaining that the global object exists as a single copy accessible anywhere and ends with the program. Execution contexts contain variable objects and have a stack structure. Closures occur when a nested function references variables in its parent function's scope. The value of 'this' depends on how a function is called. Diagrams are included to help illustrate these concepts.
Functions being first-class citizens in JavaScript offers developers a tremendous amount power and
flexibilty. However, what good is all this power if you don't know how to harness it?
This talk will provide a thorough examination of JavaScript functions. Topics
that will be covered in this talk are:
* Functions are objects
* Execution Context and the Scope Chain
* Closures
* Modifying Context
* The Various Forms of Functions.
Attendees will leave this talk understanding the power of JavaScript functions and the knowledge to apply new
techiques that will make their JavaScript cleaner, leaner and more maintainable.
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
Reactive programming models asynchronous data streams as signals that produce events over time. ReactiveCocoa is a framework that implements reactive programming in Objective-C. It uses signals to represent asynchronous data streams and operators to transform and combine signals. ReactiveCocoa code separates the logic to produce and consume data, making it more modular, reusable, testable and by reducing state and mutability. While the syntax is different, learning to think reactively can improve code quality and stability.
This document provides an overview and introduction to JavaScript basics and best practices. It covers what JavaScript is, how engines work, language features, and future developments like ES6. The basics section discusses types, variables, expressions, statements, functions, objects, and prototypical inheritance. The best practices section focuses on techniques for enterprise applications. The document is intended to help front-end developers learn JavaScript fundamentals.
"Reactive Programming with JavaScript" by Giorgio Natili
JavaScript is an asynchronous and almost single-thread language. Learning how to manage its asynchronous nature is perhaps the most important part of becoming an effective JavaScript programmer. Reactive programming tools in JavaScript provide a powerful way of “wrapping” the asynchronous callbacks into a more readable and maintainable code base. In this talk, I'll highlight the pros and cons of different reactive programming approaches and practices by demonstrating how to use Redux and Angular 2.x as the building blocks of a scalable architecture for your web app.
ReactiveCocoa is a framework for building reactive applications using signals that emit events. It allows defining data flows where events are propagated through operations like map, filter, and flatten. Signals can represent UI controls, network requests, or other asynchronous events. This allows building reactive user interfaces where UI is updated automatically in response to data changes. Operations are chained fluently on signals to transform and combine events.
ReactiveCocoa provides a common interface for handling asynchronous events from different sources like UI controls, network requests, and notifications. It uses signals that emit events to represent asynchronous data over time. Operations like filtering, mapping, and combining signals allow defining reactive workflows. Swift's support for functional programming makes it a good fit for the declarative style of ReactiveCocoa.
This document introduces Reactive Cocoa, a framework for Functional Reactive Programming in Objective-C. It describes Reactive Programming as a paradigm oriented around data flows and propagation of change. It explains the key concepts in Reactive Cocoa including streams (signals and sequences), how they allow declarative data transformations, and examples of using signals to react to user interface changes.
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2015.
http://www.ivanomalavolta.com
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2016.
http://www.ivanomalavolta.com
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Scala, Java 8 and Ruby become common. I will talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve the holy grail of OO, encapsulation.
This document provides answers to 15 questions from a final exam on Angular. The questions cover topics like the defer attribute, comparison operators, variable scoping, strict mode, the DOM, adding events, event bubbling, timeouts vs intervals, JSON parsing, AJAX calls, coding style guidelines, and more. For each question, a concise answer is provided explaining the key concept or resolving the example code provided.
Understanding Framework Architecture using Eclipseanshunjain
Talk on Framework architectures given at SAP Labs India for Eclipse Day India 2011 - Code attached Here: https://sites.google.com/site/anshunjain/eclipse-presentations
This document provides an overview of object-oriented concepts in JavaScript. It defines JavaScript and its components like ECMAScript, DOM, and BOM. It discusses how JavaScript supports object-oriented programming features like polymorphism and inheritance through prototypal inheritance despite not being a classical OOP language. The document also covers JavaScript data types, objects, scope, closures, context, and methods for changing contexts like call and apply.
This document discusses Express.js, a popular Node.js web application framework. It begins by explaining that Express makes developing websites, web apps, and APIs easier by providing route support and templating engine integration. It then demonstrates how to install Express and a templating engine like Jade. Several code examples are provided, including creating a simple REST API with routes, using Express to serve multiple pages with query parameters, and building a RESTful API for a resource like dogs. Resources for further learning about Express and Node.js are listed at the end.
This document provides an agenda and overview for a presentation on JavaScript. It discusses JavaScript's history and popularity, current implementations of JavaScript engines in browsers, and proliferation of JavaScript frameworks. The agenda outlines discussing objects, functions, scope, primitives, common mistakes, inheritance, best practices, modularity, and more. It also includes code examples demonstrating functions, closures, scope, operators, and error handling in JavaScript.
The document discusses threads, which allow for multiple paths of execution within an application. All user interface updates must occur on the main thread. While performing background tasks, one can use timers, performSelector methods, or manual NSThreads to ensure the main thread remains responsive for UI updates. JSON provides a simple format for communicating data between client and server applications on iPhone, and the SBJSON framework can be used to parse JSON strings into Objective-C objects.
Scala is a programming language created in 2001 that runs on the Java Virtual Machine. It aims to be scalable by combining object-oriented and functional programming features. Some key characteristics include its Java-like syntax that makes Java libraries and frameworks accessible, static typing for performance and documentation, and use of traits to decompose large classes and avoid fat objects. Functional programming is also supported through treating functions as first-class objects and avoiding side effects.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
JavaScript and popular programming paradigms (OOP, AOP, FP, DSL). Overview of the language to see what tools we can leverage to reduce complexity of our projects.
This part goes over language features and looks at OOP and AOP with JavaScript.
The presentation was delivered at ClubAJAX on 2/2/2010.
Blog post: http://lazutkin.com/blog/2010/feb/5/exciting-js-1/
Continued in Part II: http://www.slideshare.net/elazutkin/exciting-javascript-part-ii
javascript Event Handling and introduction to event.pptLalith86
This document provides an overview of event handling in JavaScript. It discusses how event handlers allow programs to capture and respond to events, making them event-driven. It describes two methods for handling events - inline JavaScript and defining functions in the head. Common event handlers like onClick, onMouseOver, onFocus, onBlur, onLoad and onUnload are presented along with examples. The document aims to help readers understand the concept and benefits of event handlers and write simple programs using them.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
Javascript allows interactive content on web pages and control of the browser and document. It is an interpreted scripting language that is cross-platform but support varies. Javascript can provide interactive content, control document appearance and content, and interact with the user through event handlers.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can react to events, read and write HTML elements, validate data, detect the visitor's browser, create cookies, and more. The DOM defines a standard for accessing and manipulating HTML documents. JavaScript uses objects, functions, and prototypes for object-oriented programming. Key concepts include encapsulation, inheritance, and abstraction. Events follow the capturing and bubbling phases. JavaScript supports conditionals, loops, functions, scopes, closures, and more.
This document provides an overview of event handling in web development using JavaScript. It discusses what functions and event handlers are, and how they can be defined and used to handle user interactions on a webpage. Specifically, it explains how event handlers allow capturing events like mouse clicks or focus changes and executing JavaScript code in response. It provides examples of common event handlers like onClick, onMouseOver, onLoad, and onUnload, and how they can be used both inline in HTML tags or by calling JavaScript functions. The goal is to help readers understand how to use event handlers to make their webpages interactive.
This document discusses predefined and user-defined functions in JavaScript. It explains that functions allow code to be reused by passing control between the call and definition. Both built-in functions like alert() and user-defined functions can be created. User-defined functions are defined with the function keyword and name, may accept parameters, and control returns to the call site after execution. Functions encapsulate reusable blocks of code.
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Ivano Malavolta
The document discusses conducting experiments on the software architecture of robotic systems. It describes three experiments:
1) Identifying and evaluating "green" architectural tactics for energy-efficient robotics software by mining the ROS ecosystem.
2) Empirically exploring the performance and energy trade-offs of computation offloading for ground robots communicating over WiFi.
3) Analyzing how different 2D SLAM algorithms impact resource utilization in ROS-based systems, including metrics like energy consumption, CPU usage, memory usage, and map quality.
The slides of a short presentation I gave about my experience about working in the context of EU grants. It contains tips and tricks for the before/during/after phases of a EU project.
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)Ivano Malavolta
The Green Lab allows students to measure real software products for industry-driven experiments focusing on energy efficiency, performance, and other areas. It provides infrastructure for experimenting on software, including a master course, platform, and collaboration platform. The lab contains a green computing cluster managed by Proxmox virtualization software, which hosts various virtual machines for running experiments. Hardware in the cluster includes servers, workstations, and a smartphone test farm for controlling Android devices remotely. Students use tools like Android Runner and wattsup meters to automate experiments measuring aspects like energy consumption of mobile apps. The Green Lab also serves as a learning environment where students conduct experiments for class projects and contribute to open source tools like Android Runner.
This document discusses software sustainability from Ivano Malavolta, an assistant professor. It discusses how ICT is unsustainable due to the large amounts of energy consumed by platforms like YouTube. It also discusses research on improving the energy efficiency of software, including a case study on the KPMG software platform. Additionally, it discusses experiments on the energy impact of progressive web apps and service workers. Finally, it proposes using design decision maps to help frame sustainability concerns when planning software projects.
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Ivano Malavolta
Slides of my presentation at the NIER track of the 41th International Conference on Software Engineering (ICSE 2019).
The paper is available here: http://www.ivanomalavolta.com/files/papers/ICSE_2019_NAPPA.pdf
How Maintainability Issues of Android Apps Evolve [ICSME 2018]Ivano Malavolta
Slides of my presentation at the Research track of the 34th International Conference on Software Maintenance and Evolution (ICSME 2018).
The full paper is available here: http://www.ivanomalavolta.com/files/papers/ICSME_2018.pdf
Collaborative Model-Driven Software Engineering: a Classification Framework a...Ivano Malavolta
Slides of my presentation at the Journal first track of the 40th International Conference on Software Engineering (ICSE 2018).
The accompanying extended abstract is available here: http://www.ivanomalavolta.com/files/papers/ICSE_2018_JournalFirst.pdf
The original TSE paper is available here: http://www.ivanomalavolta.com/files/papers/TSE_2017.pdf
This presentation is about a lecture I gave within the "Software Design" course of the Computer Science bachelor program, of the Vrije Universiteit Amsterdam.
http://www.ivanomalavolta.com
Modeling behaviour via UML state machines [Software Design] [Computer Science...Ivano Malavolta
This document provides an introduction to modeling behavior using UML state machines. It discusses key concepts like states, transitions, events, and state types. States represent when an object is active and can execute activities. Transitions change the object's state in response to events and can include actions. Event types include signals, operation calls, time-based and change events. The document also covers state machine notation including initial/final states, decisions nodes, parallel/orthogonal states, history states, and entry/exit points. An example state machine is provided and questions are asked to help understand state machine execution order and values.
This presentation is about a lecture I gave within the "Software Design" course of the Computer Science bachelor program, of the Vrije Universiteit Amsterdam.
http://www.ivanomalavolta.com
This presentation is about a lecture I gave within the "Software Design" course of the Computer Science bachelor program, of the Vrije Universiteit Amsterdam.
http://www.ivanomalavolta.com
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Ivano Malavolta
This presentation is about a lecture I gave within the "Software Design" course of the Computer Science bachelor program, of the Vrije Universiteit Amsterdam.
http://www.ivanomalavolta.com
Modeling and abstraction, software development process [Software Design] [Com...Ivano Malavolta
This presentation is about a lecture I gave within the "Software Design" course of the Computer Science bachelor program, of the Vrije Universiteit Amsterdam.
http://www.ivanomalavolta.com
This presentation is about a lecture I gave within the "Software systems and services" immigration course at the Gran Sasso Science Institute, L'Aquila (Italy): http://cs.gssi.infn.it/.
http://www.ivanomalavolta.com
[2017/2018] AADL - Architecture Analysis and Design LanguageIvano Malavolta
This presentation is about a lecture I gave within the "Software systems and services" immigration course at the Gran Sasso Science Institute, L'Aquila (Italy): http://cs.gssi.infn.it/.
http://www.ivanomalavolta.com
This presentation is about a lecture I gave within the "Software systems and services" immigration course at the Gran Sasso Science Institute, L'Aquila (Italy): http://cs.gssi.infn.it/.
http://www.ivanomalavolta.com
[2017/2018] Introduction to Software ArchitectureIvano Malavolta
This document provides an introduction to software architecture concepts. It defines software architecture as the selection of structural elements and their interactions within a system. Common architectural styles are described, including Model-View-Controller (MVC), publish-subscribe, layered, shared data, peer-to-peer, and pipes and filters. Tactics are introduced as design decisions that refine styles to control quality attributes. The document emphasizes that architectural styles solve recurring problems and promote desired qualities like performance, security, and maintainability.
This presentation is about a lecture I gave within the "Software systems and services" immigration course at the Gran Sasso Science Institute, L'Aquila (Italy): http://cs.gssi.it/.
http://www.ivanomalavolta.com
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc
Six months into 2024, and it is clear the privacy ecosystem takes no days off!! Regulators continue to implement and enforce new regulations, businesses strive to meet requirements, and technology advances like AI have privacy professionals scratching their heads about managing risk.
What can we learn about the first six months of data privacy trends and events in 2024? How should this inform your privacy program management for the rest of the year?
Join TrustArc, Goodwin, and Snyk privacy experts as they discuss the changes we’ve seen in the first half of 2024 and gain insight into the concrete, actionable steps you can take to up-level your privacy program in the second half of the year.
This webinar will review:
- Key changes to privacy regulations in 2024
- Key themes in privacy and data governance in 2024
- How to maximize your privacy program in the second half of 2024
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Chris Swan
Have you noticed the OpenSSF Scorecard badges on the official Dart and Flutter repos? It's Google's way of showing that they care about security. Practices such as pinning dependencies, branch protection, required reviews, continuous integration tests etc. are measured to provide a score and accompanying badge.
You can do the same for your projects, and this presentation will show you how, with an emphasis on the unique challenges that come up when working with Dart and Flutter.
The session will provide a walkthrough of the steps involved in securing a first repository, and then what it takes to repeat that process across an organization with multiple repos. It will also look at the ongoing maintenance involved once scorecards have been implemented, and how aspects of that maintenance can be better automated to minimize toil.
How Social Media Hackers Help You to See Your Wife's Message.pdfHackersList
In the modern digital era, social media platforms have become integral to our daily lives. These platforms, including Facebook, Instagram, WhatsApp, and Snapchat, offer countless ways to connect, share, and communicate.
Choose our Linux Web Hosting for a seamless and successful online presencerajancomputerfbd
Our Linux Web Hosting plans offer unbeatable performance, security, and scalability, ensuring your website runs smoothly and efficiently.
Visit- https://onliveserver.com/linux-web-hosting/
Sustainability requires ingenuity and stewardship. Did you know Pigging Solutions pigging systems help you achieve your sustainable manufacturing goals AND provide rapid return on investment.
How? Our systems recover over 99% of product in transfer piping. Recovering trapped product from transfer lines that would otherwise become flush-waste, means you can increase batch yields and eliminate flush waste. From raw materials to finished product, if you can pump it, we can pig it.
Mitigating the Impact of State Management in Cloud Stream Processing SystemsScyllaDB
Stream processing is a crucial component of modern data infrastructure, but constructing an efficient and scalable stream processing system can be challenging. Decoupling compute and storage architecture has emerged as an effective solution to these challenges, but it can introduce high latency issues, especially when dealing with complex continuous queries that necessitate managing extra-large internal states.
In this talk, we focus on addressing the high latency issues associated with S3 storage in stream processing systems that employ a decoupled compute and storage architecture. We delve into the root causes of latency in this context and explore various techniques to minimize the impact of S3 latency on stream processing performance. Our proposed approach is to implement a tiered storage mechanism that leverages a blend of high-performance and low-cost storage tiers to reduce data movement between the compute and storage layers while maintaining efficient processing.
Throughout the talk, we will present experimental results that demonstrate the effectiveness of our approach in mitigating the impact of S3 latency on stream processing. By the end of the talk, attendees will have gained insights into how to optimize their stream processing systems for reduced latency and improved cost-efficiency.
How RPA Help in the Transportation and Logistics Industry.pptxSynapseIndia
Revolutionize your transportation processes with our cutting-edge RPA software. Automate repetitive tasks, reduce costs, and enhance efficiency in the logistics sector with our advanced solutions.
YOUR RELIABLE WEB DESIGN & DEVELOPMENT TEAM — FOR LASTING SUCCESS
WPRiders is a web development company specialized in WordPress and WooCommerce websites and plugins for customers around the world. The company is headquartered in Bucharest, Romania, but our team members are located all over the world. Our customers are primarily from the US and Western Europe, but we have clients from Australia, Canada and other areas as well.
Some facts about WPRiders and why we are one of the best firms around:
More than 700 five-star reviews! You can check them here.
1500 WordPress projects delivered.
We respond 80% faster than other firms! Data provided by Freshdesk.
We’ve been in business since 2015.
We are located in 7 countries and have 22 team members.
With so many projects delivered, our team knows what works and what doesn’t when it comes to WordPress and WooCommerce.
Our team members are:
- highly experienced developers (employees & contractors with 5 -10+ years of experience),
- great designers with an eye for UX/UI with 10+ years of experience
- project managers with development background who speak both tech and non-tech
- QA specialists
- Conversion Rate Optimisation - CRO experts
They are all working together to provide you with the best possible service. We are passionate about WordPress, and we love creating custom solutions that help our clients achieve their goals.
At WPRiders, we are committed to building long-term relationships with our clients. We believe in accountability, in doing the right thing, as well as in transparency and open communication. You can read more about WPRiders on the About us page.
Are you interested in dipping your toes in the cloud native observability waters, but as an engineer you are not sure where to get started with tracing problems through your microservices and application landscapes on Kubernetes? Then this is the session for you, where we take you on your first steps in an active open-source project that offers a buffet of languages, challenges, and opportunities for getting started with telemetry data.
The project is called openTelemetry, but before diving into the specifics, we’ll start with de-mystifying key concepts and terms such as observability, telemetry, instrumentation, cardinality, percentile to lay a foundation. After understanding the nuts and bolts of observability and distributed traces, we’ll explore the openTelemetry community; its Special Interest Groups (SIGs), repositories, and how to become not only an end-user, but possibly a contributor.We will wrap up with an overview of the components in this project, such as the Collector, the OpenTelemetry protocol (OTLP), its APIs, and its SDKs.
Attendees will leave with an understanding of key observability concepts, become grounded in distributed tracing terminology, be aware of the components of openTelemetry, and know how to take their first steps to an open-source contribution!
Key Takeaways: Open source, vendor neutral instrumentation is an exciting new reality as the industry standardizes on openTelemetry for observability. OpenTelemetry is on a mission to enable effective observability by making high-quality, portable telemetry ubiquitous. The world of observability and monitoring today has a steep learning curve and in order to achieve ubiquity, the project would benefit from growing our contributor community.
Kief Morris rethinks the infrastructure code delivery lifecycle, advocating for a shift towards composable infrastructure systems. We should shift to designing around deployable components rather than code modules, use more useful levels of abstraction, and drive design and deployment from applications rather than bottom-up, monolithic architecture and delivery.
Transcript: Details of description part II: Describing images in practice - T...BookNet Canada
This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator.
Link to presentation recording and slides: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/
Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.
3. JavaScript
JavaScript is THE scripting language
Born in 1995, it is now of the most famous programming
languages
Heavily used by all major players in web and mobile development
….and remember this…
JavaScript HAS NOTHING TO DO WITH Java!!
4. Essentials
JavaScript is programming code that can be inserted into
HTML pages
à can react to events in the DOM
à can modify the DOM
Interpreted language
à see the eval() function
The HTML5 standard is adding new APIs to JavaScript
Can you list some of them?
5. Essentials
We can use the <script> tag to insert Javascript code into our
web app
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
If you want to execute code when you need it, you have to
create a function
The code in myScript is
executed immediately
We will use a module loader
to load JS
6. Expressions
An expression is any valid unit of code that resolves to a value
Four types of expressions:
• arithmetic: evaluates to a number
• string: evaluates to a sequence of chars
• logical: evaluates to true or false
• object: evaluates to an object
Yes, JavaScript is object-
oriented
7. Statements
A JS program is composed of a set of statements, which can be:
• Conditional
– if
– switch
• Loop
– for
– while, do-while
– break, continue
– for..in, forEach
• Exception handling
– throw
– try, catch
– finally
I assume you all
know these
8. Operators on expressions
Operators perform some action on expressions and may
produce other expressions as output
Five main types of operators:
• assignment
– x = x + y; x*= 3; x %= y, x = x & y
• comparison (always return a logical value)
– x == 3; x != 5; x === y; 5 > 3
• arithmetic (always return a numerical value)
• logical
– && (AND), || (OR), ! (NOT)
• String
– + (string concatenation)
Let’s discuss && and ||
9. Special operators (1)
JavaScript provides the following special operators:
• Conditional operator
condition
?
val1
:
val2
• Comma operator
– evaluates both of its operands and returns the value of the second
operand
• delete
– deletes an object, a property or an array element
delete
window.obj
• in
– checks if a property exists in an object
var
mycar
=
{make:"Opel",
model:"Tigra",
year:1999};
"make"
in
mycar;
//
returns
true
10. Special operators (2)
• instanceof
– similar to the instanceOf method in Java
myObj instanceof Object; //returns true
• new
– creates an instance of an object
var myself = new Person("Ivano Malavolta");
• this
– refers to the current object
this.name;
this[‘name’];
• typeof
– returns the type of an expression
typeof myself.name; // returns string
11. Variables (1)
Variables are declared by using the keyword var
var magicNumber = 42;
var user = App.getCurrentUser();
var loggedUser = (user.isLogged()) ? user.name : undefined
If a variable has no value yet it evaluates to undefined
If a variable has not been defined an exception will be threw:
Uncaught ReferenceError: c is not defined
Global variable: when it is declared OUTSIDE any function
à available to any other code within the app
Local variable: when it is declared INSIDE a function
12. Variables (2)
The scope of Javascript statements is based on functions (not blocks)
If you declare a variable without the var keyword, you are creating a
global variable (!)
In the browser global variables can be accessed by window.varName
this works
14. Constants and Literals
• Array
– var bands = ["NIN", "Kraftwerk", "Rammstein"];
• Boolean
– var logged= true; // false
• Integer and Floating point
– var age = 12;
– var PI = 3.14;
• String
– var hello = ‘hello’;
• Objects
– var band = {name: "NIN", founder: {name: "Trent", surname: "Reznor"}};
– band.name; // NIN
– band.founder["surname"]; // Reznor
15. Function declarations
A function declaration is composed of:
• name
• parameters
• body
Primitive parameters are passed by value
Objects are passed by reference
A function is actually an expression:
This is an example of anonymous function
16. Function Calls
Functions can be called by referring to their name and passing its
parameters
A function can produce a result by means of the return statement
Since function declarations are expressions, a function can be declared
and executed all at once
17. Functional Programming
Functions can be passed as arguments to other functions, or can be
produced as output of another function
function
map(f,a)
{
var
result
=
[],
i;
for(i=0;
i
!=a.length;
i++)
{
result[i]
=
f(a[i]);
}
return
result;
}
map(function(x)
{
return
x*x*x;
},
[0,1,2,5,10]);
result?
18. Closures
A closure is a special kind of object consisting of:
• A function
• The function’s environment
– any local variables that were in-scope at the time that the closure was
created
http://goo.gl/Ya0be
22. JavaScript event loop
Confusion about JavaScript’s asynchronous event model is quite common
Confusion leads to bugs, bugs lead to anger, and Yoda taught us the rest....
http://goo.gl/g3xvY
23. First exploration
Let’s see this piece of code
http://goo.gl/g3xvY
for
(var
i
=
1;
i
<=
3;
i++)
{
setTimeout(function(){
console.log(i);
},
0);
};
Later we will see why
the result is like this
What if a rare event happened
between these two lines of code?
24. Second exploration
Let’s see this piece of code
http://goo.gl/g3xvY
var
start
=
new
Date;
setTimeout(function(){
var
end
=
new
Date;
console.log('Time
elapsed:',
end
-‐
start,
'ms');
},
500);
while
(new
Date
-‐
start
<
1000)
{};
Hint
The setTimeout callback can’t fire until the
while loop has finished running.
25. JavaScript concurrency model
JavaScript has a concurrency model based on an event loop
Intuitively, you can consider as if your code is running from a loop like
this:
runYourScript();
while
(atLeastOneEventIsQueued)
{
fireNextQueuedEvent();
};
The two previous examples make sense now?
27. Stack
Function calls form a stack of frames
Each time a function f is called,
1. a frame f is created with its arguments and local variables
2. the frame f is pushed on top of the stack
3. all the instructions of the function f
are executed
4. when the function f returns, its frame is popped out
The JavaScript engine executes all the frames until the stack is empty
http://goo.gl/0zgXC
28. Heap
The heap stores all the objects created during the execution of
JavaScript functions
The heap is just a name to denote a large mostly unstructured region of
memory
http://goo.gl/0zgXC
29. Queue
The queue contains a list of messages to be processed
Each message has an associated function callback
When the stack is empty:
1. the first message of the queue is taken out
2. its function callback is processed
– basically, a new stack frame is created for callback and it is processed
The message processing ends when the stack becomes empty
http://goo.gl/0zgXC
30. Important remarks about the queue
Each message is processed completely before any other message is
considered
à when a function is running, it cannot be interrupted in any way
à it will always run until full completion
à it can modify data without race conditions
However, if a function takes too long, then it “stops” the app
Solutions:
• make message processing short
• split one message into several messages
• use web workers for multi-threading
http://goo.gl/0zgXC
31. Adding messages to the queue
In web browsers, a message is added when:
• an event occurs
• there is an event listener attached to the event
If an event occurs (eg a touch event), and there is no listener
à the event is lost
Examples of async functions generating messages in the queue:
• DOM interaction (touch, swipe, click…)
• timing functions (setTimeout, setInterval)
• I/O functions (read files, etc.)
• Ajax requests
http://goo.gl/0zgXC
33. Ajax
Ajax lets us fire requests from the browser to the server without
page reload
à you can update a part of the page while the user continues on
working
Basically, you can use Ajax requests to:
• load remote HTML
• get JSON data
34. Load JSON data
JSON is a lightweight alternative to XML, where data is
structured as plain JavaScript objects
36. The Ajax() call
All of jQuery’s Ajax functions are simply wrappers around the
$.ajax() method
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
error: callbackError
});
This is equivalent to
$.getJSON(url, callback);
37. Callback Functions
A callback is a function that
1. is passed as an argument to another function
2. is executed after its parent function has completed
– when an effect has been completed
– when an AJAX call has returned some data
$.get('myhtmlpage.html', myCallBack);
function myCallBack(data) {
// do something with data
}
myCallBack is invoked when the '$.get' is done getting the page
38. A note on nested callbacks
Nested callbacks tempt us to add more features by adding more
code, rather than implementing those features in manageable,
reusable pieces
39. Avoid more than two levels of function nesting
Store async results outside of the function making the async call
so that the callback doesn’t have to be nested
passwordHash has a
broader scope here
40. Promises
A promise is an object that represents a task with:
1. two possible outcomes (success or failure)
2. callbacks that fire when one outcome or the other has occurred
//
with
callbacks
$.get('/mydata',
{
success:
onSuccess,
failure:
onFailure,
always:
onAlways
});
//
with
promises
var
promise
=
$.get('/mydata');
promise.done(onSuccess);
promise.fail(onFailure);
promise.always(onAlways);
Where is the difference?
41. Why promises?
If your Ajax request has multiple effects (animation, other Ajax
requests, updating the DOM, etc.), you do not have to mix them with
the part of your app making the request
You can attach multiple callbacks to the same request
For example, you may have a single callback for showing a spinner shared across your app
You can derive new promises from existing ones
Encapsulation
Stacking
Promise derivation
42. Promise derivation
JQuery’s when method allows you to combine multiple promises
when acts as a logical AND for promise resolution and generates a
new promise that:
• is resolved as soon as all of the given Promises are resolved
• or it is rejected as soon as any one of the given Promises is rejected
var
serverData
=
{};
var
getting1
=
$.get('/1')
.done(function(result)
{serverData['1']
=
result;});
var
getting2
=
$.get('/2')
.done(function(result)
{serverData['2']
=
result;});
$.when(getting1,
getting2)
.done(function()
{
//
the
GET
information
is
now
in
serverData...
});
44. The DOM
DOM = Document Object Model
Every web page have a hierarchical structure in which every
element is contained into another: its parent.
Text elements are particular since they never have children
45. The DOM
In Javascript the document global variable stores a reference to
the object corresponding to the <html> tag
Every node of the DOM can be navigated:
document.body.parentNode
document.body.childNodes
document.body.firstChild
document.body.lastChild
document.body.nextSibling
document.body.previousSibling
46. Accessing the DOM
nodeName to get the name of the tag of a node:
document.body.firstChild.nodeName;!
!
nodeValue to get the text of a text node:
document.body.firstChild.firstChild.nodeValue;!
!
innerHTML to get/set the content of a node:
document.body.firstChild.innerHTML = "<div>Hello</div>";!
!
getElementById to get a node by its ID:
document.getElementById("title");!
!
getElementsByTagName to get a node by its type:
document.getElementsByTagName("DIV");!
!
getElementsbyClassName to get a node by its class:
document.getElementsByClassName("listElement");!
!
47. Modifying the DOM
createElement to create a new node:
var myDiv = document.createElement("A");!
!
createTextNode to create a new text node:
document.createTextNode("Hello!");!
!
appendChild to put new nodes into the DOM:
document.body.appendChild(myDiv);!
!
setAttribute to set an attribute of a node:
document.setAttribute("href", "http://www.google.it");!
48. Events
Every time the user interacts with the DOM, a set of events is
triggered in our JS application
We can listen to these events by means of registered
eventHandlers
An eventHandler is a function automatically called by the browser,
where data about the triggered event is available as a parameter
Event handlers can be unregistered
50. Event Bubbling & capturing
When an event is triggered in the DOM,
it can be:
• captured by all the elements
containing the target element
à event capturing
• captured first by the target
and then BUBBLE up through all
the HTML elements containing
the target à event bubbling
51. Event default behaviour
Each element in the DOM has a default behaviour
ex. if you tap on an <a> element, it will make the browser to point to
another location
event.preventDefault();
Cancels the event if it is cancelable, without stopping further
propagation of the event
Usually, this is the last instruction of an event handler
52. Touch events
Touch events are triggered when the user touches the display
The event can describe one or more points of contact
Touches are represented by the Touch object
each touch is described by a position, size and shape, amount of
pressure, and target element.
Lists of touches are represented by TouchList objects
53. Touch events
Main attributes of a touch event:
• TouchEvent.touches
– a TouchList of Touches
• TouchEvent.type
– the type of touch
• TouchEvent.target
– the element in the DOM
• TouchEvent.changedTouches
– a TouchList of all the Touches changed between this event and the
previous one
touchstart
touchend
touchmove
touchenter
touchcancel
54. The Touch and TouchList objects
relative to the
viewport
relative to the
whole display
56. JavaScript objects
An object in JS can be seen as a map of key/value pairs
• key: a JavaScript string
• value: any JavaScript value
Everything in JavaScript is an object, and basically all its operations
involve hash table lookups (which are very fast in our browsers!)
57. Object creation
In JavaScript an object can be created in two ways:
new-value creation
object literal syntax
var
obj
=
new
Object();
obj.name
=
"Ivano";
...
var
obj
=
{
name:
"Ivano",
surname:
"Malavolta",
details:
{
sex:
"male",
address:
”via..."
}
}
These are semantically
equivalent
58. Object properties
In JavaScript an object property can be created in two ways:
dot notation
array-like notation
obj.name
=
“Ivano”;
var
name
=
obj.name;
obj["name"]
=
”Ivano";
var
name
=
obj["name"];
These are semantically equivalent too
In the array-like notation, the property is a string
à it can be computed dynamically
59. Object Orientation (1): the model
JavaScript object model is prototype-based, rather than class-based
No notion of class, everything is an object
An object can be seen as a «template» for other objects, in this case it is
the prototype of the other objects
à it defines an initial set of properties
The inheriting objects can specify their own properties
60. Object Orientation (2): class definitions
In Java I can specify a Class. It can have special methods, Constructors,
which I execute in order to create instances of my class.
In JavaScript I directly define Constructor functions that I call to create
my object by means of the new keyword.
61. The new and this keywords
new is strongly related to 'this'.
It creates a brand new empty object, and then calls the function
specified, with 'this' set to that new object.
The function specified with 'this' does not return a value but
merely modifies the this object. It's new that returns the this
object to the calling site.
Functions that are designed to be called by 'new' are called
constructor functions. Common practise is to capitalise these
functions as a reminder to call them with new.
http://goo.gl/jBTMWX
62. Object Orientation (3): inheritance
In Java I can define a hierarchy of classes by defining subclasses via the
extends keyword
In JavaScript I can define a constructor function X, then I can say that X
acts as the prototype of constructor function Y
à X is a supertype of Y
63. Object Orientation (4): methods
In Java I can specify define methods within my class and call them by
referring to specific instances.
In JavaScript I can define properties which can be functions, then I can
call them directly on the object being used
66. Web Workers
Javascript is a single-threaded language
à If a tasks take a lot of time, users have to wait
Web Workers provide background processing capabilities to web
applications
They typically run on separate threads
à apps can take advantage of multicore CPUs
67. Web Workers
Web Workers can be used to:
• prefetch data from the Web
• perform other ahead-of-time operations to provide a much
more lively UI.
Web Workers are precious on mobile applications because they
usually need to load data over a potentially slow network
68. Web Workers
Any JS file can be launched as a worker
Example of Web Worker declaration:
var worker = new Worker(“worker.js”);
In order to be independent from other workers, each worker
script cannot access:
– the DOM
– the global window object
• (each web worker has its own self global object)
69. Web Workers concurrency model
A web worker has its own
• stack,
• heap
• message queue
Two distinct runtimes can only communicate through sending
messages via the postMessage method
This method adds a message to the other runtime if the latter
listens to message events.
70. Web Workers
The main JS script can communicate with workers via
postMessage() calls:
$(‘#button’).click(function(event) {
$(‘#output’).html(“starting”);
worker.postMessage(“start”);
});
worker.onmessage = function(event) {
$(‘#output’).html(event.data);
}
71. Web Workers
The web worker script can post back messages to the main script:
onmessage = function(event) {
if(event.data === “start”) {
var result;
// do something with result
postMessage(result);
}
}
73. Zepto
The only relevant downside of jQuery is about
PERFORMANCE
However,
1. it is not very noticeable in current class-A mobile devices
2. You can use mobile-suited alternatives to jQuery:
74. Zepto
The goal is to have a ~5-10k modular library that executes fast,
with a familiar API (jQuery)
It can be seen as a
mini-jQuery
without support for
older browsers
77. Underscore.js
A utility library for JavaScript that provides support for the usual
functional suspects (each, map, reduce, filter...)
It provides low-level utilities in the following categories:
• Collections
• Arrays
• Objects
• Functions
• Utilities
http://documentcloud.github.com/underscore/
80. Ratchet
It provides the basic building blocks for realizing well-known
mobile design patterns
Examples:
• Nav bars
• Title bars
• Lists
• Toggles
• Cards
• Popovers
• Sliders
• …
http://goratchet.com
86. Frameworks
jQueryMobile, jQuery, Backbone, etc. are beautiful tools…
However they may impact the performance of your app
à Use a framework only when it is necessary
– Don’t use jQuery only because of the $(selector) syntax!
Solution
• build your own micro-framework
• cut out Cordova plugins you do not use
• use micro-frameworks (http://microjs.com)
87. A final note
JavaScript allows you to do the same thing in many ways
In order to make your code readable (and thus maintainable), you
have to:
• follow as mush as possible known design patterns
– singleton, factory, etc.
• follow conventions
– https://github.com/rwaldron/idiomatic.js/