Expanded and updated version of my Strange Loop 2010 presentation on how to program in Google's Go language with an emphasis on the kind of tricks you might want to perform when implementing a language runtime.
Let's make a contract: the art of designing a Java APIMario Fusco
An API is what developers use to achieve some task. More precisely it establishes a contract between them and the designers of the software exposing its services through that API. In this sense we're all API designers: our software doesn't work in isolation, but becomes useful only when it interacts with other software written by other developers. When writing software we're not only consumers, but also providers of one or more API and that's why every developer should know the features of a good API. During this presentation we will go through real-world examples, also taken from the standard Java API, of good and bad API and comment them in order to show the dos and don'ts of API design. More in general we will discuss the characteristics of an easy and pleasant to use API, like consistency, discoverability and understandability, together with some basic concepts like the principle of least astonishment, and find out how to achieve them.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
Python is a high level language focused on readability. The Python community developed the concept of "Pythonic Code", requiring not only semantic correctness, but also conformity to universally acknowledged stylistic criteria.
A pre-requisite to write pythonic code is to write idiomatic code. Using the right idioms is a matter of acquired taste and experience, however, some idioms are quite easy to learn.
This presentation focuses on some of these idioms and other stylistic criteria:
* for vs. while
* iterators, itertools
* code conventions (space invaders)
* avoid default values bugs
* first order functions
* internal/external iterators
* substituting the switch statement
* properties, attributes, read only objects
* named tuples
* duck typings
* bits of metaprogramming
* exception management: LBYL vs. EAFP
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Most Scala developers are familiar with monadic precessing. Monads provide flatMap and hence for-comprehensions (syntactic sugar for map and flatMap).
Often we don't need Monads. Applicatives are sufficient in many cases.
In this talk I examine the differences between monadic and applicative processing and give some guide lines when to use which.
After a closer look to the Applicative trait I will contrast the gist of Either and cats.data.Validated (the latter being an Applicative but not a Monad).
I will also look at traversing and sequencing which harness Applicatives as well.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
Let's make a contract: the art of designing a Java APIMario Fusco
An API is what developers use to achieve some task. More precisely it establishes a contract between them and the designers of the software exposing its services through that API. In this sense we're all API designers: our software doesn't work in isolation, but becomes useful only when it interacts with other software written by other developers. When writing software we're not only consumers, but also providers of one or more API and that's why every developer should know the features of a good API. During this presentation we will go through real-world examples, also taken from the standard Java API, of good and bad API and comment them in order to show the dos and don'ts of API design. More in general we will discuss the characteristics of an easy and pleasant to use API, like consistency, discoverability and understandability, together with some basic concepts like the principle of least astonishment, and find out how to achieve them.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
Python is a high level language focused on readability. The Python community developed the concept of "Pythonic Code", requiring not only semantic correctness, but also conformity to universally acknowledged stylistic criteria.
A pre-requisite to write pythonic code is to write idiomatic code. Using the right idioms is a matter of acquired taste and experience, however, some idioms are quite easy to learn.
This presentation focuses on some of these idioms and other stylistic criteria:
* for vs. while
* iterators, itertools
* code conventions (space invaders)
* avoid default values bugs
* first order functions
* internal/external iterators
* substituting the switch statement
* properties, attributes, read only objects
* named tuples
* duck typings
* bits of metaprogramming
* exception management: LBYL vs. EAFP
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Most Scala developers are familiar with monadic precessing. Monads provide flatMap and hence for-comprehensions (syntactic sugar for map and flatMap).
Often we don't need Monads. Applicatives are sufficient in many cases.
In this talk I examine the differences between monadic and applicative processing and give some guide lines when to use which.
After a closer look to the Applicative trait I will contrast the gist of Either and cats.data.Validated (the latter being an Applicative but not a Monad).
I will also look at traversing and sequencing which harness Applicatives as well.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
After 10 years of Object Orientated Java, 2 years of Functional Programming in Scala was enough to convince me that I could never switch back. But why? The answer is simple: Functional Scala lets you think less. It reduces the number of moving parts you need to hold in your head, lets you stay focussed and saves your mental stack from overflowing.
In this talk I'll show you how to stop treating Scala as a better Java and start exploring the world of Functional Programming. I'll use code examples to demonstrate a four step path that'll let you ease yourself into the world of Functional Programming while continuing to deliver production quality code.
With each step we'll learn a new technique, and understand how it leaves you with less to think about: Hopefully this talk will convince you that Functional Scala leads to code that's easier to hold in your head, and leave you excited about learning a new paradigm.
Presentation for Android Developers about why they should consider using Kotlin. Key features of the language are discussed in comparison with Java. #LanguageChoiceMatters
http://blog.jimbaca.com
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
The Present and The Future of Functional Programming in C++Alexander Granin
Keynote talk for C++ Siberia 2019.
I'm speaking about why Functional Programming is important in C++ world, what is the philosophy of FP in C++, and what features do we have. I'm presenting a connection of constexpr and template metaprogramming to pure FP, and talking about why monads are inevitable. I'm also discussing an upcoming features in C++.
Go is a language developed by Google with multi-core in mind. Differ from other languages, concurrency is a first-class primitive in Go. This talk covers some useful patterns for dealing with concurrency.
The first cut of a talk on the R&D process in software development, including taking an invention to patent.
Includes two sets of code examples. One is Forth implemented in a 1980s dialect of Basic.
The other introduces evolutionary prototyping using a hybrid ruby/bash methodology.
Generics, Reflection, and Efficient CollectionsEleanor McHugh
This is a talk about how we structure and collate information so as to effectively process it, the language tools Go provides to help us do this, and the sometimes frustrating tradeoffs we must make when marry the real world with the digital.
We'll start by looking at basic collection types in Go: array, slice, map, and channel. These will then be used as the basis for our own user defined types with methods for processing the collected items.
These methods will then be expanded to take functions as parameters (the higher order functional style popularised by languages such as Ruby) and by using Go's Reflection package we will generalise them for a variety of tasks and uses cases.
Reflection adds an interpreted element to our programs with a resulting performance cost. Careful design can often minimise this cost and it may well amortise to zero on a sufficiently large collection however there is always greater code complexity to manage. When the data to be contained in a user defined collection is homogenous we can reduce much of this complexity by using Generics and our next set of examples will demonstrate this.
At the end of this talk you should have some useful ideas for designing your own collection types in Go as well as a reasonable base from which to explore Reflection, Generics, and the Higher-Order Functional style of programming.
Go for the paranoid network programmer, 3rd editionEleanor McHugh
Draft third edition of my #golang network programming and cryptography talk given to the Belfast Gophers Meetup. Now with an introduction to websockets.
An introduction to functional programming with goEleanor McHugh
A crash course in functional programming concepts using Go. Heavy on code, light on theory.
You can find the examples at https://github.com/feyeleanor/intro_to_fp_in_go
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Digital Identity talk from Strange Loop 2018 and Build Stuff Lithuania 2018 including walkthrough of the uPass system and the design principles behind it.
Don't Ask, Don't Tell - The Virtues of Privacy By DesignEleanor McHugh
This is a fairly technical overview of the considerations involved in architecting software systems to support privacy. Rather than focus on what the law demands - something which can change across time and jurisdictions - it looks at the real problems we need to solve to know as little about the users of computer systems as possible whilst achieving their needs.
Don't ask, don't tell the virtues of privacy by designEleanor McHugh
A very light intro talk on privacy, identity, and designing with the latter to preserve the former.
Probably makes no sense at all without the audio so if it whet's your appetite dig through my other decks on these topics. Most of those have code in for the more technically minded.
An overview of the uPass digital identity system. Covers the core problem domain and the end-to-end stack from liveness to black-box transaction store. Lots of diagrams, references to all the relevant patent applications and so forth.
An introduction to Go from basics to web through the lens of "Hello World", extracted from the Book "A Go Developer's Notebook" available from http://leanpub.com/GoNotebook
Finding a useful outlet for my many Adventures in goEleanor McHugh
A talk about my Leanpub-published living eBook: A Go Developer's Notebook. Buy my book? Write your own Book using Leanpub? Learn you some Golang for fun?
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
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/
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
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.
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/
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
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
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
2. portrait of an artist...
physics major
http:/ feyele
embedded controllers
/
software reliability
dynamic languages
network scaling or.tel an
questionable taste in music Elean or McHugh
8. Elric sent his mind into twisting tunnels of logic,
across endless plains of ideas, through mountains
of symbolism and endless universes of alternate
truths; he sent his mind out further and further
and as it went he sent with it the words which
issued from his writhing lips -- words that few
of his contemporaries would understand...
- Elric of Melniboné, Michael Moorcock
15. agnostic
no blessed programming languages
flexible platform abstractions
write once, run everywhere it matters
16. heterogeneous
a system comprises many components
components may differ in purpose and design
but they cooperate to solve problems
17. virtualisation
design discrete Turing machines
implement these machines in software
compile programs to run on them
18. networks
machines cooperate by sending messages
machine states can be serialised as messages
messages transcend process and host boundaries
19. caveat lector
danger! we’re entering strange territory
our map is missing major landmarks
and will be riddled with inaccuracies
so please tread carefully
try not to disturb the local wildlife
and don’t be put off by the pages of code
21. an elegant language
a statically-typed compiled language
object-oriented
static type declaration
dynamic type inference
garbage collection
concurrency via communication (CSP)
48. package adder
import "testing"
func TestFAdder(t *testing.T) {
error := "Result %v != %v"
f := FAdder{0.0, 1.0, 2.0}
f.Add(1)
if f.Result().(float32) != 1.0 { t.Fatalf(error, f.Result(), 1.0) }
f.Subtract(2)
if i.Result().(float32) != -1.0 { t.Fatalf(error, i.Result()), -1.0 }
var r Calculator = FAdder{-1.0, 1.0, 2.0}
for n, v := range r.(FAdder) {
if f[n] != v { t.Fatalf("Adder %v should be %v", f, r) }
}
r.Reset()
if r.Result().(float32) != *new(float32) {
t.Fatalf(error, r.Result(), *new(float32))
}
}
49. package adder
import "testing"
func TestAddingMachine(t *testing.T) {
error := "Result %v != %v"
a := &AddingMachine{ Adder: FAdder{0.0, 1.0, 2.0} }
a.Add(1)
if f, ok := a.Result().(float32); !ok {
t.Fatal("Result should be a float32")
} else if f != 1.0 {
t.Fatalf(error, a.Result(), 1.0)
}
a.Subtract(2)
if a.Result().(float32) != -1.0 { t.Fatalf(error, a.Result(), -1.0) }
r := FAdder{-1.0, 1.0, 2.0}
for n, v := range a.Adder.(FAdder) {
if r[n] != v { t.Fatalf("Adder %v should be %v", a, r) }
}
}
50. package generalise
import "reflect"
func Allocate(i interface{}, limit... int) (n interface{}) {
v := reflect.NewValue(i)
switch v := v.(type) {
case *reflect.SliceValue:
l := v.Cap()
if len(limit) > 0 { l = limit[0] }
t := v.Type().(*reflect.SliceType)
n = reflect.MakeSlice(t, l, l).Interface()
case *reflect.MapValue:
t := v.Type().(*reflect.MapType)
n = reflect.MakeMap(t).Interface()
}
return
}
51. package generalise
import . "reflect"
func SwapSlices(i interface{}, d, s, n int) {
if v, ok := NewValue(i).(*SliceValue); ok {
source := v.Slice(s, s + n)
destination := v.Slice(d, d + n)
temp := NewValue(Allocate(i, n)).(*SliceValue)
Copy(temp, destination)
Copy(destination, source)
Copy(source, temp)
} else {
panic(i)
}
}
52. package generalise
import . "reflect"
func Duplicate(i interface{}) (clone interface{}) {
if clone = Allocate(i); clone != nil {
switch clone := NewValue(clone).(type) {
case *SliceValue:
s := NewValue(i).(*SliceValue)
Copy(clone, s)
case *MapValue:
m := NewValue(i).(*MapValue)
for _, k := range m.Keys() {
clone.SetElem(k, m.Elem(k))
}
}
}
return
}
65. package main
import "fmt"
func main() {
var c chan int
c = make(chan int)
go func() {
for {
fmt.Print(<-c)
}
}()
for {
select {
case c <- 0:
case c <- 1:
}
}
} produces:
01100111010110...
66. package main
import "fmt"
func main() {
var c chan int
c = make(chan int, 16)
go func() {
for {
fmt.Print(<-c)
}
}()
go func() {
select {
case c <- 0:
case c <- 1:
}
}()
for {} produces:
} 01100111010110...
67. package generalise
import . "reflect"
type SignalSource func(status chan bool)
func (s SignalSource) Wait() {
done := make(chan bool)
defer close(done)
go s(done)
<-done
}
func (s SignalSource) WaitAll(count int) {
done := make(chan bool)
defer close(done)
go s(done)
for i := 0; i < count; i++ {
<- done
}
}
68. package generalise
type Iteration func(k, x interface{})
func (i Iteration) apply(k, v interface{}, c chan bool) {
go func() {
i(k, v)
c <- true
}()
}
70. package generalise
import . "reflect"
type Results chan interface{}
type Combination func(x, y interface{}) interface{}
func (f Combination) Reduce(c, s interface{}) (r Results) {
r = make(Results)
go func() {
Iteration(func(k, x interface{}) {
s = f(s, x)
}).Each(c)
r <- s
}()
return
}
86. package main
import . “clock”
func main() {
c := Clock{1000, make(chan int64), make(chan bool), false}
c.Start()
for i := 0; i < 3; i++ {
println("pulse value", <-c.Count, "from clock")
}
println("disabling clock")
c.Control <- false
syscall.Sleep(1000000)
println("restarting clock")
c.Control <- true
println("pulse value", <-c.Count, "from clock")
}
87. OSX 10.6.2 Intel Atom 270 @ 1.6GHz:
pulse value 0 from clock
pulse value 1 from clock
pulse value 2 from clock
disabling clock
restarting clock
pulse value 106 from clock
OSX 10.6.7 Intel Core 2 Duo @ 2.4GHz:
pulse value 0 from clock
pulse value 1 from clock
pulse value 2 from clock
disabling clock
restarting clock
pulse value 154 from clock
93. package instructions
import "fmt"
type Operation func(o []int)
type Executable interface {
Opcode() int
Operands() []int
Execute(op Operation)
}
const INVALID_OPCODE = -1
type Program []Executable
func (p Program) Disassemble(a Assembler) {
for _, v := range p { fmt.Println(a.Disassemble(v)) }
}
94. package instructions
type Instruction []int
func (i Instruction) Opcode() int {
if len(i) == 0 { return INVALID_OPCODE }
return i[0]
}
func (i Instruction) Operands() []int {
if len(i) < 2 { return []int{} }
return i[1:]
}
func (i Instruction) Execute(op Operation) {
op(i.Operands())
}
95. package instructions
type Assembler struct {
opcodes map[string] int
names map[int] string
}
func NewAssember(names... string) (a Assembler) {
a = Assembler{ make(map[string] int), make(map[int] string) }
a.Define(names...)
return
}
func (a Assembler) Define(names... string) {
for _, name := range names {
a.opcodes[name] = len(a.names)
a.names[len(a.names)] = name
}
}
96. package instructions
func (a Assembler) Assemble(name string, params... int) (i Instruction) {
i = make(Instruction, len(params) + 1)
switch opcode, ok := a.opcodes[name]; {
case ok:! i[0] = opcode
!
default:!! i[0] = INVALID_OPCODE
}
copy(i[1:], params)
return
}
97. package instructions
import "fmt"
func (a Assembler) Disassemble(e Executable) (s string) {
if name, ok := a.names[e.Opcode()]; ok {
s = name
if params := e.Operands(); len(params) > 0 {
s = fmt.Sprintf("%vt%v", s, params[0])
for _, v := range params[1:] {
s = fmt.Sprintf("%v, %v", s, v)
}
}
} else {
s = "unknown"
}
return
}
98. package main
import . “instructions”
func main() {
a := NewAssembler("noop", "load", "store")
p := Program{ a.Assemble("noop"),
a.Assemble("load", 1),
a.Assemble("store", 1, 2),
a.Assemble("invalid", 3, 4, 5) }
p.Disassemble(a)
for _, v := range p {
if len(v.Operands()) == 2 {
v.Execute(func(o []int) { o[0] += o[1] })
println("op =", v.Opcode(), "result =", v.Operands()[0])
}
}
}
99. produces:
noop
load! ! 1
store!1, 2
unknown
op = 2 result = 3