This document compares several JVM languages including Java, Scala, Groovy, Kotlin, Clojure and Ceylon. It discusses their classification as functional or object-oriented, static or dynamic typing. It also summarizes key features of each language such as support for functional programming paradigms, closures, immutable data structures, and parallel processing capabilities. The document provides code examples to illustrate concepts in Scala, Kotlin, and Groovy.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
An introduction to Kotlin for advanced Android beginners, covering command-line compilation of Kotlin files, conditional logic, val/var, basic functions, higher order functions, recursion.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
An introduction to Kotlin for advanced Android beginners, covering command-line compilation of Kotlin files, conditional logic, val/var, basic functions, higher order functions, recursion.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
[Codemotion 2015] patrones de diseño con java8Alonso Torres
Presentada en el Codemotion Madrid 2015.
Abstract:
Han pasado más de 20 años desde la publicación del famoso libro "Patrones de diseño" por el grupo conocido como "Gang of Four".
Durante años, estos patrones han mantenido su actualidad por ser lo suficientemente genéricos para todo tipo de software y resolver problemas comunes de diseño de las aplicaciones que desarrollamos a diario.
Pero algo ha cambiado con Java 8.
Con las nuevas características de Java 8, y en especial las lambdas, es necesario revisitar estos famosos patrones para adaptarlos a sus nuevas funcionalidades.
En esta charla repasaremos algunos de los famosos patrones viendo como adaptarlos a las nuevas características de Java. Además, podremos ver como mejorar nuestro tradicional diseño orientado a objetos gracias a las lambdas y a la programación funcional.
The way from monolithic to micro service architectures can hard. Overall micro services are not the all holy grail to just solve all your issues. You need to be aware that you need the right developers and the right toolset. Oh and not to forget, moving state to authorization systems doesn't mean your application is really stateless :)
Anyhow micro services are a great architecture and this deck is a short introduction on why we need to change our application architectures and what pitfalls you you have when introducing the idea of micro services.
Reaching critical masses with your application systems becomes harder every day. Caching helps to provide low latency and high availability over slow calculation, networks, databases and any other kind of external resource.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
[Codemotion 2015] patrones de diseño con java8Alonso Torres
Presentada en el Codemotion Madrid 2015.
Abstract:
Han pasado más de 20 años desde la publicación del famoso libro "Patrones de diseño" por el grupo conocido como "Gang of Four".
Durante años, estos patrones han mantenido su actualidad por ser lo suficientemente genéricos para todo tipo de software y resolver problemas comunes de diseño de las aplicaciones que desarrollamos a diario.
Pero algo ha cambiado con Java 8.
Con las nuevas características de Java 8, y en especial las lambdas, es necesario revisitar estos famosos patrones para adaptarlos a sus nuevas funcionalidades.
En esta charla repasaremos algunos de los famosos patrones viendo como adaptarlos a las nuevas características de Java. Además, podremos ver como mejorar nuestro tradicional diseño orientado a objetos gracias a las lambdas y a la programación funcional.
The way from monolithic to micro service architectures can hard. Overall micro services are not the all holy grail to just solve all your issues. You need to be aware that you need the right developers and the right toolset. Oh and not to forget, moving state to authorization systems doesn't mean your application is really stateless :)
Anyhow micro services are a great architecture and this deck is a short introduction on why we need to change our application architectures and what pitfalls you you have when introducing the idea of micro services.
Reaching critical masses with your application systems becomes harder every day. Caching helps to provide low latency and high availability over slow calculation, networks, databases and any other kind of external resource.
The days of JNI is counted, Project Panama is on the rise to tear down the walls between Java and C/C++ forever. FFI (Foreign Function Interface) technology finally arrives into the Java world.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Java som sprog har ikke bevæget sig meget de seneste år. Vi har stadig ikke closures eller funktionelle aspekter som f.eks. C# har haft siden version 3. Er Scala svaret på enhver Javaudviklers bønner eller er sproget kun interessant for tågehoveder som mig, som begynder at synes bedre og bedre om funktionsorientering? Er den store portion syntaktisk sukker, Scala bringer på bordet, bare tomme kalorier?
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at the Boston Area Scala Enthusiasts meetup, by Andrew Phillips & Nermin Serifovic. See http://www.meetup.com/boston-scala/events/228136405/
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at Scala Up North 2015, by Andrew Phillips & Nermin Serifovic. See http://scalaupnorth.com/speakers.html#andrew
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
I used these slides for a Scala workshop that I gave. They are based on these: http://www.scala-lang.org/node/4454. Thanks to Alf Kristian Støyle and Fredrik Vraalsen for sharing!
In this PDF you can learn about Kotlin Basic as well as Intermediate part. As also you can develop the android apps and publish in a google play store.
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...Jose Manuel Ortega Candel
Los benchmarks son programas que permiten evaluar el rendimiento de un sistema, componente o proceso en comparación con otros sistemas similares. Son herramientas esenciales para medir y comparar el rendimiento de hardware, software y sistemas en diferentes áreas. El objetivo es dar a conocer las principales herramientas de benchmark que disponemos hoy en día para medir el rendimiento.
Entre los puntos a tratar podemos destacar:
-Introducción a Benchmarks: Definición y propósito de los benchmarks en la medición del rendimiento
-Tipos de Benchmarks: Benchmarks sintéticos vs. Benchmarks del mundo real.Benchmarks específicos para CPU, memoria, almacenamiento, y gráficos
-Selección de Benchmarks: Consideraciones al elegir benchmarks según el tipo de aplicación y los objetivos de evaluación
En el mundo actual, las APIs juegan un papel importante en la creación de aplicaciones y servicios robustos y flexibles. Sin embargo, con la expansión de las APIs, también surge la necesidad de abordar los desafíos de seguridad asociados.
En esta charla, exploraremos en detalle el OWASP Top 10 de Seguridad en APIs, una lista de las principales vulnerabilidades que los desarrolladores y equipos de seguridad deben tener en cuenta al diseñar, desarrollar y asegurar sus APIs. Por último, comentaremos las mejores prácticas para mitigar los riesgos y garantizar la seguridad de tus APIs. Entre los puntos a tratar podemos destacar:
1.Introducir el concepto de seguridad en las APIs
2.OWASP Top 10 y su importancia para la seguridad en APIs
3.Actualización del OWASP Top 10 security en 2023
4.Herramientas para evaluar y mejorar la seguridad de tus APIs.
5.Estrategias y mejores prácticas para garantizar la seguridad de tus APIs.
La seguridad en aplicaciones web es un aspecto fundamental para garantizar la protección de los datos y la confidencialidad de los usuarios. Si nuestro objetivo es aprender como Django gestiona la seguridad, PyGoat es una aplicación desarrollada con Django vulnerable de forma intencionada que puede ser utilizada para aprender a asegurar nuestras aplicaciones Django.
En esta charla, analizamos como Django gestiona la seguridad utilizando la aplicación vulnerable Pygoat, identificando los problemas de seguridad subyacentes. Aprenderemos sobre vulnerabilidades de seguridad comunes como las que aparecen en el OWASP Top 10 en aplicaciones Django y cómo solucionarlas para que podamos mantener nuestras aplicaciones a salvo de atacantes.
Entre los puntos a tratar podemos destacar:
Introducción a la seguridad en aplicaciones Django
Pygoat como ejemplo de aplicación vulnerable
Vulnerabilidades OWASP top 10 y mitigación
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Jose Manuel Ortega Candel
En la actualidad, la tecnología blockchain y los smart contracts están revolucionando la forma en que interactuamos con la información y realizamos transacciones. Sin embargo, esta innovación no está exenta de desafíos en cuanto a la ciberseguridad se refiere. En esta charla, exploraremos los desafíos desde el punto de vista de la ciberseguridad en blockchain y smart contracts, así como las soluciones y enfoques para mitigar los riesgos asociados. A medida que continuamos adoptando estas tecnologías disruptivas, es fundamental comprender y abordar adecuadamente los aspectos de seguridad para minimizar los posibles riesgos. Entre los puntos a tratar podemos destacar:
1. Fundamentos de Blockchain y Smart Contracts 2. Desafíos de Seguridad en Blockchain 3. Seguridad en Smart Contracts 4. Auditorías y Pruebas de Seguridad en smart contracts
In the latest versions of K8s there has been an evolution regarding the definition of security strategies at the level of access policies to the cluster by users and developers. The security contexts (securityContext) allow you to define the configurations at the level of access control and privileges for a pod or container in a simple way using keywords in the configuration files.
To facilitate the implementation of these security strategies throughout the cluster, new strategies have emerged such as the Pod Security Policy (PSP) where the cluster administrator is in charge of defining these policies at the cluster level with the aim that developers can follow these policies.
Other interesting projects include Open Policy Agent (OPA) as the main cloud-native authorization policy agent for creating policies and managing user permissions for access to applications.
The objective of this talk is to present the evolution that has occurred in security strategies and how we could use them together, as well as analyze their behavior in accessing resources. Among the points to be discussed we can highlight:
-Introduction to security strategies in K8s environments
-Pod Security Admission(PSA) vs Open Policy Agent (OPA)
-Combination of different security strategies together
-Access to resources in privileged and non-privileged mode
In the latest versions of K8s there has been an evolution regarding the definition of security strategies at the level of access policies to the cluster by users and developers. The security contexts (securityContext) allow you to define the configurations at the level of access control and privileges for a pod or container in a simple way using keywords in the configuration files.
To facilitate the implementation of these security strategies throughout the cluster, new strategies have emerged such as the Pod Security Policy (PSP) where the cluster administrator is in charge of defining these policies at the cluster level with the aim that developers can follow these policies.
Other interesting projects include Open Policy Agent (OPA) as the main cloud-native authorization policy agent for creating policies and managing user permissions for access to applications.
The objective of this talk is to present the evolution that has occurred in security strategies and how we could use them together, as well as analyze their behavior in accessing resources. Among the points to be discussed we can highlight:
*Introduction to security strategies in K8s environments
*Pod Security Admission(PSA) vs Open Policy Agent (OPA)
*Combination of different security strategies together
*Access to resources in privileged and non-privileged mode
No production system is complete without a way to monitor it. In software, we define observability as the ability to understand how our system is performing. This talk dives into capabilities and tools that are recommended for implementing observability when running K8s in production as the main platform today for deploying and maintaining containers with cloud-native solutions.
We start by introducing the concept of observability in the context of distributed systems such as K8s and the difference with monitoring. We continue by reviewing the observability stack in K8s and the main functionalities. Finally, we will review the tools K8s provides for monitoring and logging, and get metrics from applications and infrastructure.
Between the points to be discussed we can highlight:
-Introducing the concept of observability
-Observability stack in K8s
-Tools and apps for implementing Kubernetes observability
-Integrating Prometheus with OpenMetrics
La computación distribuída es un nuevo modelo de computación que surgió con el objetivo de resolver problemas de computación masiva donde diferentes máquinas trabajan en paralelo formando un clúster de computación.
En los últimos años han surgido diferentes frameworks como Apache Hadoop, Apache Spark y Apache Flink que permiten resolver este tipo de problemas donde tenemos datos masivos desde diferentes fuentes de datos.
Dentro del ecosistema de Python podemos destacar las librerías de Pyspark y Dask de código abierto que permiten la ejecución de tareas de forma paralela y distribuida en Python.
Entre los puntos a tratar podemos destacar:
Introducción a la computación distribuida
Comparando tecnologías de computación distribuida
Frameworks y módulos en Python para computación distribuida
Casos de uso en proyectos Big Data
En los últimos años, las arquitecturas cloud han evolucionado a un modelo serverless que trae como principales ventajas la posibilidad de ejecutar código sin aprovisionar ni administrar servidores. Este tipo de arquitecturas permite ejecutar el código en una infraestructura con alta disponibilidad y escalado automático, así como capacidades de monitorización de forma automática. Sin embargo, estos tipos de arquitecturas introducen un conjunto completamente nuevo de implicaciones de seguridad que deben tenerse en cuenta al crear sus aplicaciones.
El OWASP Serverless Top 10 es una excelente referencia para conocer los posibles riesgos de seguridad y las consecuencias de implementar una arquitectura serverless, así como también cómo mitigarlos.
En esta charla se analizará el estado actual de la seguridad en arquitecturas serverless, los principales riesgos y cómo podríamos mitigarlos de una forma sencilla. Entre los puntos a tratar podemos destacar:
-Introducción a las arquitecturas serverless
-Seguridad en arquitecturas serverless y OWASP Serverless Top 10
-Pentesting sobre aplicaciones serverless
-Mejoras prácticas de seguridad al trabajar en entornos cloud
La adopción de arquitecturas basadas en microservicios ha crecido de manera exponencial en los últimos años. Cuando se trata de obtener la máxima seguridad utilizamos lo que se denomina arquitecturas de “confianza cero” (zero trust architecture). Las arquitecturas de este tipo establecen mecanismos de autenticación y autorización entre nuestros propios microservicios, aumentando de esta manera la seguridad en entornos altamente regulados.
El objetivo de esta charla es dar a conocer los principios básicos para construir aplicaciones utilizando arquitecturas zero trust y algunas herramientas para realizar auditorías de seguridad en entornos cloud. Entre los puntos a tratar podemos destacar:
Introducción a DevSecOps y modelado de amenazas
Modelo de confianza cero(zero trust) en la nube
Mejoras prácticas a nivel de permisos y estrategias de seguridad al trabajar en entornos cloud
Herramientas de análisis orientadas al pentesting en entornos cloud
Python has become the most widely used language for machine learning and data science projects due to its simplicity and versatility.
Furthermore, developers get to put all their effort into solving an Machine Learning or data science problem instead of focusing on the technical aspects of the language.
For this purpose, Python provides access to great libraries and frameworks for AI and machine learning (ML), flexibility and platform independence
In this talk I will try to get a selection of libraries and frameworks that can help us introduce in the Machine Learning world and answer the question that all people is doing, What makes Python the best programming language for machine learning?
In this talk I will show how to save secret keys in Docker containers and K8s in production and best practices for saving and securing distribution of secrets. With Docker and k8s secrets we can manage information related to keys that are needed at runtime but cannot be exposed in the Docker image or source code repository. These could be the main talking points:
1.Challenges of security and secret keys in containers
2.Best practices for saving and securing distribution of secrets in Docker Containers
3.Managing secrets in Kubernetes using volumes and sealed-secrets
4.Other tools for distributing secrets in containers like Hashicorp Vault and KeyWhiz
One of the best practices from a security point of view is to introduce the management of the certificates that we are going to use to support protocols such as SSL / TLS. In this talk we will explain cert-manager and his implementation in K8s as a native Kubernetes certificate management controller that allows us to manage connection certificates and secure communications through SSL/TLS protocols. Later I will explain the main functionalities and advantages that cert-manager provides, for example it allows us to validate that the certificates we are using in different environments are correct. Finally, some use cases are studied in which to use cert-manager and the integration with other services such as Let's Encrypt or HashiCorp Vault.
Python se ha convertido en el lenguaje más usado para desarrollar herramientas dentro del ámbito de la seguridad. Esta charla se centrará en las diferentes formas en que un analista puede aprovechar el lenguaje de programación Python tanto desde el punto de vista defensivo como ofensivo.
Desde el punto de vista defensivo Python es una de las mejores opciones como herramienta de pentesting por la gran cantidad de módulos que nos pueden ayudar a desarrollar nuestras propias herramientas con el objetivo de realizar un análisis de nuestro objetivo.
Desde el punto de vista ofensivo podemos utilizar Python para recolección de información de nuestro objetivo de forma pasiva y activa. El objetivo final es obtener el máximo conocimiento posible en el contexto que estamos auditando. Entre los principales puntos a tratar podemos destacar:
1.Introducción a Python para proyectos de ciberseguridad(5 min)
2.Herramientas de pentesting(10 min)
3.Herramientas Python desde el punto de vista defensivo(10 min)
4.Herramientas Python desde el punto de vista ofensivo(10 min)
Python se ha convertido en el lenguaje más usado para desarrollar herramientas dentro del ámbito de la seguridad. Esta charla se centrará en las diferentes formas en que un analista puede aprovechar el lenguaje de programación Python tanto desde el punto de vista defensivo como ofensivo.
Desde el punto de vista defensivo Python es una de las mejores opciones como herramienta de pentesting por la gran cantidad de módulos que nos pueden ayudar a desarrollar nuestras propias herramientas con el objetivo de realizar un análisis de nuestro objetivo.
Desde el punto de vista ofensivo podemos utilizar Python para recolección de información de nuestro objetivo de forma pasiva y activa. El objetivo final es obtener el máximo conocimiento posible en el contexto que estamos auditando. Entre los principales puntos a tratar podemos destacar:
1.Introducción a Python para proyectos de ciberseguridad(5 min)
2.Herramientas de pentesting(10 min)
3.Herramientas Python desde el punto de vista defensivo(10 min)
4.Herramientas Python desde el punto de vista ofensivo(10 min)
Shodan es una de las plataformas de hacking más utilizadas en todo el mundo que nos brinda un completo motor de búsqueda avanzado desde el que podemos encontrar cualquier dispositivo conectado a la red junto con sus servicios activos, puertos abiertos y posibles vulnerabilidades.
En esta charla mostraremos las principales herramientas que podemos utilizar para maximizar nuestras búsquedas en Shodan, así como desarrollar nuestros propios scripts con python para automatizar las búsquedas.
Entre los puntos a tratar podemos destacar:
-Filtros y búsquedas personalizadas en Shodan
-Detectando vulnerabilidades con Shodan
-Buscar bases de datos abiertas en Shodan
-Shodan desde lineas de comandos con ShodanCLI
La charla trataría sobre cómo usar el stack Elasticsearch, Logstash y Kibana (ELK) para respuestas ante incidentes, monitorización de logs y otras tareas relacionadas con los equipos blue team. Por ejemplo, podríamos analizar los registros basados en autenticación y eventos del sistema operativo.
Entre los puntos a tratar podemos destacar:
-Introducción al estándar ELK y cómo nos puede ayudar para crear nuestro laboratorio de análisis.
-Comentar las diferentes fuentes de datos que podríamos usar (eventos del sistema operativo, capturas de red).
-Indexación y búsqueda de datos en ElasticSearch.
-Recopilación y manipulación de datos con LogStash.
-Creación de dashboards con Kibana.
-Ejemplo de aplicación para alertar sobre eventos basados en la autenticación en el sistema operativo.
The world is advancing towards accelerated deployments using DevOps and cloud native technologies. In architectures based on microservices, container monitoring and management become even more important as we need to scale our application.
In this talk, I will show how to monitor and manage docker containers to manage the status of your applications. We will review how to monitor for security events using open source solutions to build an actionable monitoring system for Docker and Kubernetes.
Through a web interface, tools such as cadvisor, portainer and rancher give us a global overview of the containers you are running as well as facilitate their management.
These could be the main points to discuss:
Challenges in containers and architectures distributed from the point of view of monitoring and administration
Most important metrics that we can use to measure container performance.
Tools for monitoring and management of containers such as cadvisor, sysdig and portainer
Rancher as a platform for the administration of Kubernetes
In this talk I will try explain the memory internals of Python and discover how it handles memory management and object creation.
The idea is explain how objects are created and deleted in Python and how garbage collector(gc) functions to automatically release memory when the object taking the space is no longer in use.
I will review the main mechanims for memory allocation and how the garbage collector works in conjunction with the memory manager for reference counting of the python objects.
Finally, I will comment the best practices for memory managment such as writing efficient code in python scripts.
In this talk I will speak about main tips for integrating Security into DevOps. I will share my knowledge and experience and help people learn to focus more on DevOps Security. In addition to the so-called best practices, the development of efficient, readable, scalable and secure code, requires the right tools for security development.
These could be the main talking points:
-How to integrate security into iteration and pipeline application development with containers.
-How to secure development environments.
-DevOps security best practices
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
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:
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
2. INDEX
Functional programming and closures2
Language classification1
Java 8 new features3
Scala, Groovy, Kotlin, Clojure and Ceylon4
Advantages and drawbacks5
Comparing features6
4. Functional programming
•Data structure persistent and immutable
•Closures
•Higher order functions
•Pass functions to functions as parameter
•Create functions within functions
•Return functions from other functions
•Functions as first class values
5. Closures
•Reduce amount of “boiler plate” code
•Eliminate the boilerplate code of anonymous
inner classes
•Allow the use of idiomatic functional
programming code
•Allow the creation of custom control structures
•In Java 8 closures are just syntactic sugar for
defining anonymous inner classes
6. Java 8 new
features
Lambda expressions
Closures
Streams
Enhaced collections
Processing data in parallel
Pattern Filter-Map-Reduce
Annotations types
Methods References
(String s)-> System.out.println(s)
System.out::println
9. Parallel Streams
List myList = ..
Stream stream = myList.stream();
Stream parallelStream = myList.parallelStream();
Stream parallel = stream.parallel();
•Streams are sequential by default
•With Parallel you can optimize number of threads
•More efficient with bigger collections
11. Scala
Combines the paradigms of functional
programming and object-oriented
Statically typed
No types primitives like Java
Everything is an Object, including functions
Performance equivalent to Java
12. Scala features
Pattern matching
Closures,lambdas,anonymous functions
Traits and mixins for multiple inheritance
Operator overloading
Support Data Paralell like Java 8
Concurrency models(Akka,actors)
Inmutable and mutable data structures
13. Scala examples
def factorial(n : Int): Int = n match{
case 0 => 1
case x if x >0 => factorial(n-1) *n
}
val languages = List("Scala", "Groovy", "Clojure", "Kotlin")
val headList = languages.head // Scala
val tailList = languages.tail; //List( "Groovy", "Clojure", "Kotlin")
val empty = languages.isEmpty //false
def orderList(xs: List[String]): List[String] =
if (xs.isEmpty) Nil
else insert(xs.head, isort(xs.tail)
@BeanProperty
Annotation which is read by the Scala
compiler to generate getter and setter
class Bean {
@scala.reflect.BeanProperty
var name: String
}
val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers.filter((x) => x > 0)
someNumbers.filter(_ > 0)
List[Int] = List(5, 10)
scala.collection.immutable
14. Inmutability in Scala
scala> var languages = Set("Scala", "Kotlin")
languages : scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Kotlin)
scala> languages += "Clojure"
scala> languages
res: scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Kotlin, Clojure)
scala> languages -= " Kotlin "
scala> languages
res: scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Clojure)
• You can add elements in a inmutable collection
16. Java 8 vs Scala streams
bookList.parallelStream().filter(b -> b.title.equals(”Clojure”))
.collect(Collectors.toList())
bookList.par.filter(_.title == “Clojure”)
bookList.par.filter( b =>b.title == “Clojure”)
val bookFilter = bookList.par.filter(_.title.contains("Groovy"))
.foreach{i=> println(Thread.currentThread) }
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-5,5,main]
17. Kotlin
Object-oriented with functional elements
Developed by JetBrains
Statically typed like Scala
Smarts casts
Elvis operator(?) for checking null like Groovy
Type inference
100 % interoperability with Java
18. Kotlin syntax & rules
Inmutable/Mutable variables
No new keyword for create objects
No primitive types
No static members
Primary constructors
No fields, just properties
By default, all classes are final
19. Kotlin
Smart casts Maps
val languages = mapOf("Java" to "Gosling",
"Scala" to "Odersky","Groovy" to "Strachan")
for((language,author) in languages){
println("$author made $language")
}
fun eval(e: Expr): Double = when (e) {
is Num-> e.value.toDouble()
is Sum -> eval(e.left) + eval(e.right)
else ->
throw IllegalArgumentException("Unknown
expression")
}
val mapLanguages = hashMapOf<String, String>()
mapLanguages.put("Java", "Gosling")
mapLanguages.put("Scala", "Odersky")
for ((key, value) in mapLanguages) {
println("key = $key, value = $value")
}
fun patternMatching(x:Any) {
when (x) {
is Int -> print(x)
is List<*> ->{print(x.count())}
is String -> print(x.length())
!is Number -> print("Not even a number")
else -> print("can't do anything")
}
}
20. Kotlin
Operator overloading Default & name arguments
println(product(2))
println(product(2,3))
println(format(text="kotlin"))
println(format(text="kotlin", upperCase= true))
2
6
kotlin
KOTLIN
fun product(a:Int,b:Int=1):Int{
return a.times(b);
}
fun format(text:String,upperCase:Boolean=
false):String {
return if (upperCase) text.toUpperCase() else text
}
22. Kotlin
Data classes
Data annotation changes behavior of hashCode, equals, toString functions
public class Book (var isbn:Int, var title:String)
fun main(args: Array<String>) {
//Books
val book = Book(123456, "Beginning Kotlin")
val book2 = Book(123456, "Beginning Kotlin")
println(book);
println(book.hashCode());
println(book2.hashCode());
println(book.equals(book2));
if (book == book2)
println("Same Book");
if (book != book2)
println("Diferent Book");
}
books.Book@2a84aee7
713338599
168423058
false
Diferent Book
data public class Book (var isbn:Int, var title:String)
fun main(args: Array<String>) {
//Books
val book = Book(123456, "Beginning Kotlin")
val book2 = Book(123456, "Beginning Kotlin")
println(book);
println(book.hashCode());
println(book2.hashCode());
println(book.equals(book2));
if (book == book2)
println("Same Book");
if (book != book2)
println("Diferent Book");
Book(isbn=123456,
title=Beginning Kotlin)
1848623012
1848623012
true
Same Book
23. Kotlin
Classes constructor
• It is not necessary define a constructor like in Java
• You can use the class definition to pass the properties and
default values
data public class Book (var isbn:Int, var title:String="My Default Book")
fun main(args: Array<String>) {
val book = Book(123456)
println(book.title);
}
24. Kotlin
Higher order functions
• Lambda expressions
• it implicit parameter
val filter = books filter({ b: Book -> b.title.contains(“Kotlin") })
val book = Book(123455, "Beginning Java 8")
val book1 = Book(3232332, "Java 8 Advanced")
val book2 = Book(43434343, “Kotlin Advanced")
val books = Arrays.asList(book, book1,book2)
Filter[Book(isbn=43434343, title=Kotlin Advanced)]
val filter = books filter({ it.contains(“Kotlin") })
26. Kotlin vs Java list iterate
for ((index,element) in list.withIndex()) {
println(“$index$element”);
}
int index=0
for (String element:list) {
System.out.println(index+””+element);
index++
}
27. Kotlin smart cast vs Java
if (expr is Number) {
println(expr.getValue());
//expr is automatically cast to Number
}
if (expr instanceof Number) {
System.out.println((Number)expr).getValue());
}
28. Kotlin vs Java types
inference
val longJavaClassName = LongJavaClassName()
LongJavaClassName longJavaClassName =new LongJavaClassName()
29. Groovy
Java supercharged(syntactic sugar)
Object oriented and dynamic language
Optional typing like Scala and Kotlin
All type checking is at run time
It reduces Java boilerplate code including no
semi colons, no getters/setters, type
inference, null safety, elvis operators
31. Groovy
@Memoized annotation @Inmutable annotation
@Memoized
def BigInteger fibRecursiveMemoized(n) {
if (n<2) return 1
else return fibRecursiveMemoized(n-1) +
fibRecursiveMemoized(n-2)
}
TimeIt.code{println(fibonnaci.fibRecursive(40))}
TimeIt.code{println(fibonnaci.fibRecursiveMemoized(40))}
165580141
Time taken 42.083165464 seconds
165580141
Time taken 0.061408655 seconds //with memoize
import groovy.transform.Immutable
@Immutable class Language {
String title;
Long isbn;
}
def l1 = new Language (title:'Beginning Groovy',isbn:100)
def l2 = new Language (title:'Groovy advanced',isbn:200)
l1.title = 'Groovy for dummies'
// Should fail with groovy.lang.ReadOnlyPropertyException
32. Groovy
Time execution
class TimeIt {
def static code(codeBlock){
def start = System.nanoTime()
try{
codeBlock()
}finally{
def end = System.nanoTime()
println "Time taken ${(end-start)/1e9} seconds"
}
}
}
36. Clojure
Pure functional language
JVM language based in Lisp
Not Object Oriented
Dynamically typed
All data structure including list ,vectors, maps,
sequences, collections, are inmutable and fully
persistent
The main data structure is the list
The key is the use of High Order Functions
37. Clojure
Alternate implementations in functions
(defn square-or-multiply
"squares a single argument, multiplies two arguments"
([] 0) # without arguments
([x] (* x x)) # one argument
([x y] (* x y))) # two arguments
List operations
(first '(:scala :groovy :clojure))return scala
(rest '(:scala :groovy :clojure))return all elements excepts the first
(cons :kotlin '(:scala :groovy :clojure))add kotlin to head in the list
41. Clojure
Advantages Disadvantages
Very simple Not Object oriented
The language has little elements
compared with other languages
Difficult to decipher stacktraces and errors
Excellent concurrency support Requires a new way to solve problems
Easy interoperability with java There are no variables
Powerful language features
(macros,protocols)
Thre is no inheritance concept
Clojure programs run very quickly No mecanism for avoid NullPointerException
JVM is highly optimized
42. Clojure vs Java
Code reducing
(defn blank [str]
(every#? (Character/isWhitespace %)
str))
public class StringUtils {
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)))) {
return true;
}}
return false;
}}
43. Ceylon
Is very similar to Java, reducing verbosity
Object oriented with functional features
Strong static typing with type inference
Explicit module system
Comparing with Java
Eliminates static, public, protected, private
Add new modifiers like variable, shared, local
Shared is used for make visibility outside in other
modules(like public in Java)
Arrays are replaced by sequences
44. Ceylon
Sequence languages = Sequence("Java",
"Groovy","Clojure","Kotlin");
//Check if the sequence is empty
if(nonempty languages){
String? firstElementValue = languages.value(1);
String? firstElement = languages.first;
}
Sequence more =
join(languages,Sequence("Ceylon","Scala"));
Sequences Generics & Union types
Iterable<String|Boolean> list =
{“string”,true,false}
ArrayList<Integer|Float> list =
ArrayList<Integer|Float>
(1, 2, 1.0, 2.0)
46. Reducing Java verbosity
Reducing Boilerplate Code
class MyClass{
private int index;
private String name;
public MyClass(int index, String name){
this.index = index;
this.name = name;
}
}
case class MyClass(index: Int, name: String)
public class MyClass(var index:Integer,var name:String){
}
class MyClass {
int index
String name
}
class MyClass(index,name) {
shared Integer index;
shared String name;
}
(defstruct MyClass :index :name)
47. Variables definition
• In Kotlin and Scala you can define 2 types
• var myMutableVariable
• val myInmutableVariable
• In Ceylon we have variable modifier for mutable
variable Integer count=0;
count++; //OK
Integer count=0;
count++;//ERROR
val name: Type = initializer // final “variable”
var name: Type = initializer // mutable variable
48. Null-safety
•Operator ? used in Kotlin,Groovy,Ceylon
•Avoid NullPointerException
var b : String? = "b"
b = null // valid null assignment
val l = b?.length()
Elvis Operator(?:) and Safe navigation (?.)
def displayName = user.name ? user.name : "Anonymous“
def streetName = user?.address?.street
String? argument = process.arguments.first;
if (exists argument) { //checking null values
}
49. Optional Types
Optional<Object> optional = findObject(id);
//check if Optional object has value
if (optional.isPresent()) {
System.out.println(optional.get());
}
Type safe Option[T] in Scala
New class java.util.Optional
50. Optional Type in Scala
private val languages = Map(1 -> Language(1, "Java", Some("Gosling")),
2 -> Language(2, "Scala", Some("Odersky")))
def findById(id: Int): Option[Language] = languages.get(id)
def findAll = languages.values
def main(args: Array[String]) {
val language = Optional.findById(1)
if (language.isDefined) {
println(language.get.name)
}
}
val language = Optional.findById(3) None
51. Optional Type in Scala
val languages =Map("Java"->"Gosling","Scala"->"Odersky")
languages:scala.collection.immutale.Map[java.lang.String,java.lang.String]
languages get "Scala"
Option[java.lang.String] = Some(Odersky)
languages get "Groovy"
Option[java.lang.String] = None
53. Pattern matching
• Is a generalization of Java switch/case
def generalSize(x: Any) = x match {
case s: String => s.length
case m: Map[_, _] => m.size
case _ => -1
}
scala> generalSize("abc")
res: Int = 3
scala> generalSize(Map(1 -> 'a', 2 -> 'b'))
res: Int = 2
fun fib(n: Int): Int {
return when (n) {
1, 2 -> 1
else -> fib(n - 1) + fib(n - 2)
}
}
fun patternMatching(x:Any) {
when (x) {
is Int -> print(x)
is List<*> ->{print(x.size())}
is String -> print("String")
!is Number -> print("Not even a number")
else -> print("can't do anything")
}
}
54. Traits vs Java interfaces
Traits allow declare method definitions
A trait is an interface with an
implementation(behavior and/or state)
Traits support “multiple inheritance”
One class can inherit from many traits
55. Traits.Code in interfaces
trait Publication {
int number
def getNumberPublication(){
return (number)
}
}
trait Location {
String description
def getInfoPublication(){
return (description)
}
}
class MyBook implements Publication,Location{
Integer isbn
String title
def getInfoBook(){
return (isbn+ " "+title)
}
}
trait Publication {
def description() = println(“Description”)
}
class Book(var isbn:Int,var title:String) extends Publication{
def getInfoBook(){
return (isbn+ " "+title)
}
}
trait Publication{
var number:String
fun getNumberPublication(){
println(number)
}
}
class Book:Publication {
}
56. Java interoperability
object list extends App {
import java.util.ArrayList
var list : ArrayList[String] = new ArrayList[String]()
list.add("hello")
list.add("world")
println(list)
}
import collection.JavaConversions._
java.util.Arrays.asList(1,2,3).
foreach(i =>println(i))
java.util.Arrays.asList(1,2,3).
filter(_ % 2 ==0)
fun list(source: List<Int>):ArrayList<Int> {
val list = ArrayList<Int>()
for (item in source)
list.add(item)
for (i in 0..source.size() - 1)
list[i] = source[i]
return list
}
(ns clojure-http-server.core
(:require [clojure.string])
(:import (java.net ServerSocket SocketException)
(java.util Date)
(java.io PrintWriter BufferedReader
InputStreamReader BufferedOutputStream)))
57. Java interoperability
import scala.beans.BeanProperty
class Language(
@BeanProperty var name: String,
@BeanProperty var author: String) {
}
public static void main(String[] args) {
Language l1 = new Language(“Java",”Gosling”);
Language l2 = new Language(“Scala",”Odersky”);
ArrayList<Language> list = new ArrayList<>();
list.add(l1);
list.add(l2);
}
58. List Partitions
• We can use partition over a list for obtain 2 lists
scala> List(1, 2, 3, 4, 5) partition (_ % 2 == 0)
res: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5))
// partition the values 1 to 10 into a pair of lists of even and odd numbers
assertEquals(Pair(listOf(2, 4, 6, 8, 10), listOf(1, 3, 5, 7, 9)), (1..10)
.partition{ it % 2 == 0 })
59. Read file and print lines
import scala.io.Source
for (line <- Source.fromFile(“file.txt”).getLines())
println(line.length +" "+ line)
import java.nio.file.*;
import java.util.stream.Stream;
Path dict = Paths.get(“file.txt”);
Stream<String> linesStream = Files.lines(dict);
linesStream.forEach(System.out::println);
val dict = Paths.get(“file.txt")
val linesStream = Files.lines(dict)
val lines = linesStream.forEach{println(it)};
64. Conclusions
Full interoperability with Java
Reducing Java verbosity
These languages allow developer be more
productive comparing with java
Pragmatic Programmer advice: When you
learn a new language, you learn a new way
to think.