Using Forms9Patch Button Elements
Background
I often say Forms9Patch was originally written for the purpose of having NinePatch images in Xamarin.Forms. That's not completely true. I wanted NinePatch images because I had used them in Android as the background image for device independent buttons. Quite frankly,what I really wanted was SVG backgrounds but all the pieces to do that were not available at that time. Fortunately, things have changed and now - via Forms9Patch - I have both!
Another missing element for Android and Xamarin.Forms is a SegmentedControl (like iOS has). Building a SegmentedControl was a bit painful for me in Android and I dreaded what it would take in Xamarin. However, when I actually rolled up my sleeves and did it, I fell in love with what the Xamarin team had done. I was sold!
Overview
Forms9Patch has three button elements:
- Button
- StateButton¹
- SegmentedControl
All three buttons share a number of properties and behaviors for the purpose of giving you more design and functional options without more complexity.
Forms9Patch.Button
Forms9Patch.Button
is the most basic, adding the following to what Xamarin.Forms.Button
provides:
- Horizontal and vertical alignment of button's text
- Text and Background color for the selected state
- Outline and clip shape:
- Rectangle
- Square
- Circle
- Ellipse
- Obround
- Toggle behavior
- Background image
- Icon as an image or as HTML text
- Icon to text positioning:
- horizontal vs. vertical orientation
- icon before or after text
- spacing between icon and text
- Haptics (when available)
Forms9Patch.StateButton
Forms9Patch.StateButton
further extends Forms9Patch.Button
by adding the ability to toggle its properties as a function of its state. The states are:
- DefaultState
- PressingState
- SelectedState
- DisabledState
- DisabledAndSelectedState
NOTE ¹ : As of Xamarin.Forms 3+, I recommend not using Forms9Patch.StateButton
. Rather, use Forms9Patch.Button
in combination with Xamarin.Forms' new Visual State Manager. Visual State Manager is a great feature and I'm looking forward to using it!
Forms9Patch.SegmentedControl
iOS has a segmented control that, for the life of me, I don't know why isn't standard in Android, UWP, or Xamarin.Forms. It's just too useful. That being said, if I remember correctly, even the iOS segmented control doesn't support a vertical layout (please correct me if I'm wrong).
Forms9Patch.SegmentedControl provides for the following features:
- Orientation of the button list
- Toggle behavior
- Separator Width
- Horizontal and vertical alignment of button's text
- Text and Background color for the selected state
- Icon to text positioning:
- horizontal vs. vertical orientation
- icon before or after text
- spacing between icon and text
Using Forms9Patch's buttons
Shared Layout and Decoration Properties
The layout and decoration properties shared by all three Forms9Patch buttons are:
Outline/Background:
BackgroundColor
SelectedBackgroundColor
:BorderRadius
: Alternatively,OutlineRadius
BorderWidth
: Alternatively,OutlineWidth
BorderColor
: Alternatively,OutlineColor
HasShadow
Padding
: The padding between the outline and the button's content (the icon and label)
Text
TextColor
FontAttributes
FontSize
FontFamily
: the button's label's font family. Note: You can use the ResourceID of Embedded Resource fonts here!SelectedTextColor
: the color of the button's text when selectedHorizontalTextAlignment
VerticalTextAlignment
LineBreakMode
: See Xamarin.Forms.LineBreakModeAutoFit
: Autofitting algorithm to be applied to button's label's text. See Label.Autofitting.Lines
: The number of lines used for the label's text fitting. Again, see Label.Autofitting.- BackgroundBackgroundColor
BackgroundImage
: AForms9Patch.Image
that will be used as the button's background.
Icon:
IconFontFamily
: Used to specify the font family used for theIconText
property. Note: See Custom Fonts to see how to use an Embedded Resource font!TrailingIcon
: Is the icon placed before or after the label?TintIcon
: If the icon is a raster image, should the color of the non-transparent pixels be set toTextColor
?HasTightSpacing
: Iffalse
, the icon will be positioned to the outside edge of the button. Iftrue
, the icon will be positioned next to the label (separated bySpacing
).
Button and StateButton unique properties
Additionally, the Button
and StateButton
elements have these properties:
Outline
Shape
:ElementShape.Rectangle
,ElementShape.Square
,ElementShape.Circle
,ElementShape.Ellipse
, andElementShape.Obround
. Controls the shape of both the border and the background clipping region.
Text
Text
: plain text for the button's labelHtmlText
: markup text for the button's label - an alternative toText
Icon
IconImage
: AForms9Patch.Image
element to be used as the button's icon image.IconText
: An alternative toIconImage
, enabling the use of Unicode characters or special font characters as button icons. Just like theHtmlText
property, this property will decode HTML markup, allowing you to specify colors, fonts and other attributes.Orientation
: Is the icon and label arranged vertically or horizontally?Spacing
: ifTightSpacing
is true, the icon will be positionedSpacing
pixels away from the label
SegmentedControl unique properties
The SegmentedControl
has the following unique properties:
- Outline:
SeparatorWidth
: Width of the separator between segments
- Text
SyncSegmentFontSizes
: After autofitting the text in each segment to fit the available space, if this property is set totrue
, then the SegmentedControl will set the FontSize of all the segments to be the same as the smallest fitted font size.
- Selection:
SelectedSegments
: List of the selected segmentsSelectedIndexes
: List of the indexes of the selected segmentsGroupToggleBehavior
: How the buttons will behave after being selected. States: None, Radio, Multiselect;
- Layout:
IntraSegmentOrientation
: Is the icon arranged Horizontally or Vertically relative to the label?IntraSegmentSpacing
: WhenHasTightSpacing
, how much space should be between segments?Orientation
: Are the Segments arranged Horizontally or Vertically?
Segment Properties
The Segment
element is used primarily to populate the SegmentedController
and secondarily, to customize individual segments beyond the default values provided by the parent SegmentedController
.
IconImage
:Forms9Patch.Image
as the segment's optional image. It will be tinted either toFontColor
when enabled and grey when disabled if the parentSegmentControl
'sTintImage=true
and the image is a PNG with transparency.IconText
: alternative to the ImageSource property. Used to specify HTML formatted text for button's icon. Great when used with Google's Material Font.IconFontFamily
: Used to specify the font family used for theIconText
property. Note: You can use the ResourceID of Embedded Resource fonts here!Text
: the segment's optional text.HtmlText
: text formatted via subset of HTML tags. See the Using the HtmlLabel property section below for more information.FontColor
: the color of the text when enabled. Disabled segmentS use a shade of grey determined by the DarkTheme property.FontAttributes
: is the text bold or italics?IsSelected
: Is the segment in the selected state? Note: Segment's parent's GroupToggleBehavior property must be Radio or MultiSelect for this to change in response to the segment being tapped.IsEnabled
: Is the segment enabled?Orientation
: Do you want the text and image placed image on top of text (vertical) or image to the left of text (horizontal)?
Events
Button, StateButton, and Segment events
Command
: The ICommand to execute when the button/segment is pressed. NOTE: If a segment's parent's GroupToggleBehavior property is set to None, then this will fire anytime the segment is tapped. Otherwise, it will fire only when the segment transitions from unselected to selected.CommandParameter
: The parameter used in ICommand calls.Tapped
: EventHandler be called anytime a button/segment is tapped.Selected
: EventHandler be called when a button/segment transitions from unselected to selected.LongPressing
: EventHandler be called when a button/segment is being held down long enough to be considered a long press.LongPressed
: EventHandler be called when a button/segment's long press has ended.
SegmentedControl events
SegmentTapped
: Fired when one of the SegmentedControl's segments is tapped;SegmentSelected
: Fired when one of the SegmentedControl's segments transitions to the Selected stateSegmentLongPressing
: Fired when one of the SegmentedControl's segments is being held down long enough to be considered a long press.SegmentLongPressed
:: Fired when one of the SegmentedControl's segments long press has ended.
Examples
Forms9Patch Button Example
var button = new Forms9Patch.Button
{
Text = "Click me",
ToggleBehavior = true,
BackgroundColor = Color.NavajoWhite, OutlineRadius = 5,
HasShadow=true,
};
| Unselected | |
| Selected |
Forms9Patch StateButton example
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:f9p="clr-namespace:Forms9Patch;assembly=Forms9Patch"
xmlns:local="clr-namespace:Forms9PatchDemo;assembly=Forms9PatchDemo"
x:Class="Forms9PatchDemo.XamlSingleStateButtonPage"
Padding="5, 20, 5, 5">
<StackLayout>
<f9p:StateButton ToggleBehavior="true" HeightRequest="80" Alignment="Start">
<f9p:StateButton.DefaultState>
<f9p:ButtonState Text="Toggle Default State" TextColor="Blue">
<f9p:ButtonState.BackgroundImage>
<f9p:Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.button}"/>
</f9p:ButtonState.BackgroundImage>
<f9p:ButtonState.IconImage>
<f9p:Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.Info}"/>
</f9p:ButtonState.IconImage>
</f9p:ButtonState>
</f9p:StateButton.DefaultState>
<f9p:StateButton.SelectedState>
<f9p:ButtonState TextColor="Red" Text="Selected" >
<f9p:ButtonState.BackgroundImage>
<f9p:Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.image}"/>
</f9p:ButtonState.BackgroundImage>
</f9p:ButtonState>
</f9p:StateButton.SelectedState>
</f9p:StateButton>
<Label x:Name="label"/>
</StackLayout>
</ContentPage>
| Unselected | |
| Selected |
Forms9Patch SegmentedControl example
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Forms9PatchDemo.XamlSegmentedControlPage"
xmlns:f9p="clr-namespace:Forms9Patch;assembly=Forms9Patch"
xmlns:local="clr-namespace:Forms9PatchDemo;assembly=Forms9PatchDemo"
BackgroundColor = "Gray"
Padding = "40"
>
<ContentPage.Content>
<StackLayout>
<Label Text="SegmentedControl Example" TextColor="Black"/>
<f9p:SegmentedControl BackgroundColor="White" FontSize="16" TextColor="#0076FF" Orientation="Vertical" OutlineColor="#CCC" OutlineWidth="0" SeparatorWidth="1" OutlineRadius="6" Padding="5" GroupToggleBehavior="Multiselect">
<f9p:Segment Text="Pause 5"/>
<f9p:Segment Text="Pause 10"/>
<f9p:Segment Text="Pause 15"/>
<f9p:Segment Text="Cancel" TextColor="Red"/>
<f9p:Segment Text="Launch" FontAttributes="Bold"/>
</f9p:SegmentedControl>
<f9p:SegmentedControl BackgroundColor="White" Padding="5" FontSize="16" TextColor="#0076FF" OutlineColor="#CCC" OutlineWidth="0" SeparatorWidth="1" OutlineRadius="6" >
<f9p:Segment Text="A" Orientation="Vertical">
<f9p:Segment.IconImage>
<f9p:Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.ArrowR}"/>
</f9p:Segment.IconImage>
</f9p:Segment>
<f9p:Segment Text="B" Orientation="Vertical">
<f9p:Segment.IconImage>
<f9p:Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.Info}"/>
</f9p:Segment.IconImage>
</f9p:Segment>
<f9p:Segment Text="PIZZA"/>
</f9p:SegmentedControl>
</StackLayout>
</ContentPage.Content>
</ContentPage>


This style of 3D chart is not supported natively but is pretty easy to achieve - especially as all of the source code is shown below and you can just copy it!
First some variables are defined which are used in the configuration - this is so that they're easier for you to edit and manage.
Each row of bars is actually a separate chart object and they're drawn inside a dedicated function. The 3D variant options turn off the 3D axes and the regular axes are also turned off. Slight shadows are set which add to the 3D effect.
The background grid is turned off for the second and third charts but is enabled for the first - the chart at the back.
The margins are set to those defined in the variables along with the Y axis scale max value.
Finally a drawing API Y axis object is used to draw a Y axis on the right-hand-side. The color of this Y axis is transparent so the only part of it that you can see is the labels.
The second and third Bar charts are drawn when they're triggered by the previous charts animation
callback function (ie the second function is called by the first grow()
animations
callback and the third function is called by the second grow()
animations callback).
Like the code for the rest of this chart, the responsive section is not inconsiderable. It
reduces the size of the canvas, changes the X axis labels to the three-letter variations of
the weekday names, changes the margin sizes on all three objects and changes the
textSize
on the main Bar chart and the Y axis object.
<script src="RGraph.common.core.js"></script> <script src="RGraph.bar.js"></script>Put this where you want the chart to show up:
<canvas id="cvs" width="650" height="300"> [No canvas support] </canvas>This is the code that generates the chart:


The data control policy should require documented authorization for all access. The access authorization document should state granted privileges. The access privileges should be authorized by management.
Access authorization documents help define privileges and identify who authorized them.
Check the network documentation to make sure it includes access authorization documents authorized by management. Check the authorization documents to make sure they explicitly define access privileges.
Identify the job functions of each employee. Identify the data access required for each employee. Define the data access privileges for each employee based on job responsibilities. Have the management review and authorize the data access privilege specifications. Once approved, implement the data access control systems. Attach the access authorization documents to the network documentation. These documents may be paper or electronic.


algorithms
teaching
Amortized analysis of resizing-array stacks
A rigorous proof that a stack implemented with doubling arrays has constant amortized time operations; written up here since it does not seem to appear in any of the standard algorithms books.
A well-known, fundamental data structure is the implementation of a stack using resizing arrays (a.k.a. doubling arrays), where we maintain an array of $C$ items for the $n$ elements of a stack, and whenever the array becomes full, we double its size, and whenever the array becomes less that one quarter full, we halve its size. This maintains the invariant that $\frac14 C \le n \le C$.
A folklore analysis shows that this achieves constant amortized cost for all stack operations, despite the occasional expensive resizing operations.
This analysis is not a particularly hard or surprising proof by any means, but it makes a great first nontrivial example of amortized analysis, and hence I wanted to show it in my Efficient Algorithms (COMP526) lectures; see Unit 2 – Fundamental Data Structures for the full context.
The goal is to show that while any individual push/pop in a resizing-array based stack might be expensive ($\Omega(n)$ cost), any sequence of operations is necessarily much cheaper, namely $O(1)$ time per operation on average. As the dominant operation, we count array accesses, i.e., any read or write access to an array.
Part 1: Amortized costs for all operations
Basically, each operation has two types of costs for the amortized analysis: actual costs (# array accesses) and a change in potential/credits. We define the potential $\Phi = \min\lbrace n-\frac14C,\;C-n\rbrace$, and the amortized cost $a_i$ of an operation is the actual cost plus $-4$ times the change in potential. We have to analyze both costs separately.
Actual costs:
- cheap push/pop: exactly 1 array access to write/read the topmost element.
- copying push: currently there are $n$ elements on the stack, these have to be read from the old array ($n$ accesses) and written to the new array ($n$ accesses); also one more element has to be added (like in cheap push). In total that is $2n+1$ actual cost.
-
copying pop: actually exactly the same: there are $n$ elements on the stack, these have to be read from the old array ($n$ accesses) and written to the new array ($n$ accesses); also one element has to be read to be returned. In total that is $2n+1$ actual cost.
(One could avoid this very last extra read by not copying the element that we pop right after anyways; but typical implementations do not do this for convenience. It would clearly not save much either way.)
Credits / Potential change
The credits is the change in potential $\Phi = \min\lbrace n-\frac14C,\;C-n\rbrace$.
- cheap push: $n$ gets one bigger, but $C$ is unchanged. If $C-n < n-\frac14 C$, then $\Phi$ drops by one (“we lose one credit”).
- cheap pop: $n$ gets one smaller, but $C$ is unchanged. If $n-\frac14 C<C-n$, then $\Phi$ drops by one (“we lose one credit”).
- copying push: We must have had $n=C$ (i.e. $\Phi_{i-1}=0$) before this push, and we will now set $C=2n$ before the push. Then, the push increments $n$. That means the new potential $\Phi_i=(n+1)-\frac14\cdot2n=\frac12n+1$. We have earned $\frac12n+1$ credits.
- copying pop: We must have had $n=\frac14C$ (i.e. $\Phi_{i-1}=0$) before this push, and we will now make $C=2n$ before the pop; the pop itself then decrements $n$. So $\Phi_i=(n-1)-\frac14\cdot 2n = \frac12n-1$, and we have earned $\frac12n-1$ credits.
Adding up
Adding up actual cost and $-4(\Phi_i-\Phi_{i-1})$ shows that in each case the amortized costs are at most 5.
Part 2: From amortized to total actual costs
The second part is indeed the same for all amortized analyses: The total actual cost over a sequence of $m$ operations is essentially bounded by the sum of their amortized costs, plus initial/final potential; this is shown using a telescoping-sum argument:
\[5m \ge \sum_{i=1}^m a_i = \sum_{i=1}^m c_i - 4 \underbrace{\sum_{i=1}^m(\Phi_i - \Phi_{i-1})}_{=\Phi_m - \Phi_0}\]Rearranging gives
\[\sum_{i=1}^m c_i \le 5m + 4\Phi_m-4\Phi_0\]Now, we can also show using the invariant $\frac14 C \le n \le n$, i.e., $n\le C \le 4n$, that $0\le \Phi\le \frac35n$: Since $\Phi$ is piecewise linear, it suffices to consider the endpoints of the linear segments, i.e., $C = 4n$, $C = n$ and $n-\frac14 C = C-n$, i.e., $C = \frac85 n$; at these points $\Phi$ has values $0$, $0$, and $\frac35 n$, respectively.
Hence $\displaystyle\sum_{i=1}^m c_i \le 4\Phi_m -4\Phi_0 \le 5m + 2.4n \in \Theta(m+n)$.


The mailing lists have been consolidated into one Google Group.
The former mailing lists hosted at Codehaus are gone, but still available in public archives at MarkMail.


I remember when I saw my first javascript object, It was just after I had finished up the codeacademy lessons on Python. I thought to myself "something isn't right here." And to be fair, I might have been slightly on point. I mean, this is a language that has a lot of silly and broken things about it (why in God's good grace does []==[]
evaluate to FALSE!?), and midst the flurry of curly brackets and semicolons you begin to wonder what makes sense and what doesn't.
However, after getting some time to familiarize myself with the javascript object, it began to dawn on me that it actually makes a good bit of sense to construct objects in this way (aka the way we build hashes in ruby) -- after all, on the face of things, an object is merely a set of instance variables (keys) with associated values. (I understand that there's more to an object than mere attributes, but my focus for this blog post is not going to delve in the world of prototyping javascript object behaviors -- that is for another day!)
Notation-wise, the coding looks all very similar. A javascript hash, instantiated in literal notation, is pretty much done the same way you would instantiate an empty hash object in ruby -- var obj = {};
and hash = {}
, respectively.
As far as keys are concerned, the two still perform almost identically:
What then, is the difference between a Javascript object and a Ruby hash? Very few, actually. The ruby hash we created about is an instance of the Hash object in ruby, and while the Hash *class* will see many differences from a Javascript object, the fact of the matter is that both the ruby hash and the JS object contain key-pair values, very easily accessible (nothing in a javascript object is 'hidden' from anything outside of it -- unlike a ruby class, where instance variables (properties of the class) cannot be read unless explicitely permitted)
Conceptually, there's a lot of similarities. As far as the behaviors of an object versus a hash, you'll find that the Ruby hash is much, MUCH more flexible than the javascript object. Javascript has very few object methods it can employ. In fact, there are so few native to JS, that I can list them here:
Notice how little we can do to this thing? Clearly Javascript does not want us to parse through an object like we can a Hash -- no sorting, no selecting of certain elements based on a block expression, nothing. And in this sense, we discover that a Javascript object is *not* always meant to be treated like a hash -- many times, the object is instantiated by it's constructor function, performed when someone fills out a certain set of data, or form, and submits it. Javascript is not the best at manipulating that kind of data in a fluid way -- one would honestly be better off running a for loop through thr object, outputting each key/pair value into an array, manipulating the data, and then reinserting it into a new object. Seems like a lot of work for even seemingly simple sorting functions. It kind of makes one realize how spoiled we can become from our highly abstracted and powerful programming languages like Ruby and Python!
But hashes are! Perhaps, when we start bridging the gap between front-end and back-end, feeding data from user input to our back-end programs, we'll begin to see how similar the two really are. I'm excited to see how that process will begin once we start the onsite.
Back to Top


|
|
|
|
|
|
|
|
|
|
|
cmdloop(self)
Repeatedly issue a prompt, accept input, parse an initial prefix off
the received input, and dispatch to action methods, passing them the
remainder of the line as argument. |
source code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
do_forks(self,
arg)
Set the number of forks |
source code
|
|
|
|
do_serial(self,
arg)
Set the number of forks |
source code
|
|
|
|
do_verbosity(self,
arg)
Set verbosity level |
source code
|
|
|
|
|
|
|
do_list(self,
arg)
List the hosts in the current group |
source code
|
|
|
|
do_become(self,
arg)
Toggle whether plays run with become |
source code
|
|
|
|
do_remote_user(self,
arg)
Given a username, set the remote user plays are run by |
source code
|
|
|
|
do_become_user(self,
arg)
Given a username, set the user that plays are run by when using
become |
source code
|
|
|
|
do_become_method(self,
arg)
Given a become_method, set the privilege escalation method when using
become |
source code
|
|
|
|
do_check(self,
arg)
Toggle whether plays run with check mode |
source code
|
|
|
|
do_diff(self,
arg)
Toggle whether plays run with diff |
source code
|
|
|
|
|
|
|
|
|
|
|
|
|
| complete_cd(self,
text,
line,
begidx,
endidx) |
source code
|
|
|
|
completedefault(self,
text,
line,
begidx,
endidx)
Method called to complete an input line when no command-specific
complete_*() method is available. |
source code
|
|
|
|
|
|
|
|
|
Inherited from CLI :
ask_passwords ,
execute ,
get_opt ,
normalize_become_options ,
pager ,
set_action ,
validate_conflicts
Inherited from object :
__delattr__ ,
__format__ ,
__getattribute__ ,
__hash__ ,
__new__ ,
__reduce__ ,
__reduce_ex__ ,
__repr__ ,
__setattr__ ,
__sizeof__ ,
__str__ ,
__subclasshook__
Inherited from cmd.Cmd :
columnize ,
complete ,
complete_help ,
completenames ,
do_help ,
onecmd ,
parseline ,
postcmd ,
postloop ,
precmd ,
preloop ,
print_topics
|


Chapter 7 Tempo
7.1 Outline
- A tempo simulation
- Bongaarts and Feeney’s formula
- An application to the United States
- Two Americas?
- EM algorithm for unmixing mixtures
- An application to two Americas.
7.2 Summary
7.2.1 What we see is superficial. Heterogeneous models reveal what’s ``really’’ going on. (Or do they?)
- Until today, population hazards mislead
- Today, homogeneous fertility misleads
7.2.2 Wwill reverse perspectives
- We see differences we see in genotypes, in lineages, in names.
- These could be due to ``real’’ differences (heterogeneity).
- But they could also be due to luck. Everyone is the same but stochastic outcomes differ.
- Our models of individual-level randomness will have predicted dynamics, which are themselves interesting but can also be used as a ``null’’ to compare to observations.
7.3 Fertility postponement, a very simple example
Baseline
- A population has a history of 1 birth per day
- When women turn age 25, they have a daughter.
- This gives us a constant stream of births, 365 per year.
Postponement
Starting on Jan. 1, 020, everyone postponements childbearing an additional month, until they are aged 25 1/12.
How many births will there be in 2020?
How many births in 2021?
7.3.1 Continuous postponement, a shiny simulation
- [\(R(t)\)] Cumulative postponment -[\(r(t)\)] Incremental postponement \(r(t) = R'(t)\)
What is a formula for recovering original birth stream? \[ \hat{B}_{orig} = B_{obs} \times (1 + R'(t)) \] or \[ \hat{B}_{orig} = B_{obs} \times 1/ \left[1 - R'(t)\right]? \]
Note: this idea of ``recovering original’’ is one way to think about tempo adjustment.
A bigger microsimulation
- Each period will have births across a range of ages
- We’ll randomly generate the original planned birthdays
- Then we’ll shift by a continuous function \(R(t)\).
7.4 Period Shifts: Bongaarts and Feeney’s model
\[ f(a,t) = f_0(a - R(t)) (1- R'(t)) q(t) \]
-[\(f(a,t)\)] birth rate of women aged \(a\) in period \(t\) -[\(f_0\)] A constant baseline schedule (can be norm’d to sum to 1). -[\(q(t)\)] A period intensity parameter: ``quantum’’ -[\(R(t)\)] Cumulative shift.
7.4.1 An example
\[ f(a,t) = f_0(a - R(t)) (1- R'(t)) q(t) \]
- \(R_{2019} = 3\)
- \(R'_{2019} = .1\)
- \(q(2019) = 1\)
Give an expression for \(f(28,2019)\).
7.5 A derivation: due to Rodriguez
Assume no quantum effects.
Take a cohort with cumulative fertility \[ F_0(a) = \int_0^a f(x) \,dx \]
Now put in shifts so that observed fertility is from an
age \(R(t)\) years . (28'' is the new
25’’!)
\[
F(a,t) = F_0(a - R(t)) \pause = F_0(a - R(c + a))
\]
Differentiate with respect to age (which for a cohort is also time \(t\)), using chain rule
\[ f(a,t) = f_0(a - R(t)) \left[1 - R'(t)\right] \] Bingo!
7.5.1 Quantum comes at the end
Let’s re-notate our constant quantum result \[ f_0(a,t | R(t) ) = f_0(a - R(t)) \left[1 - R'(t)\right] \] Then we can incorporate period quantum on the shifted surface: \[ f(a,t) = f_0(a,t | R(t) ) q(t) = f_0(a - R(t)) \left[1 - R'(t)\right]q(t) \]
Note: If we vary quantum shifts, then \(q(t)\) will bleed into neighboring years. (a small effect, but makes model messier).
7.5.2 Tempo-adjusted TFR: counter-factual, TFR in absence of timing changes
\[ TFR(t) = \int_0^\infty f(a,t) \, da \]
Substituting our shifted birth rates with quantum \[ TFR(t) = \int_0^\infty f_0(a - R(t)) \left[1 - R'(t)\right]q(t) \] gives?
\[ TFR(t) = TFR_0 \left[1 - R'(t)\right] q(t) \] WLG, define \(TFR_0 = 1\), then \[ q(t) = \alert{ {TFR(t) \over 1 - R'(t)} \equiv TFR^*(t) } \] Voila, the BF formula
7.5.3 How do period schedules change?
For homework \[ f(a,t) = f_0(a - R(t)) \left[1 - R'(t)\right] \]
What does \[ {\partial \over \partial t} \log f(a,t) = ? \] Let’s sketch
7.6 ``Uniform’’ shifts
- BF model assumes all ages shift by \(R(t)\).
- BF model assumes all ages rise or fall by same quantum \(q(t)\)
- Violating these assumptions means change in mean age will not just reflect ``tempo’’.
- Example: What happens if people have fewer higher order births?
7.7 BF recommendation for achieving uniformity
Separate estimates for each birth order, and then combine: \[ TFR^*(t) = \sum_i TFR_i^*(t) = \sum_i {TFR_i(t) \over 1 - r_i(t)} \]
This will protect against order-specific quantum effects.
7.8 An Application to the United States
- We’ll use HFD data
- We’ll do tempo adjustment for all births
- We’ll redo by birth order
## Tempo adjustment of US fertility using HMD data and
## Bongaarts-Feeney formula
library(data.table)
source("/hdir/0/fmenares/Book/bookdown-master/codes/tempo_functions.R")
source("/hdir/0/fmenares/Book/bookdown-master/codes/utility_functions.R")
## (1) read in data and format into an array
## (2) fit bongaarts feeney without birth order
## (3) fit bongaarts feeney with birth order
## (1) read in data and format into an array
## age specific fertility rates by birth order for all countries and times
## RR means "rectangles" on Lexis surface
dt <- fread("/hdir/0/fmenares/Book/bookdown-master/data/zip_w/asfrRRbo.txt")
dt <- dt[Code == "USA"] ## keep only US
## keep only ages 15 to 49
dt <- dt[Age %in% 15:49]
print(dt)
## Code Year Age ASFR ASFR1 ASFR2 ASFR3 ASFR4 ASFR5p
## 1: USA 1933 15 0.00672 0.00647 0.00025 0.00000 0.00000 0.00000
## 2: USA 1933 16 0.01875 0.01744 0.00121 0.00009 0.00000 0.00000
## 3: USA 1933 17 0.03846 0.03337 0.00464 0.00038 0.00005 0.00002
## 4: USA 1933 18 0.06586 0.05150 0.01256 0.00154 0.00021 0.00004
## 5: USA 1933 19 0.08719 0.05946 0.02249 0.00446 0.00064 0.00014
## ---
## 2971: USA 2017 45 0.00189 0.00048 0.00045 0.00032 0.00023 0.00041
## 2972: USA 2017 46 0.00102 0.00028 0.00026 0.00016 0.00012 0.00019
## 2973: USA 2017 47 0.00059 0.00019 0.00015 0.00009 0.00005 0.00010
## 2974: USA 2017 48 0.00029 0.00010 0.00008 0.00004 0.00002 0.00005
## 2975: USA 2017 49 0.00023 0.00008 0.00005 0.00004 0.00002 0.00003
## put all order fertiility into a matrix
fat <- dt[, xtabs(ASFR ~ Age + Year)]
fat <- as.matrix(unclass(fat)) ## may cause problems, we'll see
fat1 <- dt[, xtabs(ASFR1 ~ Age + Year)]
fat2 <- dt[, xtabs(ASFR2 ~ Age + Year)]
fat3 <- dt[, xtabs(ASFR3 ~ Age + Year)]
fat4 <- dt[, xtabs(ASFR4 ~ Age + Year)]
fat5p <- dt[, xtabs(ASFR5p ~ Age + Year)]
year.vec <- colnames(fat)
age.vec <- rownames(fat)
parity.vec <- c("all", 1:5)
fat.array <- array(NA, dim = c(nrow(fat), ncol(fat), length(parity.vec)))
dimnames(fat.array) <- list(age.vec, year.vec, parity.vec)
fat.array[,,"all"] <- fat
fat.array[,,"1"] <- fat1
fat.array[,,"2"] <- fat2
fat.array[,,"3"] <- fat3
fat.array[,,"4"] <- fat4
fat.array[,,"5"] <- fat5p
## (2) fit bongaarts feeney
tfr.vec <- colSums(fat)
## (2a) by hand
mu.vec <- apply(fat, 2, get.mean)
rt.vec <- center.diff(mu.vec)
adj.tfr.vec <- tfr.vec / (1 - rt.vec)
par(mfrow = c(3,1))
plot(names(mu.vec), mu.vec)
plot(names(mu.vec), rt.vec)
abline(h =0)
plot(year.vec, tfr.vec, type = "l")
lines(year.vec, adj.tfr.vec, lty = 2)
abline(v = c(1945, 2008))
## we see fertility since 1980 has been depressed by postponment
## we see weird dynamics around end of WW2 and great recession.
## what's going on?
par(mfrow = c(1,1))
plot(year.vec, tfr.vec, type = "l")
lines(year.vec, adj.tfr.vec, lty = 2)
abline(v = c(1945, 2008))
abline(h = seq(1.5, 2.5, .1), col = "grey", lty = 3)
## can also use function to fit
adj.tfr.vec.from.fun <- bf.fit.simple(fat)$tfr.star
lines(year.vec, adj.tfr.vec.from.fun, col = "red")
## Now let's look at turbulence around WW2
par(mfrow = c(2,2))
plot(age.vec, fat[,"1944"], type = "l", ylim = c(0, .23),
ylab = "f(a)",
xlab = "age a"
)
lines(age.vec, fat[,"1945"], type = "l", col = "red")
lines(age.vec, fat[,"1946"], type = "l", col = 'orange')
lines(age.vec, fat[,"1947"], type = "l", col = "blue")
legend("topright",
legend = 1944:1947,
col = c("black", "red", "orange", "blue"),
lty = 1)
title("Age specific fertility")
##
plot(1943:1947, mu.vec[paste(1943:1947)],
ylab = "mu(t)",
xlab = "t",
col = c("black", "black", "red", "orange", "blue"),
pch = 19)
title("Mean ages")
##
plot(1943:1947, rt.vec[paste(1943:1947)],
ylab = "r(t)",
xlab = "t",
col = c("black", "black", "red", "orange", "blue"),
pch = 19)
title("Changes in mean, centered")
##
plot(1943:1947, tfr.vec[paste(1943:1947)],
ylab = "tfr",
xlab = "t",
ylim = c(1, 4),
type = "l")
lines(1943:1947, adj.tfr.vec[paste(1943:1947)],
lty = 2)
title("TFR and adjTFR")
## From 1945 to 1946, fertility goes up a lot, but more at younger
## ages. So mean goes down. BF adjustment over-compensates, and has
## quantum declining.
## What's happening from 1944-45?
## (3) fit bongaarts feeney with birth order
out <- bf.fit(fat.array)
adj.tfr.bo.vec <- out$tfr.star.out[, "bf.tfr.star"]
## pdf("usa_tempo_fig.pdf")
par(mfrow = c(1,1))
plot(year.vec, tfr.vec, type = "l", lwd = 2)
lines(year.vec, adj.tfr.vec, lty = 2)
lines(year.vec, adj.tfr.bo.vec, lty = 1, lwd = 2, col = "red")
## let's check against hfd
hfd.adj.dt <- fread("/hdir/0/fmenares/Book/bookdown-master/data/zip_w/adjtfrRR.txt",
skip = 2)
hfd.adj.dt <- hfd.adj.dt[Code == "USA"]
hfd.adj.dt[, points(Year, adjTFR, col = "red", cex = .8)]
## NULL
legend("topright",
c("tfr", "tfr* (all parities)", "tfr* (by parity)"),
col = c("black", "black", "red"),
lty = c(1, 2, 1),
lwd = c(2,1,2))
hfd.adj.dt[, lines(Year, filter(adjTFR, rep(1/7, 7)), col = "red", lwd = 4)]
## NULL
## dev.off()
## Q. Does taking birth order into account smooth WW2 turbulence?
## Q. Does taking birth order into account smooth Recession turbulence?
## Q. Does taking birth order into account, retell the baby boom?
## Q. Does taking birth order into account, retell the baby bust?
- Baby boom smaller if we account for ``pre-ponement’’.
- Fertility lull in 1970s and 80s disappears if we account for ``postponement’’
- Birth order disaggregation improves estimates of shifts from changes in mean age
- What happened with the recession?
7.9 Two Americas
Let’s look at births (all orders).
fat_movie.pdf
Let’s look at 1st births, again as if their are two latent groups: \(A\) and \(B\). (These could be
early moms'' /
late moms’’, non-college / college, pre-marital / marital, lower-class / upper class, \(\ldots\))fat_mix_movie.pdf
library(mixtools)
## simulate 2 normals
N <- 1000
x1 <- rnorm(N, mean = 22, sd = 3) ##
x2 <- rnorm(2*N, mean = 30, sd = 4)
## combine them
x <- c(x1,x2)
## use EM to infer mixture
out <- normalmixEM(x,
lambda = c(.5, .5),
mu = c(15, 35),
sigma = c(5,5))
## number of iterations= 489
## [1] 22.67040 30.49742
## [1] 3.301363 3.801764
## [1] 0.4032589 0.5967411
Seems to work great.
ages <- 10:49
dens1 <- dnorm(x = ages, mean = out$mu[1], sd = out$sigma[1]) * out$lambda[1]
dens2 <- dnorm(x = ages, mean = out$mu[2], sd = out$sigma[2]) * out$lambda[2]
par(mfrow = c(1,1))
hist(x, probability = T, col = "grey")
lines(ages, dens1, col = "red", lwd = 2)
lines(ages, dens2, col = "blue", lwd = 2)
lines(ages, dens1 + dens2, col = "black", lwd = 2)
7.9.1 An algorithm for tempo adjustment of mixtures
- Fit normal mixture to each year.
- Refit using constant variance (average). This assures shape invariance of each component, fulfilling BF assumption.
Estimate BF separately for \(A\) and \(B\), and combine.
tempo_mixed_results_figure.pdf
Identifiability?
% could do with 3 sub-populations?
7.10 Conclusions
- Postponement dilutes period births, lowers TFR
- Tempo-adjustment tries to ``put births back in’’
- Changes in mean work fine if ``shape’’ doesn’t change
- Shape can change through heterogeneity
- With strong assumptions, we can identify heterogeneity
- Declining quantum for young and postponement for old appears to be the story
7.10.1 Caveats
- Who are these latent groups? Do you start out in one and end up in the other? Do you stay in one your whole life?
- How do we project forward?
- Can we use other indicators (e.g., social class, education, marriage) to get same results?


|
SideCar
|
#include <dns_sd.h>
#include "boost/shared_ptr.hpp"
#include "boost/scoped_ptr.hpp"
#include "boost/weak_ptr.hpp"
#include "Zeroconf/Monitor.h"
Go to the source code of this file.
Data Structures | |
| class | SideCar::Zeroconf::Transaction |
| Base class for all Zeroconf classes that interact with the DNSSD library. More... | |
Namespaces | |
| Logger | |
| Namespace for the Log logging device and support classes. | |
| SideCar | |
| Namespace for all entities specific to the 331 SideCar project. | |
| SideCar::Zeroconf | |
| Namespace for entities that interface with Zeroconf library. | |


Evented Card Components
Div 1
Div 2
Div 3
Non-Evented Card Component
Div 4
This text and image are here to prove that component styling is strictly scoped to the component.


Lee Cataluna: Everybody loves this lunch lady | Honolulu Star-Advertiser
Imagine putting together a lunch for friends from high school.  Would you invite the lunch lady? Read more
Mahalo for reading the Honolulu Star-Advertiser!
You're reading a premium story. Read the full story with our Print & Digital Subscription.
Already a subscriber? Log in now to continue reading this story.
Print subscriber but without online access? Activate your Digital Account now.