How many ways do you know to do iteration with JavaScript and Node.js? While, for loop, for…in, for..of, .map(), .forEach(), streams, iterators, etc! Yes, there are a lot of ways! But did you know that JavaScript has iteration protocols to standardise synchronous and even asynchronous iteration? In this workshop we will learn about these protocols and discover how to build iterators and iterable objects, both synchronous and asynchronous. We will learn about some common use cases for these protocols, explore generators and async generators (great tools for iteration) and finally discuss some hot tips, common pitfalls, and some (more or less successful) wild ideas!
This code implements a tic-tac-toe game that can be played between two humans or a human and computer. It includes functions to create and print the game board, check for a draw, and check if a move resulted in a win. The main function handles parsing command line arguments, running the game loop, and cleaning up memory.
At the time of writing, React hooks are still in alpha but they can already be used and, since it takes a while to get used to them, it's better to understand them as soon as possible. In this talk we will see some use cases in which we refactor a class component into a hook-based functional component.
The document discusses how to use RxJS (Reactive Extensions library for JavaScript) to treat events like arrays by leveraging Observable types and operators. It explains key differences between Observables and Promises/Arrays, how Observables are lazy and cancelable unlike Promises. Various RxJS operators like map, filter, interval and fromEvent are demonstrated for transforming and composing Observable streams. The document aims to illustrate how RxJS enables treating events as collections that can be processed asynchronously over time.
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
In Java using Eclipse, I\'m suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use \'X\' or \'O\' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with \' \' for all cells)
// First, welcome message and display the board.
System.out.println(\"===== WELCOME TO THE TIC-TAC-TOE GAME!! =====\ \");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(\" Which symbol do you want to play, \\\"x\\\" or \\\"o\\\"? \");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == \'x\') ? \'o\' : \'x\';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(\" Do you want to go first (y/n)? \");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == \'y\') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(\"\ ** YOU WON. CONGRATULATIONS!! **\");
else if (winner == 1)
System.out.println(\"\ ** YOU LOST.. Maybe next time :) **\");
else
System.out.println(\"\ ** DRAW... **\");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = \' \';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column he.
The document describes a Haskell program that translates characters in one string to characters in another string. It defines a translate function that maps characters from the first string (set1) to the corresponding characters in the second string (set2). A translateString function applies the translate function to a given string, and the main function gets the set1 and set2 strings from arguments, reads stdin, applies translateString, and writes the result to stdout, catching any errors.
1. Rxjs provides a better way of handling asynchronous code through observables which are streams of values over time. Observables allow for cancellable, retryable operations and easy composition of different asynchronous sources.
2. Common Rxjs operators like map, filter, and flatMap allow transforming and combining observable streams. Operators make observables quite powerful for tasks like async logic, event handling, and API requests.
3. In Angular, observables are used extensively for tasks like HTTP requests, routing, and component communication. Key aspects are using async pipes for subscriptions and unsubscribing during lifecycle hooks. Rxjs greatly simplifies many common asynchronous patterns in Angular applications.
1. The document contains 12 C programming questions and their solutions ranging from calculating factorials and Fibonacci sequences to matrix operations like addition, multiplication, and inverse.
2. The questions cover basic programming concepts like loops, conditionals, functions as well as mathematical concepts like prime numbers, series, and matrix algebra.
3. The solutions provided implement the required logic to solve each problem using standard C syntax and functions.
This code implements a tic-tac-toe game that can be played between two humans or a human and computer. It includes functions to create and print the game board, check for a draw, and check if a move resulted in a win. The main function handles parsing command line arguments, running the game loop, and cleaning up memory.
At the time of writing, React hooks are still in alpha but they can already be used and, since it takes a while to get used to them, it's better to understand them as soon as possible. In this talk we will see some use cases in which we refactor a class component into a hook-based functional component.
The document discusses how to use RxJS (Reactive Extensions library for JavaScript) to treat events like arrays by leveraging Observable types and operators. It explains key differences between Observables and Promises/Arrays, how Observables are lazy and cancelable unlike Promises. Various RxJS operators like map, filter, interval and fromEvent are demonstrated for transforming and composing Observable streams. The document aims to illustrate how RxJS enables treating events as collections that can be processed asynchronously over time.
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
In Java using Eclipse, I\'m suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use \'X\' or \'O\' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with \' \' for all cells)
// First, welcome message and display the board.
System.out.println(\"===== WELCOME TO THE TIC-TAC-TOE GAME!! =====\ \");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(\" Which symbol do you want to play, \\\"x\\\" or \\\"o\\\"? \");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == \'x\') ? \'o\' : \'x\';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(\" Do you want to go first (y/n)? \");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == \'y\') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(\"\ ** YOU WON. CONGRATULATIONS!! **\");
else if (winner == 1)
System.out.println(\"\ ** YOU LOST.. Maybe next time :) **\");
else
System.out.println(\"\ ** DRAW... **\");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = \' \';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column he.
The document describes a Haskell program that translates characters in one string to characters in another string. It defines a translate function that maps characters from the first string (set1) to the corresponding characters in the second string (set2). A translateString function applies the translate function to a given string, and the main function gets the set1 and set2 strings from arguments, reads stdin, applies translateString, and writes the result to stdout, catching any errors.
1. Rxjs provides a better way of handling asynchronous code through observables which are streams of values over time. Observables allow for cancellable, retryable operations and easy composition of different asynchronous sources.
2. Common Rxjs operators like map, filter, and flatMap allow transforming and combining observable streams. Operators make observables quite powerful for tasks like async logic, event handling, and API requests.
3. In Angular, observables are used extensively for tasks like HTTP requests, routing, and component communication. Key aspects are using async pipes for subscriptions and unsubscribing during lifecycle hooks. Rxjs greatly simplifies many common asynchronous patterns in Angular applications.
1. The document contains 12 C programming questions and their solutions ranging from calculating factorials and Fibonacci sequences to matrix operations like addition, multiplication, and inverse.
2. The questions cover basic programming concepts like loops, conditionals, functions as well as mathematical concepts like prime numbers, series, and matrix algebra.
3. The solutions provided implement the required logic to solve each problem using standard C syntax and functions.
Digital Voltmeter displaying voltage level on a seven segment display and com...Karthik Rathinavel
• Coded an Altera FPGA board in System Verilog such that it could use the on board ADC to convert the voltage signal into a digital signal, that was displayed on a seven segment display as well as on a computer screen.
• Utilized a UART (USB to serial) to receive the voltage signal that was to be displayed on a computer.
• Controlled the selection of channel for analog input by transmitting the serial data through the UART from the computer keyboard.
This is the Java code i have for a Battleship project i am working o.pdfcalderoncasto9163
This is the Java code i have for a Battleship project i am working on, i am now wanting to
convert this to a fully graphical Gui interface, but i just cant seem to get anywhere with it, so if i
could get some help with this, i would apperciate it....(just a reminder its in JAVA)
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coordinates = getCoordinates(input);
int row = coordinates[0];
int column = coordinates[1];
ocean.shootAt(row, column);
availableSpot[row][column] = false;
isGameOver = o.
The document discusses RxJS, a library for reactive programming using Observables that provide an API for asynchronous programming with observable streams. It provides code examples of using RxJS to handle events, AJAX requests, and animations as Observables. It also compares RxJS to Promises and native JavaScript event handling, and lists several frameworks that use RxJS like Angular and Redux.
Amazing threesome, rrr... React. Redux. Real world / Ростислав Галкин (Babo)Ontico
"Все гениальное просто" — таким бы мог быть слоган Redux, одной из имплементаций FLUX-архитектуры, которой 31 мая исполняется ровно год. И вот уже практически год, как мы приняли решение использовать Redux в наших проектах. Это был осознанный риск, о котором мы ничуть не пожалели.
За этот год мы научились писать тестируемый код, избегать мутаций и применять методы оптимизации для выбранного стека. Также нам пришлось написать собственные решения для инкапсуляции состояния при написании переиспользуемых компонент и для работы с формами произвольной глубины вложенности, а также мы написали свою сетку для отображения бесконечного числа элементов.
Кроме этого, на больших нагрузках мы столкнулись с проблемами производительности рендеринга на сервере в изоморфном приложении и с успехом их решили.
Обо всем этом я расскажу в своем докладе, поделюсь тем опытом и ощущениями, которые мне лично удалось получить за время работы с React и Redux.
This document discusses React, Redux, and real-world applications. It covers topics like universal rendering, testing Redux reducers, connecting React components to Redux, using immutable data structures with Redux, performing calculations with Redux and Reselect for memoization, asynchronous actions with thunk and saga middleware, isolating Redux state for reusable components, and comparing Redux architecture to ELM.
Taming Distribution: Formal Protocols for Akka TypedRoland Kuhn
Cloud computing, reactive systems, microservices: distributed programming has become the norm. But while the shift to loosely coupled message-based systems has manifest benefits in terms of resilience and elasticity, our tools for ensuring correct behavior has not grown at the same pace. Statically typed languages like Java and Scala allow us to exclude large classes of programming errors before the first test is run. Unfortunately, these guarantees are limited to the local behavior within a single process, the compiler cannot tell us that we are sending the wrong JSON structure to a given web service. Therefore distribution comes at the cost of having to write large test suites, with timing-dependent non-determinism.
In this presentation we take a first peek at ways out of this dilemma. The principles are demonstrated on the simplest distributed system: Actors. We show how parameterized ActorRefs à la Akka Typed together with effect tracking similar to HLists can help us define what an Actor can and cannot do during its lifetime—and have the compiler yell at us when we do it wrong.
aming distribution: formal protocols for Akka TypedJ On The Beach
Cloud computing, reactive systems, microservices: distributed programming has become the norm. But while the shift to loosely coupled message-based systems has manifest benefits in terms of resilience and elasticity, our tools for ensuring correct behavior has not grown at the same pace. Statically typed languages like Java and Scala allow us to exclude large classes of programming errors before the first test is run. Unfortunately, these guarantees are limited to the local behavior within a single process, the compiler cannot tell us that we are sending the wrong JSON structure to a given web service. Therefore distribution comes at the cost of having to write large test suites, with timing-dependent non-determinism.
In this presentation we take a first peek at ways out of this dilemma. The principles are demonstrated on the simplest distributed system: Actors. We show how parameterized ActorRefs à la Akka Typed together with effect tracking similar to HLists can help us define what an Actor can and cannot do during its lifetime—and have the compiler yell at us when we do it wrong.
1. The document discusses various Python programming concepts like data types, operators, conditional statements, loops etc. through examples.
2. It shows the use of basic operators like arithmetic, comparison, logical and bitwise operators on integers, floats, strings.
3. Conditional statements like if-else and if-elif-else are demonstrated to check conditions and execute code blocks accordingly.
4. Loops like for and while are used to iterate through a sequence or repeat code execution based on a condition. Range function is used to generate sequences for for loops.
The document describes the objectives of a C++ lab course. It includes:
1. Designing classes with static members, methods with default arguments, and friend functions like a matrix and vector class.
2. Implementing a complex number class with operator overloading.
3. Implementing a matrix class with dynamic memory allocation.
4. Overloading new and delete operators for custom memory allocation.
5. Developing linked list and sorting algorithm templates.
In this talk, I’m introducing Pegomock, a mocking framework for Go, that I have written over the last 2 years. By quickly going through the idea of Dependency Injection, I'm explaining why mocks are useful in general. Afterwards, I'm diving a bit deeper into how to use Pegomock and why I think it is better than its alternatives.
i have a runable code below that works with just guessing where the .pdfarmcomputers
i have a runable code below that works with just guessing where the ships are. i need help editing
this code to be able to have a player play against computer and taking turns playing battleship.
BattleShipGame.java
package battleship;
import java.util.ArrayList;
import java.util.Scanner;
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coordinates = getCoordinates(input);
int row = coordinates[0];
int column = coordinates[1];
ocean.shootAt(row, column);
availableSpot[row][column] = false;
isGa.
The document summarizes lambda expressions and concurrency APIs in C++. It provides examples of lambda expressions with different capture modes. It also discusses features of concurrency APIs like std::future, std::promise, std::packaged_task and how to use them to asynchronously execute tasks and retrieve/propagate results and exceptions.
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...Luciano Mammino
The document discusses using iterator combinators in Rust to solve an Advent of Code puzzle in a more functional style compared to a classic imperative approach. It shows code to parse input data into batches, map lines to values, sum the values, and take the maximum. It then extends this to sort batches descending and take the top 3 sums to solve part 2 of the puzzle in a flexible way using combinators.
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoLuciano Mammino
The document outlines steps to build an invite-only website using Next.js and Airtable. It discusses:
1) Organizing guest data like name and favorite color in an Airtable database.
2) Setting up a Next.js project and retrieving invite data from Airtable using its API and creating an Invite interface.
3) Creating a Next.js API to fetch invite data based on an invite code parameter.
A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns come in three different categories. Creational patterns include the generation of object instances. Structure refers to how an object is made and how things behave and interact In this Webinar(Live Meetup) we will be covering - What is node js - When to use node js - Async I/O operations in node js - Advantages of Async/Await - Some interesting - async patterns - Performance comparison
Let's build a 0-cost invite-only website with Next.js and Airtable!Luciano Mammino
The document describes building an invite-only website using Next.js and Airtable. It outlines:
1) Organizing guest data like names and preferences in an Airtable database.
2) Creating a Next.js project and APIs to retrieve invite data from Airtable by invite code.
3) Authenticating access to Next.js pages by checking for a valid invite code parameter.
Almost every web application at some point needs a way to upload or download files… and no one seems to enjoy building reliable and scalable upload/download servers… and for good reasons too! In fact, you’ll probably need to manage long-running connections and handle files that can be quite large (i.e videos). If you are running a fully serverless backend using API Gateway and Lambda, you probably know that you are limited in terms of payload size and execution time, so things get even more complicated there. In all these cases you should consider offloading this problem to S3 by using S3 pre-signed URLs. Pre-signed URLs are a fantastic tool to handle file download and upload directly in S3 in a managed and scalable fashion. But all that glitters is not gold and S3 pre-signed URLs come with quite a few gotchas… So in this talk, we will explore some use cases, see some potential implementations of S3 pre-signed URLs and uncover some of the gotchas that I discovered while using them. By the end of this talk, you should know exactly when to use pre-signed URLs and how to avoid most of the many mistakes I made with them!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
Mais conteúdo relacionado
Semelhante a Did you know JavaScript has iterators? DublinJS
Digital Voltmeter displaying voltage level on a seven segment display and com...Karthik Rathinavel
• Coded an Altera FPGA board in System Verilog such that it could use the on board ADC to convert the voltage signal into a digital signal, that was displayed on a seven segment display as well as on a computer screen.
• Utilized a UART (USB to serial) to receive the voltage signal that was to be displayed on a computer.
• Controlled the selection of channel for analog input by transmitting the serial data through the UART from the computer keyboard.
This is the Java code i have for a Battleship project i am working o.pdfcalderoncasto9163
This is the Java code i have for a Battleship project i am working on, i am now wanting to
convert this to a fully graphical Gui interface, but i just cant seem to get anywhere with it, so if i
could get some help with this, i would apperciate it....(just a reminder its in JAVA)
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coordinates = getCoordinates(input);
int row = coordinates[0];
int column = coordinates[1];
ocean.shootAt(row, column);
availableSpot[row][column] = false;
isGameOver = o.
The document discusses RxJS, a library for reactive programming using Observables that provide an API for asynchronous programming with observable streams. It provides code examples of using RxJS to handle events, AJAX requests, and animations as Observables. It also compares RxJS to Promises and native JavaScript event handling, and lists several frameworks that use RxJS like Angular and Redux.
Amazing threesome, rrr... React. Redux. Real world / Ростислав Галкин (Babo)Ontico
"Все гениальное просто" — таким бы мог быть слоган Redux, одной из имплементаций FLUX-архитектуры, которой 31 мая исполняется ровно год. И вот уже практически год, как мы приняли решение использовать Redux в наших проектах. Это был осознанный риск, о котором мы ничуть не пожалели.
За этот год мы научились писать тестируемый код, избегать мутаций и применять методы оптимизации для выбранного стека. Также нам пришлось написать собственные решения для инкапсуляции состояния при написании переиспользуемых компонент и для работы с формами произвольной глубины вложенности, а также мы написали свою сетку для отображения бесконечного числа элементов.
Кроме этого, на больших нагрузках мы столкнулись с проблемами производительности рендеринга на сервере в изоморфном приложении и с успехом их решили.
Обо всем этом я расскажу в своем докладе, поделюсь тем опытом и ощущениями, которые мне лично удалось получить за время работы с React и Redux.
This document discusses React, Redux, and real-world applications. It covers topics like universal rendering, testing Redux reducers, connecting React components to Redux, using immutable data structures with Redux, performing calculations with Redux and Reselect for memoization, asynchronous actions with thunk and saga middleware, isolating Redux state for reusable components, and comparing Redux architecture to ELM.
Taming Distribution: Formal Protocols for Akka TypedRoland Kuhn
Cloud computing, reactive systems, microservices: distributed programming has become the norm. But while the shift to loosely coupled message-based systems has manifest benefits in terms of resilience and elasticity, our tools for ensuring correct behavior has not grown at the same pace. Statically typed languages like Java and Scala allow us to exclude large classes of programming errors before the first test is run. Unfortunately, these guarantees are limited to the local behavior within a single process, the compiler cannot tell us that we are sending the wrong JSON structure to a given web service. Therefore distribution comes at the cost of having to write large test suites, with timing-dependent non-determinism.
In this presentation we take a first peek at ways out of this dilemma. The principles are demonstrated on the simplest distributed system: Actors. We show how parameterized ActorRefs à la Akka Typed together with effect tracking similar to HLists can help us define what an Actor can and cannot do during its lifetime—and have the compiler yell at us when we do it wrong.
aming distribution: formal protocols for Akka TypedJ On The Beach
Cloud computing, reactive systems, microservices: distributed programming has become the norm. But while the shift to loosely coupled message-based systems has manifest benefits in terms of resilience and elasticity, our tools for ensuring correct behavior has not grown at the same pace. Statically typed languages like Java and Scala allow us to exclude large classes of programming errors before the first test is run. Unfortunately, these guarantees are limited to the local behavior within a single process, the compiler cannot tell us that we are sending the wrong JSON structure to a given web service. Therefore distribution comes at the cost of having to write large test suites, with timing-dependent non-determinism.
In this presentation we take a first peek at ways out of this dilemma. The principles are demonstrated on the simplest distributed system: Actors. We show how parameterized ActorRefs à la Akka Typed together with effect tracking similar to HLists can help us define what an Actor can and cannot do during its lifetime—and have the compiler yell at us when we do it wrong.
1. The document discusses various Python programming concepts like data types, operators, conditional statements, loops etc. through examples.
2. It shows the use of basic operators like arithmetic, comparison, logical and bitwise operators on integers, floats, strings.
3. Conditional statements like if-else and if-elif-else are demonstrated to check conditions and execute code blocks accordingly.
4. Loops like for and while are used to iterate through a sequence or repeat code execution based on a condition. Range function is used to generate sequences for for loops.
The document describes the objectives of a C++ lab course. It includes:
1. Designing classes with static members, methods with default arguments, and friend functions like a matrix and vector class.
2. Implementing a complex number class with operator overloading.
3. Implementing a matrix class with dynamic memory allocation.
4. Overloading new and delete operators for custom memory allocation.
5. Developing linked list and sorting algorithm templates.
In this talk, I’m introducing Pegomock, a mocking framework for Go, that I have written over the last 2 years. By quickly going through the idea of Dependency Injection, I'm explaining why mocks are useful in general. Afterwards, I'm diving a bit deeper into how to use Pegomock and why I think it is better than its alternatives.
i have a runable code below that works with just guessing where the .pdfarmcomputers
i have a runable code below that works with just guessing where the ships are. i need help editing
this code to be able to have a player play against computer and taking turns playing battleship.
BattleShipGame.java
package battleship;
import java.util.ArrayList;
import java.util.Scanner;
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coordinates = getCoordinates(input);
int row = coordinates[0];
int column = coordinates[1];
ocean.shootAt(row, column);
availableSpot[row][column] = false;
isGa.
The document summarizes lambda expressions and concurrency APIs in C++. It provides examples of lambda expressions with different capture modes. It also discusses features of concurrency APIs like std::future, std::promise, std::packaged_task and how to use them to asynchronously execute tasks and retrieve/propagate results and exceptions.
Semelhante a Did you know JavaScript has iterators? DublinJS (15)
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...Luciano Mammino
The document discusses using iterator combinators in Rust to solve an Advent of Code puzzle in a more functional style compared to a classic imperative approach. It shows code to parse input data into batches, map lines to values, sum the values, and take the maximum. It then extends this to sort batches descending and take the top 3 sums to solve part 2 of the puzzle in a flexible way using combinators.
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoLuciano Mammino
The document outlines steps to build an invite-only website using Next.js and Airtable. It discusses:
1) Organizing guest data like name and favorite color in an Airtable database.
2) Setting up a Next.js project and retrieving invite data from Airtable using its API and creating an Invite interface.
3) Creating a Next.js API to fetch invite data based on an invite code parameter.
A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns come in three different categories. Creational patterns include the generation of object instances. Structure refers to how an object is made and how things behave and interact In this Webinar(Live Meetup) we will be covering - What is node js - When to use node js - Async I/O operations in node js - Advantages of Async/Await - Some interesting - async patterns - Performance comparison
Let's build a 0-cost invite-only website with Next.js and Airtable!Luciano Mammino
The document describes building an invite-only website using Next.js and Airtable. It outlines:
1) Organizing guest data like names and preferences in an Airtable database.
2) Creating a Next.js project and APIs to retrieve invite data from Airtable by invite code.
3) Authenticating access to Next.js pages by checking for a valid invite code parameter.
Almost every web application at some point needs a way to upload or download files… and no one seems to enjoy building reliable and scalable upload/download servers… and for good reasons too! In fact, you’ll probably need to manage long-running connections and handle files that can be quite large (i.e videos). If you are running a fully serverless backend using API Gateway and Lambda, you probably know that you are limited in terms of payload size and execution time, so things get even more complicated there. In all these cases you should consider offloading this problem to S3 by using S3 pre-signed URLs. Pre-signed URLs are a fantastic tool to handle file download and upload directly in S3 in a managed and scalable fashion. But all that glitters is not gold and S3 pre-signed URLs come with quite a few gotchas… So in this talk, we will explore some use cases, see some potential implementations of S3 pre-signed URLs and uncover some of the gotchas that I discovered while using them. By the end of this talk, you should know exactly when to use pre-signed URLs and how to avoid most of the many mistakes I made with them!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
JavaScript Iteration Protocols - Workshop NodeConf EU 2022Luciano Mammino
The document discusses JavaScript iteration protocols including generators, iterators, iterables, async iterators, and async iterables.
It provides examples of using generator functions to create custom iterables. It explains that generator objects are both iterators and iterables.
The document also explains the iterator and iterable protocols, defining what makes an object an iterator and what makes an object iterable. It shows how to implement these protocols using generator functions, anonymous objects, and classes.
Finally, it covers async iteration protocols, showing how to create async iterators and async iterables, typically using async generator functions. It provides examples of built-in Node.js async iterables like readable streams.
Building an invite-only microsite with Next.js & AirtableLuciano Mammino
Imagine you are hosting a private event and you want to create a website to invite all your guests. Of course you'd like to have an easy way to just share a URL with every guest and they should be able to access all the details of the event. Everyone else should not be allowed to see the page. Even nicer if the website is customized for every guest and if you could use the same website to collect information from the guests (who is coming and who is not). Ok, how do we build all of this? But, most importantly, how do we build it quickly? How do we keep it simple and possibly host it 100% for FREE? I had to do something like this recently so, in this talk, I am going to share my solution, which involves a React SPA (built with Next.js & Vercel) and AirTable as a backend!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A look inside the European Covid Green Certificate - Rust DublinLuciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A presentation by Luciano Mammino(@loige) about what it takes to be recognised as a Senior Software Engineer:
The goal of this slides deck is to:
- Discuss what is expected from a senior software engineer (skills, mindset, duties)
- Packed with opinions (my own and more)
- For devs to be inspired
- For managers to hire, set expectations, support, and evaluate
Node.js: scalability tips - Azure Dev Community VijayawadaLuciano Mammino
You finally built that amazing start-up idea you had in mind for years and you did it using Node.js! That's Great! You just launched it on Hacker News and you are very happy and proud... but now more and more people are using it and you start to have a nasty fear that Node.js won't scale because you now... it's single-threaded! Is your project doomed now? Do you have to invest your time on rewriting it in something like C++ or maybe Rust or even Go? You'd rather invest your time on adding valuable features for your users rather than learning a new language and rewriting everything from scratch, but what if nothing works anymore? And... by the way, what the heck "single-threaded" really means?! Fear no more, dear fellow developer! In this talk, we will discuss the architecture of Node.js going through its strengths and its weaknesses. We will then talk about scalability and I will share some valuable tips and tricks to make your Node.js app scale! Spoiler alert: you probably won't need Go or Rust :)
A look inside the European Covid Green Certificate (Codemotion 2021)Luciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
1. The document discusses observability in AWS and introduces a tool called SLIC Watch that automates the configuration of CloudWatch alarms and dashboards for serverless applications.
2. SLIC Watch generates CloudFormation templates that set up application-specific dashboards and alarms using metrics from services like Lambda, DynamoDB, and API Gateway to help operators more quickly identify issues.
3. The document provides an example of how SLIC Watch could help diagnose issues like DynamoDB throttling and Lambda timeouts by automating the creation of relevant metrics and alarms without requiring manual configuration of CloudWatch.
Semplificare l'observability per progetti ServerlessLuciano Mammino
Hai mai pensato che le tue lambda functions possano fallire senza che tu te ne accorga? Se la risposta é "SI" probabilmente é perché ti sei giá "bruciato" giocando con il cloud, dove errori e fallimenti sono sempre dietro l'angolo. Purtroppo non possiamo prevenire tutti i fallimenti, pero' possiamo essere notificati quando qualcosa va storto cosí da poter reagire tempestivamente. Ma come fare a configurare il nostro ambiente AWS per raggiungere un buon livello di "Observability"? Se hai giá provato ad utilizzare CloudWatch saprai giá quanto possa essere complesso. In questo talk, esploreremo il tema dell'observability per applicazioni Serverless su AWS. Discuteremo problemi e best practices. Infine vi proporró un tool che permette di automatizzare la configurazione di CloudWatch per l'80% delle esigenze in pochi minuti!
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Luciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - EnterJS 2021Luciano Mammino
The document discusses using the Last.fm API and Node.js async iterators to search a user's listening history when only a fragment of a song title is remembered. It describes making requests to retrieve the user's recent tracks paginated over time windows to avoid duplicate results. Code examples show iterating over the pages as a stream to expose the track data for processing.
Most AWS APIs will have limits on the amount of data you can send in one request and sometimes you really need to send a lot of data! To try to maximise the amount of data you can send, while still staying within the limits, some APIs support sending gzip-compressed payloads. But how can you send a gzipped request when using the Python SDK for AWS (boto3)? Well, I needed to answer this question recently and it turned out not to be as easy as I anticipated… Let’s jump into this rabbit hole together and let’s find out the answer!
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Drona Infotech is a premier mobile app development company in Noida, providing cutting-edge solutions for businesses.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
12. loige
ITERATORS ARE LAZY!
You can consume the collection 1 item at the time
You don't need to keep all the items in memory
Great for large datasets
You can even have endless iterators!
12
13. loige
The concept of Iterators exists already in JavaScript...
🗞GOOD NEWS FROM THE WORLD...
... since ES2015!
13
14. WAIT, WHO THE HECK IS THIS GUY !? 🤷
👋I'm Luciano ( 🍕🍝 )
Senior Architect @ fourTheorem (Dublin )
nodejsdp.link
📔Co-Author of Node.js Design Patterns 👉
Let's connect!
(blog)
(twitter)
(twitch)
(github)
loige.co
@loige
loige
lmammino
14
15. ALWAYS RE-IMAGINING
WE ARE A PIONEERING TECHNOLOGY CONSULTANCY FOCUSED
ON CLOUD, AWS & SERVERLESS
loige
😇We are always looking for talent: fth.link/careers
We can help with:
Cloud Migrations
Training & Cloud enablement
Building serverless applications
Cutting cloud costs
15
18. const array = ['foo', 'bar', 'baz']
for (const item of array) {
console.log(item)
}
loige
Output:
foo
bar
baz
18
19. const str = 'foo'
for (const item of str) {
console.log(item)
}
loige
Output:
f
o
o
19
20. const set = new Set(['foo', 'bar', 'baz'])
for (const item of set) {
console.log(item)
}
loige
Output:
foo
bar
baz
20
21. const map = new Map([
['foo', 'bar'], ['baz', 'qux']
])
for (const item of map) {
console.log(item)
}
loige
Output:
[ 'foo', 'bar' ]
[ 'baz', 'qux' ]
21
22. const obj = {
foo: 'bar',
baz: 'qux'
}
for (const item of obj) {
console.log(item)
}
loige
Output:
⛔ Uncaught TypeError: obj is not iterable
OMG `for ... of`
does not work with plain objects! 😱
22
32. function * fruitGen () {
yield '🍑'
yield '🍉'
yield '🍋'
yield '🥭'
}
const fruitGenObj = fruitGen()
// generator objects are iterable!
for (const fruit of fruitGenObj) {
console.log(fruit)
}
// 🍑
// 🍉
// 🍋
// 🥭
loige 32
33. function * range (start, end) {
for (let i = start; i < end; i++) {
yield i
}
}
// generators are lazy!
for (const i of range(0, Number.MAX_VALUE)) {
console.log(i)
}
const zeroToTen = [...range(0, 11)]
loige 33
34. // generators can be "endless"
function * cycle (values) {
let current = 0
while (true) {
yield values[current]
current = (current + 1) % values.length
}
}
for (const value of cycle(['even', 'odd'])) {
console.log(value)
}
// even
// odd
// even
// ...
loige 34
35. 📝MINI-SUMMARY
loige
A generator function returns a generator object which is both an iterator and an iterable.
A generator function uses `yield` to yield a value and pause its execution. The generator object
is used to make progress on an instance of the generator (by calling `next()`).
Generator functions are a great way to create custom iterable objects.
Generator objects are lazy and they can be endless.
35
39. THE ITERATOR PROTOCOL
An object is an iterator if it has a next() method.
Every time you call it, it returns an object with the keys
done (boolean) and value.
loige 39
40. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 40
45. THE ITERABLE PROTOCOL
An object is iterable if it implements the
Symbol.iterator method, a zero-argument function
that returns an iterator.
loige 45
46. function createCountdown (from) {
let nextVal = from
return {
[Symbol.iterator]: () => ({
next () {
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
})
}
}
loige 46
47. function createCountdown (from) {
return {
[Symbol.iterator]: function * () {
for (let i = from; i >= 0; i--) {
yield i
}
}
}
}
loige 47
48. function * createCountdown () {
for (let i = from; i >= 0; i--) {
yield i
}
}
loige
🔥or just use generators!
48
49. const countdown = createCountdown(3)
for (const value of countdown) {
console.log(value)
}
// 3
// 2
// 1
// 0
loige 49
50. const iterableIterator = {
next () {
return { done: false, value: 'hello' }
},
[Symbol.iterator] () {
return this
}
}
An object can be an iterable and an iterator at the same time!
loige 50
51. 📝MINI-SUMMARY 1/2
loige
An iterator is an object that allows us to traverse a collection
The iterator protocol specifies that an object is an iterator if it has a `next()` method that
returns an object with the shape `{done, value}`.
`done` (a boolean) tells us if the iteration is completed
`value` represents the value from the current iteration.
You can write an iterator as an anonymous object (e.g. returned by a factory function), using
classes or using generators.
51
52. 📝MINI-SUMMARY 2/2
loige
The iterable protocol defines what's expected for a JavaScript object to be considered
iterable. That is an object that holds a collection of data on which you can iterate on
sequentially.
An object is iterable if it implements a special method called `Symbol.iterator` which returns
an iterator. (An object is iterable if you can get an iterator from it!)
Generator functions produce objects that are iterable.
We saw that generators produce objects that are also iterators.
It is possible to have objects that are both iterator and iterable. The trick is to create the object
as an iterator and to implement a `Symbol.iterator` that returns the object itself (`this`).
52
53. OK, very cool!
But, so far this is all synchronous iteration.
What about async? 🙄
loige 53
55. THE ASYNC ITERATOR PROTOCOL
An object is an async iterator if it has a next() method.
Every time you call it, it returns a promise that resolves to
an object with the keys done (boolean) and value.
loige 55
56. import { setTimeout } from 'node:timers/promises'
function createAsyncCountdown (from, delay = 1000) {
let nextVal = from
return {
async next () {
await setTimeout(delay)
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
}
} loige 56
59. import { setTimeout } from 'node:timers/promises'
// async generators "produce" async iterators!
async function * createAsyncCountdown (from, delay = 1000) {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
loige 59
60. THE ASYNC ITERABLE PROTOCOL
An object is an async iterable if it implements the
`Symbol.asyncIterator` method, a zero-argument
function that returns an async iterator.
loige 60
61. import { setTimeout } from 'node:timers/promises'
function createAsyncCountdown (from, delay = 1000) {
return {
[Symbol.asyncIterator]: async function * () {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
}
}
loige 61
62. HOT TIP 🔥
With async generators we can create objects that are
both async iterators and async iterables!
(We don't need to specify
Symbol.asyncIterator explicitly!)
loige 62
63. import { setTimeout } from 'node:timers/promises'
// async generators "produce" async iterators
// (and iterables!)
async function * createAsyncCountdown (from, delay = 1000) {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
loige 63
64. const countdown = createAsyncCountdown(3)
for await (const value of countdown) {
console.log(value)
}
loige 64
65. 📝MINI-SUMMARY 1/2
loige
Async iterators are the asynchronous counterpart of iterators.
They are useful to iterate over data that becomes available asynchronously (e.g. coming from a
database or a REST API).
A good example is a paginated API, we could build an async iterator that gives a new page for
every iteration.
An object is an async iterator if it has a `next()` method which returns a `Promise` that resolves
to an object with the shape: `{done, value}`.
The main difference with the iterator protocol is that this time `next()` returns a promise.
When we call next we need to make sure we `await` the returned promise.
65
66. 📝MINI-SUMMARY 2/2
loige
The async iterable protocol defines what it means for an object to be an async iterable.
Once you have an async iterable you can use the `for await ... of` syntax on it.
An object is an async iterable if it has a special method called `Symbol.asyncIterator` that
returns an async iterator.
Async iterables are a great way to abstract paginated data that is available asynchronously or
similar operations like pulling jobs from a remote queue.
A small spoiler, async iterables can also be used with Node.js streams...
66
67. A REAL USE CASE & A CHALLENGE!
loige
Async Iterables are commonly used to abstract over paginated resources. Can you implement a
paginator for the Rick & Morty API?
function createCharactersPaginator () {
// return an async iterable object that produces
// pages with name of Rick and Morty characters
// taken from the API
// https://rickandmortyapi.com/api/character
}
// This is what we want to support 👇
const paginator = createCharactersPaginator()
for await (const page of paginator) {
console.log(page)
}
67
68. IN CONCLUSION 💥
loige
JavaScript has built-in sync/async iteratable/iterators
These are great tools when you need to deal with large (or even endless) data sets
They give you great control over how to consume data incrementally
Iterator helpers are still lacking and not as mature as in other languages
... although, you should know enough to be able to create your own helpers now 😜
... and you can leverage generator functions to make your life easier!
... or you can wait for & to land
Iterator Helpers Async Iterator Helpers
... or you can use to polyfill these features today!
core-js
68
69. BONUS: A FREE WORKSHOP FOR YOU! 🎁
loige
loige.link/lets-iter-repo
git clone https://github.com/lmammino/iteration-protocols-workshop.git
cd iteration-protocols-workshop
npm i
69
70. Front cover Photo by on
Back cover photo by on
Sam Barber Unsplash
photonblast Unsplash
fourtheorem.com
THANKS! 🙌
loige
nodejsdp.link
70