This presentation explains few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with the code snippet.
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It summarizes over 40 functions, including classes() to get class names, isclass() to check if a class exists, packageclasses() to get classes in a package, addattribute() to add attributes to an object, and getattribute()/setattrbute() to get/set attribute values. Examples are given for each function.
The document discusses different data structures for representing queues and linked lists, including their implementations and operations. Queues follow FIFO ordering and can be implemented using arrays or linked lists. Linked lists allow efficient insertion/removal at both ends and can be used to implement double-ended queues (deques). Deques support efficient insertion/removal from both ends and can implement stacks and queues. Sequences generalize vectors and linked lists, introducing the concept of positions to provide implementation independence.
The document discusses functional programming concepts in Scala including creating immutable objects to represent rational numbers, using pattern matching to add rationals, and defining classes with private fields and auxiliary constructors while avoiding side effects through immutable and functional design. It provides examples of functional programming techniques like creating rational number objects that are immutable and can be freely passed around without risk of mutation, and defining methods as functions that take arguments instead of mutating object state.
This document compares the functional programming languages Haskell and Scala. It outlines their similarities such as being high-level, statically typed, and supporting functions as first-class values. It describes some of their conceptual differences like Haskell emphasizing purity and lazy evaluation while Scala allows side effects. It then provides examples to illustrate extra features of each language, such as Haskell's pointfree style and compiler extensions, and Scala's support for object-oriented and imperative programming. Finally, it discusses some practical considerations for using each language.
Refinement types are an approach for expressing more detailed properties of data types using propositional logic predicates. Liquid Haskell is a static refinement type checker capable of veryfing refinement type safety. We will examine the possibilites this approach opens for increasing development productivity.
The document discusses templates in C++. It explains that templates allow functions and classes to work with different data types using a single code definition. Template functions are called function templates, and template classes are called class templates. The document provides examples of defining class and function templates, and overloading template functions. It demonstrates how templates can be used to create generic functions that operate on multiple types of data.
The Ring programming language version 1.5.4 book - Part 33 of 185Mahmoud Samir Fayed
The document describes various functions in Ring for working with classes and objects. Some key functions covered include ispackageclass() to check if a class is in a package, classname() to get an object's class name, objectid() to get an object's ID, isobject() to check if a variable is an object, attributes() and methods() to get an object's attributes and methods, and addattribute() and addmethod() to add attributes and methods to objects.
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
The document provides documentation on Ring programming language functions for working with classes, objects, attributes and methods. It summarizes over 40 functions, including classes() to get class names, isclass() to check if a class exists, packageclasses() to get classes in a package, addattribute() to add attributes to an object, and getattribute()/setattrbute() to get/set attribute values. Examples are given for each function.
The document discusses different data structures for representing queues and linked lists, including their implementations and operations. Queues follow FIFO ordering and can be implemented using arrays or linked lists. Linked lists allow efficient insertion/removal at both ends and can be used to implement double-ended queues (deques). Deques support efficient insertion/removal from both ends and can implement stacks and queues. Sequences generalize vectors and linked lists, introducing the concept of positions to provide implementation independence.
The document discusses functional programming concepts in Scala including creating immutable objects to represent rational numbers, using pattern matching to add rationals, and defining classes with private fields and auxiliary constructors while avoiding side effects through immutable and functional design. It provides examples of functional programming techniques like creating rational number objects that are immutable and can be freely passed around without risk of mutation, and defining methods as functions that take arguments instead of mutating object state.
This document compares the functional programming languages Haskell and Scala. It outlines their similarities such as being high-level, statically typed, and supporting functions as first-class values. It describes some of their conceptual differences like Haskell emphasizing purity and lazy evaluation while Scala allows side effects. It then provides examples to illustrate extra features of each language, such as Haskell's pointfree style and compiler extensions, and Scala's support for object-oriented and imperative programming. Finally, it discusses some practical considerations for using each language.
Refinement types are an approach for expressing more detailed properties of data types using propositional logic predicates. Liquid Haskell is a static refinement type checker capable of veryfing refinement type safety. We will examine the possibilites this approach opens for increasing development productivity.
The document discusses templates in C++. It explains that templates allow functions and classes to work with different data types using a single code definition. Template functions are called function templates, and template classes are called class templates. The document provides examples of defining class and function templates, and overloading template functions. It demonstrates how templates can be used to create generic functions that operate on multiple types of data.
The Ring programming language version 1.5.4 book - Part 33 of 185Mahmoud Samir Fayed
The document describes various functions in Ring for working with classes and objects. Some key functions covered include ispackageclass() to check if a class is in a package, classname() to get an object's class name, objectid() to get an object's ID, isobject() to check if a variable is an object, attributes() and methods() to get an object's attributes and methods, and addattribute() and addmethod() to add attributes and methods to objects.
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
Learn how to work with maps in Java, how to use the Map<K, V> interface and the API classes HashMap<K,V> and TreeMap<K, V>. Learn how to work with lambda expressions and how to use the Java stream API to process sequences of elements, how to filter, transform and order sequences.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-maps-lambda-and-stream-api/
This document discusses JavaScript objects and methods for manipulating strings and performing mathematical calculations. It introduces the Math object which allows common mathematical operations and contains constants like PI. It also covers the String object which allows manipulating and processing strings, including character-level methods, searching/extracting substrings, and generating XHTML tags. Methods like split(), indexOf(), toLowerCase() are described.
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
This document provides documentation on Ring programming language classes, functions, and objects. It includes sections on getting class and method names, checking types, accessing and modifying object attributes and methods, and sharing methods between classes without inheritance. Various functions are described like classes(), isclass(), attributes(), methods(), addattribute(), and setattribute(). Examples are provided to illustrate the usage of each function.
This document discusses abstract classes and interfaces in Python. It provides examples of using abstract methods and abstract classes to define common behavior for subclasses while allowing subclasses to provide their own specific implementations. Interfaces are defined as abstract classes that contain only abstract methods, allowing subclasses to fully implement the interface. Concrete methods can also be defined in abstract classes to provide shared behavior across subclasses.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
Functional objects are immutable objects that do not have mutable state. They allow functions to be passed as arguments and returned from other functions. The document introduces functional objects using the example of a Rational number class in Scala. It demonstrates how to define a Rational class with immutable fields and methods like addition, constructors, and equality checks.
Templates in C++ allow functions and classes to operate on different data types in a generic way. Function templates define generic functions that can work on different types, while class templates define generic classes. Templates promote code reuse by defining functions and classes independently of specific types. Function templates and class templates can be overloaded and classes can inherit from class templates.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
This document discusses stacks as an abstract data type (ADT) and their implementation in Java. It begins by defining an ADT as having a specific interface of operations and axioms defining the semantics of those operations. Stacks are introduced as a LIFO data structure that supports push, pop, and top operations. The document then discusses implementing a stack interface in Java using exceptions to handle errors. It provides an example array-based stack implementation in Java using an array and index to track elements. Finally, it discusses an application of stacks to efficiently compute the span of stock price changes over time by using a stack to track previous higher prices.
This document discusses collections and queries in Java, including associative arrays (maps), lambda expressions, and the stream API. It provides examples of using maps like HashMap, LinkedHashMap and TreeMap to store key-value pairs. Lambda expressions are introduced as anonymous functions. The stream API is shown processing collections through methods like filter, map, sorted and collect. Examples demonstrate common tasks like finding minimum/maximum values, summing elements, and sorting lists.
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
This document summarizes Ring programming language functions for working with classes and objects. It describes functions such as ispackageclass() that checks if a class is in a package, classname() that returns an object's class name, and attributes() that returns an object's attributes. Other functions covered include addattribute() for adding attributes, setattribute() for setting attributes, and methods() for getting an object's methods.
This document discusses arrays in Java. It begins with an introduction to arrays as fixed-length data structures that hold multiple elements of the same type. The document then covers declaring and creating arrays, initializing arrays, and examples of using arrays, including summing array elements, displaying arrays in histograms, and analyzing survey results by storing responses in an array. The document also discusses passing arrays to methods by reference, meaning any changes made to the array in the method also change the original array. It provides an example program that passes an array to a method that directly modifies the array elements, as well as passing an array element by value so the method only modifies a copy of the primitive value.
An array is a container that holds a fixed number of values of the same type. An array's length is determined when it is created and cannot be changed. The document then provides an example of creating an integer array called "scores" with 4 elements to store the scores of 4 cricket teams. It demonstrates accessing the elements of the array using indexes and printing the team scores.
Learn how to use lists in Java, how to use List<T> and ArrayList<T>, how to process lists of elements.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-lists
The document discusses stacks as an abstract data type (ADT) and their implementation in Java. It defines stacks as LIFO data structures that support push, pop, and peek operations. An array-based implementation of stacks in Java is presented using an array and index to track elements. Growable stacks are also discussed, comparing strategies to dynamically increase the array size. The document concludes by explaining how method calls in Java programs use a stack to enable recursion and error tracing.
This document provides information on arrays and functions in Java. It discusses how to declare, initialize, access elements of arrays including multi-dimensional arrays. It also covers passing arguments to functions by value and reference, copying arrays, sorting arrays, and anonymous arrays. Functions can modify arguments passed by reference like arrays but not primitive types or object references passed by value.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
Slick is a modern database query and access library for Scala that allows working with stored data like Scala collections while controlling database access. It provides easy, concise, scalable, and safe database access. Slick supports many databases and can be set up by adding dependencies to a build file. Queries are processed by compiling them to SQL and lifting query types for translation. Queries support filtering, dropping rows, deletion, and creation.
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
Learn how to work with maps in Java, how to use the Map<K, V> interface and the API classes HashMap<K,V> and TreeMap<K, V>. Learn how to work with lambda expressions and how to use the Java stream API to process sequences of elements, how to filter, transform and order sequences.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-maps-lambda-and-stream-api/
This document discusses JavaScript objects and methods for manipulating strings and performing mathematical calculations. It introduces the Math object which allows common mathematical operations and contains constants like PI. It also covers the String object which allows manipulating and processing strings, including character-level methods, searching/extracting substrings, and generating XHTML tags. Methods like split(), indexOf(), toLowerCase() are described.
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
This document provides documentation on Ring programming language classes, functions, and objects. It includes sections on getting class and method names, checking types, accessing and modifying object attributes and methods, and sharing methods between classes without inheritance. Various functions are described like classes(), isclass(), attributes(), methods(), addattribute(), and setattribute(). Examples are provided to illustrate the usage of each function.
This document discusses abstract classes and interfaces in Python. It provides examples of using abstract methods and abstract classes to define common behavior for subclasses while allowing subclasses to provide their own specific implementations. Interfaces are defined as abstract classes that contain only abstract methods, allowing subclasses to fully implement the interface. Concrete methods can also be defined in abstract classes to provide shared behavior across subclasses.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
Functional objects are immutable objects that do not have mutable state. They allow functions to be passed as arguments and returned from other functions. The document introduces functional objects using the example of a Rational number class in Scala. It demonstrates how to define a Rational class with immutable fields and methods like addition, constructors, and equality checks.
Templates in C++ allow functions and classes to operate on different data types in a generic way. Function templates define generic functions that can work on different types, while class templates define generic classes. Templates promote code reuse by defining functions and classes independently of specific types. Function templates and class templates can be overloaded and classes can inherit from class templates.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
This document discusses stacks as an abstract data type (ADT) and their implementation in Java. It begins by defining an ADT as having a specific interface of operations and axioms defining the semantics of those operations. Stacks are introduced as a LIFO data structure that supports push, pop, and top operations. The document then discusses implementing a stack interface in Java using exceptions to handle errors. It provides an example array-based stack implementation in Java using an array and index to track elements. Finally, it discusses an application of stacks to efficiently compute the span of stock price changes over time by using a stack to track previous higher prices.
This document discusses collections and queries in Java, including associative arrays (maps), lambda expressions, and the stream API. It provides examples of using maps like HashMap, LinkedHashMap and TreeMap to store key-value pairs. Lambda expressions are introduced as anonymous functions. The stream API is shown processing collections through methods like filter, map, sorted and collect. Examples demonstrate common tasks like finding minimum/maximum values, summing elements, and sorting lists.
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
This document summarizes Ring programming language functions for working with classes and objects. It describes functions such as ispackageclass() that checks if a class is in a package, classname() that returns an object's class name, and attributes() that returns an object's attributes. Other functions covered include addattribute() for adding attributes, setattribute() for setting attributes, and methods() for getting an object's methods.
This document discusses arrays in Java. It begins with an introduction to arrays as fixed-length data structures that hold multiple elements of the same type. The document then covers declaring and creating arrays, initializing arrays, and examples of using arrays, including summing array elements, displaying arrays in histograms, and analyzing survey results by storing responses in an array. The document also discusses passing arrays to methods by reference, meaning any changes made to the array in the method also change the original array. It provides an example program that passes an array to a method that directly modifies the array elements, as well as passing an array element by value so the method only modifies a copy of the primitive value.
An array is a container that holds a fixed number of values of the same type. An array's length is determined when it is created and cannot be changed. The document then provides an example of creating an integer array called "scores" with 4 elements to store the scores of 4 cricket teams. It demonstrates accessing the elements of the array using indexes and printing the team scores.
Learn how to use lists in Java, how to use List<T> and ArrayList<T>, how to process lists of elements.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-lists
The document discusses stacks as an abstract data type (ADT) and their implementation in Java. It defines stacks as LIFO data structures that support push, pop, and peek operations. An array-based implementation of stacks in Java is presented using an array and index to track elements. Growable stacks are also discussed, comparing strategies to dynamically increase the array size. The document concludes by explaining how method calls in Java programs use a stack to enable recursion and error tracing.
This document provides information on arrays and functions in Java. It discusses how to declare, initialize, access elements of arrays including multi-dimensional arrays. It also covers passing arguments to functions by value and reference, copying arrays, sorting arrays, and anonymous arrays. Functions can modify arguments passed by reference like arrays but not primitive types or object references passed by value.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
Slick is a modern database query and access library for Scala that allows working with stored data like Scala collections while controlling database access. It provides easy, concise, scalable, and safe database access. Slick supports many databases and can be set up by adding dependencies to a build file. Queries are processed by compiling them to SQL and lifting query types for translation. Queries support filtering, dropping rows, deletion, and creation.
Evolution and Scaling of MongoDB Management Service Running on MongoDBMongoDB
"MongoDB isn't just software we release; it's software we rely on every day as part of the MongoDB Management Service (MMS). We use MongoDB to store monitoring data and backups for the databases of over 50,000 customers. Get the inside scoop on running an overwhelmingly write-heavy application as MMS engineers Steve Briskin and John Morales explain the tweaks and optimizations they use to get most out of every machine, including:
- RRD schema design to balance write throughput and read latency
- Warming indexes before inserts
- Backup snapshot storage design optimized for insert-only workloads
They will also discuss the process of migrating to 3.0 and how it has simplified their lives."
The document discusses different techniques for real-time communication between a client and server, including short polling, long polling, and websockets. It explains that websockets allow for full-duplex communication and are more efficient than polling techniques. The document then outlines how to use websockets with the Play! framework, including creating enumerators and iteratees on the server and connecting via websockets on the client. It provides a link to a Play! chat application sample that demonstrates using websockets.
This document provides an overview of Scala with MongoDB. It defines MongoDB as a document-oriented database and discusses why it is used, key terminology like documents and collections, and how to install and use MongoDB. It also explains operators in MongoDB and Scala driver libraries for MongoDB like Casbah and Salat. Casbah allows interacting with MongoDB from Scala, while Salat enables serialization between Scala case classes and MongoDB documents.
Scala with MongoDB
MongoDB is a document-oriented database management system designed for performance, horizontal scalability, high availability,open source NoSQL database(Schemaless or Non-relational) ,And advanced queryability. ➢ MongoDB is a document-based database system, and as a result, all records, or data, in MongoDB are documents.
Real time Analytics with Apache Kafka and Apache SparkRahul Jain
A presentation cum workshop on Real time Analytics with Apache Kafka and Apache Spark. Apache Kafka is a distributed publish-subscribe messaging while other side Spark Streaming brings Spark's language-integrated API to stream processing, allows to write streaming applications very quickly and easily. It supports both Java and Scala. In this workshop we are going to explore Apache Kafka, Zookeeper and Spark with a Web click streaming example using Spark Streaming. A clickstream is the recording of the parts of the screen a computer user clicks on while web browsing.
Scala for Java Developers provides an overview of Scala for Java developers. It discusses:
- The goals of understanding what Scala is, learning more about it, and installing Scala.
- An introduction to Scala including what it is, its history from 1995 to 2013, and whether it is a good fit for certain uses based on its strengths like functional programming and weaknesses like syntax.
- How to get started with Scala including required and optional software and plugins.
- Key Scala features like objects, classes, traits, pattern matching, and collections.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
The document discusses arrays and sparse matrices as data structures. It defines array and sparse matrix abstract data types, including methods for creating, accessing, and manipulating the structures. Examples are given of representing polynomials using arrays or as a sparse matrix to illustrate different implementations of these data structures.
Scala is a multi-paradigm programming language that supports functional, object-oriented and imperative programming paradigms. The document discusses Scala's support for types, expressions, objects, functions, and provides examples of using Scala for expressions, functions, control structures, patterns, spaces and actors.
In this presentation, You will get to know about Function Literal,Higher Order Function,Partial Function,Partial Applied Function,Nested Function,Closures.
The document discusses arrays and functions in C programming. It defines arrays as collections of similar data items stored under a common name. It describes one-dimensional and two-dimensional arrays, and how they are declared and initialized. It also discusses strings as arrays of characters. The document then defines functions as sets of instructions to perform tasks. It differentiates between user-defined and built-in functions, and describes the elements of functions including declaration, definition, and calling.
This document discusses first-class functions and lambda calculus. It begins with an overview of Alonzo Church and the origins of lambda calculus. It then covers first-class functions in JavaScript, functions as objects in Java, and first-class functions in Scala. The document also discusses generic higher-order functions and control abstraction.
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
The document discusses XML parsers and compares DOM and SAX parsers. DOM parsers build an in-memory tree representation of the XML document, allowing random access but using more memory. SAX parsers use callbacks to stream the XML events to the client, using less memory but providing event-based access. The document also provides an overview of the popular Xerces-J parser and gives an example of using DOM and SAX parsers to extract circle element information from an XML document.
Classes are blueprints for objects that define their fields and methods. Objects are instances of classes created using the new keyword. A class defines members like fields and methods, with fields holding an object's state and methods performing computations. A checksum is a small block of data derived from a larger block to detect errors. A checksum accumulator class tracks a running sum field to calculate checksums. Objects can access each other's private members if they are in the same file and one is the other's companion object.
The document provides an overview of Scala concepts for Java programmers, including object-oriented features, pattern matching, functional programming constructs like immutability and higher-order functions, actors and futures for concurrency, and implicits. Key concepts covered include case classes, lazy evaluation, parallel collections, currying, partial functions, and implicit parameters.
Intro to C# - part 2.pptx emerging technologyworldchannel
Arrays allow storing a collection of elements of the same type. Arrays can be one-dimensional or multi-dimensional. Functions provide reusable blocks of code that can be called from different parts of a program. Functions can accept parameters by value, reference, or output and can return values. Parameters can also be passed as arrays.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
The document discusses object-oriented programming concepts including encapsulation, inheritance, and polymorphism. It provides an example class called Point that demonstrates defining data members and member functions. It then provides a more detailed example of a Set class that implements common set operations like adding/removing elements and computing intersections/unions. The document also discusses constructors and destructors and how they are used to initialize and clean up class objects.
(How) can we benefit from adopting scala?Tomasz Wrobel
Scala offers benefits from adopting it such as increased productivity through concise and expressive code, static typing with type inference, support for both object-oriented and functional programming paradigms, and interoperability with Java. Switching from Java to Scala involves some changes like using val for immutable variables and var for mutable, but overall the syntax is quite similar which eases the transition.
1. An array is an object that stores a list of values of the same type and is made up of contiguous memory divided into slots indexed from 0 to N-1.
2. One-dimensional arrays use a single subscript to access elements, while two-dimensional and higher dimensional arrays use multiple subscripts to represent rows and columns.
3. Arrays are declared with the syntax Type[] name = new Type[size]; and elements can be accessed using name[index].
Pattern matching in Scala allows values to be matched against multiple cases like a switch statement. It can match primitives, strings, case classes, tuples, and types. For-expressions iterate over collections and can include generators to drive iteration, filters to control it, and definitions of local values. They yield a resulting collection rather than using loops.
Terratest - Automation testing of infrastructureKnoldus Inc.
TerraTest is a testing framework specifically designed for testing infrastructure code written with HashiCorp's Terraform. It helps validate that your Terraform configurations create the desired infrastructure, and it can be used for both unit testing and integration testing.
Getting Started with Apache Spark (Scala)Knoldus Inc.
In this session, we are going to cover Apache Spark, the architecture of Apache Spark, Data Lineage, Direct Acyclic Graph(DAG), and many more concepts. Apache Spark is a multi-language engine for executing data engineering, data science, and machine learning on single-node machines or clusters.
Secure practices with dot net services.pptxKnoldus Inc.
Securing .NET services is paramount for protecting applications and data. Employing encryption, strong authentication, and adherence to best coding practices ensures resilience against potential threats, enhancing overall cybersecurity posture.
Distributed Cache with dot microservicesKnoldus Inc.
A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm. Here we will look into implementation of Distributed Caching Strategy with Redis in Microservices Architecture focusing on cache synchronization, eviction policies, and cache consistency.
Introduction to gRPC Presentation (Java)Knoldus Inc.
gRPC, which stands for Remote Procedure Call, is an open-source framework developed by Google. It is designed for building efficient and scalable distributed systems. gRPC enables communication between client and server applications by defining a set of services and message types using Protocol Buffers (protobuf) as the interface definition language. gRPC provides a way for applications to call methods on a remote server as if they were local procedures, making it a powerful tool for building distributed and microservices-based architectures.
Using InfluxDB for real-time monitoring in JmeterKnoldus Inc.
Explore the integration of InfluxDB with JMeter for real-time performance monitoring. This session will cover setting up InfluxDB to capture JMeter metrics, configuring JMeter to send data to InfluxDB, and visualizing the results using Grafana. Learn how to leverage this powerful combination to gain real-time insights into your application's performance, enabling proactive issue detection and faster resolution.
Intoduction to KubeVela Presentation (DevOps)Knoldus Inc.
KubeVela is an open-source platform for modern application delivery and operation on Kubernetes. It is designed to simplify the deployment and management of applications in a Kubernetes environment. KubeVela is a modern software delivery platform that makes deploying and operating applications across today's hybrid, multi-cloud environments easier, faster and more reliable. KubeVela is infrastructure agnostic, programmable, yet most importantly, application-centric. It allows you to build powerful software, and deliver them anywhere!
Stakeholder Management (Project Management) PresentationKnoldus Inc.
A stakeholder is someone who has an interest in or who is affected by your project and its outcome. This may include both internal and external entities such as the members of the project team, project sponsors, executives, customers, suppliers, partners and the government. Stakeholder management is the process of managing the expectations and the requirements of these stakeholders.
Introduction To Kaniko (DevOps) PresentationKnoldus Inc.
Kaniko is an open-source tool developed by Google that enables building container images from a Dockerfile inside a Kubernetes cluster without requiring a Docker daemon. Kaniko executes each command in the Dockerfile in the user space using an executor image, which runs inside a container, such as a Kubernetes pod. This allows building container images in environments where the user doesn’t have root access, like a Kubernetes cluster.
Efficient Test Environments with Infrastructure as Code (IaC)Knoldus Inc.
In the rapidly evolving landscape of software development, the need for efficient and scalable test environments has become more critical than ever. This session, "Streamlining Development: Unlocking Efficiency through Infrastructure as Code (IaC) in Test Environments," is designed to provide an in-depth exploration of how leveraging IaC can revolutionize your testing processes and enhance overall development productivity.
Exploring Terramate DevOps (Presentation)Knoldus Inc.
Terramate is a code generator and orchestrator for Terraform that enhances Terraform's capabilities by adding features such as code generation, stacks, orchestration, change detection, globals, and more . It's primarily designed to help manage Terraform code at scale more efficiently . Terramate is particularly useful for managing multiple Terraform stacks, providing support for change detection and code generation 2. It allows you to create relationships between stacks to improve your understanding and control over your infrastructure . One of the key features of Terramate is its ability to detect changes at both the stack and module level. This capability allows you to identify which stacks and resources have been altered and selectively determine where you should execute commands.
Clean Code in Test Automation Differentiating Between the Good and the BadKnoldus Inc.
This session focuses on the principles of writing clean, maintainable, and efficient code in the context of test automation. The session will highlight the characteristics that distinguish good test automation code from bad, ultimately leading to more reliable and scalable testing frameworks.
Integrating AI Capabilities in Test AutomationKnoldus Inc.
Explore the integration of artificial intelligence in test automation. Understand how AI can enhance test planning, execution, and analysis, leading to more efficient and reliable testing processes. Explore the cutting-edge integration of Artificial Intelligence (AI) capabilities in Test Automation, a transformative approach shaping the future of software testing. This session will delve into practical applications, benefits, and considerations associated with infusing AI into test automation workflows.
State Management with NGXS in Angular.pptxKnoldus Inc.
NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations. In this session we will go through the main for components of NGXS -Store, Actions, State, and Select.
Authentication in Svelte using cookies.pptxKnoldus Inc.
Svelte streamlines authentication with cookies, offering a secure and seamless user experience. Effortlessly manage sessions by storing tokens in cookies, ensuring persistent logins. With Svelte's simplicity, implement robust authentication mechanisms, enhancing user security and interaction.
OAuth2 Implementation Presentation (Java)Knoldus Inc.
The OAuth 2.0 authorization framework is a protocol that allows a user to grant a third-party web site or application access to the user's protected resources, without necessarily revealing their long-term credentials or even their identity. It is commonly used in scenarios such as user authentication in web and mobile applications and enables a more secure and user-friendly authorization process.
Supply chain security with Kubeclarity.pptxKnoldus Inc.
Kube clarity is a comprehensive solution designed to enhance supply chain security within Kubernetes environments. Kube clarity enables organizations to identify and mitigate potential security threats throughout the software development and deployment process.
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
In this session, we will delve into the world of web scraping with JSoup, an open-source Java library. Here we are going to learn how to parse HTML effectively, extract meaningful data, and navigate the Document Object Model (DOM) for powerful web scraping capabilities.
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
Dive into the fundamental aspects of Akka gRPC and learn to leverage its power in building compact and efficient distributed systems. This session aims to equip attendees with the essential skills and knowledge to leverage Akka and gRPC effectively in building robust, scalable, and distributed applications.
Entity Core with Core Microservices.pptxKnoldus Inc.
How Developers can use Entity framework(ORM) which provides a structured and consistent way for microservices to interact with their respective database, prompting independence, scaliblity and maintainiblity in a distributed system, and also provide a high-level abstraction for data access.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
3. Extractor
Pattern Matching???
object ListExtractor {
val xs = 3 :: 6 :: 12 :: Nil
xs match {
case List(a, b) => a * b
case List(a, b, c) => a + b + c
case _ => 0
}
}
object knolx {
val head :: tail = List(1, 2, 3)
}
4. Extractor
If you have some student data, each is "B123456, Bob, New Delhi"
format, you want to Obtained a student number, name and place of birth
information
5. object Student {
def separate(s: String) = {
val parts = s.split(",")
if (parts.length == 3) Some((parts(0), parts(1), parts(2))
else None
}
}
object StudentApp extends App {
val student = Student.separate("B123456, Bob, New Delhi")
student match {
case Some((number, name, addr)) =>
println(s"Student Information:::name=$name,
number=$number and address=$addr")
case None => println("Wrong data found")
}
}
6. val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
This is possible??
val Student(number, name, addr) = "B123456, Bob, New Delhi"
7. Extractor (unapply)
case class Student(number: String, name: String, address: String)
val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
val info: List[Student] = ???
10. Extractor (unapply)
object StudentApp extends App {
val students = List(
"B123456,Ankit,New Delhi",
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi")
val result: List[Student] = students collect {
case Student(number, name, address) => Student(number, name, address)
}
println(result)
}
11. Extractor (unapply)
case class Student(number: String, name: String, address: String)
object Student {
def unapply(str: String): Option[(String, String, String)] = {
val parts = str.split(",")
if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None
}
}
object Utility {
def extractInformation(data: List[String]): List[Student] = {
def extractInfo(extractedInfo: List[Student], result: List[String]): List[Student] = {
result match {
case Student(number, name, address) :: tail =>
extractInfo(extractedInfo :+ Student(number, name, address), tail)
case Nil => extractedInfo
case _ :: tail => extractInfo(extractedInfo, tail)
}
}
extractInfo(List[Student](), data)
}
}
12. Safe Extractor (unapply)
object EMail {
// The extraction method (mandatory)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2) Some(parts(0), parts(1)) else None
}
}
object SafeExtractor extends App {
val any: Any = "abdhehs@knoldus.com"
any match {
case EMail(user, domain) => println(s"Matched:::${(user, domain)}")
case _ => println("Not Mathed")
}
}
13. Extractor (unapply)
object GivenNames {
def unapply(name: String): Option[(String, String)] = {
val names = name.trim.split(",")
if (names.length >= 2) Some((names(1), names(0))) else None
}
}
object ExtractNames extends App {
def greetWithFirstName(name: String) = name match {
case GivenNames(firstName, _) => "Good evening, " + firstName + "!"
case _ => "Welcome! Please make sure to fill in your name!"
}
val information = "Kumar,Abdhesh,New Delhi"
val result = greetWithFirstName(information)
println(result)
}
14. object UserName {
def unapplySeq(email: String): Option[Seq[String]] = {
val parts = email split ","
if (parts.nonEmpty) Some(parts)
else None
}
}
object UserNameApp extends App {
val name = "Kumar,Abdhesh,New Delhi"
name match {
case UserName(lastName, firstName, _*) =>
println(s"First Name=$firstName and Last Name=$lastName")
case _ => println("Not Matched")
}
val UserName(lastName, firstName, others @ _*) = name
}
Extract sequences (unapplySeq)
15. object UserName {
def unapplySeq(email: String): Option[Seq[String]] = {
val parts = email split ","
if (parts.nonEmpty) Some(parts)
else None
}
}
object UserNameApp extends App {
val name = "Kumar,Abdhesh,New Delhi"
name match {
case UserName(lastName, firstName, others @ _*) =>
println(s"First Name=$firstName and Last Name=$lastName")
case _ => println("Not Matched")
}
}
Extract sequences (unapplySeq)..
16. Wildcard operators
If you only care about the first variable you can use _* to reference the
rest of the sequence that you don't care about
using @ _* we can get the rest of the sequence assigned to others
17. Combining fixed and variable parameter
extraction
Sometimes, you have certain fixed values to be extracted that you know
about at compile time, plus an additional optional sequence of values.
def unapplySeq(object: S): Option[(T1, .., Tn-1, Seq[T])]
*unapplySeq can also return an Option of a TupleN , where the last element of the tuple
must be the
18. Combining fixed and variable parameter
extraction
object Names {
def unapplySeq(name: String): Option[(String, String, Seq[String])] = {
val names = name.trim.split(" ")
if (names.size < 2) None
else Some((names.last, names.head, names.drop(1).dropRight(1)))
}
}
object MixedExtractor {
def greet(fullName: String) = fullName match {
case Names(lastName, firstName, _*) => "Good morning, " + firstName +
" " + lastName + "!"
Case _ => "Welcome! Please make sure to fill in your name!"
}
}
19. A Boolean Extractor
object StudentBool {
def unapply(student: String): Boolean = student.contains("Allahabad")
}
object BooleanExtractorApp extends App {
val name = "B123456,Ankit,Allahabad"
name match {
case studentI @ StudentBool() => println(studentI)
case _ => println("Not Found")
}
}
20. A Boolean Extractor
object StudentBool {
def unapply(student: String): Boolean =
student.contains("Allahabad")
}
object BooleanExtractorApp extends App {
val students = List(
"B123455,Anand,New Delhi",
"B123454,Satendra,New Delhi",
"B123456,Ankit,Allahabad")
students collect {
case std @ StudentBool() => std
}
}
21. Instances of a class with unapply method
class Splitter(sep: Char) {
def unapply(v: String): Option[(String, String)] = (v indexOf sep) match {
case x if (x > 0) => Some((v take x, v drop x + 1))
case _ => None
}
}
object SimpleExtractor extends App {
val SplitOnComma = new Splitter(',')
"1,2" match { case SplitOnComma(one, two) => println(one, two) }
//All extractors can also be used in assignments
val SplitOnComma(one, two) = "1,2"
}
22. Every Regex object in Scala has an
extractor
object RegexExtractor extends App {
val Decimal = new Regex("""(-)?(d+)(.d*)?""")
val input = "for -1.0 to 99 by 3"
for (s <- Decimal findAllIn input) println _
val dec = Decimal findFirstIn input
val Decimal(sign, integerpart, decimalpart) = "-1.23"
println((sign, integerpart, decimalpart))
val Decimal(signI, integerpartI, decimalpartI) = "32323"
// Regex to split a date in the format Y/M/D.
val regex = "(d+)/(d+)/(d+)".r
val regex(year, month, day) = "2010/1/13"
}
23. Extractor Rules
unapply () method called extractor
unapply can’t be overloaded (because it always takes the the same
argument).
25. Where Implicits are Tried
Implicits are used in three places in Scala
○ Conversions to an expected type
■ For objects passed in to a function that expects a different type
26. Where Implicits are Tried..
○ Conversions of the receiver of a selection
■ For when methods are called on an object that doesn't have
those methods defined, but an implicit conversion does
(e.g. -> method for maps)
27. Where Implicits are Tried...
○ Implicit Parameters
■ Provide more information to a called method about what the
caller wants
■ Especially useful with generic functions
28. Rules for Implicit
Marking Rule: Only definitions marked implicit are available
The implicit keyword is used to mark which declarations the
compiler may use as implicits.
implicit def intToString(x: Int) = x.toString
def dbl2Str(d: Double): String = d.toString // ignored
29. Rules for Implicit
Scope Rule: An inserted implicit conversion must be in
scope as a single identifier, or be associated with the source
or target type of the conversion.
The Scala compiler will only consider implicit conversions that are in
scope
The compiler will also look for implicit definitions in the companion object
of
the source or expected target types of the conversion
30. Rules for Implicit
Non-Ambiguity Rule: An implicit conversion is only inserted if
there is no other possible conversion to insert.
One-at-a-time Rule: Only one implicit is tried.
The compiler will never rewrite x + y to convert1(convert2(x)) + y.
32. Naming Conventions for Implicit
Can have arbitrary names
The compiler doesn't care
Naming should be chosen for two considerations:
Explicit usage of the conversion
Explicit importing into scope for the conversion
33. Implicits Methods
The idea is to be able to extend functionality of an existing class with new
methods in a type safe manner.
34. Implicits Methods
class MyInteger(val i: Int) {
def myNewMethod = println("hello from myNewMethod")
def inc = new MyInteger(i + 1)
}
object MyIntegerConvertor {
implicit def int2MyInt(i: Int) = new MyInteger(i)
implicit def myInt2Int(mI: MyInteger) = mI.i
}
object ImplicitMethods extends App {
import MyIntegerConvertor._
val result = 1.myNewMethod
val inc = 2.inc
def takesInt(i: Int) = println(i)
takesInt(inc)
takesInt(5.inc)
}
35. Implicits Parameters
It is similar to default parameters, but it has a different
mechanism for finding the “default” value.
The implicit parameter is a parameter to method or constructor that is
marked as implicit.
This means if a parameter value is not mentioned then the
compiler will search for an “implicit” value defined within a scope.
37. Implicits Parameters
Matching implicit arguments
Implicits are totally typesafe, and are selected based on the static type of
the
arguments. Here are some examples to show how things work.
def speakImplicitly(implicit greeting: String) = println(greeting)
implicit val aUnit = ()
speakImplicitly //no implicit argument matching parameter type
String was found.
38. Implicits Parameters
Implicit arguments of subtypes
def sayThings(implicit args: List[Any]) = args.foreach(println(_))
implicit val nothingNiceToSay: List[Any] = Nil
sayThings
implicit val hello: List[String] = List("Hello world");
sayThings
39. Implicits Parameters
/**
One important restriction is that there can only be a single
implicit keyword per method. It must be at the start of a
parameter list (which also makes all values of that parameter
list be implicit).
*/
def pp(a: Int)(implicit i: Int) = println(a, i)
//both i and b are implicit
def pp(a: Int)(implicit i: Int, b: Long) = println(a, i, b)
def pp(implicit i: Int, b: Long) = println(i, b)
def pp(implicit i: Int, b: Long*) = println(i, b)
def pp(b: Long*)(implicit i: Int) = println(i, b)
/When you have a implicit keyword in the first of parameter list, all the
parameters in this list are implicit!
40. Implicit Classes
Must take exactly one parameter (Though can have a
second, implicit parameter list)
Must be defined where a method could be defined (not at top
level)
Generated method will have same name as the class, so can
be imported together.
41. Implicit Classes
object Helpers {
implicit class IntWithTimes(x: Int) {
def times[A](f: => A): Unit = {
def loop(current: Int): Unit =
if (current > 0) {
f
loop(current - 1)
}
loop(x)
}
}
}
object ImpliciClasses {
import Helpers._
5 times println("HI")
}
42. Implicit Classes
Implicit classes have the following restrictions:
1. They must be defined inside of another trait / class / object .
2.They may only take one nonimplicit argument in their constructor.
3. There may not be any method, member or object in scope with the same name as the
implicit class.
43. Sort User Defined Objects
case class Employee(id: Int, firstName: String, lastName:
String)
object Employee {
implicit def orderingByName[A <: Employee]: Ordering[A] =
Ordering.by(e => e.firstName)
val orderingById: Ordering[Employee] = Ordering.by(e => e.id)
}
44. Sort User Defined Objects
object ImplicitBox extends App {
val employees = List(
Employee(1, "A", "AA"),
Employee(4, "D", "AA"),
Employee(5, "E", "EE"),
Employee(2, "B", "BB"),
Employee(3, "C", "CC"))
val sortByName = employees.sorted
println(s"Sort Employee by name=${sortByName}")
val sortById = employees.sorted(Employee.orderingById)
println(s"Sort Employee by Id=${sortById}")
}
45. How can I chain/nest implicit conversions?
Scala does not allow two such implicit conversions taking
place, however, so one cannot got from A to C using an
implicit A to B and another implicit B to C .
Is there a way around this restriction?
Scala has a restriction on automatic conversions to add a
method, which is that it won’t apply more than one
conversion in trying to find methods.
46. How can I chain/nest implicit conversions?
object T1 {
implicit def toA(n: Int): A = new A(n)
implicit def aToB(a: A): B = new B(a.n, a.n)
implicit def bToC(b: B): C = new C(b.m, b.n, b.m + b.n)
// won't work
//println(5.total)
//println(new A(5).total)
// works
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
47. How can I chain/nest implicit conversions?
// def m[A <% B](m: A) is the same thing as
// def m[A](m: A)(implicit ev: A => B)
object T2 extends App {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
// works
println(5.total)
println(new A(5).total)
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
48. update method
a(x) = y, the compiler interprets this to as a.update(x, y)
class PhonebookExpend {
private val numbers = scala.collection.mutable.Map[String, (Int, Int)]()
def apply(name: String) = numbers(name)
def update(name: String, number: (Int, Int)) = numbers(name) = number
}
object EchoUpdate extends App {
val e = new Echo()
e("hello", "hi") = "knoldus"
//e("hello") = ("salut", "bonjour")
val book2 = new PhonebookExpend()
book2("jesse") = (123, 4567890)
val (areaCode, local) = book2("jesse")
}