Chapter 2 Lecture 2
2.1 RMarkdown
Now that we know some basic R syntax, let’s learn a little about RMarkdown. You will drive yourself crazy (and fail to generate a reproducible workflow!) running code directly in the console. RMarkdown is really key for collaborative research, so we’re going to get started with it early and then use it for the rest of the course.
An RMarkdown file will allow us to weave markdown text with chunks of R code to be evaluated and output content like tables and plots.
File -> New File -> RMarkdown… -> Document of output format HTML, OK.
You can give it a Title like “My Project”. Then click OK.
OK, first off: by opening a file, we are seeing the 4th pane of the RStudio console, which is essentially a text editor. This lets us organize our files within RStudio instead of having a bunch of different windows open.
Let’s have a look at this file — it’s not blank; there is some initial text is already provided for you. Notice a few things about it:
- There are white and grey sections. R code is in grey sections, and other text is in white.
Let’s go ahead and “Knit HTML” by clicking the blue yarn at the top of the RMarkdown file. When you first click this button, RStudio will prompt you to save this file. Create a new folder for it somewhere that you will be able to find again (such as your Desktop or Documents), and name that folder something you’ll remember (like training_files
).
What do you notice between the two?
Notice how the grey R code chunks are surrounded by 3 backticks and {r LABEL}
. These are evaluated and return the output in form of an html file, that you could host on a website for example or print into a pdf or word document if you like.
Here, R shows you two examples related to two of its example datasets that come with the R language, cars
and pressure
. The output for summary(cars)
shows the descriptive statistics for the two variables in the car dataset, speed
and distance
. The figure below generates a scatterplot from the pressure
dataset, showing the vapor pressure of mercury (in millimeters) as a function of temperature in degrees Celsius.The output plot shows the relationship between the two variables.
Notice how the code plot(pressure)
is not shown in the HTML output because of the R code chunk option echo=FALSE
written at the beginning of the code chunk like this {r, echo=FALSE}
.
More details…
This RMarkdown file has 2 different languages within it: R and Markdown.
We don’t know that much R yet, but you can see that we are taking a summary of some data called ‘cars’, and then plotting. There’s a lot more to learn about R, and we’ll get into it for the next few days.
The second language is Markdown. This is a formatting language for plain text, and there are only about 15 rules to know.
Notice the syntax for:
- headers get rendered at multiple levels:
#
,##
- bold:
**word**
There are some good cheatsheets to get you started, and here is one built into RStudio: Go to Help > Markdown Quick Reference
Important: note that the hashtag #
is used differently in Markdown and in R:
- in R, a hashtag indicates a comment that will not be evaluated. You can use as many as you want:
#
is equivalent to######
. It’s just a matter of style. - in Markdown, a hashtag indicates a level of a header. And the number you use matters:
#
is a “level one header”, meaning the biggest font and the top of the hierarchy.###
is a level three header, and will show up nested below the#
and##
headers.
Learn more: http://rmarkdown.rstudio.com/
2.1.1 Your Turn
- In Markdown, Write some italic text, and make a numbered list. And add a few subheaders. Use the Markdown Quick Reference (in the menu bar: Help > Markdown Quick Reference).
- Reknit your html file.
2.1.2 Code chunks
OK. Now let’s practice with some of those commands.
Create a new chunk in your RMarkdown first in one of these ways:
- click “Insert > R” at the top of the editor pane
- type by hand ```{r} ```
- if you haven’t deleted a chunk that came with the new file, edit that one
Now, let’s write some R code.
x <- 4*3
x
Now, hitting return does not execute this command; remember, it’s just a text file. To execute it, we need to get what we typed in the the R chunk (the grey R code) down into the console. How do we do it? There are several ways (let’s do each of them):
- copy-paste this line into the console.
- select the line (or simply put the cursor there), and click ‘Run’. This is available from
- the bar above the file (green arrow)
- the menu bar: Code > Run Selected Line(s)
- keyboard shortcut: command-return
- click the green arrow at the right of the code chunk
2.1.3 Your turn
Add a few more commands to your file. Execute them by trying the three ways above. Then, save your R Markdown file.
2.2 R functions, help pages
So far we’ve learned some of the basic syntax and concepts of R programming, how to navigate RStudio, and RMarkdown, but we haven’t done any complicated or interesting programming processes yet. This is where functions come in!
R has a mind-blowing collection of built-in functions that are used with the same syntax: function name with parentheses around what the function needs in order to do what it was built to do. When you type a function like this, we say we are “calling the function”. function_name(argument1 = value1, argument2 = value2, ...)
.
As our first function, we will introduce read.csv
, which will be in the first lines of many of your future scripts. It does exactly what it says, it reads in a csv file to R, but we don’t quite know how to use it yet. The help pages in RStudio will help us with this!
To access the help page for read.csv
, enter the following into your console:
?read.csv
The help pane will show up in the lower right hand corner of your RStudio.
You can see from this pane that the help page for this function is actually for a family of related functions that read in data. The help page tells the name of the package in the top left, and is broken down into sections:
- Description: An extended description of what the function does.
- Usage: The arguments of the function(s) and their default values.
- Arguments: An explanation of the data each argument is expecting.
- Details: Any important details to be aware of.
- Value: The data the function returns.
- See Also: Any related functions you might find useful.
- Examples: Some examples for how to use the function.
The help for read.csv
has a lot of information in it, as this function has a lot of arguments, but the first one seems pretty critical. We have to tell it what file to look for. Let’s get a file!
2.3 Sampling in R
Let’s conduct a survey with pilots who reside in Alaska. For that, we first need a sample frame and then create a sample.
2.3.1 Download a sample frame for pilots
The Federal Aviation Administration (FAA) publishes the contact information for pilots on its website here: FAA Airmen Certification Database, and download this zip file to your downloads folder.
Unzip the folder and move the PILOT_BASIC.csv
file into a place you can easily find it. I recommend creating a folder called data
in your previously-created directory training_files
, and putting the file there.
2.3.2 Use a function to read a file into R
Now we have to tell read.csv
how to find the file. We do this using the file
argument which you can see in usage section in the help page. In RMarkdown, you can either use absolute paths (which will start with your home directory ~/
) or paths relative to the location of the RMarkdown. RStudio and RMarkdown have some great autocomplete capabilities when using relative paths, so we will go that route. Assuming you have moved your file to a folder within training_files
called data
, your read.csv
call will look like this:
pilots <- read.csv("data/PILOT_BASIC.csv")
You should now have an object of the class data.frame
in your environment called pilots
. Check your environment pane to ensure this is true. How many pilots are in this dataframe?
Note that in the help page there are a whole bunch of arguments that we didn’t use in the call above. Some of the arguments in function calls are optional, and some are required. Optional arguments will be shown in the usage section with a name = value
pair, with the default value shown. If you do not specify a name = value
pair for that argument in your function call, the function will assume the default value (example: header = TRUE
for read.csv
). Required arguments will only show the name of the argument, without a value. Note that the only required argument for read.csv
is file
.
Many R users (including myself) will override the default stringsAsFactors
argument. The following code will turn all character variables into character strings. read.csv(“data/PILOT_BASIC.csv”, stringsAsFactors = FALSE)
And there’s also help for when you only sort of remember the function name: double-questionmark:
??install
Not all functions have (or require) arguments:
date()
## [1] "Mon Feb 18 14:08:16 2019"
2.3.3 Using data.frames
A data.frame
is a two dimensional data structure in R that mimics spreadsheet behavior. It is a collection of rows and columns of data, where each column has a name and represents a variable, and each row represents a measurement of that variable. When we ran read.csv
, the object pilots
that we created is a data.frame
.  Here are a few, give them each a try:
- click on the word
pilots
in the environment pane - click on the arrow next to
pilots
in the environment pane - execute
head(pilots)
in the console - execute
View(pilots)
in the console
2.3.4 Subsetting data to get the appropriate sample frame
Let’s say we are interested in conducting a survey with pilots who reside in Alaska. Then we need to subset this national database into a dataset that includes just pilots who reside in Alaska.To do this we need to know how Alaska residents are coded. It looks like the STATE variable will help. But there Alaska could be coded in any way. Check the metadata that comes with the dataset on the website, or use the following code to see how Alaska may be coded. This code will return all the unique values in the STATE variable.
unique(pilots$STATE)
pilotsAK <- subset(pilots,STATE=="AK")
How large is our population of pilots?
2.3.5 Your Turn!
Use the function nrow() to find out.
2.3.6 Calculating sample size
First we need to calculate the desired sample size for which we need the following: Np
- population size prop
- proportion of population expected to choose one of two response categories: If we don’t know about these expectations, we assume prop = 0.5 for a 50/50 split. Then we are more conservative (get a larger required sample) than assuming a 80/20 split. serror
- acceptable amount of sampling error of the true population value, let’s set it at 3% conf
- confidence level, also called p-value, let’s say 95%. For calculations we use the decimal 0.95
Let’s first declare the values for each of the variables above.
Np <- 7663
prop <- 0.5
serror <- 0.03
conf <- 0.95
The confidence level will give us the z-score
or z-statistic
which we will need for calculating the sample size. For a 95% confidence interval, you want to know how many standard deviations away from the mean your point estimate is (the “z-score”). To get that, you take off the 5% “tails”. Working in percentile form you have 1-.95 which yields a value 0.05. Divide that in half to get 0.025. So we basically do this: (1-conf)/2
.
In R, use the qnorm
function to get the “critical value”. Since you only care about one “side” of the curve (the values on either side are mirror images of each other) and you want a positive number, pass the argument lower.tail=FALSE.
zscore <- qnorm((1-conf)/2,lower.tail=FALSE)
For a 95% confidence interval this should be about 1.96
Now we are ready to calculate the sample size, Ns
Ns <- Np * prop *(1-prop)/((Np-1)*(serror/zscore)^2+prop*(1-prop))
Ns
## [1] 936.7516
2.3.7 Drawing a sample of size Ns from the sample frame, pilotsAK
First we are going to install the sampling package that let’s us draw a random sample without replacement. Install the sampling
package or by typing install.packages(sampling) in the console.
install.packages(sampling)
library(sampling)
library(dplyr)
Now we need to create the simple random sample without replacement, for our first letter mail out
sam.srswor2 <- srswor(n=Ns,N=Np)
sample.srswor2 <- pilotsAK[which(x=(sam.srswor2 ==1)),]
Finally, we select just the columns needed for names and addresses and save the file as a csv so we can share it and open in Excel for mailmerge, etc.
mailout <- select(sample.srswor2, FIRST.NAME, LAST.NAME, STREET.1, CITY, ZIP.CODE)
write.csv(mailout,"data/mailout.csv")


Our platforms will stop existing!
To protest against the planned EU copyright directive,
we will simulate how the internet would look if the directive passes the European Parliament.
Many platforms, including the German Wikipedia,
will turn dark on March 21!
What's the problem?
With article 13 and other parts of the directive, small and medium-sized plattforms will be forced to implement uploadfilters or restrictiv measures.
For many platforms and boards, this is beyond their capabilities, and their survival is threatened.
Detailed information about the directive can be found on Julia Reda's blog
What can you do?
- Sign the petition
- Go to the Demonstration on March 23
- Mail your MdEP
- Call you MdEP
- Write a letter to your MdEP
Be part of the #321EUOfflineDay!
How to implement #321EUOfflineDay on your websiteHelp with snippets/plugins, and content/design improvements for this page would be highly appreciated!
Other sites/more information
Participating platforms
If you want to be part of this list, contact us via blackout(at)margau.net


A well-known educational institution, Anshu Memorial Academy in Rajapakar, Vaishali was founded in the year 2017. This Primary Schools takes pride in the holistic and innovative learning methods which have helped them raise the bar in the field of education. The centre follows a well-researched curriculum that is based on the play way method of learning. This school offers education for children in different age groups. There are a host of other supplementary activities that children can enroll in to enhance their skill set. In a populous suburb of vaishali, this centre is situated near Bhatha Chowk of Rajapakar.
Undoubtedly it is one of the best Primary Schools in Rajapakar, Vaishali.
Infrastructure and other Facilities at Anshu Memorial Academy
Anshu Memorial Academy in Rajapakar has an environment which is not only child-friendly but engaging for children to learn and have fun at the same time. It has spacious classrooms that are well appointed with various amenities and facilities. This centre employs caring and involved certified teachers that play an instrumental role in the learning and development of the kids.


Midnight Planétarium Watch
Description Midnight Planétarium Watch
Poetic Complications® watches provide a unique vision of time, in which craft skills combine with technical prowess to bring stories to life. Their intricate mechanisms offer precious moments of emotion, marked by the distinctive imagination of Van Cleef & Arpels.
Poetic Complications Collection, Midnight Planétarium Watch. 44 mm pink gold case; pink gold bezel; aventurine dial, pink gold sun and shooting star, serpentine Mercury, chloromelanite Venus, turquoise Earth, red jasper Mars, blue agate Jupiter, sugilite Saturn. Pink gold crown with sapphire case back.  Self-winding mechanical movement (Stern Manufacture), equipped with a Christiaan Van der Klaauw module developed exclusively for Van Cleef & Arpels, 48 hour power reserve. Numbered and unlimited edition.
The Midnight Planétarium watch offers the fascinating possibility of wearing the universe at your wrist. The dial depicts a miniature reproduction of the Sun and the six planets visible to the naked eye: Mercury, Venus, Mars, Jupiter, Saturn and Earth. Thanks to an exclusive module, each planet moves on its own disc at its genuine speed of rotation.
After three years of work, Midnight Planétarium was unveiled at the annual Salon International de la Haute Horlogerie (SIHH), held every January in Geneva. The watch contains 396 separate parts and features the six closest planets accurately orbiting the sun.
Created by Van Cleef & Arpels in partnership with Christiaan van der Klaauw, Midnight Planétarium is an incredible timepiece that features six bejewelled planets in our solar system accurately rotating around our Sun.
Each of the planets are represented by precious and semi-precious stones, ranging from red jasper to serpentine and turquoise. There is also a ‘lucky day’ feature that uses the bezel to allow owners to select any day of the year as your ‘lucky day’ and the Earth will fall underneath the painted star on the watch’s crystal on that day every year.
Before you rush out to buy one for your stargazing friend, make sure you can afford the staggering $245,000 price tag!
Buy
Daily wear
The water resistance of your watch is adapted to daily use that may involve exposure to small splashes of water. Nevertheless, we recommend that you do not immerse your watch in water. Always keep the crown and/or the push-piece in their initial positions, except when performing adjustments, and take care to change the joints regularly, to prevent any infiltration. We recommend avoiding exposure of your watch to extreme temperatures (less than 32°F; greater than 140°F) that risk damaging the joints or the bracelet or strap. We advise you to protect your watch by keeping it away from intense magnetic sources (such as magnets or household appliances) that can have an impact on the proper functioning of the movement. We recommend avoiding exposure of your watch to cosmetic products or acidic or chemical substances.
Cleaning and storing
In general, we recommend that you clean your watch using a soft dry cloth, paying particular attention to the bracelet or strap. The bracelets and straps on Van Cleef & Arpels watches are made from noble materials including leather, gold and platinum. Leather is a material that ages naturally over time. To preserve it, we recommend avoiding all contact with water, humidity and cosmetic products. Bracelets in gold and platinum may be cleaned using a soft brush soaked in warm water with PH neutral soap, rinsed in clear water and dried using a soft cloth. Be sure to hold the head of the watch out of the water during this manipulation. When you are not wearing your watch, we advise you to store it in its original case, to protect it from any impact and scratches.
Precautions for use
It is recommended that you avoid changing the time between 10PM and 2AM, as during this time the pinions in the movement are repositioned to automatically change the date. Quartz watches function using a battery that has an average life of 2 to 3 years, depending on the model. We recommend that you never leave a dead battery in your watch, as it could damage the movement. Watches with self-winding or manual-winding mechanical movements function using an oscillating weight. Ideally, you should wind your watch daily before wearing it. Self-winding watches wind naturally when they are worn. To wind your watch correctly, we recommend that you start by adjusting the bracelet or strap precisely on your wrist.
Mercury
Earth
Mars
Saturn
Jupiter
Venus


{% extends "base.html" %} {% import 'bootstrap/wtf.html' as wtf %} {% block app_content %}
Welcome to the AutoML web application. This application is designed to make AutoML available to domain experts.
The workflow of the application is as follows:
1. Upload a raw dataset
2. Create one or more (sub)sets from this raw dataset to do your analysis on
3. Let AutoML create a good model for your data a model based on the provided subset
4. Check the results when the model is done processing
On the menu bar above you can find the buttons to do each of these steps
An overview of the already uploaded datasets, subsets and analyisis results is available here:


If you're interested in my work , please feel free to contact me! I'd love to chat.
Saint Paul, MN and sometimes DC!
linkedin profile
github profile
katiejolly6@gmail.com


async_v20: Asynchronous OANDA v20 client¶
A foreign exchange client
Disclaimer¶
- Losses can exceed investment.
- async_v20 and its creator has no affiliation with OANDA. And is not endorsed by OANDA in any manner.
- async_v20 is in Beta stage and has not been tested on a live OANDA account
- Use at own risk
Features¶
- Exposes the entire v20 API `
- immutable objects
- No *args, **kwargs In client methods. So no guessing what arguments a method takes
- Serialize objects directly into pandas Series or DataFrame objects
- Construct concurrent trading algorithms
installation¶
$ pip install async_v20
async_v20 is built with aiohttp. It is therefore recommended to also install cchardet and aiodns as per aiohttp documentation `
$ pip install cchardet
$ pip install aiodns
Why async_v20?¶
There are many OANDA clients for python already available so why create another? The main driver for creating async_v20 was to facilitate better risk management, by allowing user’s to concurrently monitor account status and trade currency’s.
An unintended consequence of async_v20 is the ability to create clear segregation between implementation ideas.
A simple example might contain a coroutine for the following:
- Monitoring overall account status
- Watching price stream and triggering buy/sell signals
- Monitoring individual trades and closing movements against held positions
A synchronous implementation would require considerable effort to determine which task communicates with the server next. async_v20 removes this burden by using aiohttp
Further goals of async_v20 has been to lower the barrier of entry for algorithmic trading by providing a complete and simple to use interface.
Tutorial¶
Source code¶
Can be found on GitHub
Please feel free to file an issue on the bug tracker if you have found a bug or have some suggestion in order to improve the client.
Dependencies¶
- python >= 3.6
- aiohttp >= 2.2.5
- ujson >= 1.35’
- yarl >= 0.12.0’
- pandas


Last Name
Last Name
Address
City
State
Zip/Postal Code
Country
Bulgaria
United State
Other
Phone (country code, area code, number)
+(
)
E-mail
Birth date
Month
Day
Year (4 digit)
Gender
Male
Female
Starting date
Spring 2006
Summer 2006
Comments/Questions


Solutions
Issuers
Investors
Service Providers
Events
Blog
About
ST-20 Standard
Careers
Developers
Contact Us
Subscribe to stay up to date on the security token revolution.
 Unsubscribe at any time.


Dead man found inside car in Beltola area of Guwahati city
STAFF REPORTER
GUWAHATI: A parked car (AS 01 BM 8136) at Beltola Tiniali with the driver inside caught the attention of the local people when it did not move for many hours. The driver appeared to be unconscious. Basistha police was contacted and the driver, identified as Rajkumar Deori of Dispur, was taken to GMCH but was declared dead on arrival.
Also read: Unidentified body recovered in the city
Also watch: Govt all set to push for the contentious Citizenship Bill in the winter session of Parliament


class: small *Online/Offline Equivalence*: What our interplanetary tomorrow can teach us about building apps today *How to use the slides*: * P toggle presenter notes * ? help menu * → next slide Also, [here's the source](https://github.com/chadoh/online-offline-equivalence) --- class: middle # *Online/Offline Equivalence* What our interplanetary tomorrow can teach us about building apps today --- background-image: url(img/instantaneous-communication.png) ??? Prologue: We live in a special time! Whole-species instantaneous communication is a short-lived phenomenon for a technological civilization of sufficient longevity. --- # me --- # Chad Ostrowski --- background-image: url(img/YouAreHereInTheGalaxy.jpg) ??? I live in the Orion arm of the Milky Way galaxy --- background-image: url(img/earth_pacific_lrg.jpg) background-size: cover ??? more specifically, I live on a water planet called Earth --- background-image: url(img/eastern-seaboard.jpg) background-size: cover ??? I live in a city called Lancaster --- background-image: url(img/entire.life:chadoh.png) ??? Here's what I've been up to for the past 14 years. --- background-image: url(img/entire.life:chadoh-made-with.png) ??? You can make your own life chart on Entire.Life, which I built and maintain in my free time --- background-image: url(img/entire.life:chadoh-made-with-decorated.png) ??? Get one! https://entire.life --- background-image: url(img/citrusbyte.png) ??? During the day, I work at citrusbyte: innovate like a startup, even if you aren't one. We're hiring! --- class: middle * twitter.com/chadoh * github.com/chadoh * entire.life/chadoh * medium.com/@chadoh --- background-image: url(img/cosmic-algae.png) ??? Disclaimer: I am cosmic algae. I am not an expert, I am learning with you. Correct me if you notice mistakes! Comic from [Poorly Drawn Lines](http://poorlydrawnlines.com/comic/spaceship-earth/) --- ## *Where we're going* 1. Problems of future's present 2. Solutions 1. Offline First 2. Distributed Web --- # let's go on a journey --- # [How far is it to Mars?](http://www.distancetomars.com/) --- # 56 million km --- 56,000,000 km ÷ 300,000 km/s = # *3 light minutes* --- # *6 minute latency* (during the fast part of the year) --- # at the closest! --- background-image: url(img/mars-one-announces-100-finalists-vying-to-be-first-people-on-mars-image-2.jpg) ??? Mars One wants to establish a permanent human colony on Mars by 2030 --- background-image: url(img/mars-settler-internet.jpg) ??? Mars One says that, for astronauts on Mars, > Easy Internet access will be limited to their preferred sites that are constantly updated on the local Mars web server. Other websites will take between 6 and 45 minutes to appear on their screen - first 3-22 minutes for your click to reach Earth, and then another 3-22 minutes for the website data to reach Mars. Contact friends at home is possible by video, voice or text message–e-mail, WhatsApp, sms–but real time dialogue is not possible, because of the time delay. --- "preferred sites that are constantly updated on the local Mars web server" --- # does this even qualify as the Internet? --- background-image: url(img/protesters.jpg) background-size: cover ??? protesters during the Arab Spring --- the internet is # *a discussion* --- the internet is # *many-to-many* --- the internet is # *controlled by its participants* --- the internet is # *a great democratizer* --- # and if I *can't contribute* --- # then it *doesn't count* --- Let's think through it --- background-image: url(img/patreon-no-share.png) ??? Here's a simple page of text; the sort Mars One might imagine when it says "preferred sites to be updated on local Mars server" --- background-image: url(img/patreon.png) ??? Except even this page expects interactivity! Is it acceptable to leave Martians out of this sort of discussion? --- background-image: url(img/social-media-icons.png) ??? At a next level of interactivity, we have social media sites. These are certainly many-to-many! You are expected to contribute. Instagram would not be very "Insta" on Mars! --- background-image: url(img/slack.jpg) ??? Finally, all the apps that require real-time collaboration would just be totally broken on Mars --- *meanwhile, in 2017* # why should we care? --- ## tomorrow's problems ## === ## today's problems but *bigger* ??? Thesis statement. So if we start solving tomorrow's problems now, we will fix current problems and improve the current world. I'll phrase a lot of this talk around helping and serving people. If that's not motivating for you, you're welcome to translate "helping people" into "making money" in your head. Every now and then, it might actually be true that you can help people and make money off of them at the same time. --- *Earth problem 1* # Latency --- background-image: url(img/amazon-data-centers.png) ??? Depending on where you've deployed your app and where your customers are, they could experience some significant latencies. Six minutes? --- background-image: url(img/internet-penetration-over-time.gif) ??? This image shows how the internet grew worldwide from 2000 - 2012. Found on [Vox - 40 Maps That Explain The Internet](https://www.vox.com/a/internet-maps) Lots of countries are starting to come online, but the infrastructure still isn't reliable. An internet that works even on Mars would make using the internet much more feasible for these people. --- # [86 million](http://www.internetlivestats.com/internet-users/nigeria/) ??? The number of internet users in Nigeria, with just 46% of population online. That's a large number of people to be helped. --- background-image: url(img/airplane-mode.png) ??? Then there are all the more prosaic times that we have poor network connectivity. The network has many edges where disconnection and flaky connections are a regular occurrence. --- *Earth Problem 2* # Censorship --- background-image: url(img/egyptian-internet-shutdown.png) ??? in January 2011, Egypt shut down its whole country's access to the internet --- background-image: url(img/protesters.jpg) background-size: cover ??? That brings us back to these folks. Trying to organize for democracy during the Arab Spring. --- background-image: url(img/risk-of-disconnection.png) ??? This image shows worldwide risk of countries being disconnected from the internet as of 2014. Found on [Vox - 40 Maps That Explain The Internet](https://www.vox.com/a/internet-maps) --- background-image: url(img/san-franciscan-internet-shutdown.jpg) ??? in August 2011, San Francisco shut down the internet --- background-image: url(img/world-censorship.png) ??? Then of course, there's internet censorship, which is a similar problem. Would internet that works even on Mars fix this, too? --- *Earth Problem 3* ## data growth outpaces network speed --- background-image: url(img/du-stacks-to-moon.png) ??? From https://www.emc.com/leadership/digital-universe/2014iview/index.htm --- background-image: url(img/iot-embedded-systems-du.png) ??? From https://www.emc.com/leadership/digital-universe/2014iview/index.htm --- background-image: url(img/used_intl_bw_for_ars_technica-4f9a9cf-intro.png) ??? From [Ars Technica in 2012](https://arstechnica.com/features/2012/05/bandwidth-explosion-as-internet-use-soars-can-bottlenecks-be-averted/): Bandwidth explosion: As Internet use soars, can bottlenecks be averted? Bandwidth usage is soaring, driven by the proliferation of Internet-connected devices. --- background-image: url(img/nielsen-law-internet-speed-trend-curve.png) ??? From [Nielson](https://www.nngroup.com/articles/law-of-bandwidth/): > Nielsen's law is similar to the more established Moore's law. Unfortunately, comparing the two laws shows that bandwidth grows slower than computer power. Moore's law says that computers double in capabilities every 18 months, which corresponds to about 60% annual growth. --- background-image: url(img/neilsons-law-vs-moores-law.png) ??? Again from [Nielsen](https://www.nngroup.com/articles/law-of-bandwidth/): > As shown in the table, bandwidth will remain the gating factor in the experienced quality of using the internet medium. ## growth in data demand outpaces network speed Making the internet work on Mars means Martians would be able to get content directly from each other, rather than needing to wait for a round-trip to Earth. An internet built in this way would also get around bottlenecks in delivering super-fast 4K video, VR experiences, and the increasingly huge IoT data sets created here on Earth. --- # what do we do ??? So what do we do about it? It would be super great if we could build one intermediate layer between users and websites which solved this whole problem without existing websites needing to change. Is that possible? No. That is not possible. The basic architecture of web pages and apps need to change. What will this new app architecture look like? Well, there are two parts to this solution. One is here, right now, and you can start using it. These are the technologies that fit under the banner of Offline First. The second approach--and the bigger change--is the Distributed Web. This is currently emerging, and if you get involved, you can inform the sort of future we fall into. --- one step at a time --- background-image: url(img/roundtrips/blank.png) --- background-image: url(img/roundtrips/12lm.png) --- background-image: url(img/roundtrips/blank.png) --- background-image: url(img/roundtrips/http1-step1.png) --- background-image: url(img/roundtrips/http1-step2.png) --- background-image: url(img/roundtrips/http1-step3.png) --- background-image: url(img/roundtrips/http1-step4.png) --- background-image: url(img/roundtrips/http1-step5.png) --- class: center, middle # 😞 --- *improvement 1* # HTTP/2 ??? [Much info](https://http2.github.io/faq/#why-revise-http)! --- background-image: url(img/roundtrips/blank.png) --- background-image: url(img/roundtrips/http1-step1.png) --- background-image: url(img/roundtrips/http2-step2.png) ??? This feature of HTTP/2 is called Server Push --- background-image: url(img/roundtrips/http2-step3.png) --- class: center, middle # 🎉 --- class: center, middle # 😕 --- class: center, middle # ☹ ??? It gets worse! --- background-image: url(img/roundtrips/http2-step4.png) --- background-image: url(img/roundtrips/http2-step5.png) --- background-image: url(img/roundtrips/http2-step6.png) --- background-image: url(img/roundtrips/http2-step7.png) --- background-image: url(img/roundtrips/http2-step8.png) --- background-image: url(img/roundtrips/http2-step9.png) --- class: center, middle # 😞 --- *improvement 2* # Service Workers --- # What are *Service Workers*? --- ## periodic background syncs
 *rich offline experiences*
 push notifications ??? From [Service Workers: An Introduction](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers) > Rich offline experiences, periodic background syncs, push notifications—functionality that would normally require a native application—are coming to the web. Service workers provide the technical foundation that all these features rely on. --- background-image: url(img/sw-fetch.png) ??? Service Workers run in the background, intercept calls that the page makes, and can respond with cached content.  Browser-based technologies that store data locally, to be synced back to server (maybe) when connection is available --- # Can I use it yet? [yes](http://caniuse.com/#search=localstorage) and [yes](http://caniuse.com/#search=indexeddb) --- # lots of tools to make it easier --- background-image: url(img/localForage.jpg) ??? [localForage](https://localforage.github.io/localForage/) makes using localStorage and related tech easier --- background-image: url(img/PouchDB.png) ??? [PouchDB](https://pouchdb.com/) allows you to read and write data directly on the device, and then sync this data to the cloud when you have an internet connection. --- background-image: url(img/rxdb.png) ??? [RxDB](https://pubkey.github.io/rxdb/) --- background-image: url(img/swarm.png) ??? [Swarm](http://swarmjs.github.io/) --- background-size: auto background-image: url(img/synceddb.png) ??? [SyncedDB](https://github.com/paldepind/synceddb) --- background-size: auto background-image: url(img/shareddb.png) ??? [SharedDB](https://github.com/share/sharedb) --- background-image: url(img/hoodie-js-framework-for-offline-first-apps.png) ??? [Hoodie](http://hood.ie/) is a backend for JS apps that makes offline first simple. From Hoodie's FAQ: > Hoodie core only provides typical backend APIs, for user authentication and data persistence. It does not interact with the DOM at all. It perfectly works with any MV* framework or template engines. Hoodie and other orgs doing seminal thinking about new UX conundrums in an Offline First paradigm. --- background-image: url(img/roundtrips/sw-step9.png) --- background-image: url(img/roundtrips/ls-step2.png) --- background-image: url(img/roundtrips/ls-step3.png) --- background-image: url(img/roundtrips/ls-step4.png) --- background-image: url(img/roundtrips/ls-step5.png) --- background-image: url(img/roundtrips/ls-step6.png) --- class: middle, center # 😅 --- *Service Workers* + *Local Storage* ≈ # Progressive Web Apps --- *Service Workers* + *Local Storage* ≈ # Offline First ??? From [Bradley Holt](https://medium.com/ibm-watson-data-lab/offline-first-whats-in-a-name-89c410910694): > With an Offline First approach you design your app for the most resource-constrained environments first, and then apply progressive enhancement techniques to make your app work better and better as it has access to more and more resources. > > Using an Offline First approach means that your app will not only work offline, but your app will work better when it has access to only a flaky network connection, and your app will even work better when it has a great network connection. Without this intent to design your app for the progression from offline to limited connectivity to great connectivity, there would be no reason to call it Offline First. --- class: middle, center # 😅 --- class: middle, center # 😓 --- background-image: url(img/roundtrips/blank.png) --- background-image: url(img/roundtrips/earth-centric.png) --- background-image: url(img/roundtrips/blank.png) --- background-image: url(img/roundtrips/sw-step9.png) --- background-image: url(img/roundtrips/ls-step7.png) --- background-image: url(img/roundtrips/ls-step8.png) --- background-image: url(img/roundtrips/ls-step9.png) --- background-image: url(img/roundtrips/ls-stepA.png) --- background-image: url(img/roundtrips/ls-stepB.png) --- background-image: url(img/roundtrips/ls-stepC.png) --- background-image: url(img/roundtrips/ls-stepD.png) --- # we need a better architecture --- background-color: white background-image: url(img/client-server-model.svg) ??? Everything we've talked about so far has been constrained by the _client-server model architecture_. Devices can't talk directly to each other, they require the internet to mediate their conversation. --- background-image: url(img/types-of-networks.jpg) ??? Three types of networks: centralized, decentralized, and distributed. Source: On Distributed Communications Networks, Paul Baran, 1962. More info: https://www.oreilly.com/ideas/understanding-the-blockchain --- background-image: url(img/types-of-networks-yay-distributed.jpg) --- *The Distributed Web* ## where two or more devices are gathered, there the Internet is also --- background-image: url(img/roundtrips/ls-stepD.png) --- background-image: url(img/roundtrips/dist-1.png) --- class: middle, center # how? --- class: middle, center # BitTorrent? --- background-image: url(img/bittorrent-6.gif) ??? From [How Stuff Works](http://computer.howstuffworks.com/bittorrent2.htm) --- class: middle, center # git? --- background-image: url(img/git-data-structure.png) background-color: white ??? git uses a completely distributed data model --- background-image: url(img/git-object-model.png) ??? The git object model: a Merkle DAG (Directed Acyclic Graph) --- background-size: auto background-image: url(img/ralph-merkle.jpg) ??? This data structure was created by [Ralph Merkle](https://en.wikipedia.org/wiki/Ralph_Merkle) --- background-image: url(img/git-object-model-merkle-tree.png) --- background-image: url(img/git-object-model-merkle-directed.png) --- background-image: url(img/git-object-model-merkle-dag.png) --- class: middle, center # 1:1 # file:hash --- class: middle, center *3fa0d4b98* ↔ *"Hello, World"* --- So, # can we use git & BitTorrent together? --- background-image: url(img/ipfs-is-the-distributed-web.jpg) ??? More info: https://ipfs.io --- "similar to the original aims of the Web, but IPFS is actually more similar to a single bittorrent swarm exchanging git objects" [github.com/ipfs/ipfs](https://github.com/ipfs/ipfs) --- class: middle, center # 🎉 --- *improvement 4* # IPFS --- "IPFS is a distributed file system that seeks to connect all computing devices with the same system of files." [github.com/ipfs/ipfs](https://github.com/ipfs/ipfs) --- "IPFS is becoming a new major subsystem of the internet. If built right, it could complement or replace HTTP. It could complement or replace even more. It sounds crazy. It is crazy." [github.com/ipfs/ipfs](https://github.com/ipfs/ipfs) --- # how does it work? --- # *Content Addressable* --- class: cramped h t t p s : / / * t w i t t e r . c o m * / A l s h a h e e e d / s t a t u s / 8 6 0 2 5 7 9 9 8 4 4 6 4 2 8 1 6 ??? If all you want is the content of the tweet, you don't really care that it lives on Twitter's servers.  IPFS, on the other hand, addresses content by a hash unique to that content. You can get it from anyone on the network. You can store it so people near you can quickly retrieve it from your computer. --- background-image: url(img/roundtrips/dist-1.png) --- background-image: url(img/roundtrips/dist-2.png) --- class: middle, center # 😁 --- class: middle, center # 😒 --- background-image: url(img/roundtrips/dist-2.png) --- background-image: url(img/roundtrips/dist-3.png) --- background-image: url(img/roundtrips/dist-4.png) --- background-image: url(img/roundtrips/dist-5.png) --- background-image: url(img/roundtrips/dist-6.png) --- background-image: url(img/roundtrips/dist-3.png) --- background-image: url(img/roundtrips/dist-7.png) --- background-image: url(img/roundtrips/dist-8.png) --- background-image: url(img/roundtrips/dist-9.png) --- background-image: url(img/roundtrips/dist-A.png) --- background-image: url(img/roundtrips/dist-B.png) --- background-image: url(img/roundtrips/dist-C.png) --- # Can we do this? --- # Can we do this? *Yes* --- *improvement 5* # IPFS PubSub --- background-image: url(img/ipfs-pubsub-crdts.png) --- # one more puzzle piece --- ## hooray for *distributed files and data*, what about... *server-side logic*? --- ## hooray for *distributed files and data*, what about ~~server-side~~ *incorruptible* logic? --- background-image: url(img/roundtrips/dist-2.png) --- background-image: url(img/roundtrips/dist-D.png) --- background-image: url(img/roundtrips/dist-E.png) --- background-image: url(img/roundtrips/dist-F.png) --- background-image: url(img/roundtrips/dist-G.png) --- background-image: url(img/distributed-consensus.gif) ??? The blockchain allows trustless interactions between peers in a pseudonymous network. Learn more: https://www.youtube.com/watch?v=bBC-nXj3Ng4 --- *we need* # distributed consensus --- class: middle, center # aka --- class: middle, center # blockchain --- class: middle, center # aka --- class: middle, center # bitcoin --- class: middle, center # or --- class: middle, center # *ethereum* --- background-image: url(img/ethereum.jpg) ??? ethereum allows creating smart contracts that get run and validated by all machines participating in the blockchain --- *improvement 6* # Ethereum --- # we did it! --- # we have a fully-functional app! --- # for any network edge! --- # we fixed Martian internet! --- # we fixed latency! --- # we fixed censorship! --- # we can put data close to where it's needed! --- class: middle, center # 😊 --- class: middle, center # 😲 --- background-image: url(img/democratic-autonomous-organization.jpg) ??? build a democratic autonomous organization.jpg --- background-image: url(img/democratic-autonomous-organization-highlights.jpg) --- *YOU CAN BUILD:* * A virtual organization where members vote on issues * A transparent association based on shareholder voting * Your own country with an unchangeable constitution * A better delegative democracy --- class: middle, center # 😵 --- # *wrapping up* --- ## *where we've been* 1. Problems of future's present – *solved* 2. Solutions 1. Offline First – *use it now!* 2. Distributed Web – *help shape its future!* ??? Advice from [@inkel](http://twitter.com/inkel): Don't engage with people that ask a "question" that is in fact a comment or a _I might know better about the subject you're talking about and this is why_. Instead tell them it's a great question and that you can discuss the subject on the hallway track. After all, it's your presentation, not theirs 😉 --- # Resources --- background-image: url(img/juan-benet-stanford-seminar.jpg) ??? Stanford Seminar - IPFS and the Permanent Web: https://www.youtube.com/watch?v=HUVmypx9HGI --- * http://offlinefirst.org/ * https://ipfs.io/ * https://ethereum.org/ * https://github.com/chadoh/online-offline-equivalence/


Dashboard / Here you can see all of your quizzes and statistics
All Campaigns
| Quiz Name | Quiz Link | Status | Date Created | Views | Leads | Social Shares | CTA Clicks | Conversion Rate | |
|---|---|---|---|---|---|---|---|---|---|
| {{quiz.name}} | {{quiz.quizLink}} | {{quiz.quizStatusName}} | {{quiz.created|date:'MM/dd/yyyy'}} | {{quiz.views||0}} | {{quiz.leadsCaptured||0}} | {{quiz.shareCount||0}} | {{quiz.ctaClicks||0}} | {{(quiz.leadsCaptured/quiz.views*100)||0|number:2}}% |


Dialog contains a set of built-in predicates for checking if a value is of a particular type. They are:
(unbound $X)
Succeeds if and only if $X is currently an unbound variable.
(number $X)
Succeeds if and only if $X is bound to a number.
(word $X)
Succeeds if and only if $X is bound to a dictionary word.
(empty $X)
Succeeds if and only if $X is bound to an empty list.
(non-empty $X)
Succeeds if and only if $X is bound to a non-empty list.
(list $X)
Succeeds if and only if $X is bound to a list (empty or non-empty).
The last one comes with an extra feature:
(object $X)
If $X is bound to an object, the query succeeds. If it is bound to anything else, the query fails. But if $X is unbound, *(object $X) backtracks over every object in the game.
The Dialog language is designed for symbolic manipulation, predicate logic, and storytelling. Arithmetic is possible, but the syntax is rather clunky.
($A plus $B into $C)
A and B must be bound to numbers; C is unified with their sum. If the result is outside the valid range of numbers, the query fails.
($A minus $B into $C)
A and B must be bound to numbers; C is unified with their difference. If the result is outside the valid range of numbers, the query fails.
($A times $B into $C)
A and B must be bound to numbers; C is unified with their product. If the product is outside the valid range of numbers, the query succeeds, but the numeric result is unpredictable (i.e. it depends on the interpreter).
($A divided by $B into $C)
A and B must be bound to numbers; C is unified with the (integer) quotient after dividing A by B. The query fails if B is zero.
($A modulo $B into $C)
A and B must be bound to numbers; C is unified with the remainder after dividing A by B. The query fails if B is zero.
(random from $A to $B into $C)
A and B must be bound to numbers, such that B is greater than or equal to A. A random number in the range A to B (inclusive) is picked, and then unified with C.
($A < $B)
This predicate succeeds if and only if A is numerically less than B.
($A > $B)
This predicate succeeds if and only if A is numerically greater than B.
Common to all of the above predicates is that they fail if A or B is unbound, or bound to a non-number. C may be bound or unbound; it is unified with the result of the computation.
To check for numerical equality, use regular unification, i.e. ($ = $).
All numbers in Dialog are restricted to the range 0–16383 (inclusive). This range directly supports four-digit numbers such as years and PIN codes. Pocket money should be fairly straightforward to implement by counting in cents; story authors (or library developers) that require more sophisticated number crunching will have to get creative.
To change the current text style, use the built-in predicates (bold), (italic), (reverse), and (fixed pitch) to enable each respective style, and (roman) to disable all four.
The built-in predicate (uppercase) forces the next character to be printed in uppercase. The standard library uses this to define a number of convenient predicates such as:
| (The $Obj) | (uppercase) (the $Obj) |
To clear the screen below the status bar area, use (clear). To clear the entire screen and disable the status bar, use (clear all). Be aware that on some interpreters, clearing interferes with the player's ability to scroll back and review earlier parts of the play session.
The built-in predicate (space $) prints a given number of space characters in succession.
Its vertical counterpart, (par $), produces a paragraph break with a height corresponding to the given number of blank lines. Adjacent paragraph breaks are merged based on the maximum specified height, so (par 5) (par 7) produces seven blank lines.
| (program entry point) | |
| (clear all) | |
| (par 10) | |
| (space 10) | |
| (bold) | |
| This text is printed in bold, starting at row 11, column 11. |
User input is represented by dictionary words.
The Dialog compiler collects all dictionary words mentioned explicitly in the source code (with the @-prefix or as bare words inside lists), as well as every literal word that can come out of a (collect words) or (determine object $) expression. In addition, the system makes sure to provide a single-letter dictionary word for every character supported by the underlying platform. Together, these words make up what's called the game-wide dictionary.
It may be helpful to know that there's a difference between dictionary words at the Dialog level, and the native, low-level words of the Z-machine. Dialog dictionary words are an abstraction over several different kinds of internal representation. That being said, it is the specific constraints of the low-level Z-machine dictionary that determine where the split occurs between the essential and optional parts of a given dictionary word.
There are two built-in predicates for obtaining input from the player. One waits for a single keypress, while the other reads a full line of input.
| (get key $Char) |
This predicate waits for the player to type a character.
Some interpreters indicate that the game is waiting for input by displaying a flashing cursor. Others don't, so story authors may wish to prompt the reader explicitly.
The parameter, $Char, is unified with a dictionary word representing the character that was typed, e.g. @e if the E key was pressed. Note that dictionary words are case-insensitive, so for letters of the alphabet there is no way to tell whether the player was holding shift or not.
Some special keys correspond to dictionary words that can't be represented directly in Dialog source code. The dictionary words for these keys can be obtained at runtime, by querying the following built-in predicates:
| (word representing return $Char) | |
| (word representing space $Char) | |
| (word representing backspace $Char) | |
| (word representing up $Char) | |
| (word representing down $Char) | |
| (word representing left $Char) | |
| (word representing right $Char) |
A simple keypress dispatcher might look like this:
| (program entry point) | |
| (get key $Key) | |
| (handle keypress $Key) | |
| (handle keypress @a) | |
| 'A' was pressed. | |
| (handle keypress @b) | |
| 'B' was pressed. | |
| (handle keypress (word representing return $)) | |
| RETURN was pressed. |
| (get input $WordList) |
This query blocks execution until the player types a line of input, followed by return. Different interpreters provide different levels of line-editing facilities, ranging from simple backspace handling all the way up to input history and spell checking.
The parameter, $WordList, is unified with a list where each element represents a word typed by the player. The punctuation characters full stop, comma, double quote, semicolon, and asterisk are treated as individual words; the remaining text is separated into words by whitespace. If a word is recognized as one that appears in the program-wide dictionary, then the element will be that dictionary word. Else, if the word is a decimal number in the range 0–16383, the element will be that number.
If the word was neither recognized, nor found to be a decimal number, then Dialog will attempt to remove certain word endings, and check whether the remaining part of the word exists in the dictionary. This procedure is necessary for games written in e.g. German, whereas English games generally do not require it.
To specify removable endings, add one or more rule definitions to the predicate (removable word endings). Each rule body should consist of one or more word endings:
| (removable word endings) | |
| %% German adjective endings | |
| en es em e | |
| (removable word endings) | |
| %% German noun endings | |
| e en s es |
The part that remains after removing the ending is referred to as the stem of the word. If the stem consists of at least two letters, and exists in the program-wide dictionary, then the resulting dictionary word will have the stem as its essential part, and the ending as its optional part. During comparison (unification with another bound value), only the essential part is considered. During printing, both the essential part and the optional part are printed.
During tracing, dictionary words are displayed with a plus sign (+) separating the essential and optional parts. Thus, if the German word “klein” is part of the game-wide dictionary, and the player enters KLEINES, that word appears as @klein+es in the trace logs, and unifies successfully with @klein.
If a word of input isn't recognized at all, even after considering the removable word endings, then it's an unrecognized dictionary word. It can still be stored in a variable, retrieved, and printed back, and it will unify successfully with other instances of the same unrecognized word. When tracing is enabled, unrecognized dictionary words are displayed with a plus sign at the end.
For instance, the input TAKE 02 UNKNOWNWORD,X BALL may, depending on the contents of the dictionary, be represented by the list: [take 2 unknownword , x ball]. As part of a trace, it might be displayed as [take 2 unknownword+ , x ball].
Special gotcha: Recall that zero-prefixed numbers in the source code, as well as numbers that are out of range, are treated as words. If 007 appears in the program in such a way that it becomes part of the program-wide dictionary, then it will show up as a dictionary word in the list returned by (get input $). Otherwise, it will be represented by the numerical value 7.
During parsing, it is often necessary to scan a list for certain keywords, and then split it into two sublists, representing the elements on either side of the matched keyword. It is straightforward to implement this using ordinary rules in Dialog. However, for performance reasons the language also provides a built-in predicate:
| (split $Input by $Keywords into $Left and $Right) |
$Input and $Keywords must be lists of simple values, i.e. they mustn't contain sublists.
The $Input list will be scanned, starting at its head, until the first element that also appears in $Keywords is found. A list of the elements that came before the keyword is unified with $Left, and a list of the elements that follow it is unified with $Right. That is, neither $Left nor $Right includes the keyword itself.
When invoked as a multi-query, the predicate backtracks over each matching position. Thus:
| *(split [the good , the bad and the ugly] | |
| by [and ,] | |
| into $Left and $Right) |
will succeed twice: First, binding $Left to [the good] and $Right to [the bad and the ugly], and then a second time binding $Left to [the good , the bad] and $Right to [the ugly].
The split-by predicate can also be used to check whether a list contains one or more of a set of keywords. The standard library uses it that way in the following rule definition:
| ($X contains one of $Y) | |
| (split $X by $Y into $ and $) |
This section is mainly of concern for library programmers, so story authors may safely skip it.
Dialog has a special construct for matching player input against in-world object names in a very efficient way:
| (determine object $Obj) | |
| object generator | |
| (from words) | |
| word generator | |
| (matching all of $Input) |
This statement will backtrack over every object $Obj for which:
• object generator succeeds, and
• word generator, when exhausted, emits at least every word in the $Input list.
The variable $Obj should appear both in the object generator and in the word generator, and the object generator should contain a multi-query to backtrack over a set of objects. A canonical example is:
| (determine object $Obj) | |
| *($Obj is in scope) | |
| (from words) | |
| *(dict $Obj) | |
| (matching all of $Input) |
A non-optimizing compiler could deal with this construct as follows: First, compile normal code for the object generator. Then, exhaust every branch of the word generator, collecting all its output into a temporary list of words. Finally, check that every word of $Input appears in the temporary list.
However, the Dialog compiler and debugger both perform the following optimization: At compile-time, they analyze the word generator statically, and construct a reverse lookup table, mapping words of input to objects. At runtime, this table is consulted first, based on $Input, to determine what objects the player might be referring to. So, for instance, if the input is LARGE HAT, and there are only two game objects for which (dict $Obj) can produce both of those words, then $Obj will now be bound to each of those two objects in turn. But if there are dozens of large hats, $Obj may instead be left unbound; the compiler is allowed to make a trade-off between speed and memory footprint. Either way, after this step, the operation proceeds as in the unoptimized case.
The following built-in predicates are useful for debugging:
(breakpoint)
If the program is currently running inside the interactive debugger, suspend execution and print the current source code filename and line number. When execution resumes, this query succeeds.
If the program is running on the Z-machine, the query simply succeeds.
(trace on)
Enables tracing. Following this, debugging information will be printed when queries are made, and when rule bodies are entered. The interactive debugger will also report when solutions are found, and when dynamic predicates are updated.
(trace off)
Disables tracing.
If your program source code contains a query to (trace on) anywhere, the Z-machine backend will insert extra instructions all over the generated code, to deal with tracing. This is known as instrumenting the code, and it makes the program slower and larger. Thus, you'll only want to use these predicates temporarily, during debugging. The compiler prints a warning when it adds the extra instructions.
Please be aware that the Dialog compiler and debugger do optimize your program, and you will be tracing the optimized code, so certain queries and rules will be missing from the debug printouts. You will generally want to do all your tracing in the debugger, which mercifully turns off some of the more confusing optimizations. That being said, tracing the optimized Z-code is highly useful when trying to speed up a program.
The following built-in predicates offer low-level control over the interpreter and the Dialog runtime. This is decidedly in the domain of library code, so story authors rarely need to worry about these predicates.
(quit)
Immediately terminates the program. This predicate neither fails nor succeeds.
(restart)
Resets the program to its initial state. The only part of the game state that may survive a restart is the state of the output machinery (including the current style and on-screen contents, and whether the transcript feature is on or off). If the operation succeeds, execution resumes from the start of the program. If there is an error, or the interpreter doesn't support restarting, execution continues normally, i.e. the query succeeds.
(save $ComingBack)
Attempts to save the current game state to a file. The interpreter takes care of asking the player for a filename. In the event of a save error, or if the operation was cancelled, the query fails. On success, the parameter is unified with 0 if we just saved the state, and with 1 if we just restored the state from a file saved by this query.
(restore)
Attempts to restore the current game state from a file. The interpreter takes care of asking the player for a filename. The only part of the game state that may survive a restore is the state of the output machinery (including the current style and on-screen contents, and whether the transcript feature is on or off). If the operation succeeds, execution resumes after the query from which the save file was written. Otherwise, in the event of a load error or if the operation was cancelled, execution continues normally, i.e. the query succeeds.
(save undo $ComingBack)
Works just like (save $), but stores the game state in a buffer in memory. This operation is typically invoked once per move.
(undo)
Works like (restore), but restores the game state from the undo buffer. If there is no saved undo state, the predicate fails. If there's some other problem—such as the interpreter imposing a limit on the number of undo states that are retained in memory—the predicate succeeds, and execution continues normally.
(interpreter supports undo)
Succeeds if and only if the current interpreter declares that it supports undo functionality.
(script on)
Enables the transcript feature. The interpreter takes care of asking the player for a filename. If the operation succeeds, the query suceeds. In case of an error, or if the operation was cancelled, the query fails.
(script off)
Disables the transcript feature. This predicate always succeeds.
(display memory statistics)
Prints a line of information specific to the compiler backend, about the peak memory usage in the heap, auxiliary heap, and long-term heap areas. Currently, only the Z-machine backend does this. The size of these areas can be adjusted by passing commandline options to the compiler. During debugging and testing, you may wish to invoke this predicate just before quitting, as it will tell you how close you are to the limits.


#include <SearchListener.h>
Inheritance diagram for WFAPI::SearchListener:
Public Types | |
| CURRENT_IMAGES_OK | |
| The current images are ok to be used. | |
| CURRENT_IMAGES_NOT_OK | |
| The current images are not ok and will be deleted. | |
| UPDATED_IMAGES_OK | |
| The images have been updated and are ok to use. | |
| enum | ImageStatus { CURRENT_IMAGES_OK, CURRENT_IMAGES_NOT_OK, UPDATED_IMAGES_OK } |
Public Member Functions | |
| SearchListener () | |
| virtual | ~SearchListener () |
| virtual void | searchDetailsReply (RequestID requestID, const SearchItemArray &searchItemArray) |
| virtual void | searchReply (RequestID requestID, const SearchHeadingArray &searchHeadings, bool final) |
| virtual void | searchCategoriesUpdated () |
| virtual void | nextSearchReply (RequestID requestID, const SearchItemArray &searchItemArray, wf_uint32 heading) |
| virtual void | extendedSearchReply (RequestID requestID, const SearchItemArray &searchItemArray, wf_uint32 heading) |
| virtual void | topRegionsChanged () |
| virtual void | totalNbrOfHitsReply (RequestID requestID, SearchHeadingArray searchHeadingArray) |
| virtual void | headingImagesStatusUpdated (ImageStatus currentStatus) |
| virtual void | categoryImagesStatusUpdated (ImageStatus currentStatus) |
| virtual void | resultImagesStatusUpdated (ImageStatus currentStatus) |
| virtual void | categoryTreeReceived (RequestID requestID, bool treeUpdated) |
Create a subclass and implement the callbacks and add a subclass object to the SearchInterface to start getting search callbacks.
The error function, declared in the super class Listener, will be called for all requests that returns with an error.
This enum describes different statuses for image sets. It is used in the ...ImageStatusUpdated callback functions.
| WFAPI::SearchListener::SearchListener | ( | ) |
Constructor.
| virtual WFAPI::SearchListener::~SearchListener | ( | ) | [virtual] |
Destructor.
| virtual void WFAPI::SearchListener::categoryImagesStatusUpdated | ( | ImageStatus | currentStatus | ) | [inline, virtual] |
This function will be called after a search to indicate the current status of the search category images.
| currentStatus | The current status of the images. |
| virtual void WFAPI::SearchListener::categoryTreeReceived | ( | RequestID | requestID, | |
| bool | treeUpdated | |||
| ) | [inline, virtual] |
A reply to the category tree update request. This does not necesarily mean that the category tree has been updated since there might not be any other category tree for the coordinates supplied in the request.
| requestID | The identification of the category tree request sent from the SearchInterface. | |
| treeUpdated | If this is true it means that we have received an updated version of the category tree. False if the category tree is up to date. |
| virtual void WFAPI::SearchListener::extendedSearchReply | ( | RequestID | requestID, | |
| const SearchItemArray & | searchItemArray, | |||
| wf_uint32 | heading | |||
| ) | [inline, virtual] |
A reply for a extended search request.
| requestID | The identification of the search request sent from the SerchInterface. | |
| searchItemArray | List of the requested search results. | |
| heading | The heading that the search results belongs to, it is the same heading as the caller requested more search results for. |
| virtual void WFAPI::SearchListener::headingImagesStatusUpdated | ( | ImageStatus | currentStatus | ) | [inline, virtual] |
This function will be called after a search to indicate the current status of the search heading images.
| currentStatus | The current status of the images. |
| virtual void WFAPI::SearchListener::nextSearchReply | ( | RequestID | requestID, | |
| const SearchItemArray & | searchItemArray, | |||
| wf_uint32 | heading | |||
| ) | [inline, virtual] |
A reply for a request for more search results for a specific heading.
| requestID | The identification of the search request sent from the SerchInterface. | |
| searchItemArray | List of the requested search results. | |
| heading | The heading that the search results belongs to, it is the same heading as the caller requested more search results for. |
| virtual void WFAPI::SearchListener::resultImagesStatusUpdated | ( | ImageStatus | currentStatus | ) | [inline, virtual] |
This function will be called after a search to indicate the current status of the search result images.
| currentStatus | The current status of the images. |
| virtual void WFAPI::SearchListener::searchCategoriesUpdated | ( | ) | [inline, virtual] |
Contains a reply for an issued search of categories.
| virtual void WFAPI::SearchListener::searchDetailsReply | ( | RequestID | requestID, | |
| const SearchItemArray & | searchItemArray | |||
| ) | [inline, virtual] |
A reply for a search details.
| requestID | The identification of the search details request sent from the SearchInterface. | |
| searchItemArray | The SearchItems with the details. |
| virtual void WFAPI::SearchListener::searchReply | ( | RequestID | requestID, | |
| const SearchHeadingArray & | searchHeadings, | |||
| bool | final | |||
| ) | [inline, virtual] |
A reply for a search.
| requestID | The identification of the search request sent from the SearchInterface. | |
| searchHeadings | The reply headings with the search results. | |
| final | If this is the final reply or there will be more calls following this one. The same RequestID will be used for all the replies. |
| virtual void WFAPI::SearchListener::topRegionsChanged | ( | ) | [inline, virtual] |
Called when the current top regions has been changed, for example after a end user has bought access to a new country.
| virtual void WFAPI::SearchListener::totalNbrOfHitsReply | ( | RequestID | requestID, | |
| SearchHeadingArray | searchHeadingArray | |||
| ) | [inline, virtual] |
A reply with the total number of hits
| requestID | The identification of the search request sent from the the SearchInterface. | |
| searchHeadingArray | A list that contains the total number of hits for each heading. |


|
graphics() |
Default constructor |
|
graphics(unsigned width, unsigned height) |
Creates a graphics object that size is width by height in pixel. |
|
graphics(const graphics&) |
Copy constructor, the resource is not copyed, the tow graphics objects refer to
the same resource. |
|
graphics& operator=(const graphics&) |
Assigns an existing resource to another graphics object. |
|
void bitblt(int x, int y, unsigned width, unsigned height, nana::gui::native_window_type
wnd) |
Transfers a width and height block of off-screen buffer from wnd to the graphics
object |
|
void bitblt(int x, int y, unsigned width, unsigned height, nana::paint::graphics&
source) |
Transfers a width and height block of off-scree buffer from source to the graphics
object at (x, y) |
|
void bitblt(int x, int y, unsigned width, unsigned height, nana::paint::graphics&
source, int src_x, int src_y) |
Transfers a width and height block of off-scree buffer from source to the graphics
object at (x, y) |
|
void blend(const graphics& dest, int x, int y) |
blends the dest with the graphics object and save into dest |
|
void blend(int x, int y, unsigned width, unsigned height, colour_t color) |
blends the specifed block width the specified color |
|
bool changed() const |
Returns true if the graphics object is operated |
|
bool empty() const |
Returns true if the graphics object does not refer to any resource. |
|
hdc_type handle() const |
Returns the platform-dependent resource handle. |
|
unsigned height() const |
Returns the height of the off-screen buffer. |
|
void line(int x1, int y1, int x2, int y2, colour_t color) |
Draws a line from point (x1, y1) to point (x2, y2) in the specified color. |
|
void make(unsigned width, unsigned height) |
Creates a bitmap resource that size is width by height in pixel |
|
static colour_t mix(colour_t color1, colour_t color2, unsigned persent) |
Mixs the color1 and color2 |
|
void paste(const graphics& dest, int x, int y) const |
Paste the graphics object into the dest at (x, y) |
|
void paste(const nana::gui::native_window_type wnd, int x, int y) const |
Paste the graphics object into a platform-dependent window at (x, y) |
|
void paste(hdc_type hdc, int x, int y) const |
Paste the graphics object into a platform-dependent DC at (x, y) |
|
void rectangle(int x, int y, unsigned width, unsigned height, colour_t color, bool
solid) |
Draws a width and height rectangle at (x, y) in the specified color. |
|
void release() |
Release the resource graphics object refers to. |
|
void resize(unsigned width, unsigned height) |
Adjusts the resource size into specified size in width by height in pixel |
|
void rgb_to_wb() |
Transform a color graphics into black&white. |
|
void set_pixel(int x, int y, colour_t color) |
Sets the colour of the specified pixel |
|
void setsta() |
Clears the status if the graphics object had been changed |
|
void shadow_rectangle(int x, int y, unsigned width, unsigned height, colour_t begin,
color_t end, bool vertical) |
Draws a width and height rectangle at (x, y) and the color in range of [begin, end] |
|
void stretch_paste(const graphics& dest, int x, int y, unsigned length, int
x2, int y2, unsigned length2) |
Pastes the graphics object into dest, and top line is at (x, y) in length, and bottom
line is at (x2, y2) in length2. |
|
void stretch_paste(hdc_type dc, int x, int y, unsigned length, int x2, int y2, unsigned
length2) |
Pastes the graphics object into platform-dependent DC, and top line is at(x, y)
in length, and bottom line is at(x2, y2) in length2 |
|
void string(int x, int y, colour_t color, const nana::string& text) |
Prints a string of text at the position (x, y) in the specified color. |
|
void string(int x, int y, colour_t color, const nana::string& text, unsigned
length) |
Prints a string of text at the position (x, y) in the specified color and
|
|
nana::size text_extent_size(const nana::char_t*) const |
Computes the width and height of the specified string of text. |
|
nana::size text_extent_size(const nana::string&) const |
Computes the width and height of the specified string of text. |
|
nana::size text_extent_size(const nana::string& text, unsigned length) const |
Computes the width and height of the specified string of text with the specified
length. |
|
void transparent_paste(graphics& gc, int x, int y, colour_t color) const |
Pastes the graphics object at (x, y) into gc, and ignroe the color of gixel |
|
void typeface(const font&) |
Selects a specified font type into the graphics object. |
|
unsigned width() const |
Returns the width of the off-screen buffer |


SlaveofCommand
The SLAVEOF command can change the replication settings of a slave on the fly.If a Redis server is arleady acting as slave, the command SLAVEOF NO ONE
will turn off the replicaiton turning the Redis server into a MASTER.In the proper form SLAVEOF hostname port
will make the server a slave of thespecific server listening at the specified hostname and port.
If a server is already a slave of some master, SLAVEOF hostname port
willstop the replication against the old server and start the synchrnonizationagainst the new one discarding the old dataset.
The form SLAVEOF no one
will stop replication turning the server into aMASTER but will not discard the replication. So if the old master stop workingit is possible to turn the slave into a master and set the application touse the new master in read/write. Later when the other Redis server will befixed it can be configured in order to work as slave.
Status code reply


Constructor
# <ProgressBar spent remaining />
Shows progress in a given Project. By giving spent and remaining time (in hours) it computes the progress and shows it in the UI.
PropTypes:
| Name | Type | Required | Description | Default |
|---|---|---|---|---|
spent |
number | No | How many hours have already been spent | 30 |
remaining |
number | No | What is the remaining number of hours | 40 |


if (!isOrderPage()) { ?>
Russian translation services, Ukrainian translation services and other Language translation services by 1translate.com agency
Cart
$
if (!isOrderPage()) { ?>
11 people (9 translators and 2 managers)
are online right now at your service!
email:
<EMAIL_ADDRESS>} ?>
} else { ?>
Home
Contacts
Customer care:
<EMAIL_ADDRESS>} ?>
if (!isOrderPage()) { ?>
Home
generateTopNavigationMenu("","
","
"); ?>
} ?>


One?
also known as OneQA minimalist card game for Tabletop Simulator.
One? is a custom designed card game for Tabletop Simulator by Antipraktika. Each card has been hand crafted to look elegant whilst still having a clear purpose. Designed in Figma, the cards have a soft color palette and have either text written using the Noto Sans font or an icon.
One? has scripts written specifically to make the game easier to play for those that don't know the rules. The scripts are optional, however, and can be disabled if you'd rather manually play the game or have your own custom rules in mind. If you have created a fun rule and want to have it published, feel free to open an issue on GitHub and it may be added to the 'House Rules' rulebook along with its own script to automate it (if possible).


In an attempt to help with RFM network issues I've added a tool to a copy of the rfm2pi (rfm69) firmware to assist with diagnosing RF issues such as interference, heavy traffic etc
It uses the RFM69's RSSI to plot a real time (vertical) trace of the RF signal. the sample rate can be defined between 0.1s and 2.55s using the "y" as a command via a serial console. (eg 100y sets a 1 sample per second trace and 25y sets 4 samples per second)
The group, quiet mode and frequency settings can be set and altered as usual to help locate an issue,
Since it doesn't effect the normal running of the firmware when not enabled, I have submitted a pull request to the rfm2pi repo so hopefully it can get included as standard, emonhub can also be altered to ignore these lines and prevent loads of "non-numerical data" messages filling up the logfiles.
Adding a trace_mode to rfm2pi firmware
Submitted by pb66 on Fri, 10/07/2015 - 18:29In an attempt to help with RFM network issues I've added a tool to a copy of the rfm2pi (rfm69) firmware to assist with diagnosing RF issues such as interference, heavy traffic etc
It uses the RFM69's RSSI to plot a real time (vertical) trace of the RF signal. the sample rate can be defined between 0.1s and 2.55s using the "y" as a command via a serial console. (eg 100y sets a 1 sample per second trace and 25y sets 4 samples per second)
The group, quiet mode and frequency settings can be set and altered as usual to help locate an issue,
Although there is an issue in JeeLib with using "promiscuous mode" ie group 0, more on this can be found in the Data loss due to RF packets getting corrupted thread and I have enquired over at JeeLabs about a fix.
Since it doesn't effect the normal running of the firmware when not enabled, I have submitted a pull request to the rfm2pi repo so hopefully it can get included as standard, emonhub can also be altered to ignore these lines and prevent loads of "non-numerical data" messages filling up the logfiles.
Paul


Quiz Me!
send
Question
Question Type
Multiple Choice
Identification
True or False
Enumeration
Materialize Select


Supervision and Monitoring
This chapter outlines the concept behind supervision, the primitives offered and their semantics. For details on how that translates into real code, please refer to the corresponding chapters for Scala and Java APIs.
What Supervision Means
As described in Actor Systems supervision describes a dependency relationship between actors: the supervisor delegates tasks to subordinates and therefore must respond to their failures. When a subordinate detects a failure (i.e. throws an exception), it suspends itself and all its subordinates and sends a message to its supervisor, signaling failure. Depending on the nature of the work to be supervised and the nature of the failure, the supervisor has a choice of the following four options:
- Resume the subordinate, keeping its accumulated internal state
- Restart the subordinate, clearing out its accumulated internal state
- Stop the subordinate permanently
- Escalate the failure, thereby failing itself
It is important to always view an actor as part of a supervision hierarchy, which explains the existence of the fourth choice (as a supervisor also is subordinate to another supervisor higher up) and has implications on the first three: resuming an actor resumes all its subordinates, restarting an actor entails restarting all its subordinates (but see below for more details), similarly terminating an actor will also terminate all its subordinates. It should be noted that the default behavior of the preRestart hook of the Actor class is to terminate all its children before restarting, but this hook can be overridden; the recursive restart applies to all children left after this hook has been executed.
Each supervisor is configured with a function translating all possible failure causes (i.e. exceptions) into one of the four choices given above; notably, this function does not take the failed actor’s identity as an input. It is quite easy to come up with examples of structures where this might not seem flexible enough, e.g. wishing for different strategies to be applied to different subordinates. At this point it is vital to understand that supervision is about forming a recursive fault handling structure. If you try to do too much at one level, it will become hard to reason about, hence the recommended way in this case is to add a level of supervision.
Akka implements a specific form called “parental supervision”. Actors can only be created by other actors—where the top-level actor is provided by the library—and each created actor is supervised by its parent. This restriction makes the formation of actor supervision hierarchies implicit and encourages sound design decisions. It should be noted that this also guarantees that actors cannot be orphaned or attached to supervisors from the outside, which might otherwise catch them unawares. In addition, this yields a natural and clean shutdown procedure for (sub-trees of) actor applications.
Warning
Supervision related parent-child communication happens by special system messages that have their own mailboxes separate from user messages. This implies that supervision related events are not deterministically ordered relative to ordinary messages. In general, the user cannot influence the order of normal messages and failure notifications. For details and example see the Discussion: Message Ordering section.
The Top-Level Supervisors
An actor system will during its creation start at least three actors, shown in the image above. For more information about the consequences for actor paths see Top-Level Scopes for Actor Paths.
/user: The Guardian Actor
The actor which is probably most interacted with is the parent of all user-created actors, the guardian named "/user". Actors created using system.actorOf() are children of this actor. This means that when this guardian terminates, all normal actors in the system will be shutdown, too. It also means that this guardian’s supervisor strategy determines how the top-level normal actors are supervised. Since Akka 2.1 it is possible to configure this using the setting akka.actor.guardian-supervisor-strategy, which takes the fully-qualified class-name of a SupervisorStrategyConfigurator. When the guardian escalates a failure, the root guardian’s response will be to terminate the guardian, which in effect will shut down the whole actor system.
/system: The System Guardian
This special guardian has been introduced in order to achieve an orderly shut-down sequence where logging remains active while all normal actors terminate, even though logging itself is implemented using actors. This is realized by having the system guardian watch the user guardian and initiate its own shut-down upon reception of the Terminated message. The top-level system actors are supervised using a strategy which will restart indefinitely upon all types of Exception except for ActorInitializationException and ActorKilledException, which will terminate the child in question. All other throwables are escalated, which will shut down the whole actor system.
/: The Root Guardian
The root guardian is the grand-parent of all so-called “top-level” actors and supervises all the special actors mentioned in Top-Level Scopes for Actor Paths using the SupervisorStrategy.stoppingStrategy, whose purpose is to terminate the child upon any type of Exception. All other throwables will be escalated … but to whom? Since every real actor has a supervisor, the supervisor of the root guardian cannot be a real actor. And because this means that it is “outside of the bubble”, it is called the “bubble-walker”. This is a synthetic ActorRef which in effect stops its child upon the first sign of trouble and sets the actor system’s isTerminated status to true as soon as the root guardian is fully terminated (all children recursively stopped).
What Restarting Means
When presented with an actor which failed while processing a certain message, causes for the failure fall into three categories:
- Systematic (i.e. programming) error for the specific message received
- (Transient) failure of some external resource used during processing the message
- Corrupt internal state of the actor
Unless the failure is specifically recognizable, the third cause cannot be ruled out, which leads to the conclusion that the internal state needs to be cleared out. If the supervisor decides that its other children or itself is not affected by the corruption—e.g. because of conscious application of the error kernel pattern—it is therefore best to restart the child. This is carried out by creating a new instance of the underlying Actor class and replacing the failed instance with the fresh one inside the child’s ActorRef; the ability to do this is one of the reasons for encapsulating actors within special references. The new actor then resumes processing its mailbox, meaning that the restart is not visible outside of the actor itself with the notable exception that the message during which the failure occurred is not re-processed.
The precise sequence of events during a restart is the following:
- suspend the actor (which means that it will not process normal messages until resumed), and recursively suspend all children
- call the old instance’s preRestart hook (defaults to sending termination requests to all children and calling postStop)
- wait for all children which were requested to terminate (using context.stop()) during preRestart to actually terminate; this—like all actor operations—is non-blocking, the termination notice from the last killed child will effect the progression to the next step
- create new actor instance by invoking the originally provided factory again
- invoke postRestart on the new instance (which by default also calls preStart)
- send restart request to all children which were not killed in step 3; restarted children will follow the same process recursively, from step 2
- resume the actor
What Lifecycle Monitoring Means
Note
Lifecycle Monitoring in Akka is usually referred to as DeathWatch
In contrast to the special relationship between parent and child described above, each actor may monitor any other actor. Since actors emerge from creation fully alive and restarts are not visible outside of the affected supervisors, the only state change available for monitoring is the transition from alive to dead. Monitoring is thus used to tie one actor to another so that it may react to the other actor’s termination, in contrast to supervision which reacts to failure.
Lifecycle monitoring is implemented using a Terminated message to be received by the monitoring actor, where the default behavior is to throw a special DeathPactException if not otherwise handled. In order to start listening for Terminated messages, invoke ActorContext.watch(targetActorRef). To stop listening, invoke ActorContext.unwatch(targetActorRef). One important property is that the message will be delivered irrespective of the order in which the monitoring request and target’s termination occur, i.e. you still get the message even if at the time of registration the target is already dead.
Monitoring is particularly useful if a supervisor cannot simply restart its children and has to terminate them, e.g. in case of errors during actor initialization. In that case it should monitor those children and re-create them or schedule itself to retry this at a later time.
Another common use case is that an actor needs to fail in the absence of an external resource, which may also be one of its own children. If a third party terminates a child by way of the system.stop(child) method or sending a PoisonPill, the supervisor might well be affected.
Delayed restarts with the BackoffSupervisor pattern
Provided as a built-in pattern the akka.pattern.BackoffSupervisor implements the so-called exponential backoff supervision strategy, starting a child actor again when it fails, each time with a growing time delay between restarts.
This pattern is useful when the started actor fails [1] because some external resource is not available, and we need to give it some time to start-up again. One of the prime examples when this is useful is when a PersistentActor fails (by stopping) with a persistence failure - which indicates that the database may be down or overloaded, in such situations it makes most sense to give it a little bit of time to recover before the peristent actor is started.
| [1] | A failure can be indicated in two different ways; by an actor stopping or crashing. |
The following Scala snippet shows how to create a backoff supervisor which will start the given echo actor after it has stopped because of a failure, in increasing intervals of 3, 6, 12, 24 and finally 30 seconds:
val childProps = Props(classOf[EchoActor])
val supervisor = BackoffSupervisor.props(
Backoff.onStop(
childProps,
childName = "myEcho",
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2 // adds 20% "noise" to vary the intervals slightly
))
system.actorOf(supervisor, name = "echoSupervisor")
The above is equivalent to this Java code:
import scala.concurrent.duration.Duration;
final Props childProps = Props.create(EchoActor.class);
final Props supervisorProps = BackoffSupervisor.props(
Backoff.onStop(
childProps,
"myEcho",
Duration.create(3, TimeUnit.SECONDS),
Duration.create(30, TimeUnit.SECONDS),
0.2)); // adds 20% "noise" to vary the intervals slightly
system.actorOf(supervisorProps, "echoSupervisor");
Using a randomFactor to add a little bit of additional variance to the backoff intervals is highly recommended, in order to avoid multiple actors re-start at the exact same point in time, for example because they were stopped due to a shared resource such as a database going down and re-starting after the same configured interval. By adding additional randomness to the re-start intervals the actors will start in slightly different points in time, thus avoiding large spikes of traffic hitting the recovering shared database or other resource that they all need to contact.
The akka.pattern.BackoffSupervisor actor can also be configured to restart the actor after a delay when the actor crashes and the supervision strategy decides that it should restart.
The following Scala snippet shows how to create a backoff supervisor which will start the given echo actor after it has crashed because of some exception, in increasing intervals of 3, 6, 12, 24 and finally 30 seconds:
val childProps = Props(classOf[EchoActor])
val supervisor = BackoffSupervisor.props(
Backoff.onFailure(
childProps,
childName = "myEcho",
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2 // adds 20% "noise" to vary the intervals slightly
))
system.actorOf(supervisor, name = "echoSupervisor")
The above is equivalent to this Java code:
import scala.concurrent.duration.Duration;
final Props childProps = Props.create(EchoActor.class);
final Props supervisorProps = BackoffSupervisor.props(
Backoff.onFailure(
childProps,
"myEcho",
Duration.create(3, TimeUnit.SECONDS),
Duration.create(30, TimeUnit.SECONDS),
0.2)); // adds 20% "noise" to vary the intervals slightly
system.actorOf(supervisorProps, "echoSupervisor");
The akka.pattern.BackoffOptions can be used to customize the behavior of the back-off supervisor actor, below are some examples:
val supervisor = BackoffSupervisor.props(
Backoff.onStop(
childProps,
childName = "myEcho",
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2 // adds 20% "noise" to vary the intervals slightly
).withManualReset // the child must send BackoffSupervisor.Reset to its parent
.withDefaultStoppingStrategy // Stop at any Exception thrown
)
The above code sets up a back-off supervisor that requires the child actor to send a akka.pattern.BackoffSupervisor.Reset message to its parent when a message is successfully processed, resetting the back-off. It also uses a default stopping strategy, any exception will cause the child to stop.
val supervisor = BackoffSupervisor.props(
Backoff.onFailure(
childProps,
childName = "myEcho",
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2 // adds 20% "noise" to vary the intervals slightly
).withAutoReset(10.seconds) // the child must send BackoffSupervisor.Reset to its parent
.withSupervisorStrategy(
OneForOneStrategy() {
case _: MyException => SupervisorStrategy.Restart
case _ => SupervisorStrategy.Escalate
}))
The above code sets up a back-off supervisor that restarts the child after back-off if MyException is thrown, any other exception will be escalated. The back-off is automatically reset if the child does not throw any errors within 10 seconds.
One-For-One Strategy vs. All-For-One Strategy
There are two classes of supervision strategies which come with Akka: OneForOneStrategy and AllForOneStrategy. Both are configured with a mapping from exception type to supervision directive (see above) and limits on how often a child is allowed to fail before terminating it. The difference between them is that the former applies the obtained directive only to the failed child, whereas the latter applies it to all siblings as well. Normally, you should use the OneForOneStrategy, which also is the default if none is specified explicitly.
The AllForOneStrategy is applicable in cases where the ensemble of children has such tight dependencies among them, that a failure of one child affects the function of the others, i.e. they are inextricably linked. Since a restart does not clear out the mailbox, it often is best to terminate the children upon failure and re-create them explicitly from the supervisor (by watching the children’s lifecycle); otherwise you have to make sure that it is no problem for any of the actors to receive a message which was queued before the restart but processed afterwards.
Normally stopping a child (i.e. not in response to a failure) will not automatically terminate the other children in an all-for-one strategy; this can easily be done by watching their lifecycle: if the Terminated message is not handled by the supervisor, it will throw a DeathPactException which (depending on its supervisor) will restart it, and the default preRestart action will terminate all children. Of course this can be handled explicitly as well.
Please note that creating one-off actors from an all-for-one supervisor entails that failures escalated by the temporary actor will affect all the permanent ones. If this is not desired, install an intermediate supervisor; this can very easily be done by declaring a router of size 1 for the worker, see Routing or Routing.
Contents


See: Description
| Class | Description |
|---|---|
| BiStreams |
A Streams add-on to work with key/value pairs hydrated in
Tuple2 . |
| IOStreams |
A Streams add-on to work with IO components such as ChronicleStreams.
|
| Promise<O> |
A
Promise is a stateful event container that accepts a single value or error. |
| Promises |
Helper methods for creating
Promise instances. |
| Stream<O> |
Base class for components designed to provide a succinct API for working with future values.
|
| Streams |
A public factory to build
Stream , Streams provide for common transformations from a few structures such as
Iterable or Future to a Stream, in addition to provide for combinatory operations (merge, switchOnNext...). |
| StreamUtils |
A simple collection of utils to assist in various tasks such as Debugging
|
| StreamUtils.StreamVisitor |
| Enum | Description |
|---|---|
| Promise.FinalState |
Signal
rather than by using reactor.bus.selector.Selector Selectors
and reactor.bus.EventBus Reactors directly.


VIP In-Store Preview Party. Win prizes, save big, and exclusive sneak peek. You're the first to know.


About Us
Extremely impressive apps
We are small team of passionate developers, designers and marketers who want to create some awesome mobile apps which make difference in customers lives.
- Our aim is to work on primarily consumer apps, business app and also productivity tools for app developers.
- RayTechnoto first application is Japji Shaib Hindi Punjabi (with Audio) iphone app, sacred hymen of Sikh Gurubani, and it’s dedicated to almighty god, Waheguru.
Services
These apps are available only on the App Store for iPhone and iPad.
Voice Recorder
'Voice Recorder App' – Record Unlimited Audio – is a voice recorder app for android smartphones and tablets. Due to its amazing versatility, simplicity & recording ability, you can use our voice recorder app to dictate notes and memos as well as record meeting, lecture, interview, and day to day sounds.
App Share
'App Share App' app lets you easily share apps to your friends, extract apk file to your phone and uninstall apps from your phone.
Solid Colors Wallpapers HD
'Solid Color Wallpapers' is designed for wallpaper lovers who prefer Solid Color backgrounds like solid black backgrounds, white color backgrounds.