Chapter 3 Probability Basics
3.1 Equally Likely Events
If we flip a coin it is said that heads and tails have the same probability because the percentage of both heads and tails tend toward \(50\%\) as the number of coin flips increases. Think of a probability as the percent of time an outcome occurs when many trials are performed. Here are the results of a simulation.
| Number of Trials | Percent Heads |
|---|---|
| 10 | 60% |
| 1,000 | 48.1% |
| 100,000 | 50.005% |
When we make a “random selection” it means that every possible selection has equal probability. For example, a randomly selected card from a deck of \(52\) cards has probability \(\frac{1}{52}\) of being a 2 of clubs.
When every possible outcome has equal probability, the formula for the probability of some subset of the outcomes is:
\[\frac{\text{Number of Selected Outcomes}}{\text{Number of Total Possible Outcomes}}\]
What is the probability of drawing 4 aces when we randomly select 5 cards from a deck? The number of ways to draw 4 aces is \({4 \choose 4} = 1\) because there are 4 aces and we must select all of them. There are 48 cards to select that are not aces which leads to \({48 \choose 1} = 48\) outcomes.
The number of ways to draw 4 aces is: \[{4 \choose 4}{48 \choose 1} = 48\]
The number of ways to draw 5 cards is: \[{52 \choose 5}\]
The answer is then: \[\frac{{4 \choose 4}{48 \choose 1}}{{52 \choose 5}} = \frac{48}{2598960} = \frac{1}{54145}\]
3.2 Terminology
3.2.1 Sample Spaces and Events
In probability we talk about experiments, sample spaces, and events.
When we flip a coin or roll a die that is an experiment. Experiments have a set of possible outcomes that happen with some probability.
The set of all possible outcomes of an experiment is the sample space. When we flip a coin once the sample space is \(S=\{H,T\}\). When we flip a coin twice the sample space is \(S=\{HH,HT,TH,TT\}\).
Events represent a set of possible outcomes from an experiment. When we flip two coins there is an event for flipping two heads, \(E_\text{both heads}=\{HH\}\). There is also an event for not flipping two heads \(E_\text{not both heads}=\{HT,TH,TT\}\). An event is a subset of the sample space. It may represent a single outcome of our experiment, or it may represent several of the possible outcomes: \[E \subseteq S\]
We can rewrite our formula for probabilities when all outcomes of an experiment are equally likely using \(n(E)\) for the number of selected outcomes. \[\frac{\text{Number of Selected Outcomes}}{\text{Number of Total Possible Outcomes}} = \frac{n(E)}{n(S)}\]
Example: Rolling Dice
We roll two dice and want to calculate the probability that the dice sum to 4. Define the experiment, sample space, event, and calculate the probability of the event.
The experiment is rolling two dice.
The sample space has 36 elements, we can define it in set-builder notation: \[\{(a,b)|a,b \in \{1,2,3,4,5,6\}\}\] The event contains the elements of the sample space summing to 4. \[E = \{(1,3),(3,1),(2,2)\}\] The probability is \[\frac{\text{Number of Selected Outcomes}}{\text{Number of Total Possible Outcomes}} = \frac{n(E)}{n(S)} = \frac{3}{36}=\frac{1}{12}\]
3.3 Probability Functions
There is a function called a probability function, denoted \(P\), that calculates the probability of an event. When we flip a coin twice the probability of getting a head and a tail is: \[P(\{HT, TH\})=.5\] For experiments where all outcomes are equally likely: \[P(E) = \frac{n(E)}{n(S)}\] A probability is between \(0\) and \(1\) because an event can’t happen less than \(0\%\) of the time or more than \(100\%\) of the time. More formally, \(P\) is a function that takes an event as input and gives a number between \(0\) and \(1\) as output. In notation: \[P:E \mapsto [0,1]\]
If we are being more mathematically rigorous, this rule about probabilities being between \(0\) and \(1\) is derived from some more basic assumptions and not intuition about the percentage of times something occurs. Let’s talk about these basic assumptions.
3.3.1 Probability Axioms
There are three fundamental assumptions (called axioms) about probability functions from which our other laws are derived.
First Axiom - For an event \(E\), and probability function \(P\): \[P(E) \geq 0\] Second Axiom - For a sample space \(S\): \[P(S)=1\] Third Axiom - If \(E1, E2, ...En\) are mutually exclusive events: \[P(\bigcup\limits_{i=1}^{\infty} E_{i})=P(E_1 \cup E_2 \cup...\cup En \cup...) = P(E1)+P(E2)+...+P(En)+...\] For two mutually exclusive events events the third axiom is: \[P(E_1 \cup E_2) = P(E_1)+P(E_2)\]
There are several formulas that are useful for this exam that can be derived from these axioms. We can derive the formula for the probability of the complement of an event: \[P(A)+P(A^C) = P(A \cup A^C) = \ P(S) = 1 \ using \ Axioms \ 2 \ and \ 3\] Since \(P(A^C)+P(A) = 1 \implies P(A^C) = 1-P(A)\).
Here are some useful formulas that can be derived from these axioms. \[Complements: \ P(A^C) = 1 - P(A) \\ Upper \ Bound:P(A) \leq 1 \\ General \ Probability \ of \ 2 \ Unions: P(A \cup B) = P(A) + P(B) - P(A \cap B) \\ 3 \ Unions: P(A \cup B \cup C) = \\ P(A) + P(B) + P(C) - P(A \cap B)-P(B \cap C)-P(C \cap A) + P(A \cap B \cap C)\]
Notice that these formulas are the same as our formulas for the size of the set if we swap out \(P\) for \(n\) and \(1\) for \(n(S)\).
Example: Coin Flipping and Axioms
If we flip a coin, heads and tails are mutually exclusive events. \[P(\{H\} \cup \{T\}) = P(\{H\})+P(\{T\}) = .5 + .5 = 1\] We know that \(P(\{H\}), P(\{T\})=.5\) from our formula for equally likely events at the beginning of the chapter. Note that \(S = \{H\} \cup \{T\}\) so this example also illustrates that \(P(S)=1\).
3.4 Conditional Probability and Independence
| Fluffy | Not Fluffy | Total | |
|---|---|---|---|
| Cats | 21 | 18 | 39 |
| Dogs | 35 | 26 | 61 |
| Total | 56 | 44 | 100 |
We make estimates about the overall population of pets using the results of a survey about pets. To do this we pretend that the pets in the survey represent the entire population of pets.
We can calculate the probability of a pet being fluffy using our formula for equally likely events: \[\frac{\text{Number of Fluffy Pets}}{\text{Total Number of Pets}} = \frac{n(\text{Fluffy})}{n(\text{Pets})} = \frac{56}{100}\]
We can calculate the probability of a pet being a fluffy cat as: \[\frac{\text{Number of Fluffy Cats}}{\text{Total Number of Pets}} = \frac{n(\text{Fluffy} \cap \text{Cat})}{n(\text{Pets})} = \frac{21}{100}\]
We can also calculate the probability of a pet being fluffy, given that the pet is a cat: \[\frac{\text{Number of Fluffy Cats}}{\text{Total Number of Cats}} = \frac{n(\text{Fluffy} \cap \text{Cat})}{n(\text{Cats})}=\frac{21}{39}\] Calculating the probability of a pet being fluffy given that the pet is a cat is an example of conditional probability because in the denominator we do not include all of the possible pets, but only the cats. There is a special notation for conditional probabilities: \[\text{Probability Pet is Fluffy given that Pet is a Cat} = P(\text{Pet is Fluffy}|\text{Pet is a Cat})\] The general formula for conditional probabilities uses probabilities instead of set sizes. If all outcomes are equally likely either the probability or set size formula will give the same result: \[\frac{P(\text{Fluffy} \cap \text{Cat})}{P(\text{Cat})} = \frac{n(\text{Fluffy and Cat})/n(\text{Pets})}{n(\text{Cat})/n(\text{Pets})} = \frac{n(\text{Fluffy}\cap\text{Cat})}{n(\text{Cat})}\]
3.4.1 Conditional Probability Formulas
The probability of event \(A\) given that event \(B\) has occurred is denoted \(P(A|B)\) and pronounced “the probability of A given B”. The general formula for this is \[P(A|B)=\frac{P(A \cap B)}{P(B)}\]
For experiments where all outcomes have equal probabilities \(P(A|B)\) can be calculated with set sizes. The derivation for forumla this was done in our example with fluffy cats. \[P(A|B)=\frac{n(A \cap B)}{n(B)}\]
We can calculate the probability of the intersection using the probability of the given event with the conditional probability. This formula is easiest to conceptualize if you imagine an event B happening with probability \(P(B)\) and then an event \(A\) happening with probability \(P(A|B)\). \[P(A|B) \times P(B) = P(A \cap B)\]
3.4.2 Independence
Events are independent if they do not influence each other. The first flip of a coin will not impact the second flip so these events are independent.
Let the event that the first card pulled without replacement from a deck is a jack be \(J_1\) and the event that the second card pulled is a jack is \(J_2\).  The event \(J_1\) has an effect on \(J_2\) and these events are not independent.
Definition of Independence: Events \(A\) and \(B\) are said to be independent if \(P(A|B)=P(A)\).
This definition is equivalent to \(P(A \cap B) = P(A) \times P(B)\) after substitution with the conditional probability formulas. This identity has it’s own name:
Multiplication Rule for Independent Events: If \(A\) and \(B\) are independent events then \(P(A \cap B) = P(A) \times P(B)\).
Let \(H_n\) be the event that the nth flip of a coin is heads so that \(H_2\) means the second coin flip is heads. The multiplication rule for independent events works for more than two events if all events are mutually independent so that \(P(H_1 \cap H_2 \cap H_3 \cap H_4)=P(H_1)\times P(H_2)\times P(H_3)\times P(H_4) = (\frac{1}{2})^4\).
3.5 Bayes Theorem
3.5.1 Bayes Theorem Intuition
Suppose 1% of the population uses drugs. 98% of drug users test positive on a drug test and 2% of non-users test positive. What is the probability that a person testing positive for a drug test has used drugs?
Using the above tree diagram and the definition of conditional probability we calculate: \[P(User|Positive) = \frac{P(User \cap Positive)}{P(Positive)}= \\ \frac{P(User \cap Positive)}{P(Positive \cap Not \ User) + (Positive \cap User)} =\\ \frac{P(Positive|User) \times P(User)}{P(Positive|User) \times P(User)+P(Positive|Not \ User) \times P(Not \ User)} = \\ \frac{.0099}{.0099+.0099}=\frac{1}{2}\]
Let’s explain these steps in more detail.
3.5.2 Law of Total Probability
In our calculation when we go from the first to the second line we use the identity \(P(Positive)=P(Positive \cap User)+P(Positive \cap Not \ User)\), but how do we know this is true? \(Positive \cap User\) only contains drug users and \(Positive \cap Not \ User\) only contains non-users. These events are mutually exclusive so \(P(Positive \cap User)+P(Positive \cap Not \ User) = P((Positive \cap User) \cup (Positive \cap Not \ User))\) using our third probability axiom. Using the distributive property for intersections with the identities \[A^C \cup A = Sample \ Space, \quad A \cap (Sample \ Space) = A\] we can see that: \[(Positive \cap User) \cup (Positive \cap Not \ User) = Positive \cap (User \cup Not \ User) = \\ Positive \cap (Sample \ Space) = Positive\] This is how we know that \(P(Positive)=P(Positive \cap User)+P(Positive \cap Not \ User)\).
There is a more general formulation of this known as the law of total probability:
Events \(A_1,A_2,...,A_n\) are said to be a partition of the sample space \(S\) if \(A_1 \cup A_2 \cup... \cup A_n=S\) and if for all \(i,j: \ A_i \cap A_j = \emptyset\). This just means that the sets \(A_1,A_2,...,A_n\) cover the whole set and there is no overlap between the sets.
If sets \(A_1,A_2,...,A_n\) partition \(S\) then for any event \(E\) we have the law of total probability: \[P(E) = P(E \cap (A_1 \cup A_2 \cup ... \cup A_n)) = \\ P(E \cap A_1) + P(E \cap A_2) + ... + P(E \cap A_n) = \\ P(E|A_1) \times P(A_1) +...+ P(E|A_n) \times P(A_n)\]
Here is a visual explaining the intuition behind the equality in the first line of the equations above:
The proof of the law of total probability is outlined in our discussion of drug users.
3.5.3 Bayes Theorem Formula
<IP_ADDRESS> Derivation Using Law of Total Probability
In our previous example every person is either a drug user or not so this partitions the sample space into two regions, \(User\) and \(Not \ User\). We can use the definition of conditional probability to say: \[P(User|Positive)=\frac{P(User \cap Positive)}{P(Positive)}\] We use the law of total probability in the denominator to expand it and convert all expressions of the form \(P(A \cap B)\) to expressions of the form \(P(B | A) \times P(A)\). The result is: \[\frac{P(Positive|User) \times P(User)}{P(Positive|User) \times P(User)+P(Positive|Not \ User) \times P(Not \ User)}\]
<IP_ADDRESS> Bayes Theorem Statement
For a partition \(A_1,A_2,...,A_n\) and event \(E\): \[P(E|A_k) = \frac{P(E|A_k) \times P(A_k)}{P(E|A_1) \times P(A_1) +...+ P(E|A_n) \times P(A_n)}\]


A step-by-step introduction to QATrack+ administration (continued)¶
In this part of the tutorial we will create a test list made up of the 6 tests we defined in the previous part of this tutorial.
Creating the test list¶
To create the test list, visit the Test Lists link under the QA section from the main admin page and then click on Add test list in the top right hand corner.
Give the test list the name Machine Output and slug machine-output. We will ignore the description and sublist fields for now.
Under the Test list memberships section click on green cross/Add another Test list membership link at the bottom to make a 6th text box appear. Now click the first magnifying glass and click on the Temperature test in the window that pops up.
Repeat this step for the other 5 tests we defined at which point the Test list memberships section should look like:
If you now click Save and continue editing the memberships section should show the actual tets names (and macro names):
That’s it! Now that we’ve created our tests and test list we can assign it to the unit we created earlier. This is covered in the next step of this tutorial.


PTPVSubscriptionDetails
@interface PTPVSubscriptionDetails : NSObject <PTPVAPIResponseDecodable>
Represents the subscription details
-
Unique identifier of the user registered in the system. It will come back empty in the case of error.
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSString *idUser;
Swift
var idUser: String? { get set }
-
Token code associated with the DS_IDUSER.
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSString *tokenUser;
Swift
var tokenUser: String? { get set }
-
Amount of the operation in integer format. 1.00 EURO = 100, 4.50 EUROS = 450…
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSNumber *amount;
Swift
@NSCopying var amount: NSNumber? { get set }
-
Original reference of the operation + [DS_IDUSER] + date of the transaction in format YYYYMMDD.
Example:
DS_SUBSCRIPTION_ORDER = Luis_3268314
The charge of the subscription to DS_IDUSER 32 on December 23, 2030 the system will return it as DS_SUBSCRIPTION_ORDER:
DS_SUBSCRIPTION_ORDER = Luis_3268314[23]20301223
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSString *order;
Swift
var order: String? { get set }
-
Currency of the transaction. - see: more details at http://developers.paytpv.com/en/documentacion/monedas . - see: PTPVCurrency
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) PTPVCurrency *currency;
Swift
var currency: String? { get set }
-
Authentication bank code of the transaction.
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSString *authCode;
Swift
var authCode: String? { get set }
-
Country of the issuer of the card in ISO3 Code (ex.: 724 = Spain). May be left empty.
Declaration
Objective-C
@property (readwrite, copy, nonatomic, nullable) NSString *cardCountry;
Swift
var cardCountry: String? { get set }


For full functionality of this page it is necessary to enable JavaScript.
Here are the instructions
how to enable JavaScript
in your web browser.
© 1983–2022
Леонид Князев


Home
(current)
About
Register
Login
Sign up
×
First Name
Last Name
Username
Your email
Your password
Confirm password
Sign in
×
Your username
Your password
Welcome to Expense-Receipt-Manager
An easy way to keep account of expenses
and manage receipts ......


Before Change
while True:
try:
if legacy_get_next:
with tf.compat.v1.errors.raise_exception_on_not_ok_status() as status:
self._reader.GetNext(status)
else:
self._reader.GetNext()
except (tf.errors.DataLossError, tf.errors.OutOfRangeError) as e:
logger.debug("Cannot read more events: %s", e)
After Change
try:
yield next(self._iterator)
except StopIteration:
logger.debug("End of file in %s", self._file_path)
break
except tf.errors.DataLossError as e:
// We swallow partial read exceptions; if the record was truncated
// and a later update completes it, retrying can then resume from


Type Inference
Garter, aka Guaranteed Type Enforced Reliability, is an extensnion of FDL with statically inferred types.
garter
starts with fer-de-lance
and makes one major addition and a minor deletion, in particular, we
- add static types,
- replace unbounded tuples, with pairs.
That is, we now have a proper type system and the Checker
is extended to infer types for all sub-expressions.
The code proceeds to compile
(i.e. Asm
generation) only if it type checks.
This lets us eliminate a whole bunch of the dynamic tests
assertType TNumber
assertType TBool
assertType TTuple
assertBound
etc. as code that typechecks is guaranteed to pass the checks at run time.
Strategy
Lets start with an informal overview of our strategy for type inference; as usual we will then formalize and implement this strategy.
The core idea is this:
- Traverse the
Expr
… - Generating fresh variables for unknown types…
- Unifying function input types with their arguments …
- Substituting solutions for variables to infer types.
Lets do the above procedure informally for a couple of examples!
Example 1: Inputs and Outputs
Example 2: Polymorphism
Example 3: Higher-Order Functions
Strategy Recap
- Traverse the
Expr
… - Fresh variables for unknown types…
- Unifying function input types with their arguments …
- Substituting solutions for variables to infer types …
- Generalizing types into polymorphic functions …
- Instantiating polymorphic type variables at each use-site.
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Syntax
First, lets see how the syntax of our garter
changes to enable static types.
Syntax of Types
A Type
is one of:
data Type
= TInt -- Int
| TBool -- Bool
| [Type] :=> Type -- (t1,...,tn) => t
| TVar TVar -- a, b, c
| TPair Type Type -- (t0, t1)
| TCtor Ctor [Type] -- e.g. C[t1,...,tn]
deriving (Eq, Ord)
here Ctor
and TVar
are just string names:
newtype Ctor
= CT String -- e.g. "List", "Tree"
deriving (Eq, Ord)
newtype TVar
= TV String -- e.g. a, b, c
deriving (Eq, Ord)
Finally, a polymorphic type is represented as:
Example: Monomorphic Types
A function that
- takes two input
Int
- returns an output
Int
Has the monomorphic type (Int, Int) => Int
Which we would represent as a Poly
value:
(Forall [] ([TInt, TInt] :=> TInt)) :: Poly
Note: If a function is monomorphic (i.e. not polymorphic), we can just use the empty list of TVar
.
Example: Polymorphic Types
Similarly, a function that
- takes a value of any type and
- returns a value of the same type
Has the polymorphic type forall a. (a) => a
Which we would represent as a Poly
value:
Forall [TV "a"] ([TVar (TV "a")] :=> (TVar (TV "a")))
Note: Haskell allows OverloadedStrings
which lets us treat "a"
as both a TVar
and a Type
as needed. So we can rewrite the above as:
Forall ["a"] (["a"] :=> "a")
Similarly, a function that takes two values and returns the first, can be given a Poly
type forall a, b. (a, b) => a
which is represented as:
Forall ["a", "b"] (["a", "b"] :=> "a")
Syntax of Expressions
To enable inference garter
simplifies the language a little bit.
Dynamic tests
isNum
andisBool
are removed,Tuples always have exactly two elements; you can represent
(x, y, z)
as(x, (y, z))
.Tuple access is limited to the fields
Zero
andOne
(instead of arbitrary expressions).
data Expr a
= ...
| Tuple (Expr a) (Expr a) a -- Tuples have 2 elems
| GetItem (Expr a) Field a -- Access 0-th or 1-st elem
| Fun (Bind a) Sig [Bind a] (Expr a) a -- named functions
data Field
= Zero -- 0-th field
| One -- 1-st field
data Sig
= Infer -- no specification, infer scheme
| Check Poly -- check that function has given (poly-) type
| Assume Poly --
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Substitutions
Our informal algorithm proceeds by
- Generating fresh type variables for unknown types,
- Traversing the
Expr
to unify the types of sub-expressions, - By substituting a type variable with a whole type.
Lets formalize substitutions, and use it to define unification.
Representing Substitutions
We represent substitutions as a record with two fields:
data Subst = Su
{ suMap :: M.Map TVar Type -- ^ hashmap from type-var := type
, suCnt :: !Int -- ^ counter used to generate fresh type vars
}
suMap
is a map from type variables to types,suCnt
is a counter used to generate new type variables.
For example, exSubst
is a substitution that maps a
, b
and c
to Int
, Bool
and (Int, Int) => Int
respectively.
exSubst :: Subst
exSubst = Su m 0
where
m = (M.fromList [ ("a", TInt)
, ("b", TBool)
, ("c", [TInt, TInt] :=> TInt) ])
apply exSubst ([Int, "zong"] :=> Bool)
Applying Substitutions
The main use of a substition is to apply it to a type, which has the effect of replacing each occurrence of a type variable with its substituted value (or leaving it untouched if it is not mentioned in the substitution.)
We define an interface for “things that can be substituted” as:
and then we define how to apply
substitutions to Type
, Poly
, and lists and maps of Type
and Poly
.
For example,
returns
by replacing "a"
and "b"
with TInt
and TBool
and leaving “z” alone.
QUIZ
Recall that exSubst = ["a" := TInt, "b" := TBool]
…
What should be the result of
apply exSubst (Forall "a" (["a"] :=> "a"))
Forall ["a"] ([TInt] :=> TBool)
Forall ["a"] (["a" ] :=> "a" )
Forall ["a"] (["a"] :=> TBool)
Forall ["a"] ([TInt] :=> "a")
Forall [ ] ([TInt] :=> TBool)
Bound vs. Free Type Variables
Indeed, the type
forall a. (a) => a
is identical to
forall z. (z) => a
A bound type variable is one that appears under a
forall
.A free type variable is one that is not bound.
We should only substitute free type variables.
Applying Substitutions
Thus, keeping the above in mind, we can define apply
as a recursive traversal:
apply _ TInt = TInt
apply _ TBool = TBool
apply su (TVar a) = M.findWithDefault (TVar a) a (suMap su)
apply su (ts :=> t) = apply su ts :=> apply su t
apply su (Forall as t) = Forall as $ apply (unSubst as su) t
where unSubst
removes the mappings for as
from su
Creating Substitutions
We can start with an empty substitution that maps no variables
Extending Substitutions
we can extend the substitution by assigning a variable a
to type t
extSubst :: Subst -> TVar -> Type -> Subst
extSubst su a t = su { suMap = M.insert a t su' }
where
su' = apply (mkSubst [(a, t)]) (suMap su)
Telescoping
Note that when we extend [b := a]
by assigning a
to Int
we must take care to also update b
to now map to Int
. That is, we want:
extSubst [ "b" := "a" ] "a" TInt
to be
[ "b" := TInt, "a" := TInt ]
That is why we:
apply [a := Int]
to update the old substitution to getsu'
insert
the new assignmenta := Int
intosu'
.
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Unification
Next, lets use Subst
to implement a procedure to unify
two types, i.e. to determine the conditions under which the two types are the same.
| T1 | T2 | Unified | Substitution |
|---|---|---|---|
Int |
Int |
Int |
empSubst |
a |
Int |
Int |
a := Int |
a |
b |
b |
a := b |
a -> b |
a -> d |
a->d |
b := d |
a -> Int |
Bool -> b |
Bool -> Int |
a := Bool, b:=Int |
Int |
Bool |
Error | Error |
Int |
a -> b |
Error | Error |
a |
a -> Int |
Error | Error |
- The first few cases: unification is possible,
- The last few cases: unification fails, i.e. type error in source!
Occurs Check
The very last failure:
a
in the first type occurs inside free inside the second type!If we try substituting
a
witha -> Int
we will just keep spinning forever! Hence, this also throws a unification failure.
Exercise
Can you think of a program that would trigger the occurs check failure? (You’ve probable written several such programs in 130 and 131!)
Implementing Unification
We implement unification as a function:
such that
returns a substitution su'
that extends su
with with the assignments needed to make t1
the same as t2
, i.e. such that apply su' t1 == apply su' t2
.
The code is pretty much the table above:
unify :: SourceSpan -> Subst -> Type -> Type -> Subst
unify _ su TInt TInt = su
unify _ su TBool TBool = su
unify sp su (TVar a) t = varAsgn sp su a t
unify sp su t (TVar a) = varAsgn sp su a t
unify sp su (is :=> o) (is' :=> o') = unify (unifys sp su is is') (apply s1 o) (apply s1 o')
unify sp _ t1 t2 = abort (errUnify sp t1 t2)
The helpers
unifys
recursively callsunify
on lists of types:varAsgn
extendssu
with[a := t]
if required and possible!
varAsgn :: SourceSpan -> Subst -> TVar -> Type -> Subst
varAsgn sp su a t
| t == TVar a = su -- assigned to itself, do nothing
| a `elem` freeTvars t = abort (errOccurs sp a t) -- oops, fails occurs check!
| otherwise = extSubst su a t -- extend su with [a := t]
We can test out the above table:
λ> :set -XOverloadedStrings
λ> unify junkSpan empSubst TInt TInt
(fromList [], 0)
λ> unify junkSpan empSubst (["a"] :=> TInt) ([TBool] :=> "b")
(fromList [(a,Bool), (b,Int)], 0)
λ> unify junkSpan empSubst ("a") (["a"] :=> TInt)
*** Exception: "Type error: occurs check fails: a occurs in (a) => Int"...
λ> unify junkSpan empSubst TInt TBool
*** Exception: "Type error: cannot unify Int and Bool" ...
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Generalize and Instantiate
Ok, the next step is an easy one. Recall the example:
For the expression lambda(x): x
we inferred the type (a0) => a0
We needed to generalize the above:
- to assign
id
thePoly
-type:forall a0. (a0) => a0
We needed to instantiate the above Poly
-type at each use
- at
id(7)
the functionid
hasType
(Int) => Int
- at
id(true)
the functionid
hasType
(Bool) => Int
Lets see how to implement those two steps.
Type Environments
To generalize
a type, we
- Compute its (free) type variables,
- Remove the ones that may still be constrained by other in-scope program variables.
We represent the types of in scope program variables as type environment
i.e. a Map
from program variables Id
to their (inferred) Poly
type.
Generalize
We can now implement generalize
as:
generalize :: TypeEnv -> Type -> Poly
generalize env t = Forall as t -- 4. slap a `Forall` on the unconstrained vars
where
tvs = freeTvars t -- 1. compute tyVars of `t`
evs = freeTvars env -- 2. compute tyVars of `env`
as = L.nub (tvs L.\\ evs) -- 3. compute unconstrained vars: (1) minus (2)
The helper freeTvars
computes the set of variables that appear inside a Type
, Poly
and TypeEnv
:
-- | type-vars of a Type
freeTvars TInt = []
freeTvars TBool = []
freeTvars (TVar a) = [a]
freeTvars (ts :=> t) = freeTvars ts ++ freeTvars t
-- | type-vars of a Poly (we remove the "bound" forall-vars)
freeTvars (Forall as t) = freeTvars t L.\\ as
-- | type-vars of an TypeEnv
freeTvars (TypeEnv m) = freeTvars [s | (x, s) <- M.toList m]
Instantiate
Next, to instantiate a Poly
of the form
Forall [a1,...,an] t
we:
- Generate fresh type variables,
b1,...,bn
for each “parameter”a1...an
- Substitute
[a1 := b1,...,an := bn]
in the “body”t
.
For example, to instantiate
we
- Generate a fresh variable e.g.
"a66"
, - Substitute
["a" := "a66"]
in the body["a"] :=> "a"
to get
Implementing Instantiate
We implement the above as:
instantiate :: Subst -> Poly -> (Subst, Type)
instantiate su (Forall as t) = (su', apply suInst t)
where
(su', as') = freshTVars su n
suInst = mkSubst (zip as as')
n = length as
Question Why does instantiate
return a Subst
?
Lets run it and see what happens!
λ> :set -XOverloadedStrings
λ> let tId = Forall ["a"] (["a"] :=> "a")
λ> let (su0, id0) = instantiate empSubst tId
λ> let (su1, id1) = instantiate su0 tId
λ> id0
(a0) => a0
λ> id1
(a1) => a1
As in anf
and label
- The
fresh
calls bump up the counter … - But must use the returned
Subst
for future calls.
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Inference
Finally, we have all the pieces to implement the actual type inference procedure ti
The function ti
takes as input:
- A
TypeEnv
mapping in-scope variables to their inferred (Poly
)-types, - A
Subst
containing the current substitutions and fresh-variable-counter, - An
Expr
whose type we want to infer.
and returns as output a pair of:
- The inferred type for the given
Expr
and - The extended
Subst
resulting from- generating fresh type variables and
- doing the unification needed to check the
Expr
.
Lets look at how ti
is implemented for the different cases of expressions.
Inference: Literals
For numbers and booleans, we just return the respective type and the input Subst
without any modifications.
Inference: Variables
For identifiers, we
- lookup their type in the
env
and - instantiate type-variables to get different types at different uses.
Why do we instantiate? Recall the id
example!
Inference: Let-bindings
Next, lets look at let-bindings:
ti env su (Let x e1 e2 _) = ti env'' su1 e2 -- (5)
where
(su1, t1) = ti env su e1 -- (1)
env' = apply su1 env -- (2)
s1 = generalize env' t1 -- (3)
env'' = extTypeEnv x s1 env' -- (4)
In essence,
- Infer the type
t1
fore1
, - Apply the substitutions from (1) to the
env
, - Generalize
t1
to make it aPoly
types1
, - Extend the env to map
x
tos1
and, - Infer the type of
e2
in the extended environment.
Inference: Function Definitions
Next, lets see how to infer the type of a function i.e. Lam
ti env su (Lam xs body) = (su3, apply su3 (tXs :=> tOut)) -- (5)
where
(su1, tXs :=> tOut) = freshFun su (length xs) -- (1)
env' = extTypesEnv env (zip xs tXs) -- (2)
(su2, tBody) = ti env' su1 body -- (3)
su3 = unify su2 tBody (apply su2 tOut) -- (4)
Inference works as follows:
- Generate a function type with fresh variables for the unknown inputs (
tXs
) and output (tOut
), - Extend the
env
so the parametersxs
have typestXs
, - Infer the type of
body
under the extendedenv'
astBody
, - Unify the expected output
tOut
with the actualtBody
- Apply the substitutions to infer the function’s type
tXs :=> tOut
.
Inference: Function Calls
Finally, lets see how to infer the types of a call i.e. App
ti env su (App f es) = (su4, apply su4 tOut) -- (6)
where
(su1, tF) = ti env su f -- (1)
env' = apply su1 env -- (2)
(su2, tEs) = L.mapAccumL (ti env') su1 es -- (3)
(su3, tOut) = freshTVar su2 -- (4)
su4 = unify su3 tF (tEs :=> tOut) -- (5)
The code works as follows:
- Infer the type of the function
f
astF
, - Apply resulting substitutions to
env
(as before), - Infer the types of the inputs
es
astEs
, - Generate a variable for the unknown output type,
- Unify the actual input-output
tEs :=> tOut
with the expectedtF
- Return the (substituted)
tOut
as the inferred type of the expression.
Note: In your starter code we factor out steps 3-6, i.e. the code that checks the arguments and infers the output type into tiApp
to let us reuse it to handle extensions
Plan
- Types
- Expressions
- Variables & Substitution
- Unification
- Generalize & Instantiate
- Inferring Types
- Extensions
Extensions
The above gives you the basic idea, now you will have to implement a bunch of extensions.
- Primitives
- (Recursive) Functions
- Type Checking
Extensions: Primitives
What about primitives ?
add1(e)
,print(e)
,e1 + e2
etc.
What about branches ?
if cond: e1 else: e2
What about tuples ?
(e1, e2)
ande[0]
ande[1]
All of the above can be handled as applications to special functions.
For example, you can handle add1(e)
by treating it as passing a parameter e
to a function with type:
(Int) => Int
Similarly, handle e1 + e2
by treating it as passing the parameters [e1, e2]
to a function with type:
(Int, Int) => Int
Can you figure out how to similarly account for branches, tuples, etc. by filling in suitable implementations of:
prim2Poly
ifPoly
tupPoly
,fieldPoly
HINT: Use the implementation for prim1Poly
(and instApp
, tiApp
) in the starter code as a guide.
Extensions: (Recursive) Functions
Extend or modify the code for handling Lam xs e
so that you can handle Fun f xs e
. This is mostly straightforward:
- You can basically reuse the code as is
- Except if
f
appears in the body ofe
Can you figure out how to modify the environment under which e
is checked to handle the above case?
Extensions: Type Checking
While inference is great, it is often useful to specify the types.
While inference is great, it is often useful to specify the types.
- They can describe behavior of untyped code
- They can be nice documentation, e.g. when we want a function to have a more restrictive type.
Assuming Specifications for Untyped Code
For example, we can implement lists as tuples and tell the type system to:
- trust the implementation of the core list library API, but
- verify the uses of the list library.
We do this by:
def null() as forall a. () => List[a]:
false
in
def link(h, t) as forall a. (a, List[a]) => List[a]:
(h, t)
in
def tail(l) as forall a. (List[a]) => List[a]:
l[1]
in
def length(l):
if l == null():
0
else:
1 + length(tail(l))
in
let l0 = link(0, link(1, link(2, null())))
in
length(l0)
The as
keyword tells the system to trust the signature, i.e. to assume it is ok, and to not check the implementations of the function (see how ti
works for Assume
.)
However, the signatures are used to ensure that null
, link
and tail
are used properly, for example, if we tried the following
link(1, link(true, null()))
we should get an error:
tests/input/err-list.gtr:9:1-24: Type error: cannot unify Int and Bool
9| link(1, link(true, null()))
^^^^^^^^^^^^^^^^^^^^^^^
Checking Specifications
Finally, sometimes we may want to restrict a function be used to some more specific type than what would be inferred.
garter
allows for specifications on functions using the ::
operator. For example, you may want a special function that just compares two Int
for equality:
def eqInt(x, y) :: (Int, Int) => Bool :
x == y
in
eqInt(17, 19)
As another example, you might write a swapList
function that swaps pairs of lists The same code would swap arbitrary pairs, but lets say you really want it work just for lists:
def null() as forall a. () => List[a]:
false
in
def link(h, t) as forall a. (a, List[a]) => List[a]:
(h, t)
in
def swapList(p) :: forall a.((List[a], List[b])) => (List[b], List[a]) :
(p[1], p[0])
in
let l0 = link(1, null())
, l1 = link(true, null())
in
swapList((l0, l1))
Can you figure out how to extend the ti
procedure to handle the case of Fun f (Check s) xs e
, and thus allow for checking type specifications?
HINT: You may want to factor out steps 2-5 in the ti
definition for Lam xs body
— i.e. the code that checks the body
has type tOut
when xs
have type tXs
— into a separate function to implement the ti
cases for
Fun f (Infer) xs e
Fun f (Check) xs e
This is a bit tricky, and so am leaving it as Extra Extra Credit.


The Half-Domain/Half-Primitive Proxy
I recently spent a few years working in the retail sector building web APIs. Some of these projects were greenfield but I also worked on a number of existing (brownfield) services too. As you might expect working on variations of a theme you start to see patterns developing in the way the services are designed and implemented.
There are apparently only so many ways you can skin a cat and once you have chosen your programing language and web service framework many things naturally fall into place as you have bought into their paradigms. Plenty has been written about these frameworks and how to use them but that’s not the pattern of focus here, this article looks at the other end of the wire – the client proxy – an area with less attention to detail.
When building a web API the ultimate deliverable is the service itself, more commonly these days a REST API using JSON as the wire-level content format. If you’re building an API in the enterprise you may have to support XML too but that seems to be heavily declining as JSON has been the lingua-franca of Internet APIs for some time. The service might be deployed on premise or in the cloud and could be self-hosted, i.e. you own the hosting process, or run as part of a shared web service such as IIS. Hence any client that wants to talk to your service needs to be fluent in HTPP and JSON too. There are plenty of libraries available for handling these low-level details; the client use cases we are interested in though sit just a little higher up the call stack.
The most likely client in the beginning will be the set of acceptance tests used to describe and verify the service’s various behaviours. In something reasonably small and well defined like a web service the balance of the testing pyramid [1] may be skewed in favour of more customer tests and less programmer tests as they provide the perfect opportunity for outside-in [2] development. Yes, unit tests are still highly useful for those behaviours which are much harder to invoke from the outside without exposing back-door endpoints, such as error recovery, but the lion’s share can be invoked by an external client.
Therefore our primary need for a proxy is to facilitate the writing of acceptance tests for our service. Our test cases need to be able to invoke our API in a variety of ways to ensure we cover both the happy paths but also the less happy ones too by ensuring both malicious and accidentally malformed inputs are correctly handled and the caller is provided with as much information as possible to correct the error of their ways. For example we might write a test like this to check that a REST resource is correctly secured:
[TestFixture]
public class orders_are_secured
{
[Test]
public void request_returns_unauthorised_when_token_is_missing()
{
const string customerId = “123456789”;
var request = new FetchOrdersRequest(customerId);
request.RemoveHeader("Authorization");
var proxy = new ShopProxy();
var response = proxy.Send(request);
Assert.That(response.StatusCode, Is.EqualTo(401));
}
}
While acceptance tests take care of all the fine details about how the service works you probably want something a little simpler to just “kick the tyres” during (or just after) a deployment. You could repurpose the acceptance tests, minus any that use private APIs to perturb the clock or other internals details, but they are often overkill when all you really want to do is exercise some core customer journeys. For example one journey might be to find the most recent order for a known test customer (as we’ve just exercised the journey to place an order for them and already know it succeeded):
public static void
ViewLatestOrder(CustomerId customerId, ...)
{
var shop = new ShopProxy();
var token = shop.AcquireCustomerToken(customerId, credentials);
var orders = shop.FetchLatestOrders(customerId, token);
. . .
}
Deployment isn’t the only time when you might want to exercise your API in this way though; you’ll want to keep doing it all through the day as part of your monitoring strategy. The use of “canaries” is a common technique for firing requests into your system at repeated intervals to allow you to record how it’s behaving. If you can capture some performance data at the same time [3] you have an easy way to track the change in performance over time from the client’s perspective (if you can invoke it from another data centre) and correlate that with the load at those moments in time.
Even during development or bug fixing it’s still useful to be able to run the smoke tests quickly over your local build, especially if the acceptance tests take some shortcuts, such as hosting the API in-process. For example, whenever changing something other than functional code that will affect the set of deployed artefacts, like adding or removing assemblies or updating 3rd party package, it’s useful to do a full build and deploy locally and then run the smoke tests before committing. This is to ensure nothing has been left out, like a configuration setting or binary that will cause the service to choke on start-up and unnecessarily disrupt the delivery pipeline.
In my recent “Toolbox” column Libraries, Console Apps and GUIs [4] I described how I’ve found that home-grown tools often have a habit of being useful to a wider audience, such as a support team. Hence when you have a simple tool that can exercise a few basic journeys you already have all the code you need to provide fine-grained access to your service through, say, a command line interface.
For something like a REST API which has been built on open protocols and for which the Internet provides a bewildering array of tools it might seem a little wasteful putting a custom tool together. In the early life of an HTTP service a tool like CURL or a Chrome extension such as Postman can provide everything you need to poke the endpoints and see the responses. However once you start needing to make calls out to more than once service to accomplish a bigger task, such as requesting an access token from an authentication service, the friction starts to accumulate.
At this point that shell script which fuses together CURL for the HTTP aspects, along with, say, JQ for the JSON parsing starts to become a little unwieldy, especially if you’re on the Windows platform where these tools aren’t installed by default. A Windows heavy enterprise will probably use an NTLM based proxy too for accessing the outside world which can create another world of pain if you’re trying to use open source tooling [5]. Hence putting together a little .Net based tool (or PowerShell script which uses .Net under the covers) can hide this unnecessary noise from the (support) user. Fortunately CURL is one of those tools which can punch its way through an NTLM proxy (with the relevant command line switches), although you still need to watch out for certificate problems if the organisation uses its own. (Self-signed certificates are a common technique in the enterprise at the moment for monitoring traffic to the outside world.)
With the various API endpoints exposed through a little command line tool it makes it really easy to automate simple support and administration tasks. Instead of stitching together low-level tools like CURL and JQ you can work at a higher level of abstraction which makes the already daunting tasks of comprehending a shell script just that little bit easier. For example I might need to check the loyalty points balance for an arbitrary customer that would first require a special, short-lived “administration token” to be obtained using my separate administrative credentials:
> PointsAdmin
view-balance --customer 123456 --administrator %MY_ADMIN_LOGIN% --password
%MY_ADMIN_PASSWORD%
42.5
This approach can also be used as an alternative to monkeying around with the database. While there may be times when a one-off database tweak might be necessary it’s preferable to factor support and administration functions directly into the API (secured of course) so that the chances of corrupting any data are minimised by accidentally violating some invariant which is enforced in the service code rather than the database (a necessity with the newer document-oriented databases).
One natural by-product of creating an independent proxy for your service is that you have something which other service consumers might find useful, assuming of course they are using the same language or runtime. In the enterprise arena where the desire is to minimise the number of unique languages and runtimes in play it’s highly likely that one more consumers may find your wares of interest. (With the CLR and JVM the programming language does not have to be the same but in my experience enterprises still limit the number of languages even on these runtimes despite the built-in interoperability benefits.)
That said it’s easy for shared libraries like this to become a burden on the team, especially when the consumers assume they form a supported part of the product. If that is a responsibility the team wishes to take on, then so be it, but unless this is agreed upon the proxy should be considered nothing more than a “leg up” to help a consumer bootstrap their use of the service. They should have the choice of whether to fork your source and customise it, or build their own. Removing this supporting role often goes against the commonly established enterprise goal of maximising efficiency, but it is necessary to ensure the higher purpose of decoupling the service and consumer deliveries where possible.
On the face of it providing a proxy may not seem like much of a burden but the interfaces and data types are only one part of what it takes to write a solid, reliable client. Once you start factoring in logging [6], instrumentation, and monitoring [7] the need to provide hooks to allow your code to interoperate with whatever product choices the caller has chosen for these concerns adds to the complexity. If you plan to use your own technical and domain types [8] too, e.g. Optional, Date, CustomerId, etc. then these need to be easily accessible so the consumer doesn’t need to ship half your service libraries as well as their own just to use it.
In my experience these various use cases, when they do eventually appear, will end up as a discrete set of different libraries or tools. Consequently by the time the pattern begins to surface the design has long passed the point where a simple refactoring can bring together the various strands into a single coherent component. What follows below is one common path I’ve observed.
The proxy used in the acceptance tests will no doubt evolve
in a very rough-and-ready fashion. Being “merely” test code there will be
little thought put into how the tests need to talk to the service under inspection
and so the code will probably suffer from a form of Primitive Obsession [9]
where the native HTTP client library will feature heavily. Eventually common utility
methods will be introduced but no serious refactoring will take place and the
need to verify both happy and error paths will lead to a smorgasbord of
overloads with some throwing and others returning values. Being used solely for
testing (at this point) there’s a good chance that the test framework assertion
methods will be interwoven with the proxy code (rather than there being a clear
boundary between “sending the request” and “validating the response”), e.g.
public string OpenTestAccount(string customer)
{
var request = new OpenAccountRequest{ Customer = customer };
var response = ShopProxy.Send<OpenAccountResponse>(request);
Assert.That(response.StatusCode, Is.EqualTo(200));
Assert.That(response.AccountId, Is.Not.Empty);
return response.AccountId;
}
[Test]
public void closing_an_account_returns_ok()
{
var accountId = OpenTestAccount(“. . .”);
var request = new CloseAccountRequest{ AccountId = accountId };
var response = ShopProxy.Send(request);
Assert.That(response.StatusCode, Is.EqualTo(200));
}
In the early days of an API where you’re not even sure what conventions it will adopt, such as what URL structure to use, query parameters vs body, headers, etc. the API needs to evolve quickly. If the initial focus is on the happy path then the size of the proxy interface may be quite small and easily maintainable but as the error paths begin to play a role and more control is needed around the URL, headers and body content, the more work is needed to keep everything in sync and make sure that every test really does exercise the behaviour it thinks it does. If the API changes quite radically, e.g. a change in the “resource” structure, then a lot of ad-hoc test code might need fixing up – treating test code as a first class citizen is important for supporting rapid change.
As alluded to earlier if the service is based on open protocols, like HTTP, then it’s certainly possible to cobble together whatever you need from established open source tools, like CURL. Deployment tools like Ansible and dynamic languages like Python have plenty of modules for both high-level tasks, like configuring a machine, and lower-level tasks, such as testing port connectivity and making basic transport requests. Therefore it’s quite possible that unless the development and deployment teams are aligned (if they’re not one and the same) they will each use what they know best and create their own method for testing the service’s availability. This isn’t a problem per-se unless the development team wants to iterate quickly over their API and it causes friction down the delivery pipeline due to unexpectedly breaking the deployment and monitoring processes.
This is one of the reasons why operations’ concerns must be factored into any user stories and the definition of “done” should include monitoring and alerting updates as well the more obvious developer oriented tasks.
A similar argument can probably be made for any support requirements – they will use whatever off-the-shelf tools they can find or are already used to. Similarly if they have a choice between directly accessing the database and trying to go through the API, the path of least resistance leads to the former choice unless their needs are also explicitly factored into the service design and tooling.
The reason for choosing open protocols is that it affords any consumers the ability to choose what technologies they prefer for accessing the service. Therefore on the principle of “use before reuse” [10] there is unlikely to be a direct need to provide a formal client proxy unless the team happens to be responsible for maintaining a number of related services and therefore there is something to be gained from having a component that can be shared.
What is highly unlikely to occur (unless it’s a conscious decision) is that the proxy developed for the acceptance tests can be easily factored out into a separate component that is then reusable in both scenarios. It is more likely the other way around, i.e. reusing the client SDK for some aspects of the acceptance tests (happy paths), if the refactoring costs are considered worth it.
Although the pattern uses the term “proxy” it should be pointed out that this use is not entirely in keeping with the classic Proxy pattern described in the seminal book on Design Patterns by “The Gang of Four” [11]. One of the key traits of the pattern described in that book is that the proxy exposes the same interface as the underlying object. In essence a proxy in their eyes is entirely transparent and acts purely as a surrogate for the real deal. In this article the underlying transport class provided by the language runtime fulfils that role, which for .Net would be HttpClient for the HTTP protocol.
One of the most important aspects of the Design Patterns movement was the attempt to introduce a common vocabulary to make it easier to talk about similar design concepts. Hence it feels a little awkward not to stick to the letter of the law, so to speak, and use it for something which is more loosely related. For me proxies have been placeholders for remote objects and services ever since I wrote my first RPC code on a Sun 3/60 workstation at university and therefore I feel the surrogate aspect of this design is in keeping with their pattern, even if the exposure of a different interface is not. Hopefully no one will be confused by my choice of term because I’ve painted outside the lines in a few places.
That does not mean though that we are entirely excluded from using the other patterns in that seminal work for describing our “creation”. On the contrary this pattern is essentially just the composition of two of their other classics – Adapter and Façade.
The following diagram shows the general shape of the pattern:
Working slightly unusually from the network end back up to the caller we begin with the underlying transport class that provides the true proxy for the service we want to access which is often provided by the language runtime. Being a general purpose class this needs to exposes everything that anyone would ever likely want to do to access a service using the type of network transport in question. For something like HTTP this could include everything ranging from simple JSON REST APIs up to streaming content of different media types using different encodings.
Our requirements however are often far more meagre and what we initially need is to reduce that all-encompassing interface down into something simpler and more focused. For example if we’re talking to a microservice using HTTP and JSON we can simplify a lot of the interface and make many more assumptions about the responses. In design pattern terms this simplification is known as a façade.
With the transport layer interface largely simplified, albeit still with some elements of complexity to allow ourselves enough control over the more unusual requests we’ll be sending, such as during testing, we now need to hide that grunge for the client that isn’t interested in any of that but wants something richer and more intuitive.
Hence the front-facing half of the proxy is more akin to an Adapter from the original Gang of Four book. In this instance its role is to present an interface to the caller that deals in rich types, which is typically why we’re using a statically typed language, and convert them into the more text oriented world of the façade. Likewise the return path transforms the responses from text to types and also maps any failures into a more suitable error mechanism.
There is an element of further simplification going on here too, so it is also façade-like in nature, but its primary purpose is to provide a different interface rather than a simpler version of the same one.
Now that we have a grasp on the various forces that are driving the design and a feel for the overall pattern shape we can look at the interfaces of the two halves in more detail. This time we’ll look at them in the more conventional order starting with the consumer’s perspective and then moving behind the curtain.
For normal production use it is desirable to move away from a typical “stringly typed” interface and instead traffic in rich domain types like dates, product identifiers and enumerations. At this level, if you’re using a statically type language, then the type system can work for you, both to help catch silly mistakes but also provide you with hints through tools like IntelliSense.
To invoke a simple query on the service shouldn’t require you to know how to format the URL, or what goes in the header, or how dates and times need to be passed in JSON (which has no native date or time type). The domain level interface abstracts all of this away and hides enough of the transport details to make remote calls appear less remote (avoiding overly chatty interfaces).
var shop = new
ShopProxy(hostname);
var lastMonth = DateTime.Now.AddDays(-30);
var orders = shop.FindOrders(lastMonth, Status.Delivered);
The network is unreliable though and so error handling probably takes the form of exceptions as recovery from low-level transient request failures will likely take the form of continuous retries somewhere further up the stack. A basic exception hierarchy can support the most common catastrophic error scenarios, such as timeouts, disconnections, service failures (e.g. 500 and 503), client errors (e.g. 400), etc. Buried in these exceptions might be more fine-grained diagnostic context but the exception type itself should be enough to indicate if it’s a (fast) retry scenario, there is something more fundamentally broken at the client end and a (slow) retry or triaging is required, or the request is just broken and we need to “return to sender”.
While exceptions might be a suitable technique for handling transport level failures there are a number of HTTP error codes which fall into the less exceptional end of the spectrum, such as 404 which means a resource couldn’t be found. While this might be down to a bug in your client (you’ve requested the wrong thing due to a URL formatting error) if there is a chance, either through concurrency or due to later deletion, that it might not exist then an Optional<T> would probably be a better return type, e.g.
public Optional<Balance>
FetchBalance(AccountId accountId)
{
var request = new FetchBalanceRequest(accountId);
var response = proxy.Send<BalanceResponse>(request);
if (response.Succeeded)
return Optional<Balance>.Some(response.Content.Balance);
else if (response.StatusCode == 404)
return Optional<Balance>.None;
else
throw new BalanceFetchError(. . .);
}
Likewise if updating a resource can fail due to concurrency conflicts then it’s better to represent that in the interface so the caller stands a better chance of realising they need to do more work than simply keep sending the same request again and again. (They may choose to turn it into a “conflict” exception type but that’s their judgement call.)
A key rationale for the split in the design is that the domain-level proxy sits on top of the primitive-level proxy and therefore has the opportunity to compensate for idiosyncrasies in the representation chosen by the service so the caller gets a more cohesive interface. A common example is where a web API chooses to represent domain errors by returning a 200 status code and a body instead of using the preferred 4XX status codes. In my recent article on monitoring [5] I gave another example of where a 400 status code was used instead of a 404 when a resource was missing. In both these cases the normal REST semantics have been “abused” and therefore we need to transform an apparent success or failure into the other realm – it’s the job of the domain-level proxy to hide these kinds of edges. (If the service provider ever releases a new version of the interface that corrects these defects the domain interface should remain unaffected.)
public Optional<AccountId>
LookupAccount(CardNumber cardNumber)
{
var request = new LookupAccountRequest(cardNumber);
var response = primitiveProxy.Send<LookupResponse>(request);
if (response.Failed)
ThrowError(response);
if ( (response.StatusCode == 200)
&& (!response.Content.Error.IsEmpty()) )
{
throw new AccountLookupError(response.Content.Error);
}
return response.Content.AccountId.ToOptional();
}
As we’ll see in a moment though the consumer always has the possibility of dropping down a level if the richer interface doesn’t provide the kind of semantics they’re looking for.
While the outer layer focuses heavily on the happy path and tries to make things easier for the consumer by leveraging the type system, the inner layer provides a more raw experience whilst still shielding the caller from all the gory details of the underlying transport mechanism. The aim is still to provide a coherent API whilst at the same time giving them more control over the various elements of the request and response when required.
Hence whereas the domain-level proxy will traffic in rich domain types the primitive-level proxy will likely deal in basic structures and string based values. The client will also have the option to control the headers and URL if required, whilst using any additional building blocks provided for those aspects they chose to adopt the default behaviour for. Another classic Gang of Four pattern, Builder, can be used to provide full control while helper methods can be added to get the ball rolling, e.g.
public class FetchOrdersRequest
{
public Headers Headers { get; }
public Content Content { get; }
public class Content
{
public string AccountId { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
}
}
public static FetchOrdersRequest BuildFetchOrdersRequest(this
ShopProxy proxy, AccountId accountId, Date from, Date to)
{
return new FetchOrdersRequest
{
Headers = proxy.DefaultHeaders,
Content = new Content
{
AccountId = accountId.ToString(),
FromDate = from.ToIso8601(),
ToDate = to.ToIso8601(),
},
};
}
When writing acceptance tests you usually want to create various malformed requests to test your validation code, these require as much of the request to be production-like as possible with only one aspect mutated in each scenario. Hence to avoid false positives the test should leverage as much of the real production code as possible to format the request whilst still being able to tweak the one aspect under test. For example we might write a test like this to check we only allow dates to be sent in ISO 8601 format:
[Test]
public void non_iso_8601_format_from_date_generates_an_error()
{
// . . .
var request = new FindOrdersRequest(accountId, fromDate, toDate);
request.Content.FromDate = “01/01/2001”;
var response = proxy.Send<FindOrdersResponse>(request);
Assert.That(response.StatusCode, Is.EqualTo(400));
Assert.That(response.Error.Content, Does.Contain(“ISO-8601”));
}
The approach to parsing the response and error handling will also typically be more manual. Rather than throw exceptions the primitive-level proxy will largely return composite values that contain both the successful result and the error on failure. The caller then inspects the return value and queries the relevant part of the structure and acts accordingly. In the case of a successful request the body will contain the content, if any, whereas in the failure scenario any combination of the result code, headers and body could be used to formulate a richer error value. A complex result type for a JSON based REST API might look something like this:
public class HttpResult<ContentType,
ErrorType>
{
public bool Succeeded { get; }
public int StatusCode { get; }
// On success.
public ContentType Content { get; }
// On failure.
public ErrorType Error { get; }
// For diagnostics.
public Headers Headers { get; }
public string Body { get; }
}
Although we could have used an Optional<T> type for the success and error contents
and foregone the Succeeded
property I’ve chosen instead to make those an implementation detail here (not
shown) and force the caller to query the Succeeded
property to decide which content object should then be inspected – Content or Error.
Network-level problems, such as failing to resolve the target hostname, could
be dealt with either way. On the one hand sticking entirely to exceptions or return
values makes for a more consistent interface however in reality these low-level
failures may be outside the remit of what you’re trying to allow recovery of,
just like an out-of-memory issue. (In the enterprise arena where I’ve applied
this approach the only recovery from network issues is essentially to “wait it
out”. Host configuration errors can usually be spotted at deployment time by
proactively probing during service start-up.)
Like any design pattern this is a solution to a problem in a particular context. If your context is building a service for which you intend to write some client code in a number of different guises, such as acceptance tests or other tooling, where you will likely need a mixture of high-level and lower-level interaction, then splitting your proxy in half may make sense. Naturally you should be wary of over-engineering your design, however at the same time keep an eye out to see if you can reduce some complexity on the client-side by removing a little duplication before it becomes irreversible.
[1] Test Pyramid, Martin Fowler,
https://martinfowler.com/bliki/TestPyramid.html
[2] TDD - From the Inside Out or the Outside In?, Georgina
Mcfadyen,
https://8thlight.com/blog/georgina-mcfadyen/2016/06/27/inside-out-tdd-vs-outside-in.html
[3] Simple Instrumentation, Chris Oldwood, Overload 116,
https://accu.org/index.php/journals/1843
[4] In The Toolbox - Libraries, Console Apps & GUIs,
Chris Oldwood, C Vu 30-2,
http://www.chrisoldwood.com/articles/in-the-toolbox-libraries-console-apps-and-guis.html
[5] The Curse of NTLM Based HTTP Proxies, Chris Oldwood,
http://chrisoldwood.blogspot.com/2016/05/the-curse-of-ntlm-based-http-proxies.html
[6] Causality - Relating Distributed Diagnostic Contexts,
Chris Oldwood, Overload 114,
https://accu.org/index.php/journals/1870
[7] Monitoring: Turning Noise into Signal, Chris Oldwood,
Overload 144,
https://accu.org/index.php/journals/2488
[8] Primitive Domain Types - Too Much Like Hard Work?, Chris
Oldwood,
http://chrisoldwood.blogspot.com/2012/11/primitive-domain-types-too-much-like.html
[9] PrimitiveObsession, C2 Wiki,
http://wiki.c2.com/?PrimitiveObsession
[10] Simplicity Before Generality, Use Before Reuse, Kevlin
Henney,
https://medium.com/@kevlinhenney/simplicity-before-generality-use-before-reuse-722a8f967eb9
[11] Design Patterns: Elements of Reusable Object-Oriented
Software, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides,
https://en.wikipedia.org/wiki/Design_Patterns
Chris Oldwood
16 June 2018
Chris is a freelance programmer who started out as a bedroom coder in the 80’s writing assembler on 8-bit micros. These days it's enterprise grade technology in plush corporate offices. He also commentates on the Godmanchester duck race and can be easily distracted via<EMAIL_ADDRESS>or @chrisoldwood.


  Most people are in sweatshirts still but my kids are down to swimsuits and splashing at the water’s edge 😂
2/3/2019, 5:57:55 AM
Favs: 17
Retweets: 0
link


Side Chains
A dApp running on its own side chain removes the risk that one single dApp could shut down the whole network whenever it's spammed. This gives developers the power they need to build revolutionary dApps with the supported languages C#, Java, Solidity and Python (support for additional programming languages will be added later).
- Phantasma allows infinite side chains to be deployed.
- Main and side chains can validate 10k transactions per block.
- The maximum total transactions per second (TPS) is the amount of side chains plus the main chain multiplied by the maximum TPS of each chain.
- Infinite side chains coupled with the inter-chain technology Phantasma implements in its network allows all chains to be connected.


Before Change
checkpoint_path = logdir / "checkpoints" / f"{checkpoint_name}.pth"
print("Load config")
config: Dict[str, dict] = load_config(config_path)
runner_params = config.get("runner_params", {}) or {}
// Get expdir name
config_expdir = Path(config["args"]["expdir"])
// We will use copy of expdir from logs for reproducibility
expdir = Path(logdir) / "code" / config_expdir.name
print("Import experiment and runner from logdir")
experiment_fn, runner_fn = import_experiment_and_runner(expdir)
experiment: ConfigExperiment = experiment_fn(config)
print(f"Load model state from checkpoints/{checkpoint_name}.pth")
if stage is None:
stage = list(experiment.stages)[0]
model = experiment.get_model(stage)
checkpoint = load_checkpoint(checkpoint_path)
unpack_checkpoint(checkpoint, model=model)
runner: runner_fn = runner_fn(**runner_params)
runner.model, runner.device = model, device
if loader is None:
loader = 0
After Change
runner.model = model_dump
return result
logger.info("Tracing is running...")
traced_model = trace_model(
model=model,
predict_fn=predict_fn,
batch=batch,


{% extends 'base.html'%} {% import 'macros.html' as macro%} {% block content %}
This application that will help you preview news articles from various sources.


This is the root/header template of home page and will be present in all the child views
This is the root/footer template of home page and will be present in all the child views


Local variables are only available in the methods in which they are declared, and not shared across the entire object. A variable can be identified as being a local variable if all the letters in it’s name are lowercase. In the example above, bedrooms_value, bathroom_value, and area_value are all local variables. Those variables do not need to be access outside of the method, therefore it is best to keep them as local variable to limit their accessibility.
Instance variables are bound to the specific instance of the class. By binding itself to the entire object, an instance variable makes itself available to every methods of the object. Instance variables are prefixed with @ in their name, hence bedroom, bathroom, and area are instance variables. As instance variables, they can be accessed within the house_value method.
Class variables are variables that are shared among the entire class, not just the instances of the class. Class variable will only have one value that exists for every objects created from the class. If one object changes the class variable’s value, then the new value will change for all other instance variables. Class variables are prefixed with @@ in their names. In the above example, number_of_house is a class variable with a default value of 0. With each object instantiated from the House class, number_of_house increases by 1. The new value is then represented by all objects of the House class.
Global variables are accessible from anywhere in the Ruby program. The use of global variables should be limited because global variables can be changed from anywhere, which complicates the debugging process. Global variables can be defined with a prefix $ in from it’s name. In the above example, location is the global variable, which mean location can be access from anywhere.


Tweet #1
[in a normal speaking voice from top row of football stadium] Good luck today guys
— Brendan O'Hare (@brendohare) September 14, 2014
I like sports, but I also find the humor in taking them too seriously. Here are some tweets I've gathered that perfectly encapsulate the hilarity of what we're actually watching:
[in a normal speaking voice from top row of football stadium] Good luck today guys
— Brendan O'Hare (@brendohare) September 14, 2014
Lacrosse is my favorite sport that combines looking like you're trying to catch a butterfly with having no friends
— jhorts (@dearjhonletter) September 29, 2015
glad the athlete on my fave team said hed just take it one game at a time.was worried hed try to take it 3-4games at a time which is bad
— TRPMBLY PCKALESK (@Tormny_Pickeals) November 17, 2013
one time i slam dunked a basketball so good we were out of school for a week people just needed time to process
— capitalism liker (@HumanPog) July 5, 2013
Why Can't I Find Out Anything About This Superb Owl #superbowl
— Jackson (@tree_bro) February 6, 2011
"No, dude. The CENTER center." - the only possible archery coach advice
— Ryan Nanni (@celebrityhottub) July 28, 2012


A Spry Validation Checkbox widget is a checkbox or group of checkboxes in an HTML code form that display valid or invalid states when the user selects or fails to select a checkbox. For example, you can add a Validation Checkbox widget to a form in which a user might be required to make three selections. If the user fails to make all three selections, the widget returns a message stating that the minimum number of selections was not met.
A version of this file is available on Adobe LiveDocs. Please check it for comments and updates.
The following example shows a Validation Checkbox widget in various states.
The Validation Checkbox widget includes a number of states (for example, valid, invalid, required value, and so on). You can alter the properties of these states by using the Property inspector, depending on the desired validation results. A Validation Checkbox widget can validate at various points (for example, when the user clicks outside the widget, as the user makes selections, or when the user tries to submit the form).
Whenever a Validation Checkbox widget enters one of these states through user interaction, the Spry framework logic applies a specific CSS class to the HTML container for the widget at run time. For example, if a user tries to submit a form, but makes no selections, Spry applies a class to the widget that causes it to display the error message, “Please make a selection.” The rules that control the style and display states of error messages reside in the SpryValidationCheckbox.css file that accompanies the widget.
The default HTML code for the Validation Checkbox widget, usually inside a form, is made up of a container span tag that surrounds the input type="checkbox" tag of the checkbox. The HTML code for the Validation Checkbox widget also includes script tags in the head of the document and after the widget’s HTML code.
The HTML code for the Validation Checkbox widget also includes script tags in the head of the document and after the widget’s HTML code. The script tag in the head of the document defines all of the JavaScript functions related to the Checkbox widget. The script tag after the widget code creates a JavaScript object that makes the checkbox interactive.
Following is the HTML code for a Validation Checkbox widget:
 ...    <link href="SpryAssets/SpryValidationCheckbox.css" rel="stylesheet" type="text/css" />   <form id="form1" name="form1" method="post" action="">   <input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/>  Please make a selection.  </form>
In the code, the new JavaScript operator initializes the Checkbox widget object, and transforms the span content with the ID of sprycheckbox1 from static HTML code into an interactive page element.
The span tag for the error message in the widget has a CSS class applied to it. This class (which is set to display:none; by default), controls the style and visibility of the error message, and exists in the accompanying SpryValidationCheckbox.css file. When the widget enters different states as a result of user interaction, Spry places different classes on the container for the widget, which in turn affects the error-message class.
You can add other error messages to a Validation Checkbox widget by creating a span tag (or any other type of tag) to hold the text of the error message. Then, by applying a CSS class to it, you can hide or show the message, depending on the widget state.
You can change the default appearance of the Validation Checkbox widget's states by editing the corresponding CSS rule in the SpryValidationCheckbox.css file. For example, to change the background color for a state, edit the corresponding rule or add a new rule (if it’s not already present) in the style sheet.
In the preceding example, span tags create the structure for the widget:
Container SPAN INPUT type="checkbox" Error message SPAN
You can, however, use almost any container tag to create the widget.
Container DIV INPUT type="checkbox" Error Message P
Spry uses the tag ID (not the tag itself) to create the widget. Spry also displays error messages using CSS code that is indifferent to the actual tag used to contain the error message.
The ID passed into the widget constructor identifies a specific HTML element. The constructor finds this element and looks inside the identified container for a corresponding input tag. If the ID passed to the constructor is the ID of the input tag (rather than a container tag), the constructor attaches validation triggers directly to the input tag. If no container tag is present, however, the widget cannot display error messages, and different validation states alter only the appearance of the input tag element (for example, its background color).
The SpryValidationCheckbox.css file contains the rules that style the Validation Checkbox widget and its error messages. You can edit these rules to style the look and feel of the widget and error messages. The names of the rules in the CSS file correspond to the names of the classes specified in the widget’s HTML code.
The following is the CSS code for the SpryValidationCheckbox.css file:
/*Validation Checkbox styling classes*/ .checkboxRequiredMsg, .checkboxMinSelectionsMsg, .checkboxMaxSelectionsMsg{ display: none; } .checkboxRequiredState .checkboxRequiredMsg, .checkboxMinSelectionsState .checkboxMinSelectionsMsg, .checkboxMaxSelectionsState .checkboxMaxSelectionsMsg { display: inline; color: #CC3333; border: 1px solid #CC3333; }
The SpryValidationCheckbox.css file also contains extensive comments, explaining the code and the purpose for certain rules. For further information, see the comments in the file.
For example, create a folder called SpryAssets in the root folder of your web site, and upload the SpryValidationCheckbox.js file to it. The SpryValidationCheckbox.js file contains all of the information necessary for making the Checkbox widget interactive.

Make sure that the file path to the SpryValidationCheckbox.js file is correct. This path varies depending on where you’ve placed the file in your web site.
<link href="SpryAssets/SpryValidationCheckbox.css" rel="stylesheet" type="text/css" />
Make sure that the file path to the SpryValidationCheckbox.css file is correct. This path varies depending on where you’ve placed the file in your web site.
<input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/>
 <input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/>

The new JavaScript operator initializes the Checkbox widget object, and transforms the span tag content with the ID of sprycheckbox1 from static HTML code into an interactive checkbox object. The Spry.Widget.ValidationCheckbox method is a constructor in the Spry framework that creates checkbox objects. The information necessary to initialize the object is contained in the SpryValidationCheckbox.js JavaScript library that you linked to at the beginning of this procedure.
Make sure that the ID of the checkbox widget’s container span tag matches the ID parameter you specified in the Spry.Widgets.ValidationCheckbox method. Make sure that the JavaScript call comes after the HTML code for the widget.
The complete code looks as follows:
 ...  <link href="SpryAssets/SpryValidationCheckbox.css" rel="stylesheet" type="text/css" />    <input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/>
Create a span tag (or any other type of tag) to display the error message, and assign the appropriate class to it, as follows:
 <input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/> Please make a selection.
The checkboxRequiredMsg rule is located in the SpryValidationCheckbox.css file, and is set to display:none by default. When the widget enters a different state through user interaction, Spry applies the appropriate class—the state class—to the container of the widget. This action affects the error-message class, and by extension, the appearance of the error message.
For example, the following shows the CSS rule from the SpryValidationCheckbox.css file:
.checkboxRequiredMsg, .checkboxMinSelectionsMsg, .checkboxMaxSelectionsMsg{ display: none; } .checkboxRequiredState .checkboxRequiredMsg, .checkboxMinSelectionsState .checkboxMinSelectionsMsg, .checkboxMaxSelectionsState .checkboxMaxSelectionsMsg { display: inline; color: #CC3333; border: 1px solid #CC3333; }
By default, no state class is applied to the widget container, so that when the page loads in a browser, the error message text in the preceding HTML code example only has the checkboxRequiredMsg class applied to it. (The property and value pair for this rule is display:none, so the message remains hidden.) If the user fails to make a selection, however, Spry applies the appropriate class to the widget container, as follows:
 <input type="checkbox" name="checkbox1" value="1"/> <input type="checkbox" name="checkbox2" value="2"/> Please make a selection.
In the preceding CSS code, the state rule with the contextual selector .checkboxRequiredState .checkboxRequiredMsg overrides the default error-message rule responsible for hiding the error message text. Thus, when Spry applies the state class to the widget container, the state rule determines the appearance of the widget, and displays the error message inline in red with a 1-pixel solid border.
Following is a list of default error-message classes and their descriptions. You can change these classes and rename them. If you do so, don’t forget to change them in the contextual selector also.
| Error message class |
Description |
|---|---|
.checkboxRequiredMsg |
Causes error message to display when the widget enters the required state |
.checkboxMinSelectionsMsg |
Causes error message to display when the widget enters the minimum number of selections state |
.checkboxMaxSelectionsMsg |
Causes error message to display when the widget enters the maximum number of selections state |
Note: You cannot rename state-related class names because they are hard-coded as part of the Spry framework.
By default, the Validation Checkbox widget validates when the user clicks the submit button. You can, however, set two other options: blur or change. The validateOn:["blur"] parameter causes the widget to validate whenever the user clicks outside the widget. The validateOn:["change"] parameter causes the widget to validate as the user makes selections.
To specify when validation occurs, add a validateOn parameter to the constructor as follows:

As a convenience, you can discard the brackets if your validateOn parameter contains a single value (for example, validateOn: "blur"). If the parameter contains both values, however (validateOn:["blur", "change"]), include brackets in the syntax.
By default, a Validation Checkbox widget is set to required. If you insert a number of checkboxes on your page, however, you can specify a minimum and maximum selection range. For example, if you have six checkboxes within the span tag for a single Validation Checkbox widget, and you want to make sure that the user selects at least three checkboxes, you can set such a requirement for the entire widget.
To specify a minimum or maximum number of selections, add the minSelections property or maxSelections property (or both) and a value to the constructor, as follows:

By default, Validation Checkbox widgets require the user to make at least one selection before submitting the form. You can, however, make selections optional for the user.
To change the required status of a checkbox, add the isRequired property to the constructor and set its value to false, as follows:

The SpryValidationCheckbox.css file provides the default styling for the Validation Checkbox widget. You can customize the widget by changing the appropriate CSS rule. The CSS rules in the SpryValidationCheckbox.css file use the same class names as the related elements in the widget’s HTML code, so it’s easy for you to know which CSS rules correspond to the widget and its error states.
The SpryValidationCheckbox.css file should already be included in your website before you start customizing.
The SpryValidationCheckbox.css file contains extensive comments, explaining the code and the purpose for certain rules. For further information, see the comments in the file.
By default, error messages for the Validation Checkbox widget appear in red with a 1-pixel solid border surrounding the text.
To change the text styling of Validation Checkbox widget error messages, use the following table to locate the appropriate CSS rule, and then change the default properties, or add your own text styling properties and values.
| Text to style |
Relevant CSS rule |
Relevant properties to change |
|---|---|---|
Error message text |
.checkboxRequiredState .checkboxRequiredMsg, .checkboxMinSelectionsState .checkboxMinSelectionsMsg, .checkboxMaxSelectionsState .checkboxMaxSelectionsMsg |
color: #CC3333; border: 1px solid #CC3333; |
While you can replace error message-related class names with class names of your own by changing the rules in the CSS and the class names in the HTML code, you cannot change or replace state-related class names, because the behaviors are hard-coded as part of the Spry framework. You can, however, override the default state-related class name with your own class name by specifying a new value in the third parameter of the widget constructor.
To change widget state-related class names, add one of the overriding options to the third parameter of the widget constructor, and specify your custom class name, as follows:

The following table provides a list of options you can use to override built-in state-related class names.
| Option |
Description |
|---|---|
requiredClass |
Overrides the "checkboxRequiredState" built-in value |
minSelectionsClass |
Overrides the "checkboxMinSelectionsState" built-in value |
maxSelectionsClass |
Overrides the "checkboxMaxSelectionsState" built-in value |
Copyright © 2006. Adobe Systems Incorporated. All rights reserved.


SSE profit rises as it calls for political action on renewables
by Edward ThicknesseBig Six energy supplier SSE swung back into profit in this morning’s half-year results, as its chief executive called on the next government to put renewable power at the front and centre of their climate change plans.
Read more: Competition watchdog to examine £500m Ovo Energy SSE deal
The figures
Reported profit rose to £128.9m from a loss of £284.6m last year, as the energy giant bounced back from a tough 2018.
Earnings per share reached 6.2p, up from -26.4p in 2018.
However, the energy supplier incurred a £489.1m impairment on the sale of its household energy and services business in the UK, which Ovo Energy agreed to buy in September for £500m.
The results are SSE’s first since the company agreed to sell the division to Ovo. The one-off charge was stripped out of the main results as the business has been declared held for sale.
Why it’s interesting
The deal with Ovo is expected to complete in early 2020, pending the result of an investigation by the Competition and Markets Authority (CMA).
This is good news for SSE, who had previously tried to sell the division to Npower, only for the deal to fall through.
The sale will leave SSE as predominantly a supplier of renewable energy, and results showed that a wet and windy autumn had meant the company generated more electricity than expected from its wind turbines, with profit for SSE Renewables at £149.9m.
Chief executive Alistair Phillips-Davies used the results to call on the government to put renewable power at the front and centre of their climate change plans.
Read more: SSE sells energy services business to Ovo in £500m deal
He said: “The climate emergency needs action now and offshore wind has proven itself to be one of the most cost effective ways this country can decarbonise and get on the road to Net Zero.
“Coupled with lifting the moratorium on onshore, the next Government could deliver at least another 10GW of clean, green energy, before the end of its term – enough to power over seven million homes.”
In September, SSE won contracts to build the UK’s largest offshore wind farm to-date, at Doggerbank off the east coast of England. It will also build Scotland’s largest wind-farm, Seagreen, off the coast of Fife.
What SSE said:
Richard Gillingwater, chair of SSE, said:
“SSE is progressing well in the execution of its low–carbon strategy with the sale of SSE Energy Services leading to group more focussed on renewable energy and regulated electricity networks.
“Clearly some headwinds remain in the sector with political uncertainty and aspects of UK government policy being subject to judicial process, however, we have strong optionality to create value through the low carbon transition and deliver our dividend commitments.”
Main image credit: Getty


The goal of nflcolors is to provide easy access to NFL team colors and palettes.
You can install nflcolors from GitHub with:
# install.packages("devtools")
devtools::install_github("corysauve/nflcolors")
nflcolors has palettes for all 32 teams in the National Football League (NFL). Colors are sourced from primary uniforms and logos. All teams are accessed via their team abbreviation.
library(nflcolors)
names(teams)
#> [1] "ARZ" "ATL" "BAL" "BUF" "CAR" "CHI" "CIN" "CLE" "DAL" "DEN" "DET" "GB"
#> [13] "HOU" "IND" "JAX" "KC" "LAC" "LAR" "LV" "MIA" "MIN" "NE" "NO" "NYG"
#> [25] "NYJ" "PHI" "PIT" "SF" "SEA" "TB" "TEN" "WAS"
You can create a team palette with team_colors()
, along with an image of the palette.
kc_palette <- team_colors("KC")
You can also select a specific number of colors.
kc_palette <- team_colors("KC", 2)
I welcome any contributions or suggestions for improving the package! Please open an issue to do so.
The nflcolors package is licensed under the MIT License. Please see the LICENSE for more details.
Inspiration for this package originally came from the wonderful nationalparkcolors package, which provides color palettes for various National Park posters.


CBQN is the primary offline implementation, and has build instructions in its own repository. Here and elsewhere it's expected to be installed as bqn
. For Windows, build in WSL or see WinBQN below.
Third-party packages are available for Windows and a few Linux distributions. Because they run on an unknown target system, none of these packages are built with the highest-performance settings. If you need top speed (you probably don't!) you should compile CBQN for the target hardware instead.
| OS/distro | Package | Type |
|---|---|---|
| Windows download | WinBQN | Binary |
| Arch AUR | cbqn-git |
Source |
| Nix | cbqn |
Source/Binary |
| Guix | cbqn |
Source/Binary |
For tools related to running BQN, see the editor plugins and fonts page. Also, Beacon is a cross-platform IDE just for BQN, and iBeacon is an iOS REPL with BQN plus K!
All these websites run BQN, in your browser unless marked with "server-side" (JS is native Javascript; the Wasm engine is WebAssembly compiled from CBQN).
| Link | Style | Engine | Comments |
|---|---|---|---|
| Online REPL | One-shot | JS | "Explain", error marker |
| BQNPAD | Session | JS, Wasm | Preview, syntax coloring |
| Attempt This Online | TIO | CBQN | Server-side |
| Do Stuff Online | TIO | JS | |
| Razetime | Session | JS | |
| ktye/zoo | Session | JS | Many array languages |
| Observable | Notebook | JS | For import in Observable |
| BQN-80 | One-shot | JS | Create animations |
| week.golf | Challenge | CBQN | Code golf, server-side |
Details about CBQN as well as the Javascript and other implementations follow.
Both CBQN and JS BQN are implemented using components written in BQN itself: the compiler, and primitive implementations. The host language provides a bytecode VM and basic functionality for the primitives, and can replace primitives with native implementations for better performance. It also provides system values, so that which ones are supported depends on the host. This setup allows embedding, where programs in the host language can evaluate BQN code.
Support in the following languages has been implemented:
The file docs/bqn.js is zero-dependency Javascript, and can be loaded from HTML or Node.js. For command line use, call the Node.js script bqn.js, passing a file and •args
, or -e
to execute all remaining arguments directly and print the results.
BQN.rkt is an independent implementation entirely in Racket, with primitives that operate on native Racket arrays (as these are multi-dimensional) and a compiler that converts from BQN to Racket syntax. It's incomplete as of this writing.
dzaima/BQN is an implementation in Java created by modifying the existing dzaima/APL, and should be easy to run on desktop Linux and Android. It was historically the main implementation, but is now updated only to stay up to date with language changes. Major missing functionality is dyadic Depth (⚇
) and set functions ⊐⊒∊⍷
with rank >1, and there are various small differences from the BQN spec, mostly to do with rank, handling of atoms, fills, and headers. It uses UTF-16 instead of UTF-32, so that characters like 𝕩
don't behave correctly.
The only remaining dzaima/BQN script here is test/dzaima
, which can be used to test the self-hosted primitives but has been superseded by test/unit
.
BQN2NGN is a prototype implementation in Javascript built to experiment with the language. It's now abandoned.


Use arrow keys to navigate this website. Pay attention to the arrows in the bottom-right of the page; you can sometimes press the down arrow key to go "down" some slides and into more detail on a topic. If you get lost, press the Escape key to view all slides at a glance.
Middle school students have a lot of energy. While we want to make sure we can accomplish eveything on our agenda, that might not happen if students are bouncing off the walls.
I've learned how to "steer" or "funnel" student energy in a direction that would lead to the accomplishment of our tasks. Rather than diluting or inhibiting such energy, I have gained insight on how to transform it in such a way that everyone benefits, rather than gets distracted by, a student's energy.
A few of our students in my film club group had an incredible amount of energy, but it became distracting to other students. How could I control this energy?
After reading Robert Fried's "The Passionate Teacher", and read his section on classroom discipline, I realized that it would be better to redirect my students' energy, rather than get rid of it. Students devoid of energy or passion would not have fun in film club.
Fun may be another key to renewal as passionate teachers. It can't hurt to look at each day's classes with a determination to have some fun teaching. It reminds us that in the learning business, work and play are not opposites; that most of a child's early learning comes from play; and that playfullness in a quality that adults cherish as well.
Robert Fried, "The Passionate Teacher", Page 184
Take that energy and funnel it into our lesson! Use it!
This passage inspired me to re-examine how I was "keeping the peace" among my students. Rather than just focusing on work or fun, I could combine them both for maximum effect.
Using this knowledge, I promoted some silly moments among my actors as I guided them through their scenes, but also transformed some jokes into poignant moments to remember. I also injected my own silliness into aspects of our acting lessons, and used my silliness as a moment for the actors to remember and think about throughout the acting process.
By applying the silliness in the air into a tense moment in our script, I could grab their attention and hold it tight.
As a teaching assistant and volunteer, students will always have expectations of an instructor who is both firm and fun. Outliers on both sides are frequent, but how is it possible to be both someone people can learn from and laugh with?
This insight will enable me to more effectively communicate and engage with students of all ages. The ideas I've learned are not specific to any age, but are universal in nature.
 Whether I am in my office hours, leading a discussion section, or guiding students in the Hour of Code, there is always a sense of admiration for someone's ability to mesh work and fun. I hope to use what I have learned in that way: to be the person people look up to as a passionate and "punny" guy.
The energy from the previous does not exist if students aren't engaged or excited about something going on. Let's make them excited about film club, and give students reasons to be involved and "with it".
Afford students the opportunities and knowledge to become an active participant in a lesson; rather than a sink for knowledge (taking it in but not giving anything back,) they could become an important link in the chain of our film club group.
I came to this realization while preparing for my Book Lesson presentations. I was assigned the chapters on promoting student excellence. I quickly realized that excellence could only go so far as a student wanted to participate and involve themselves in the process of learning.
Teachers should draw more assignments from real-world situations and create projects that are collaborative by nature...
Mark Bauerlein, "The Paradox of Classroom Boredom"
There is hardly an instructional unit that cannot be transformed into a job that students can plan, organize, carry out and complete for the good of the community.
Mark Fried, "The Passionate Teacher", Page 207
Those quotes, in addition to the survey results from students' initial placements from the start of the semester, allowed me and my other instructors to provide each student with a legitimate role and position in the film club. These were roles that they were inclined to become passionate about, and gave 110% every day in an effort to succeed and get the job done.
We wanted to give each student a set of responsibilities that would be suited to their strengths, but also challenge them in new ways. This connects student's excitement about something (acting, editing, camerawork) with how engaged they would be in that role.
The ability to assist students in becoming excited about the lesson at hand is especially poignant for me as a student. Though I often find myself on the instructor end as a TA, I can take the same lessons and apply them to my being a student.
How can I become engaged and excited about something that I, at first glance, don't really care for? How can I help my friend struggling to do the same?
How am I absorbing knowledge in lecture and at Dewitt Middle School? Am I doing this in the most effective way possible, or not? Can I revise how I am approaching a topic in order to learn it better, or help other people (my friends and students) understand it better?
Metacognition was one of the first concepts we covered in lecture; it was discussed by Professor Duff, and I wrote it in my notes as the following:
Introspection of learning + knowledge; effectiveness of learning and consuming information so that we can use it.
The nature of the lectures themselves also prompted me to think about how I thought. Prof. Duff's lecture style was very different from those of other classes. This prompted me to re-examine how I took in information.
Through my work with DeWitt Middle School students, I learned to take information from my surroundings in a different way than before. I was now the teacher and the student. How could I transform knowledge so that it applied in both areas?
Thinking about how you think is a sort of mental "check". Have I learned something effectively? Am I thinking about something in a way that stimulates critical insight and thought about a topic? This sort of mental thought is one that should be promoted in classrooms everywhere.
I strongly believe that there is are right and wrong ways to thinking; metacognition can help both students and teachers determine how good their way of thinking is, and aid them in their endeavors to improve. Whether it is receiving knowledge, delivering it, or a combination of the two, metacognition can give individuals pause and ask them to re-examine what they are doing.