A quick introduction to the object-oriented programming language Ruby, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
Delivered as plenary at USENIX LISA 2013. video here: https://www.youtube.com/watch?v=nZfNehCzGdw and https://www.usenix.org/conference/lisa13/technical-sessions/plenary/gregg . "How did we ever analyze performance before Flame Graphs?" This new visualization invented by Brendan can help you quickly understand application and kernel performance, especially CPU usage, where stacks (call graphs) can be sampled and then visualized as an interactive flame graph. Flame Graphs are now used for a growing variety of targets: for applications and kernels on Linux, SmartOS, Mac OS X, and Windows; for languages including C, C++, node.js, ruby, and Lua; and in WebKit Web Inspector. This talk will explain them and provide use cases and new visualizations for other event types, including I/O, memory usage, and latency.
JSP technology has facilitated the segregation of the work of a Web designer and a Web developer.
A Web designer can design and formulate the layout for the Web page by using HTML.
On the other hand, a Web developer working independently can use java code and other JSP specific tags to code the business logic.
The simultaneous construction of the static and dynamic content facilitates development of quality applications with increased productivity.
Recently The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language.
파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥Seomgi Han
서버 자원의 효율성을 극대화하기 위해서는 흔히 비동기 프로그래밍 방식을 적용합니다. 파이썬에서도 비동기 프로그래밍 방식으로 웹서비스를 제공하기 위해서 여타 웹프레임워크 프로젝트가 탄생했습니다. Tornado부터 시작하여, Aiohttp, Sanic, Vibora 등과 같은 프로젝트가 이러한 목적을 갖고 있는 프로젝트입니다. 그 중에서도 Vibora나 Sanic 등과 같은 프로젝트는 서로 자기가 처리 능력이 좋다며 자랑하고 있습니다. 그 이유로 비동기 방식을 활용하기 때문이라고 하는데, 설명을 들여다보면 빠지지 않고 나오는 단어가 있습니다. 바로 uvloop입니다.
uvloop이 무엇인지 궁금하여 알아보면, 다시 libuv라는 라이브러리를 만날 수 있습니다.
이 프로그램에서는 libuv가 어떤 방향성을 갖고 디자인되었으며, 어떤 기능을 갖고 있기에 다수의 프로젝트에서 사용하게 되었는지, 파이썬의 기본 라이브러리인 asyncio와는 어떤 차이점이 있는지를 알아봅니다. 또한 파이썬으로 만들어진 몇몇 웹프레임워크가 어떤 처리 능력을 보여주는지 직접 테스트해본 결과를 공유합니다.
Servlet architecture comes under a java programming language used to create dynamic web applications. Mainly servlets are used to develop server-side applications. Servlets are very robust and scalable. Before introducing servlets, CGI (common gateway interface) was used.
This is a presentation I prepared for a local meetup. The audience is a mix of web designers and developers who have a wide range of development experience.
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConJérôme Petazzoni
Containers are everywhere. But what exactly is a container? What are they made from? What's the difference between LXC, butts-nspawn, Docker, and the other container systems out there? And why should we bother about specific filesystems?
In this talk, Jérôme will show the individual roles and behaviors of the components making up a container: namespaces, control groups, and copy-on-write systems. Then, he will use them to assemble a container from scratch, and highlight the differences (and likelinesses) with existing container systems.
PHP is the most commonly used server-side programming and deployed more than 80% in web server all over the world. However, PHP is a 'grown' language rather than deliberately engineered, making writing insecure PHP applications far too easy and common. If you want to use PHP securely, then you should be aware of all its pitfalls.
An Attacker's View of Serverless and GraphQL Apps - Abhay Bhargav - AppSec Ca...Abhay Bhargav
Serverless Technology (Functions as a Service) is fast becoming the next "big thing" in the world of distributed applications. Organizations are investing a great deal of resources in this technology as a force-multiplier, cost-saver and ops-simplification cure-all. Especially with widespread support from cloud vendors, this technology is going to only become more influential. However, like everything else, Serverless apps are subject to a a wide variety of attack possibilities, ranging from attacks against access control tech like Function Event Injection, JWTs, to NoSQL Injection, to exploits against the apps themselves (deserialization, etc) escalating privileges to other cloud component.
On the other hand GraphQL (API Query Language) is the natural companion to serverless apps, where traditional REST APIs are replaced with GraphQL to provide greater flexibility, greater query parameterization and speed. GraphQL is slowly negating the need for REST APIs from being developed. Combined with Serverless tech/Reactive Front-end frameworks, GraphQL is very powerful for distributed apps. However, GraphQL can be abused with a variety of attacks including but not limited to Injection Attacks, Nested Resource Exhaustion attacks, Authorization Flaws among others.
This talk presents a red-team perspective of the various ways in which testers can discover and exploit serverless and/or GraphQL driven applications to compromise sensitive information, and gain a deeper foothold into database services, IAM services and other other cloud components. The talk will have some demos that will demonstrate practical attacks and attack possibilities against Serverless and GraphQL applications.
Delivered as plenary at USENIX LISA 2013. video here: https://www.youtube.com/watch?v=nZfNehCzGdw and https://www.usenix.org/conference/lisa13/technical-sessions/plenary/gregg . "How did we ever analyze performance before Flame Graphs?" This new visualization invented by Brendan can help you quickly understand application and kernel performance, especially CPU usage, where stacks (call graphs) can be sampled and then visualized as an interactive flame graph. Flame Graphs are now used for a growing variety of targets: for applications and kernels on Linux, SmartOS, Mac OS X, and Windows; for languages including C, C++, node.js, ruby, and Lua; and in WebKit Web Inspector. This talk will explain them and provide use cases and new visualizations for other event types, including I/O, memory usage, and latency.
JSP technology has facilitated the segregation of the work of a Web designer and a Web developer.
A Web designer can design and formulate the layout for the Web page by using HTML.
On the other hand, a Web developer working independently can use java code and other JSP specific tags to code the business logic.
The simultaneous construction of the static and dynamic content facilitates development of quality applications with increased productivity.
Recently The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language.
파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥Seomgi Han
서버 자원의 효율성을 극대화하기 위해서는 흔히 비동기 프로그래밍 방식을 적용합니다. 파이썬에서도 비동기 프로그래밍 방식으로 웹서비스를 제공하기 위해서 여타 웹프레임워크 프로젝트가 탄생했습니다. Tornado부터 시작하여, Aiohttp, Sanic, Vibora 등과 같은 프로젝트가 이러한 목적을 갖고 있는 프로젝트입니다. 그 중에서도 Vibora나 Sanic 등과 같은 프로젝트는 서로 자기가 처리 능력이 좋다며 자랑하고 있습니다. 그 이유로 비동기 방식을 활용하기 때문이라고 하는데, 설명을 들여다보면 빠지지 않고 나오는 단어가 있습니다. 바로 uvloop입니다.
uvloop이 무엇인지 궁금하여 알아보면, 다시 libuv라는 라이브러리를 만날 수 있습니다.
이 프로그램에서는 libuv가 어떤 방향성을 갖고 디자인되었으며, 어떤 기능을 갖고 있기에 다수의 프로젝트에서 사용하게 되었는지, 파이썬의 기본 라이브러리인 asyncio와는 어떤 차이점이 있는지를 알아봅니다. 또한 파이썬으로 만들어진 몇몇 웹프레임워크가 어떤 처리 능력을 보여주는지 직접 테스트해본 결과를 공유합니다.
Servlet architecture comes under a java programming language used to create dynamic web applications. Mainly servlets are used to develop server-side applications. Servlets are very robust and scalable. Before introducing servlets, CGI (common gateway interface) was used.
This is a presentation I prepared for a local meetup. The audience is a mix of web designers and developers who have a wide range of development experience.
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConJérôme Petazzoni
Containers are everywhere. But what exactly is a container? What are they made from? What's the difference between LXC, butts-nspawn, Docker, and the other container systems out there? And why should we bother about specific filesystems?
In this talk, Jérôme will show the individual roles and behaviors of the components making up a container: namespaces, control groups, and copy-on-write systems. Then, he will use them to assemble a container from scratch, and highlight the differences (and likelinesses) with existing container systems.
PHP is the most commonly used server-side programming and deployed more than 80% in web server all over the world. However, PHP is a 'grown' language rather than deliberately engineered, making writing insecure PHP applications far too easy and common. If you want to use PHP securely, then you should be aware of all its pitfalls.
An Attacker's View of Serverless and GraphQL Apps - Abhay Bhargav - AppSec Ca...Abhay Bhargav
Serverless Technology (Functions as a Service) is fast becoming the next "big thing" in the world of distributed applications. Organizations are investing a great deal of resources in this technology as a force-multiplier, cost-saver and ops-simplification cure-all. Especially with widespread support from cloud vendors, this technology is going to only become more influential. However, like everything else, Serverless apps are subject to a a wide variety of attack possibilities, ranging from attacks against access control tech like Function Event Injection, JWTs, to NoSQL Injection, to exploits against the apps themselves (deserialization, etc) escalating privileges to other cloud component.
On the other hand GraphQL (API Query Language) is the natural companion to serverless apps, where traditional REST APIs are replaced with GraphQL to provide greater flexibility, greater query parameterization and speed. GraphQL is slowly negating the need for REST APIs from being developed. Combined with Serverless tech/Reactive Front-end frameworks, GraphQL is very powerful for distributed apps. However, GraphQL can be abused with a variety of attacks including but not limited to Injection Attacks, Nested Resource Exhaustion attacks, Authorization Flaws among others.
This talk presents a red-team perspective of the various ways in which testers can discover and exploit serverless and/or GraphQL driven applications to compromise sensitive information, and gain a deeper foothold into database services, IAM services and other other cloud components. The talk will have some demos that will demonstrate practical attacks and attack possibilities against Serverless and GraphQL applications.
JavaScript and popular programming paradigms (OOP, AOP, FP, DSL). Overview of the language to see what tools we can leverage to reduce complexity of our projects.
This part goes over more language features and looks at FP, and DSLs with JavaScript.
The presentation was delivered at ClubAJAX on 3/2/2010.
Blog post: http://lazutkin.com/blog/2010/mar/4/exciting-js-2/
Beginning is Part I: http://www.slideshare.net/elazutkin/exciting-javascript-part-i
The talk focuses on the processes and requirements to ship a software, which was written with MacRuby, to the end user. I present libraries and tools, that are helpful for this purpose and show how to use them.
Klepsydra is based in lock-free programming. This kind of programming is the high-level wrapper of the atomic operations in the processor, in particular the so-call compare-and-swap or CAS operation. It was invented back in the 70s, but it didn’t really become popular until the early 90s, when it was implemented in higher-level languages and then it really took off when Java included it in the early 2010s.
Lock-free programming consists of attempting repeatedly to write data in a small piece of memory until the data is in a consistent state. This is usually depicted as a plane trying to land in a busy airport. If the runway is busy, it flies away and then tries it once and again until success.
This technique is substantially lighter than the traditional mutex operation, because it is just specific to a one small piece of memory, as opposed to mutex, which blocks a big portion of the memory. That is why the traditional lock systems are not deterministic, while lock-free systems are more granular and deterministic. It works remarkably more efficient.
Our own ring buffer is wrapped in what we call the Klepsydra SDK. It is just another library that is installed in the operating system that receives data from multiple sources. It is essentially a memory sharing system.
https://klepsydra.com/klepsydra-ros-2-executor-a-ring-buffer-to-rule-them-all/
JavaScript and popular programming paradigms (OOP, AOP, FP, DSL). Overview of the language to see what tools we can leverage to reduce complexity of our projects.
This part goes over language features and looks at OOP and AOP with JavaScript.
The presentation was delivered at ClubAJAX on 2/2/2010.
Blog post: http://lazutkin.com/blog/2010/feb/5/exciting-js-1/
Continued in Part II: http://www.slideshare.net/elazutkin/exciting-javascript-part-ii
These slides, covering the topics of Software Maintenance and Evolution, are introductory slides to the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium
An introductory lecture on Context-Oriented Programming, part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium. This particular lecture was made by Dr. Sebastian Gonzalez in close collaboration with Prof. Kim Mens.
Software Reuse and Object-Oriented Programmingkim.mens
These slides on Software Reuse and Object-Oriented Programming are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium
These slides on Object-Oriented Design Heuristics are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium.
This presentation on Object-Oriented Application Frameworks is part of a larger course LINGI2252 on Software Maintenance and Evolution, given at UCL university in Belgium.
Towards a Context-Oriented Software Implementation Frameworkkim.mens
Context-aware systems must manage the dynamic selection, activation, and execution of feature variants according to changing contexts, detected from data gathered from their surrounding execution environment. Many context-oriented programming languages focus only on the implementation level by providing appropriate language abstractions for implementing behavioural variations that can adapt dynamically to changing contexts. They often ignore or presuppose the existence of mechanisms to deal with earlier aspects such as the gathering of sensory input and context discovery. In this presentation we discuss a layered software architecture that reconciles all these aspects in a single implementation framework, which can be customised by application programmers into actual context-aware applications. This framework and a simulator to test applications build using this framework we recently implemented in Ruby and Ruby on Rails.
Towards a Taxonomy of Context-Aware Software Variabilty Approacheskim.mens
Modern software systems demand more and more smart capabilities depending on their context of use, as well as the ability to dynamically adapt these capabilities according to sensed context changes. This requires appropriate techniques for modelling, representing and handling context-aware software variability. While traditional variability modelling approaches like feature orientation and software product lines are evolving to address the increased dynamicity and context specificity required for this new generation of software systems, new paradigms such as context-oriented programming have emerged. Although developed independently, since they address similar issues, many similarities exist between these approaches. The purpose of this work is to define, categorise and compare key concepts shared by these approaches.
Such a taxonomy is a first step towards a better understanding of the differences and similarities between different approaches for managing context-aware software variability, and to achieve a cross-fertilisation between them.
An introductory lecture on context-oriented programming, part of a full course on Programming Paradigms at UCL university in Belgium, focussing on reflection and meta programming techniques in a variety of languages. This particular lecture was made by Sebastian Gonzalez in close collaboration with Kim Mens.
An introduction to the basics of reflection and meta programming, part of a full lecture on programming paradigms at UCL university in Belgium, with reflection and meta programming as theme. (Further lectures focus more in depth on reflection and meta programming in a variety of programming languages such as Smalltalk, Ruby and Java.) Slides created collaboratively by Kim Mens and Roel Wuyts.
After a previous introductory lecture on the basics of reflection in Java, in this lecture we take a closer look at some more advanced reflective features of the language such as dynamic proxies, call stack introspection and instrumentation. This lecture is part of a full course on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
An introduction to the basics of reflection in the object-oriented programming language Java, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
An introduction to some advanced language features of the object-oriented programming language Ruby, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme. This lecture looks into the Ruby features of higher-order programming (lambdas), singleton methods, mixin modules, reflection and metaprogramming.
A quick introduction to the object-oriented programming language Smalltalk, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
A gentle and intuitive introduction to reflection and meta programming, part of a full lecture on programming paradigms at UCL university in Belgium, with reflection and meta programming as theme. (Further lectures focus more in depth on reflection and meta programming in a variety of languages such as Smalltalk, Ruby and Java.)
Managing the Evolution of Information Systems with Intensional Views and Rela...kim.mens
Like any software system, information systems suffer from structural inconsistencies that may arise during system evolution. Appropriate tools are needed to encode the structural regularities the system should adhere to, and to check conformance of the system against those regularities upon evolution. Taking inspiration from the intensional views approach to document and verify structural regularities in source code, we developed a similar tool to document and verify structural regularities in large databases. Regularities are expressed by the user at a high level in a graphical user interface, and then translated into relational algebra in order to check the regularities over the data. Discovered inconsistencies are presented back to the user in appropriate high-level data views. As a case study, the developed tool was successfully applied to a safety critical information system deployed at a large Belgian university. It is used by the rescue services to accurately locate users based on the location of their IP phones from which an emergency call was made.
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...University of Maribor
Slides from talk:
Aleš Zamuda: Remote Sensing and Computational, Evolutionary, Supercomputing, and Intelligent Systems.
11th International Conference on Electrical, Electronics and Computer Engineering (IcETRAN), Niš, 3-6 June 2024
Inter-Society Networking Panel GRSS/MTT-S/CIS Panel Session: Promoting Connection and Cooperation
https://www.etran.rs/2024/en/home-english/
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Sérgio Sacani
Since volcanic activity was first discovered on Io from Voyager images in 1979, changes
on Io’s surface have been monitored from both spacecraft and ground-based telescopes.
Here, we present the highest spatial resolution images of Io ever obtained from a groundbased telescope. These images, acquired by the SHARK-VIS instrument on the Large
Binocular Telescope, show evidence of a major resurfacing event on Io’s trailing hemisphere. When compared to the most recent spacecraft images, the SHARK-VIS images
show that a plume deposit from a powerful eruption at Pillan Patera has covered part
of the long-lived Pele plume deposit. Although this type of resurfacing event may be common on Io, few have been detected due to the rarity of spacecraft visits and the previously low spatial resolution available from Earth-based telescopes. The SHARK-VIS instrument ushers in a new era of high resolution imaging of Io’s surface using adaptive
optics at visible wavelengths.
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptxMAGOTI ERNEST
Although Artemia has been known to man for centuries, its use as a food for the culture of larval organisms apparently began only in the 1930s, when several investigators found that it made an excellent food for newly hatched fish larvae (Litvinenko et al., 2023). As aquaculture developed in the 1960s and ‘70s, the use of Artemia also became more widespread, due both to its convenience and to its nutritional value for larval organisms (Arenas-Pardo et al., 2024). The fact that Artemia dormant cysts can be stored for long periods in cans, and then used as an off-the-shelf food requiring only 24 h of incubation makes them the most convenient, least labor-intensive, live food available for aquaculture (Sorgeloos & Roubach, 2021). The nutritional value of Artemia, especially for marine organisms, is not constant, but varies both geographically and temporally. During the last decade, however, both the causes of Artemia nutritional variability and methods to improve poorquality Artemia have been identified (Loufi et al., 2024).
Brine shrimp (Artemia spp.) are used in marine aquaculture worldwide. Annually, more than 2,000 metric tons of dry cysts are used for cultivation of fish, crustacean, and shellfish larva. Brine shrimp are important to aquaculture because newly hatched brine shrimp nauplii (larvae) provide a food source for many fish fry (Mozanzadeh et al., 2021). Culture and harvesting of brine shrimp eggs represents another aspect of the aquaculture industry. Nauplii and metanauplii of Artemia, commonly known as brine shrimp, play a crucial role in aquaculture due to their nutritional value and suitability as live feed for many aquatic species, particularly in larval stages (Sorgeloos & Roubach, 2021).
Nutraceutical market, scope and growth: Herbal drug technologyLokesh Patil
As consumer awareness of health and wellness rises, the nutraceutical market—which includes goods like functional meals, drinks, and dietary supplements that provide health advantages beyond basic nutrition—is growing significantly. As healthcare expenses rise, the population ages, and people want natural and preventative health solutions more and more, this industry is increasing quickly. Further driving market expansion are product formulation innovations and the use of cutting-edge technology for customized nutrition. With its worldwide reach, the nutraceutical industry is expected to keep growing and provide significant chances for research and investment in a number of categories, including vitamins, minerals, probiotics, and herbal supplements.
Phenomics assisted breeding in crop improvementIshaGoswami9
As the population is increasing and will reach about 9 billion upto 2050. Also due to climate change, it is difficult to meet the food requirement of such a large population. Facing the challenges presented by resource shortages, climate
change, and increasing global population, crop yield and quality need to be improved in a sustainable way over the coming decades. Genetic improvement by breeding is the best way to increase crop productivity. With the rapid progression of functional
genomics, an increasing number of crop genomes have been sequenced and dozens of genes influencing key agronomic traits have been identified. However, current genome sequence information has not been adequately exploited for understanding
the complex characteristics of multiple gene, owing to a lack of crop phenotypic data. Efficient, automatic, and accurate technologies and platforms that can capture phenotypic data that can
be linked to genomics information for crop improvement at all growth stages have become as important as genotyping. Thus,
high-throughput phenotyping has become the major bottleneck restricting crop breeding. Plant phenomics has been defined as the high-throughput, accurate acquisition and analysis of multi-dimensional phenotypes
during crop growing stages at the organism level, including the cell, tissue, organ, individual plant, plot, and field levels. With the rapid development of novel sensors, imaging technology,
and analysis methods, numerous infrastructure platforms have been developed for phenotyping.
What is greenhouse gasses and how many gasses are there to affect the Earth.moosaasad1975
What are greenhouse gasses how they affect the earth and its environment what is the future of the environment and earth how the weather and the climate effects.
Seminar of U.V. Spectroscopy by SAMIR PANDASAMIR PANDA
Spectroscopy is a branch of science dealing the study of interaction of electromagnetic radiation with matter.
Ultraviolet-visible spectroscopy refers to absorption spectroscopy or reflect spectroscopy in the UV-VIS spectral region.
Ultraviolet-visible spectroscopy is an analytical method that can measure the amount of light received by the analyte.
Richard's aventures in two entangled wonderlandsRichard Gill
Since the loophole-free Bell experiments of 2020 and the Nobel prizes in physics of 2022, critics of Bell's work have retreated to the fortress of super-determinism. Now, super-determinism is a derogatory word - it just means "determinism". Palmer, Hance and Hossenfelder argue that quantum mechanics and determinism are not incompatible, using a sophisticated mathematical construction based on a subtle thinning of allowed states and measurements in quantum mechanics, such that what is left appears to make Bell's argument fail, without altering the empirical predictions of quantum mechanics. I think however that it is a smoke screen, and the slogan "lost in math" comes to my mind. I will discuss some other recent disproofs of Bell's theorem using the language of causality based on causal graphs. Causal thinking is also central to law and justice. I will mention surprising connections to my work on serial killer nurse cases, in particular the Dutch case of Lucia de Berk and the current UK case of Lucy Letby.
ESR spectroscopy in liquid food and beverages.pptxPRIYANKA PATEL
With increasing population, people need to rely on packaged food stuffs. Packaging of food materials requires the preservation of food. There are various methods for the treatment of food to preserve them and irradiation treatment of food is one of them. It is the most common and the most harmless method for the food preservation as it does not alter the necessary micronutrients of food materials. Although irradiated food doesn’t cause any harm to the human health but still the quality assessment of food is required to provide consumers with necessary information about the food. ESR spectroscopy is the most sophisticated way to investigate the quality of the food and the free radicals induced during the processing of the food. ESR spin trapping technique is useful for the detection of highly unstable radicals in the food. The antioxidant capability of liquid food and beverages in mainly performed by spin trapping technique.
Lateral Ventricles.pdf very easy good diagrams comprehensive
Introduction to Ruby
1. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Lecture 6 :
Introduction to Ruby
LSINF 2335
Programming Paradigms
Prof. Kim Mens
UCL / EPL / INGI
Partly inspired on :
• the pickaxe book “Programming Ruby” by Dave Thomas
• slides by Prof. Tom Mens (UMons)
• slides by Prof. Wolfgang De Meuter (VUB)
• an update to the slides made by Benoît Daloze (UCL)
3. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
What is Ruby?
■ Originally conceived by Yukihiro Matsumoto
– February 24, 1993, Japan
• first public release in 1995
• Feb 24, 2013: Ruby 2.0 release
– motivation:
• “wanted a scripting language [...] more powerful than Perl,
and more object-oriented than Python”
• wanted a natural and very expressive language in which
programmers can easily express themselves
– language named after a precious gemstone
• à la “Perl”
– is an open source project
3
4. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
What is Ruby?
■ Ruby is an interpreted, object-oriented,
dynamically typed programming language with
strong reflective and scripting facilities
– Compact syntax inspired by Python and Perl
– Semantics akin to dynamically class-based languages like
Smalltalk
– Scripting facilities akin to those of Python and Perl
• manipulation of text files
• file handling
• execution of system tasks
• support for regular expressions
• ... 4
5. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Ruby’s “killer app”
■ Ruby on Rails (a.k.a. “Rails” or “RoR”)
– Open-source web-application framework
– Implemented in Ruby
– Allows you to quickly create powerful web applications
– Based on model-view-controller pattern
– Web-application =
• Ruby program + database + webserver
5
6. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Scaffolding
■ “Scaffolding” in RoR is a particular use of meta-progamming to
construct database-backed web-applications
– essentially stub generation
■ [construction] : a temporary framework used to support people
and material in the construction or repair of large buildings
■ [programming] : a meta-programming technique for quickly
building software applications
– in RoR, rather than programming the application, the programmer specifies a
template from which the application code can be generated
• programmer specifies a template describing how the application
database may be used
• compiler uses this specification to generate application code
– to create, read, update and delete database entries
• template is a "scaffold" on which a more powerful application is built 6
8. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Getting started with Ruby
8
RUBY VERSION
Kim:~ kimmens$ ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin10.8.0]
Kim:~ kimmens$ irb -v
irb 0.9.6(09/06/30)
SIMPLE COMMAND PROMPT EXAMPLES
Kim:~ kimmens$ irb
>> 3+4
=> 7
>> "Kim"+"Mens"
=> "KimMens"
PRINTING
>> puts "Hello World"
Hello World
=> nil
>> 3.times { puts "Ruby" }
Ruby
Ruby
Ruby
=> 3
irb = Interactive Ruby
puts is a standard Ruby
method that writes its argument(s)
to the console, adding a newline
after each.
9. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Getting started with Ruby
9
METHOD DEFINITIONS
>> def product(n1,n2)
>> n1 * n2
>> end
=> nil
>> product(3,4)
=> 12
>> def fib(n)
>> if n <= 1 then n
>> else fib(n-1) + fib(n-2)
>> end
>> end
=> nil
>> fib(1)
=> 1
>> fib(3)
=> 2
>> fib(5)
=> 5
>> fib(10)
=> 55
10. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
10
VARIABLES
>> a=1
=> 1
>> b=2
=> 2
>> a+b
=> 3
>> a = ""
=> ""
>> 3.times { a = a + "Ruby" }
=> 3
>> a
=> "RubyRubyRuby"
LOADING FROM FILE
>> require "./SINF2335/Ruby/FactorialProgram.rb"
51090942171709440000
=> true
def factorial(n)
result = 1
(2..n).each do |i|
result *= i
end
result
end
puts factorial(21)
Getting started with Ruby
13. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Ruby’s language features
■ Purely object-oriented (everything is an object)
■ Dynamically typed
■ Message passing is only control-structure
■ Single class based inheritance
■ Automatic garbage collection
■ Exception handling
■ First-class closures (blocks)
■ Reflective facilities
■ Features for program evolution (e.g., mixins)
■ Embedded scripting facilities (e.g. regular expressions)
■ In addition, it comes with a large standard library
13
Like Smalltalk
14. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Everything is an object
# Numbers :
1 77.0 -12 12.5e23
# Symbols :
:a :red
# Strings :
"HellonWorld", 'Hello World'
# Booleans :
true false 1 < 2
# Arrays :
[] [1,2,3] [1,true,"Hello"]
# Hashes (a.k.a. dictionaries):
{ :PGD => 18, :GD => 16, :D => 14, :S => 12 }
# Even nil is an object (that happens to represent nothing)
# Even a class is an object 14
42.class => Fixnum
:foo.class => Symbol
"Ruby".class => String
true.class => TrueClass
[1,2,3].class => Array
{ :a => 1 }.class => Hash
nil.class => NilClass
Fixnum.class => Class
Similar to Smalltalk.
No primitive types as in Java.
15. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Message passing
# Parameterless messages
"Ruby".reverse()
# Kernel messages with parameters
Kernel.print("Ruby")
Kernel.print("Ruby","Ruby","Ruby")
# Message chaining
"Ruby".reverse().upcase().length()
# Undefined method error
"Ruby".foo()
# Arithmetic operators
-12.abs()
4.+(5)
"Ruby".*(3)
15
Every message send produces a
result (or an error)
receiver.message(arg1,arg2,...,argn)
receiver can be dropped
for Kernel methods
parentheses are optional
17. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Shorthand notation
# Parameterless messages
"Ruby".reverse
"Ruby".foo
# Messages with parameters
print "Ruby"
print "Ruby", "Ruby", "Ruby"
print("Ruby", "Ruby", "Ruby")
Message chaining
"Ruby".reverse.upcase.length
# Arithmetic operators
-12.abs
4 + 5
"Ruby" * 3
17
To avoid the problem of knowing
what argument goes with what
method call, use parentheses...
18. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Method naming conventions
# Predicate methods end by “?”
0.zero?
[1,2,3].include? 2
# Destructive methods by “!”
a = "Ruby"
a.reverse!
# For many destructive methods there is also a non-destructive variant
# Conversion methods start by to_
40.to_s.reverse
"40".to_i
(1..3).to_a
# Method names (usually) start with a lowercase letter
18
19. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Control structures
19
postfix notation :
if <cond>
<body>
elsif <cond>
<body>
else
<body>
end
while <cond>
<body>
end
<expression> while <cond>
<expression> if <cond>
<expression> unless <cond>
<expression> until <cond>
until <cond>
<body>
end
In Ruby, only nil and false do not
represent the truth in conditions
20. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Object creation
■ Ex-nihilo
– literal objects are created by writing them down without
an explicit constructor message
■ Instance creation method
– To create objects from classes
• Array.new, Hash.new, ComplexPolar.new(r,teta)
■ Initialize method
– initializes instance variables upon object creation
– is called by new, passing all parameters that were passed
to new
20
21. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Class definition
class ComplexCartesian
# Constructor method
def initialize(x,y)
@x = x # Instance variable
@y = y # Instance variable
end
# Method definitions
def r
Math.sqrt(@x**2 + @y**2)
end
def theta
Math.atan2(@y, @x)
end
end
# Instance creation
c = ComplexCartesian.new(1,2)
# Using the instance
puts c.r
21
Attention:
@x is an instance variable
(‘@’ is part of its name)
x is a normal variable
No separators for statements.
Each statement on a separate line.
Indentation is not significant.
No need to explicitly declare
instance variables
22. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Scoping and naming of Variables
■ Syntax:
– Global variables (globally visible)
$pi
– Class variables (same for all instances)
@@epsilon
– Instance variables (unique for each instance)
@x, @y
– Local (local to a method)
temp = y/x
– Block (parameters of a block)
{ |entry| entry * entry }
■ Rules:
– Variable names start with lowercase
– Constants start with uppercase and so most class and module names!
22
Variables are dynamically typed.
Variables don’t contain values
but pointers to objects (like in
Java or Smalltalk)
Global and class variables are
not often used.
25. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Access control
■ Ruby provides 3 levels of access control for methods
– checked at run-time, not statically
1. public
• can be called by anyone
• default when nothing is specified
2. protected
• can be called by any object of the defining class and its
subclasses, very rarely used
3. private
– only on implicit receiver ( meth(arg), not self.meth(arg) )
25
28. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Blocks
■ Blocks are “chunks of code”
– that can be passed to a method
– not really first-class functions
• but Ruby also has a notion of Procs which are first class objects (see later)
■ Examples
3.times { print "Ruby" } # prints 'Ruby' 3 times
3.times do print "Ruby" end # alternative syntax
['I', 'like', 'Ruby'].each do |entry| # using block to iterate
print entry, ' ' # over a collection
end
[1,2,3,4,5].map { |entry| entry * entry }
# => [1, 4, 9, 16, 25]
fact = 1
1.upto(5) { |i| fact *= i }
fact
Similar in usage to
Smalltalk blocks
(though not exactly the same)
29. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Yielding blocks
■ Blocks are chunks of code that can be passed to
methods
– for example to implement iterators
■ Those methods can execute that block when needed
– by using the yield keyword
29
def say_something
yield("I", "like")
yield("We all", "love")
end
say_something do |person, verb|
puts "#{person} #{verb} Ruby"
end
31. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Strings
■ Double quoted strings
– can contain special characters
"RubynRubynRubyn"
– and support expression extrapolation
"Good night, #{name}"
"Good night, #{name.capitalize}"
"#{$greeting}, #{@name}"
– and find-and-replace primitives
x = "RubynRubynRubyn"
x["Ruby"] = "Dear"
x => "DearnRubynRubyn"
– transform string into array of strings by line breaks
x.lines.to_a
– convert array of strings back in string with line breaks
x.join
31
Substitutes expression
#{expr} in the string by
its value converted by
to_s
Difference between
'...' and "..." is the
amount of processing
Ruby does on the string.
32. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
String manipulation
■ Break up a single string into an array
"RubynRubynRubyn".split("n")
■ Join an array of strings into a single string
["Ruby", "Ruby", "Ruby"].join("n")
■ Remove extra spaces before and at the end of a string
" Hello there ".strip # => "Hello there"
■ Arithmetic operators on strings
"Ruby" * 3 # => "RubyRubyRuby"
■ And many, many, many more:
upcase, capitalize, center, chars, chomp, end_with?, (g)sub, scan, ...
32
33. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Regular expressions
■ notation: /pattern/
/this|that/ # matches either 'this' or 'that'
/th(is|at)/ # use of parens in patterns
/ab+c/ # matches 'a', then one or more 'b', then 'c'
/ab*c/ # matches 'a', then zero or more 'b', then 'c'
/sdw./ # for whitespace, digit, character in word,
any character
■ matching
line =~ /this|that/ # matches string with pattern
line.sub(/this|that/, 'foo') # replaces first occurrence
line.gsub(/this|that/, 'foo') # replaces every occurrence
■ regular expressions are objects too
/this|that/.class # => Regexp
33
36. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Scripting, set mtime from exiftime
■ A simple script to set the modification time of a
JPG picture from its “time of capture”
#!/usr/bin/env ruby
Dir["**/*.{jpg,JPG}"].each do |picture|
times = `exiftime #{picture}`
.scan(/(?:d+:d+:d+ ?){2}/)
.map { |time| Time.new(*time.split(/W/) }
unless times.all? { |time| time == times.first }
raise "Not same times: #{times}"
end
File.utime(File.atime(picture), times.first, picture)
end
36
38. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Complex numbers in Ruby
Cartesian coordinates
38
class ComplexCartesian
EPSILON = 0.00000001
def initialize(x,y)
@x, @y = x, y
end
private
attr_writer :x, :y
public
attr_reader :x, :y
def r
@r ||= Math.hypot(x, y)
end
...
# Class definition
# Constant
# Initialize instance vars
# Use of Math module
# Parallel declaration
# Private methods from here
# Setter methods
# Public methods from here
# Getter method
# Getter method with lazy
initialization
@r ||= expr
is shorthand for
@r = @r || expr
which is shorthand for
39. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
39
class ComplexCartesian
...
def theta
@theta ||= Math.atan2(y,x)
end
def to_s
"#{x} + #{y}i"
end
def to_cartesian
self # nothing needs to be done
end
def to_polar
ComplexPolar.new(r, theta)
end
...
# Conversion method to string
# self refers to receiving
object
Complex numbers in Ruby (ctd.)
Cartesian coordinates
# Note the use of expression
extrapolation
to_s is called by Ruby
automatically whenever it
wants to print an object
# Instance creation
# More conversion methods
40. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
40
class ComplexCartesian
...
def ==(c)
same?(x, c.x) and same?(y, c.y)
end
private
def same?(x, y)
(x - y).abs < EPSILON
end
public
def +(c)
ComplexCartesian.new(self.x + c.x, self.y + c.y)
end
def *(c)
ComplexPolar.new(self.r * c.r, self.theta + c.theta)
end
...
end
# Equality method
# Auxilary method (private)
# Arithmetic operators
Complex numbers in Ruby (ctd.)
Cartesian coordinates
# Public methods again
# Use of constant
41. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
41
class ComplexPolar < ComplexCartesian
def initialize(r, theta)
@r, @theta = r, theta
end
def x
@x ||= @r * Math.cos(@theta)
end
def y
@y ||= @r * Math.sin(@theta)
end
private
attr_writer :r, :theta
public
attr_reader :r, :theta
...
# Inheritance
Complex numbers in Ruby
Polar coordinates
42. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
42
class ComplexPolar < ComplexCartesian
...
# to_s
# arithmetic operators
# private def same?(x,y)
def to_cartesian
ComplexCartesian.new(x,y)
end
def to_polar
self
end
def ==(c)
same?(r, c.r) and same?(theta, c.theta)
end
end
# Inherited methods
# Overridden method
Complex numbers in Ruby (ctd.)
Polar coordinates
43. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
43
require 'test/unit'
class TC_ComplexTest < Test::Unit::TestCase
def setup
@cc = ComplexCartesian.new(1, 1)
@cp = ComplexPolar.new(Math.sqrt(2), Math::PI / 4)
...
end
def test_self_comparison
assert_equal @cc, @cc
assert_equal @cp, @cp
end
def test_comparison_polar
assert_equal @cp, @cc.to_cartesian
assert_equal @cp, @cc.to_polar
end
def test_addition
assert_equal ComplexCartesian.new(2, 2), @cp + @cp
end
...
end
Complex numbers in Ruby
Unit testing
# import Test::Unit module
# define test class
# setup infrastructure
# test methods
# assert equality
44. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
44
require 'rspec'
describe 'Complex numbers' do
let :cartesian do
ComplexCartesian.new(1, 1)
end
let :polar do
ComplexPolar.new(Math.sqrt(2), Math::PI / 4)
end
it 'is identical to itself' do
cartesian.should == cartesian
polar.should == polar
end
it 'can be converted to the other type and still be equal' do
polar.to_cartesian.should == cartesian
cartesian.to_polar.should == polar
end
it 'supports addition' do
(cartesian + cartesian).should == ComplexCartesian.new(2, 2)
end
...
end
Complex numbers in Ruby
Behavioral testing with RSpec
# import RSpec gem
# define example group
# setup infrastructure
# example
# in natural order
46. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
■ Ruby has become a popular language
■ Very low-entry cost
– read-eval-print loop (irb, pry)
– plug-and-play
■ Easy digestible and readable syntax
■ Extensive libraries: Rubygems
■ Very powerful (compared to other main-stream applications)
■ “Killer-app”: Ruby-on-Rails
■ Advanced reflective and meta-programming facilities
■ Advanced scripting facilities
Conclusion
46
47. LSINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Conclusion
■ Some negative points
– automatic declaration of instance variables
– often things can be done in many different ways
(alternative syntax, shorthand notations)
• can be seen as positive: use the one that works best for you
• can be seen as negative: need to be able to read the one
that doesn’t work best for you as well
– a method in a subclass can override its parent method’s
visibility rules
47
class Base
def a_method
puts "Got here"
end
private :a_method
end
class Derived1 < Base
public :a_method
end
class Derived2 < Base
end