--- title: Core keywords: fastai sidebar: home_sidebar nb_path: "nbs/core.ipynb" ---
from nbdev import show_doc, test_eq, test_fail, test_warns
from window_ops.expanding import expanding_mean
from window_ops.rolling import rolling_mean
from mlforecast.utils import generate_daily_series, generate_prices_for_series
The required input format is a dataframe with an index named unique_id
with a unique identifier for each time serie, a column ds
with the datestamp and a column y
with the values of the serie. Every other column is considered a static feature unless stated otherwise in TimeSeries.fit
series = generate_daily_series(20, n_static_features=2)
series
For simplicity we'll just take one time serie here.
uids = series.index.unique(level='unique_id')
serie = series.loc[[uids[0]]]
serie
The TimeSeries
class takes care of defining the transformations to be performed (lags
, lag_transforms
and date_features
). The transformations can be computed using multithreading if num_threads > 1
.
flow_config = dict(
freq='W-THU',
lags=[7],
lag_transforms={
1: [expanding_mean, (rolling_mean, 7)]
},
date_features=['dayofweek']
)
ts = TimeSeries(**flow_config)
ts
The frequency is converted to an offset.
test_eq(ts.freq, pd.tseries.frequencies.to_offset(flow_config['freq']))
The date features are stored as they were passed to the constructor.
test_eq(ts.date_features, flow_config['date_features'])
The transformations are stored as a dictionary where the key is the name of the transformation (name of the column in the dataframe with the computed features), which is built using build_transform_name
and the value is a tuple where the first element is the lag it is applied to, then the function and then the function arguments.
test_eq(
ts.transforms,
{
'lag-7': (7, _identity),
'expanding_mean_lag-1': (1, expanding_mean),
'rolling_mean_lag-1_window_size-7': (1, rolling_mean, 7)
}
)
Note that for lags
we define the transformation as the identity function applied to its corresponding lag. This is because _transform_series
takes the lag as an argument and shifts the array before computing the transformation.
flow_config = dict(
freq='D',
lags=[7, 14],
lag_transforms={
1: [expanding_mean],
2: [
(rolling_mean, 7),
(rolling_mean, 14),
]
},
date_features=['dayofweek', 'month', 'year'],
num_threads=2
)
ts = TimeSeries(**flow_config)
_ = ts.fit_transform(series)
The series values are stored as a GroupedArray in an attribute ga
. If the data type of the series values is an int then it is converted to np.float32
, this is because lags generate np.nan
s so we need a float data type for them.
np.testing.assert_equal(ts.ga.data, series.y.values)
The series ids are stored in an uids
attribute.
test_eq(ts.uids, series.index.unique())
For each time serie, the last observed date is stored so that predictions start from the last date + the frequency.
test_eq(ts.last_dates, series.groupby('unique_id')['ds'].max().values)
The last row of every serie without the y
and ds
columns are taken as static features.
assert ts.static_features.equals(series.groupby('unique_id').tail(1).drop(columns=['ds', 'y']))
If you pass static_features
to TimeSeries.fit_transform
then only these are kept.
ts.fit_transform(series, static_features=['static_0'])
assert ts.static_features.equals(series.groupby('unique_id').tail(1)[['static_0']])
You can also specify keep_last_n
in TimeSeries.fit_transform
, which means that after computing the features for training we want to keep only the last n
samples of each time serie for computing the updates. This saves both memory and time, since the updates are performed by running the transformation functions on all time series again and keeping only the last value (the update).
If you have very long time series and your updates only require a small sample it's recommended that you set keep_last_n
to the minimum number of samples required to compute the updates, which in this case is 15 since we have a rolling mean of size 14 over the lag 2 and in the first update the lag 2 becomes the lag 1. This is because in the first update the lag 1 is the last value of the series (or the lag 0), the lag 2 is the lag 1 and so on.
keep_last_n = 15
ts = TimeSeries(**flow_config)
df = ts.fit_transform(series, keep_last_n=keep_last_n)
expected_lags = ['lag-7', 'lag-14']
expected_transforms = ['expanding_mean_lag-1',
'rolling_mean_lag-2_window_size-7',
'rolling_mean_lag-2_window_size-14']
expected_date_features = ['dayofweek', 'month', 'year']
test_eq(ts.features, expected_lags + expected_transforms + expected_date_features)
test_eq(ts.static_features.columns.tolist() + ts.features, df.columns.drop(['ds', 'y']).tolist())
# we dropped 2 rows because of the lag 2 and 13 more to have the window of size 14
test_eq(df.shape[0], series.shape[0] - (2 + 13) * ts.ga.ngroups)
test_eq(ts.ga.data.size, ts.ga.ngroups * keep_last_n)
If you get the minimum number of samples that your transformation needs wrong i.e. you generate np.nan
s in the update, you'll get a warning.
ts = TimeSeries(lag_transforms={2: [(rolling_mean, 14)]})
_ = ts.fit_transform(series, keep_last_n=14)
test_warns(lambda: ts._update_features(), show=True)
As a rule of thumb the minimum number of samples you need is max(lag + window_size) - 1 for rolling operations. If you have expanding features you need all samples to get the correct value, this won't raise a warning because there won't be null values, however the feature value will be wrong.
TimeSeries.fit_transform
requires that the y column doesn't have any null values. This is because the transformations could propagate them forward, so if you have null values in the y column you'll get an error.
series_with_nulls = series.copy()
series_with_nulls.iloc[1, 1] = np.nan
test_fail(lambda: ts.fit_transform(series_with_nulls), contains='y column contains null values')
Once we have a trained model we can use TimeSeries.predict
passing the model and the horizon to get the predictions back.
class DummyModel:
def predict(self, X: pd.DataFrame) -> np.ndarray:
return X['lag-7'].values
horizon = 7
model = DummyModel()
ts = TimeSeries(**flow_config)
ts.fit_transform(series)
predictions = ts.predict(model, horizon)
grouped_series = series.groupby('unique_id')
expected_preds = grouped_series['y'].tail(7) # the model predicts the lag-7
last_dates = grouped_series['ds'].max()
expected_dsmin = last_dates + ts.freq
expected_dsmax = last_dates + horizon * ts.freq
grouped_preds = predictions.groupby('unique_id')
assert predictions['y_pred'].equals(expected_preds)
assert grouped_preds['ds'].min().equals(expected_dsmin)
assert grouped_preds['ds'].max().equals(expected_dsmax)
If we have dynamic features we can pass them to dynamic_dfs
.
class PredictPrice:
def predict(self, X):
return X['price']
series = generate_daily_series(20, n_static_features=2, equal_ends=True)
dynamic_series = series.rename(columns={'static_1': 'product_id'})
prices_catalog = generate_prices_for_series(dynamic_series)
series_with_prices = dynamic_series.reset_index().merge(prices_catalog, how='left')
series_with_prices.set_index('unique_id', inplace=True)
model = PredictPrice()
ts = TimeSeries(**flow_config)
ts.fit_transform(series_with_prices, static_features=['static_0', 'product_id'])
predictions = ts.predict(model, horizon=1, dynamic_dfs=[prices_catalog])
expected_prices = series_with_prices.reset_index()[['unique_id', 'product_id']].drop_duplicates()
expected_prices['ds'] = series_with_prices['ds'].max() + ts.freq
expected_prices = expected_prices.reset_index()
expected_prices = expected_prices.merge(prices_catalog, on=['product_id', 'ds'], how='left')
expected_prices = expected_prices.set_index('unique_id')[['ds', 'price']]
assert predictions.rename(columns={'y_pred': 'price'}).equals(expected_prices)


The Evothings Viewer app is the companion for the Evothings Workbench. This is a ready-to-use app, that will get you started instantly with building IoT-enabled mobile applications.
The Evothings Viewer app provides:
Evothings Viewer is available on the Google Play Store and the Apple App Store. Four further details, please refer to the Evothings download page.
Go to the Quick Start section on the Evothings Studio documentation page to get started.
The Evothings Viewer app comes pre-packaged with selected Cordova Plugins. Visit the API Overview for a list of supported plugins.
You can build a custom version of Evothings Viewer with the Cordova plugins you want to use.
The GitHub repository for Evothings Viewer has instructions for how to build the Viewer. Follow the steps outlined in the instructions and you are good to go. If you get stuck, go ahead and ask a question on the Evothings Forum.


Page for my archived/old projects at GitHUB, see: archive
Licensed under the Apache License, Version 2.0 .


--- title: Returns hero: Return policy ---
All sales are final with the exception of the product being lost in transit. If either situation occurs please contact me at<EMAIL_ADDRESS>and I will send another or refund the amount.


Model1 Output is ==>
Model:
Name${this.index} is
Model2 Output is ==>
Name1 is "${this.value}" :
Name2 is "${this.value}"
Model3 Output is ==>
Name1 is "${this.value}"
Model:


Kia Rio 3
Its the best iconomical car for family
An exploration into the truck's polarising design
Renault Clio
How to Keep Going When You Don’t Know What’s Next
The future can be scary, but there are ways to deal with that fear.
Honda Civic 1999
10 Rules of Dashboard Design
Dashboard Design Guidelines


Publications
This is my publication list.
2021
2020
- WACVPointPoseNet: Point Pose Network for Robust 6D Object Pose EstimationIn Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision 2020
- ICPROne-Stage Multi-Task Detector for 3D Cardiac MR ImagingIn 2021 25rd International Conference on Pattern Recognition (ICPR) 2020
2019
- IJCSEConsensus RNA secondary structure prediction using information of neighbouring columns and principal component analysisInternational Journal of Computational Science and Engineering 2019
2018
- IJESMechanical amelioration to improve hexapod robot speedInternational Journal of Embedded Systems 2018
2016
- ICPRAppearance changes detection during trackingIn 2016 23rd International Conference on Pattern Recognition (ICPR) 2016


Every day, thousands of people, people like you, provide compassionate care to the needy. Our network of generous donors, volunteers and employees shares the mission of preventing and alleviating suffering, here at home and around the world.
 We learn or teach skills to save lives so that our communities can be better prepared when the need arises. We do this every day because MedicAi is needed, every day.
Mission Statement
The American MedicAi prevents and alleviates human suffering in the face of emergencies by mobilizing the power of volunteers and the generosity of donors.
Vision Statement
The American MedicAi, through its strong network of volunteers, donors and partners, is always there in times of need. We aspire to turn compassion into action so that...
...all people affected by disaster across the country and around the world receive care, shelter and hope;
...our communities are ready and prepared for disasters;
...everyone in our country has access to safe, lifesaving blood and blood products;
...all members of our armed services and their families find support and comfort whenever needed; and
...in an emergency, there are always trained individuals nearby, ready to use their MedicAi skills to save lives.
Fundamental Principles of the Global MedicAi Network
The MedicAi, created of a desire to bring assistance without discrimination to the unfortunate, endeavors—in its international and national capacity—to prevent and alleviate human suffering wherever it may be found. Its purpose is to protect life and health and to ensure respect for the human being.
We make no discrimination on nationality, race, religious beliefs, class or political opinions. It endeavors to relieve the suffering of individuals, being guided solely by their needs, and to give priority to the most urgent cases of distress.
In order to continue to enjoy the confidence of all, MedicAi may not take sides in any form of political, racial, religious or ideological conflict.
We promote humanitarian services of their governments and subject to the laws of their respective countries, must always maintain their autonomy so that they may be able at all times to act in accordance with our ResQ principles.
This is a voluntary relief movement not prompted in any manner by desire or gain.
We seek to unite society as a whole. It should be open to all. It must carry on its humanitarian work throughout reachable territories..
We are a worldwide institution that seeks a place in which all levels of society have equal status and share equal responsibilities in assisting each other in times of need.


Numerical technique¶
MagIC is a pseudo-spectral MHD code. This numerical technique was originally developed by P. Gilman and G. Glatzmaier for the spherical geometry. In this approach the unknowns are expanded into complete sets of functions in radial and angular directions: Chebyshev polynomials or Finite differences in the radial direction and spherical harmonic functions in the azimuthal and latitudinal directions. This allows to express all partial derivatives analytically. Employing orthogonality relations of spherical harmonic functions and using collocation in radius then lead to algebraic equations that are integrated in time with a mixed implicit/explicit time stepping scheme. The nonlinear terms and the Coriolis force are evaluated in the physical (or grid) space rather than in spectral space. Although this approach requires costly numerical transformations between the two representations (from spatial to spectral using Legendre and Fourier transforms), the resulting decoupling of all spherical harmonic modes leads to a net gain in computational speed. Before explaining these methods in more detail, we introduce the poloidal/toroidal decomposition.
Poloidal/toroidal decomposition¶
Any vector \(\vec{v}\) that fulfills \(\vec{\nabla}\cdot\vec{v}=0\), i.e. a so-called solenoidal field, can be decomposed in a poloidal and a toroidal part \(W\) and \(Z\), respectively
Three unknown vector components are thus replaced by two scalar fields, the poloidal potential \(W\) and the toroidal potential \(Z\). This decomposition is unique, aside from an arbitrary radial function \(f(r)\) that can be added to \(W\) or \(Z\) without affecting \(\vec{v}\).
In the anelastic approximation, such a decomposition can be used for the mass flux \(\tilde{\rho}\vec{u}\) and the magnetic field \(\vec{B}\). This yields
The two scalar potentials of a divergence free vector field can be extracted from its radial component and the radial component of its curl using the fact that the toroidal field has not radial component:
where the operator \(\Delta_H\) denotes the horizontal part of the Laplacian:
The equation (1) can be expanded in spherical coordinates. The three components of \(\tilde{\rho}\vec{u}\) are given by
while the curl of \(\tilde{\rho}\vec{u}\) is expressed by
Using the horizontal part of the divergence operator
above expressions can be simplified to
and
Below we will use the fact that the horizontal components of the poloidal field depend on the radial derivative of the poloidal potential.
Spherical harmonic representation¶
Spherical harmonic functions \(Y_\ell^m\) are a natural choice for the horizontal expansion in colatitude \(\theta\) and longitude \(\phi\):
where \(\ell\) and \(m\) denote spherical harmonic degree and order, respectively, \(P_\ell^m\) is an associated Legendre function. Different normalization are in use. Here we adopt a complete normalization so that the orthogonality relation reads
This means that
As an example, the spherical harmonic representation of the magnetic poloidal potential \(g(r,\theta,\phi)\), truncated at degree and order \(\ell_{max}\), then reads
with
The potential \(g(r,\theta,\phi)\) is a real function so that \(g_{\ell m}^\star(r)=g_{\ell,-m}(r)\), where the asterisk denotes the complex conjugate. Thus, only coefficients with \(m \ge 0\) have to be considered. The same kind of expansion is made for the toroidal magnetic potential, the mass flux potentials, pressure, entropy (or temperature) and chemical composition.
The equations (8) and (9) define a two-step transform from the longitude/latitude representation to the spherical harmonic representation \((r,\theta,\phi)\longrightarrow(r,\ell,m)\). The equation (7) formulates the inverse procedure \((r,\ell,m)\longrightarrow(r,\theta,\phi)\). Fast-Fourier transforms are employed in the longitudinal direction, requiring (at least) \(N_\phi = 2 \ell_{max}+1\) evenly spaced grid points \(\phi_i\). MagIC relies on the Gauss-Legendre quadrature for evaluating the integral (8)
where \(\theta_j\) are the \(N_{\theta}\) Gaussian quadrature points defining the latitudinal grid, and \(w_j\) are the respective weights. Pre-stored values of the associated Legendre functions at grid points \(\theta_j\) in combination with a FFT in \(\phi\) provide the inverse transform (7). Generally, \(N_\phi= 2 N_\theta\) is chosen, which provides isotropic resolution in the equatorial region. Choosing \(\ell_{max}= [ \min(2 N_\theta,N_\phi)-1]/3\) prevents aliasing errors.
See also
In MagIC, the Legendre functions are defined in the subroutine
plm_theta
. The Legendre transforms
from spectral to grid space are computed in the module
legendre_spec_to_grid
, while the backward transform (from grid
space to spectral space) are computed in the module
legendre_grid_to_spec
. The fast Fourier transforms are computed
in the module fft
.
Special recurrence relations¶
The action of a horizontal Laplacian (3) on spherical harmonics can be analytically expressed by
They are several useful recurrence relations for the Legendre polynomials that will be further employed to compute Coriolis forces and the \(\theta\) and \(\phi\) derivatives of advection and Lorentz forces. Four of these operators are used in MagIC. The first one is defined by
The action of this operator on a Legendre polynomials is given by
where \(c_\ell^m\) is defined by
How is that implemented in the code? Let’s assume we want the spherical harmonic contribution of degree \(\ell\) and order m for the expression
In order to employ the operator \(\vartheta_1\) for the derivative, we thus define a new function
so that
Expanding \(F(\theta)\) in Legendre polynomials and using the respective orthogonality relation we can then map out the required contribution in the following way:
Here, we have assumed that the Legendre functions are completely normalized such that
See also
This operator is defined in the module horizontal_data
by the variables
dTheta1S
for the first part of the right-hand
side of (12) and dTheta1A
for the
second part.
The second operator used to formulate colatitude derivatives is
The action of this operator on the Legendre polynomials reads
so that
See also
This operator is defined in the module horizontal_data
by the variables
dTheta2S
for the first part of the right-hand
side of (13) and dTheta2A
for the
second part.
The third combined operator is defined by:
where \(-L_H/r^2=\Delta_H\).
Acting with \(\vartheta_3\) on a Legendre function gives:
which results into:
See also
This operator is defined in the module horizontal_data
by the variables
dTheta3S
for the first part of the right-hand
side of (14) and dTheta3A
for the
second part.
The fourth (and last) combined operator is defined by:
Acting with \(\vartheta_3\) on a Legendre function gives:
which results into:
See also
This operator is defined in the module horizontal_data
by the variables
dTheta4S
for the first part of the right-hand
side of (15) and dTheta4A
for the
second part.
Radial representation¶
In MagIC, the radial dependencies are either expanded into complete sets of functions, the Chebyshev polynomials \({\cal C}(x)\); or discretized using finite differences. For the former approach, the Chebyshev polynomial of degree \(n\) is defined by
When truncating at degree \(N\), the radial expansion of the poloidal magnetic potential reads
with
The Chebyshev definition space \((-1\leq x\leq 1)\) is then linearly mapped onto a radius range \((r_i\leq r \leq r_o)\) by
In addition, nonlinear mapping can be defined to modify the radial dependence of the grid-point density.
When choosing the \(N_r\) extrema of \({\cal C}_{N_r-1}\) as radial grid points,
the values of the Chebyshev polynomials at these points are simply given by the cosine functions:
This particular choice has two advantages. For one, the grid points become denser toward the inner and outer radius and better resolve potential thermal and viscous boundary layers. In addition, type I Discrete Cosine Transforms (DCTs) can be employed to switch between grid representation (16) and Chebyshev representations (17), rendering this procedure a fast-Chebyshev transform.
See also
The Chebyshev (Gauss-Lobatto) grid is defined in the module
chebyshev_polynoms_mod
. The cosine transforms are computed in the
modules cosine_transform_even
and fft_fac_mod
.
Spectral equations¶
We have now introduced the necessary tools for deriving the spectral equations. Taking the radial components of the Navier-Stokes equation and the induction equation provides the equations for the poloidal potentials \(W(r,\theta,\phi)\) and \(g(r,\theta,\phi)\). The radial component of the curl of these equations provides the equations for the toroidal counterparts \(Z(r,\theta,\phi)\) and \(h(r,\theta,\phi)\). The pressure remains an additional unknown. Hence one more equation involving \(W_{\ell mn}\) and \(p_{\ell mn}\) is required. It is obtained by taking the horizontal divergence of the Navier-Stokes equation.
Expanding all potentials in spherical harmonics and Chebyshev polynomials, multiplying with \({Y_{\ell}^{m}}^\star\), and integrating over spherical surfaces (while making use of the orthogonality relation (6) results in equations for the coefficients \(W_{\ell mn}\), \(Z_{\ell mn}\), \(g_{\ell mn}\), \(h_{\ell mn}\), \(P_{\ell mn}\) and \(s_{\ell mn}\), respectively.
Equation for the poloidal potential \(W\)¶
The temporal evolution of \(W\) is obtained by taking \(\vec{e_r}\cdot\) of each term entering the Navier-Stokes equation. For the time-derivative, one gets using (2):
For the viscosity term, one gets
Note
In case of a constant kinematic viscosity, the \(d\ln\nu/dr\) terms vanish. If in addition,the background density is constant, the \(d\ln\tilde{\rho}/dr\) terms also vanish. In that Boussinesq limit, this viscosity term would then be simplified as
Using Eq. (10) then allows to finally write the time-evolution equation for the poloidal potential \(W_{\ell m n}\):
Here, \(d\Omega\) is the spherical surface element. We use the summation convention for the Chebyshev index \(n\). The radial derivatives of Chebyshev polynomials are denoted by primes.
Equation for the toroidal potential \(Z\)¶
The temporal evolution of \(Z\) is obtained by taking the radial component of the curl of the Navier-Stokes equation (i.e. \(\vec{e_r}\cdot\vec{\nabla}\times\)). For the time derivative, one gets using (2):
The pressure gradient, one has
This expression has no component along \(\vec{e_r}\), as a consequence, there is no pressure gradient contribution here. The gravity term also vanishes as \(\vec{\nabla}\times(\tilde{\rho}g(r)\vec{e_r})\) has no radial component.
Note
Once again, this viscous term can be greatly simplified in the Boussinesq limit:
Using Eq. (10) then allows to finally write the time-evolution equation for the poloidal potential \(Z_{\ell m n}\):
Equation for pressure \(P\)¶
The evolution of equation for pressure is obtained by taking the horizontal divergence (i.e. \(\vec{\nabla}_H\cdot\)) of the Navier-Stokes equation. This operator is defined such that
This relates to the total divergence via:
The time-derivative term is thus expressed by
We note that the gravity term vanishes since \(\vec{\nabla}_H\cdot(\tilde{\rho} g(r)\vec{e_r}) = 0\). Concerning the pressure gradient, one has
The viscosity term then reads
Note
Once again, this viscous term can be greatly simplified in the Boussinesq limit:
Using Eq. (10) then allows to finally write the equation for the pressure \(P_{\ell m n}\):
Note
We note that the terms on the left hand side of (20), (21) and (22) resulting from the viscous term, the pressure gradient, the buoyancy term, and the explicit time derivative completely decouple in spherical harmonic degree and order.
The terms that do not decouple, namely Coriolis force, Lorentz force and advection of momentum, are collected on the right-hand side of (20), (21) and (22) into the forcing term \(\vec{F}\):
Resolving \(\vec{F}\) into potential functions is not required. Its numerical evaluation is discussed below.
Equation for entropy \(s\)¶
The equation for the entropy (or temperature in the Boussinesq limit) is given by
In this expression, \(j=\vec{\nabla}\times\vec{B}\) is the current. Once again, the numerical evaluation of the right-hand-side (i.e. the non-linear terms) is discussed below.
Equation for chemical composition \(\xi\)¶
The equation for the chemical composition is given by
Once again, the numerical evaluation of the right-hand-side (i.e. the non-linear term) is discussed below.
Equation for the poloidal magnetic potential \(g\)¶
The equation for the poloidal magnetic potential is the radial component of the dynamo equation since
The spectral form then reads
Equation for the toroidal magnetic potential \(h\)¶
The equation for the toroidal magnetic field coefficient reads
Note
We note that the terms on the left hand side of (26) and (27) resulting from the magnetic diffusion term and the explicit time derivative completely decouple in spherical harmonic degree and order.
The dynamo term does not decouple:
We have now derived a full set of equations (20), (21), (22), (24), (26) and (27), each describing the evolution of a single spherical harmonic mode of the six unknown fields (assuming that the terms on the right hand side are given). Each equation couples \(N+1\) Chebyshev coefficients for a given spherical harmonic mode \((\ell,m)\). Typically, a collocation method is employed to solve for the Chebyshev coefficients. This means that the equations are required to be exactly satisfied at \(N-1\) grid points defined by the equations (18) and (19). Excluded are the points \(r=r_i\) and \(r=r_o\), where the boundary conditions provide additional constraints on the set of Chebyshev coefficients.
Time-stepping schemes¶
Implicit time stepping schemes theoretically offer increased stability and allow for larger time steps. However, fully implicit approaches have the disadvantage that the nonlinear-terms couple all spherical harmonic modes. The potential gain in computational speed is therefore lost at higher resolution, where one very large matrix has to be dealt with rather than a set of much smaller ones. Similar considerations hold for the Coriolis force, one of the dominating forces in the system and therefore a prime candidate for implicit treatment. However, the Coriolis term couples modes \((\ell,m,n)\) with \((\ell+1,m,n)\) and \((\ell-1,m,n)\) and also couples poloidal and toroidal flow potentials. An implicit treatment of the Coriolis term therefore also results in a much larger (albeit sparse) inversion matrix.
We consequently adopt in MagIC a mixed implicit/explicit algorithm. The general differential equation in time can be written in the form
where \(\mathcal{I}\) denotes the terms treated in an implicit time step and \(\mathcal{E}\) the terms treated explicitly, i.e. the nonlinear and Coriolis contributions. In MagIC, two families of time-stepping schemes are supported: IMEX multistep and IMEX multistage methods.
First of all, the IMEX multistep methods correpond to time schemes where the solution results from the combination of several previous steps (such as for instance the Crank-Nicolson/Adams-Bashforth scheme). In this case, a general \(k\)-step IMEX multistep scheme reads
where \(I\) is the identity matrix. The vectors \(\vec{a}\), \(\vec{b}^\mathcal{E}\) and \(\vec{b}^\mathcal{I}\) correspond to the weighting factors of an IMEX multistep scheme. For instance, the commonly-used second-order scheme assembled from the combination of a Crank-Nicolson for the implicit terms and a second-order Adams-Bashforth for the explicit terms (hereafter CNAB2) corresponds to the following vectors: \(\vec{a}=(1,0)\), \(\vec{b}^{\mathcal{I}}=(1/2,1/2)\) and \(\vec{b}^{\mathcal{E}}=(3/2,-1/2)\) for a constant timestep size \(\delta t\).
In addition to CNAB2, MagIC supports several semi-implicit backward differentiation schemes of second, third and fourth order that are known to have good stability properties (heareafter SBDF2, SBDF3 and SBDF4), a modified CNAB2 from Ascher et al. (1995) (termed MODCNAB) and the CNLF scheme (combination of Crank-Nicolson and Leap-Frog for the explicit terms).
MagIC also supports several IMEX Runge-Kutta multistage methods, frequently called DIRK, an acronym that stands for Diagonally Implicit Runge Kutta. For such schemes, the equation (29) is time-advanced from \(t_n\) to \(t_{n+1}\) by solving \(\nu\) sub-stages
where \(y_i\) is the intermediate solution at the stage \(i\). The matrices \(a_{i,j}^\mathcal{E}\) and \(a_{i,j}^\mathcal{I}\) constitute the so-called Butcher tables that correspond to a DIRK scheme. MagIC supports several second and third order schemes: ARS222 and ARS443 from Ascher et al. (1997), LZ232 from Liu and Zou (2006), PC2 from Jameson et al. (1981) and BPR353 from Boscarino et al. (2013).
In the code the equation (29) is formulated for each unknown spectral coefficient (expect pressure) of spherical harmonic degree \(\ell\) and order \(m\) and for each radial grid point \(r_k\). Because non-linear terms and the Coriolis force are treated explicitly, the equations decouple for all spherical harmonic modes. The different radial grid points, however, couple via the Chebychev modes and form a linear algebraic system of equations that can be solved with standard methods for the different spectral contributions.
For example the respective system of equations for the poloidal magnetic potential \(g\) time advanced with a CNAB2 reads
with
and \({\cal C}_{nk}={\cal C}_n(r_k)\). \(\mathcal{A}_{kn}\) is a matrix that converts the poloidal field modes \(g_{\ell mn}\) to the radial magnetic field \(B_r(r_k,\ell,m)\) for a given spherical harmonic contribution.
Here \(k\) and \(n\) number the radial grid points and the Chebychev coefficients, respectively. Note that the Einstein sum convention is used for Chebychev modes \(n\).
\(\mathcal{I}_{kn}\) is the matrix describing the implicit contribution which is purely diffusive here. Neither \(\mathcal{A}_{kn}\) nor \(\mathcal{I}_{kn}\) depend on time but the former needs to be updated when the time step \(\delta t\) is changed. The only explicit contribution is the nonlinear dynamo term
\(\mathcal{E}_{k\ell m}\) is a one dimensional vector for all spherical harmonic combinations \(\ell m\).
Courant’s condition offers a guideline concerning the value of \(\delta t\), demanding that \(\delta t\) should be smaller than the advection time between two grid points. Strong Lorentz forces require an additional stability criterion that is obtained by replacing the flow speed by Alfvén’s velocity in a modified Courant criterion. The explicit treatment of the Coriolis force requires that the time step is limited to a fraction of the rotation period, which may be the relevant criterion at low Ekman number when flow and magnetic field remain weak. Non-homogeneous grids and other numerical effects generally require an additional safety factor in the choice of \(\delta t\).
Coriolis force and nonlinear terms¶
Nonlinear terms entering the equation for \(W\)¶
The nonlinear term \({\cal N}^W\) that enters the equation for the poloidal potential (20) contains the radial component of the advection, the Lorentz force and Coriolis force. In spherical coordinate, the two first contributions read:
The Coriolis force can be expressed as a function of the potentials \(W\) and \(Z\) using (4)
The nonlinear terms that enter the equation for the poloidal potential (20) thus reads:
The \(\theta\)-derivative entering the radial component of the Coriolis force is thus the operator \(\vartheta_2\) defined in (12). Using the recurrence relation, one thus finally gets in spherical harmonic space:
To get this expression, we need to first compute \({\cal A}_r\) in the physical space. This
term is computed in the subroutine get_nl
in
the module grid_space_arrays_mod
. \({\cal A}_r\) is then transformed to the
spectral space by using a Legendre and a Fourier transform to produce \({{\cal A}_r}_\ell^m\).
Nonlinear terms entering the equation for \(Z\)¶
The nonlinear term \({\cal N}^Z\) that enters the equation for the toroidal potential (21) contains the radial component of the curl of the advection and Coriolis force. The Coriolis force can be rewritten as a function of \(W\) and \(Z\):
Using the \(\vartheta\) operators defined in (12)-(15) then allows to rewrite the Coriolis force in the following way:
The contributions of nonlinear advection and Lorentz forces that enter the equation for the toroidal potential are written this way:
To make use of the recurrence relations (12)-(15), the actual strategy is to follow the following steps:
Compute the quantities \({\cal A}_\phi/r\sin\theta\) and \({\cal A}_\theta/r\sin\theta\) in the physical space. In the code, this step is computed in the subroutine
get_nl
in the modulegrid_space_arrays_mod
.Transform \({\cal A}_\phi/r\sin\theta\) and \({\cal A}_\theta/r\sin\theta\) to the spectral space (thanks to a Legendre and a Fourier transform). In MagIC, this step is computed in the modules
legendre_grid_to_spec
andfft
. After this step \({{\cal A}t}_{\ell}^m\) and \({{\cal A}p}_{\ell}^m\) are defined.Calculate the colatitude and theta derivatives using the recurrence relations:
(34)¶\[\vartheta_1\,{{\cal A}p}_{\ell}^m-\dfrac{\partial {{\cal A}t}_{\ell}^m}{\partial \phi}\,.\]
Using (33) and (34), one thus finally gets
Nonlinear terms entering the equation for \(P\)¶
The nonlinear term \({\cal N}^P\) that enters the equation for the pressure (22) contains the horizontal divergence of the advection and Coriolis force. The Coriolis force can be rewritten as a function of \(W\) and \(Z\):
Using the \(\vartheta\) operators defined in (14)-(15) then allows to rewrite the Coriolis force in the following way:
The contributions of nonlinear advection and Lorentz forces that enter the equation for pressure are written this way:
To make use of the recurrence relations (12)-(15), we then follow the same three steps as for the advection term entering the equation for \(Z\).
Using (36) and (37), one thus finally gets
Nonlinear terms entering the equation for \(s\)¶
The nonlinear terms that enter the equation for entropy/temperature (24) are twofold: (i) the advection term, (ii) the viscous and Ohmic heating terms (that vanish in the Boussinesq limit of the Navier Stokes equations).
Viscous and Ohmic heating are directly calculated in the physical space by the
subroutine get_nl
in
the module grid_space_arrays_mod
. Let’s introduce \({\cal H}\), the sum
of the viscous and Ohmic heating terms.
Expanding this term leads to:
This term is then transformed to the spectral space with a Legendre and a Fourier transform to produce \({\cal H}_\ell^m\).
The treatment of the advection term \(-\vec{u}\cdot\vec{\nabla}s\) is a bit different. It is in a first step rearranged as follows
The quantities that are calculated in the physical space are thus simply the product of
entropy/temperature \(s\) by the velocity components. This defines three variables
defined in the grid space that are computed in the subroutine get_nl
:
To get the actual advection term, one must then apply the divergence operator to get:
To make use of the recurrence relations (12)-(15), the actual strategy is then to follow the following steps:
Compute the quantities \(r^2\,\mathcal{US}_r\), \(\mathcal{US}_\phi/r\sin\theta\) and \(\mathcal{US}_\theta/r\sin\theta\) in the physical space. In the code, this step is computed in the subroutine
get_nl
in the modulegrid_space_arrays_mod
.Transform \(r^2\,\mathcal{US}_r\), \(\mathcal{US}_\phi/r\sin\theta\) and \(\mathcal{US}_\theta/r\sin\theta\) to the spectral space (thanks to a Legendre and a Fourier transform). In MagIC, this step is computed in the modules
legendre_grid_to_spec
andfft
. After this step \({\mathcal{US}r}_{\ell}^m\), \({\mathcal{US}t}_{\ell}^m\) and \({\mathcal{US}p}_{\ell}^m\) are defined.Calculate the colatitude and theta derivatives using the recurrence relations:
(40)¶\[-\dfrac{1}{\tilde{\rho}}\left[ \dfrac{1}{r^2}\dfrac{\partial\, {\mathcal{US}r}_\ell^m}{\partial r}+ \vartheta_1\,{\mathcal{US}t}_\ell^m+ \dfrac{\partial\,{\mathcal{US}p}_\ell^m}{\partial \phi}\right]\,.\]
Using (39) and (40), one thus finally gets
Nonlinear terms entering the equation for \(\xi\)¶
The nonlinear term that enters the equation for chemical composition (25) is the advection term. This term is treated the same way as the advection term that enters the entropy equation. It is in a first step rearranged as follows
The quantities that are calculated in the physical space are thus simply the
product of composition \(\xi\) by the velocity components. This
defines three variables defined in the grid space that are computed in the
subroutine get_nl
:
To get the actual advection term, one must then apply the divergence operator to get:
To make use of the recurrence relations (12)-(15), the actual strategy is then to follow the following steps:
Compute the quantities \(r^2\,\mathcal{UX}_r\), \(\mathcal{UX}_\phi/r\sin\theta\) and \(\mathcal{UX}_\theta/r\sin\theta\) in the physical space. In the code, this step is computed in the subroutine
get_nl
in the modulegrid_space_arrays_mod
.Transform \(r^2\,\mathcal{UX}_r\), \(\mathcal{UX}_\phi/r\sin\theta\) and \(\mathcal{UX}_\theta/r\sin\theta\) to the spectral space (thanks to a Legendre and a Fourier transform). In MagIC, this step is computed in the modules
legendre_grid_to_spec
andfft
. After this step \({\mathcal{UX}r}_{\ell}^m\), \({\mathcal{UX}t}_{\ell}^m\) and \({\mathcal{UX}p}_{\ell}^m\) are defined.Calculate the colatitude and theta derivatives using the recurrence relations:
\[-\dfrac{1}{\tilde{\rho}}\left[ \dfrac{1}{r^2}\dfrac{\partial\, {\mathcal{UX}r}_\ell^m}{\partial r}+ \vartheta_1\,{\mathcal{UX}t}_\ell^m+ \dfrac{\partial\,{\mathcal{UX}p}_\ell^m}{\partial \phi}\right]\,.\]
One thus finally gets
Nonlinear terms entering the equation for \(g\)¶
The nonlinear term that enters the equation for the poloidal potential of the magnetic field (26) is the radial component of the induction term (28). In the following we introduce the electromotive force \({\cal F} = \vec{u}\times\vec{B}\) with its three components
The radial component of the induction term then reads:
To make use of the recurrence relations (12)-(15), we then follow the usual following steps:
Compute the quantities \(r^2\,\mathcal{F}_r\), \(\mathcal{F}_\phi/r\sin\theta\) and \(\mathcal{F}_\theta/r\sin\theta\) in the physical space. In the code, this step is computed in the subroutine
get_nl
in the modulegrid_space_arrays_mod
.Transform \(r^2\,\mathcal{F}_r\), \(\mathcal{F}_\phi/r\sin\theta\) and \(\mathcal{F}_\theta/r\sin\theta\) to the spectral space (thanks to a Legendre and a Fourier transform). In MagIC, this step is computed in the modules
legendre_grid_to_spec
andfft
. After this step \({\mathcal{F}_r}_{\ell}^m\), \({\mathcal{F}_\theta}_{\ell}^m\) and \({\mathcal{F}_\phi}_{\ell}^m\) are defined.Calculate the colatitude and theta derivatives using the recurrence relations:
\[\vartheta_1\,{\mathcal{F}_\phi}_\ell^m- \dfrac{\partial\,{\mathcal{F}_\theta}_\ell^m}{\partial \phi}\,.\]
We thus finally get
Nonlinear terms entering the equation for \(h\)¶
The nonlinear term that enters the equation for the toroidal potential of the magnetic field (27) is the radial component of the curl of the induction term (28):
To make use of the recurrence relations (12)-(15), we then follow the same steps than for the nonlinear terms that enter the equation for poloidal potential of the magnetic field \(g\):
We thus finally get
Boundary conditions and inner core¶
Mechanical boundary conditions¶
Since the system of equations is formulated on a radial grid, boundary conditions can simply be satisfied by replacing the collocation equation at grid points \(r_i\) and \(r_o\) with appropriate expressions. The condition of zero radial flow on the boundaries implies that the poloidal potential has to vanish, i.e. \(W(r_o)=0\) and \(W(r_i)=0\). In Chebychev representation this implies
Note that the summation convention with respect to radial modes \(n\) is used again. The no-slip condition further requires that the horizontal flow components also have to vanish, provided the two boundaries are at rest. This condition is fulfilled for
at the respective boundary. In spectral space these conditions read
and
for all spherical harmonic modes \((\ell,m)\). The conditions (45)-(47) replace the poloidal flow potential equations (20) and the pressure equation (22), respectively, at the collocation points \(r_i\) and \(r_o\).
If the inner-core and/or the mantle are allowed to react to torques, a condition based on the conservation of angular momentum replaces condition (47) for the mode \((\ell =1,m=0)\):
The tensor \(\mathsf{I}\) denotes the moment of inertia of inner core or mantle, respectively, \(\omega\) is the mantle or inner-core rotation rate relative to that of the reference frame, and \(\Gamma_{L,\nu}\) are the respective torques associated with Lorentz or viscous forces. The torques are expressed by
and
where \(\mathrm{d}S = r^2\sin\theta \mathrm{d}\theta\mathrm{d}\phi\) and \(r\in[r_i,r_o]\) in the above expressions. Using the following equality
the viscous torques can be expressed by
where the sign in front depends whether \(r=r_o\) or \(r=r_i\).
Free-slip boundary conditions require that the viscous stress vanishes, which in turn implies that the non-diagonal components \(\mathsf{Sr}_{r\phi}\) and \(\mathsf{S}_{r\theta}\) of the rate-of-strain tensor vanish. Translated to the spectral representation this requires
We show the derivation for the somewhat simpler Boussinesq approximation which yields the condition
where the index H denotes the horizonal flow components. In terms of poloidal and toroidal components this implies
and
which can be fulfilled with
and
In spectral representation this then reads
Thermal boundary conditions¶
For Entropy or temperature in the Boussinesq approximation either fixed value of fixed flux conditions are used. The former implies
at \(r_i\) and/or \(r_o\), while the latter means
In spectral representation for example the respective entropy condition read
Appropriate constant values need to be chosen and are instrumental in driving the dynamo when flux conditions are imposed.
Boundary conditions for chemical composition¶
For the chemical composition, either the value or the flux is imposed at the boundaries. The former implies:
at \(r_i\) and/or \(r_o\), while the latter means
In spectral representation, this then reads
Magnetic boundary conditions and inner core¶
Three different magnetic boundary conditions are implemented in MagIC. The most simple one is the conceptual condition at the boundary to an infinite conductor. Surface current in this conductor will prevent the internally produced magnetic field from penetrating so that the field has to vanish at the boundary. The condition are thus the same as for a rigid flow (with boundaries at rest). We only provide the spectral representation here:
Note that the summation convention with respect to radial modes \(n\) is used again. The no-slip condition further requires that the horizontal flow components also have to vanish, provided the two boundaries are at rest. This condition is fulfilled for
More complex are the conditions to an electrical insulator. Here we actually use matching condition to a potential field condition that are formulated like boundary conditions. Since the electrical currents have to vanish in the insulator we have \(\nabla\times\vec{B}\), which means that the magnetic field is a potential field \(\vec{B}^I=-\vec{\nabla} V\) with \(\Delta V=0\). This Laplace equation implies a coupling between radial and horizontal derivatives which is best solved in spectral space. Two potential contributions have to be considered depending whether the field is produced above the interface radius \(r_{BC}\) or below. We distinguish these contributions with upper indices I for internal or below and E for external or above. The total potential then has the form:
with the two spectral potential representations \(V_{\ell m}^I\) and \(V_{\ell m}^E\). This provides well defined radial derivative for both field contributions. For boundary \(r_o\) we have to use the first contribution and match the respective field as well as its radial derivative to the dynamo solution. The toroidal field cannot penetrate the insulator and thus simply vanishes which yields \(h=0\) or
in spectral space. The poloidal field then has to match the potential field which implies
for the horizontal components and
for the radial. In spectral space these condition can be reduce to
Combining both allows to eliminate the potential and finally leads to the spectral condition used in MagIC:
Analogous consideration lead to the respective condition at the interface to an insulating inner core:
If the inner core is modelled as an electrical conductor, a simplified dynamo equation has to be solved in which the fluid flow is replaced by the solid-body rotation of the inner core. The latter is described by a single toroidal flow mode \((\ell=1,m=0)\). The resulting nonlinear terms can be expressed by a simple spherical harmonic expansion, where the superscript \(I\) denotes values in the inner core and \(\omega_I\) its differential rotation rate:
The expensive back and forth transformations between spherical harmonic and grid representations are therefore not required for advancing the inner-core magnetic field in time.
In the inner core the magnetic potentials are again conveniently expanded into Chebyshev polynomials. The Chebyshev variable \(x\) spans the whole diameter of the inner core, so that grid points are dense near the inner-core boundary but sparse in the center. The mapping is given by:
Each point in the inner core is thus represented twice, by grid points \(({r,\theta,\phi})\) and \(({-r,\pi-\theta,\phi+\pi})\). Since both representations must be identical, this imposes a symmetry constraint that can be fulfilled when the radial expansion comprises only polynomials of even order:
An equivalent expression holds for the toroidal potential in the inner core. FFTs can again by employed efficiently for the radial transformation, using the \(M\) extrema of \({\cal C}_{2 M-1}(r)\) with \(x>0\) as grid points.
The sets of spectral magnetic field equations for the inner and the outer core are coupled via continuity equations for the magnetic field and the horizontal electric field. Continuity of the magnetic field is assured by (i) continuity of the toroidal potential, (ii) continuity of the poloidal potential, and (iii) continuity of the radial derivative of the latter. Continuity of the horizontal electric field demands (iv) that the radial derivative of the toroidal potential is continuous, provided that the horizontal flow and the electrical conductivity are continuous at the interface. These four conditions replace the spectral equations (26), (27) on the outer-core side and equations (50), (51) on the inner-core side. Employing free-slip conditions or allowing for electrical conductivity differences between inner and outer core leads to more complicated and even non-linear matching conditions.


-
digital photo frames revierw
Vertex adds Black Box warning label after at least two deaths from ...
Dec 20, 2012. after taking Incivek in combination with two other drugs to treat hepatitis C. The new alert, sometimes called a Black Box warning because it .
http://www.bostonglobe.com/business/2012/12/20/vertex-adds-black-box-warning-label-after-least-two-deaths-from-hepatitis-drug-combination-using-its-incivek-treatment/07QQFrYwdrB2I3JwNqHrxK/story.html
-
university of wisconsin logo paper
Mail Services - Facilities Management - Boston College
May 10, 2012 . BC Mail Services policies for students and their parents. . Students can now retrieve their mailbox combination through the Agora Portal-Other Services- Mailbox Combination Distribution. . Pick up your newspaper daily.
http://www.bc.edu/offices/facilities/facservices/admin/mail.html
-
furniture moving pads for sale
DMM 707 Periodicals
Mailers who prepare Periodicals publications as a combined mailing by merging . White or other light-colored paper must be used for the address label. . First- Class Mail or any Standard Mail, combination envelopes or containers with .
http://pe.usps.com/text/dmm300/707.htm
-
on stage speaker stands
Box Lock-China Box Lock Manufacturers & Suppliers - Made in China
607 Products . Various...As fashion jewelry or gifts box accessories, paper cards' accessories. . Combination lock We Cixi Thumb Locks have specialized in safe . Gardening Metal Wall Mounted Mailbox/ Mail Box/ Letter Box Lock (JHC-2088 .
http://www.made-in-china.com/products-search/hot-china-products/Box_Lock.html
-
campbell river travel lidge
Electronic W-2 and 1099 Filing Guidelines -- Commonwealth of ...
Jan 15, 2013 . If you file Form VA-6 online and mail paper W-2 or 1099 forms, include the Form . will appear and you will need to attempt the upload again with the box checked . . Forms 1099 Combined Federal / State Filing Program .
http://www.tax.virginia.gov/site.cfm?alias=WithholdingTax2
-
what's the population of virginia
Frequently Asked Questions - Sixth College - UC San Diego
I know my PO Box number,... but how do I get my combination? . vacuum the common ares, clean the bathrooms, restock toilet paper, and clean the laundry rooms. . Normal mail is sorted and delivered to your PO Box every weekday by 4p.
http://sixth.ucsd.edu/residential-life/faqs.html
-
human resources stock photo
How to Recycle Plastic and Paper | National Geographic
Together, paper and plastic make up 40 percent of the garbage discarded by the average . cardboard, magazines, phone books, mail, grocery bags and cereal boxes, . These include a combination of paper and other materials, which makes .
http://greenliving.nationalgeographic.com/recycle-plastic-paper-2166.html
-
chemistry labs easy experiment
Wedding Card Boxes, Holders, Cages - Wedding Decorations
Find unique, handmade wedding card boxes and other card holders from independent artisans on Etsy, a global marketplace. Get ideas for unique card holders.
http://www.etsy.com/browse/weddings/decor/card-box
-
make your own coins
How to Recycle Cartons - Juice Box Recycling | Carton Council
To make this work at the facility, it is easier to modify how containers are sorted than paper. In the end, as long as all cartons are sorted and baled together, the .
http://www.recyclecartons.com/carton-recycling-faqs/
-
bukit kiara equestrian club
Postal Antiques - Collector Information | Collectors Weekly
Before email, cable news, telephones, or even the telegraph, the postal service . Jewelry + Watches, Home + Furniture, Pottery + Glass, Paper + Books, Music + .
http://www.collectorsweekly.com/office/postal
-
animated gif grizzly bear
New PRO-100 Photo Printer - B&H Photo Video
Receive an American Express® Reward Card by mail with purchase of select . box (if claiming one of the printer and camera or lens and paper combination .
http://www.bhphotovideo.com/FrameWork/Rebates_Promos/033113_CANON_PRO-100.pdf
-
bad credit granteed loan personal credit
Managing Household Records | USA.gov
Mar 7, 2013 . When was the last time you couldn't find an important paper you . your documents and allow you to transfer them via e-mail and easily make back-up copies. . Safe deposit box keys and/or safe combination; Computer user .
http://www.usa.gov/Topics/Money/Personal-Finance/Managing-Household-Records.shtml
-
richard cartwright john white kent uk
box - definition of box by the Free Online Dictionary, Thesaurus and ...
(often in combination) any of various small cubicles, kiosks, or shelters a telephone box or . 12. a central agency to which mail is addressed and from which it is collected or . cereal box - a paper box in which breakfast cereals are sold .
http://www.thefreedictionary.com/box
-
free journal articles on erik erikson
A Wire Screen-filter Paper Combination for the Measurement o ...
A Wire Screen-filter Paper Combination for the Measurement of Fractions of . An email with instructions to reset your password will be sent to that address. Email: . By checking this box, you'll stay logged in for 14 days or until you logout.
http://journals.lww.com/health-physics/Fulltext/1974/05000/A_Wire_Screen_filter_Paper_Combination_for_the.5.aspx
-
super 8 stafford texas
Staples® Copy Paper, 8 1/2" x 11", Case | Staples®
Shop our great selection of Staples® Copy Paper, Mobility Center - Cell Phones & Accessories, Mobility . May not be valid in combination with other offers.
http://www.staples.com/Staples-Copy-Paper-8-1-2-x-11-Case/product_135848
-
design studio mission statement
DMM 601 Mailability
6.0 Mailing ContainersSpecial Types of Envelopes and Packaging . Post, no mailpiece may measure more than 108 inches in length and girth combined. . Uncoated stock refers to nonglossy paper covers and also to pieces with coated .
http://pe.usps.com/text/dmm300/601.htm
-
wholesale vending machine candy
Leonard Paper Company
Email<EMAIL_ADDRESS>For over 65 years Leonard Paper Company has been the premiere wholesale supplier of janitorial supplies and foodservice .
http://www.leonardpaper.com/
-
united parcel service accident
Instructions for Form 5500-EZ - Internal Revenue Service
Mar 5, 2012 . Or, use the official printed paper Form 5500-EZ . Mail Form 5500-EZ for plan year 2011 to the IRS office in Ogden . combination with one or more one- participant plans . not check this box if you have ever filed for this plan, .
http://www.irs.gov/pub/irs-pdf/i5500ez.pdf
-
just cause and theft
Business Tax Guide - Department of Revenue
I provide a combination of product sales and services. . Mail: On your paper excise tax return, fill in the. No Business Activity box. Sign and date the return .
http://dor.wa.gov/docs/pubs/excisetax/filtaxreturn/bustaxguide.pdf
-
loni h u ler
Smooth Paper | CLASSIC CREST® Papers | Neenah Paper
CLASSIC CREST® Papers are guaranteed to be the papers you can rely on to do it all. Oferring the most weights, sizes, digital skus and envelopes.
http://www.neenahpaper.com/FinePaper/CLASSICCRESTPapers


public class RequestQueue
extends java.lang.Object
Calling add(Request)
will enqueue the given Request for dispatch,
resolving from either cache or network on a worker threadId, and then delivering
a parsed response on the main threadId.
| Modifier and Type | Class and Description |
|---|---|
static interface |
RequestQueue.RequestFilter
A simple predicate or filter interface for Requests, for use by
cancelAll(RequestFilter) . |
| Modifier and Type | Field and Description |
|---|---|
protected Cache |
cache
Cache interface for retrieving and storing responses.
|
protected CacheDispatcher |
cacheDispatcher
The cache dispatcher.
|
protected java.util.concurrent.PriorityBlockingQueue<Request<?>> |
cacheQueue
The cache triage queue.
|
static int |
DEFAULT_NETWORK_THREAD_POOL_SIZE
Number of network request dispatcher threads to start.
|
protected ResponseDelivery |
delivery
Response delivery mechanism.
|
static java.lang.String |
EVENT_CACHE_DISPATCHER_START |
static java.lang.String |
EVENT_CACHE_DISPATCHER_STOP |
static java.lang.String |
EVENT_NETWORK_DISPATCHER_START |
static java.lang.String |
EVENT_NETWORK_DISPATCHER_STOP |
protected Network |
network
Network interface for performing requests.
|
protected NetworkDispatcher.NetworkDispatcherFactory |
networkDispatcherFactory
Network dispatcher factory
|
protected NetworkDispatcher[] |
networkDispatchers
The network dispatchers.
|
protected java.util.concurrent.PriorityBlockingQueue<Request<?>> |
networkQueue
The queue of requests that are actually going out to the network.
|
| Constructor and Description |
|---|
RequestQueue(Cache cache,
Network network)
Creates the worker pool.
|
RequestQueue(Cache cache,
Network network,
int threadPoolSize)
Creates the worker pool.
|
RequestQueue(Cache cache,
Network network,
int threadPoolSize,
ResponseDelivery delivery)
Creates the worker pool.
|
public static final java.lang.String EVENT_CACHE_DISPATCHER_START
public static final java.lang.String EVENT_CACHE_DISPATCHER_STOP
public static final java.lang.String EVENT_NETWORK_DISPATCHER_START
public static final java.lang.String EVENT_NETWORK_DISPATCHER_STOP
protected final java.util.concurrent.PriorityBlockingQueue<Request<?>> cacheQueue
protected final java.util.concurrent.PriorityBlockingQueue<Request<?>> networkQueue
public static final int DEFAULT_NETWORK_THREAD_POOL_SIZE
protected final Cache cache
protected final Network network
protected final ResponseDelivery delivery
protected NetworkDispatcher[] networkDispatchers
protected CacheDispatcher cacheDispatcher
protected NetworkDispatcher.NetworkDispatcherFactory networkDispatcherFactory
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery)
start()
is called.cache
- A Cache to use for persisting responses to disknetwork
- A Network interface for performing HTTP requeststhreadPoolSize
- Number of network dispatcher threads to createdelivery
- A ResponseDelivery interface for posting responses and errorspublic RequestQueue(Cache cache, Network network, int threadPoolSize)
start()
is called.cache
- A Cache to use for persisting responses to disknetwork
- A Network interface for performing HTTP requeststhreadPoolSize
- Number of network dispatcher threads to createpublic RequestQueue withCacheDispatcher(CacheDispatcher cacheDispatcher)
public RequestQueue withNetworkDispatcherFactory(NetworkDispatcher.NetworkDispatcherFactory networkDispatcherFactory)
public void start()
public void stopWhenDone()
public <R extends RequestQueue> R addQueueMarkerListener(RequestListener.MarkerListener markerListener)
public <R extends RequestQueue> R removeQueueMarkerListener(RequestListener.MarkerListener markerListener)
public <R extends RequestQueue> R addMarker(java.lang.String tag, java.lang.Object... args)
RequestQueue
R
- tag
- args
- public void stop()
public int getSequenceNumber()
public void cancelAll(RequestQueue.RequestFilter filter)
filter
- The filtering function to usepublic void cancelAll(java.lang.Object tag)
public <R extends Request<T>,T> R add(R request)
request
- The request to servicepublic final NetworkResponse transformResponse(Request<?> request, NetworkResponse response)
public RetryPolicy.Factory getRetryPolicyFactory()
public RequestQueue setRetryPolicyFactory(RetryPolicy.Factory retryPolicyFactory)
public RedirectPolicy.Factory getRedirectPolicyFactory()
public RequestQueue setRedirectPolicyFactory(RedirectPolicy.Factory redirectPolicyFactory)
public io.apptik.comm.jus.ConnectivityManager.Factory getConnectivityManagerFactory()
public RequestQueue setConnectivityManagerFactory(io.apptik.comm.jus.ConnectivityManager.Factory connectivityManagerFactory)
public NoConnectionPolicy.Factory getNoConnectionPolicyFactory()
public RequestQueue setNoConnectionPolicyFactory(NoConnectionPolicy.Factory noConnectionPolicyFactory)
public RequestQueue addAuthenticatorFactory(Authenticator.Factory factory)
public RequestQueue removeAuthenticatorFactory(Authenticator.Factory factory)
public RequestQueue addConverterFactory(Converter.Factory factory)
public RequestQueue removeConverterFactory(Converter.Factory factory)
public RequestQueue addRequestTransformer(Transformer.RequestTransformer transformer)
public RequestQueue removeRequestTransformer(Transformer.RequestTransformer transformer)
public RequestQueue addResponseTransformer(Transformer.ResponseTransformer transformer)
public RequestQueue removeResponseTransformer(Transformer.ResponseTransformer transformer)
public RequestQueue addListenerFactory(RequestListener.ListenerFactory listenerFactory)
public RequestQueue removeListenerFactory(RequestListener.ListenerFactory listenerFactory)
public Converter<NetworkResponse,?> getResponseConverter(java.lang.reflect.Type type, java.lang.annotation.Annotation[] annotations)
public int getCurrentRequests()
public int getWaitingRequests()


"x" "1" "BARNI,E BAROLO,C QUAGLIOTTO,P VALLDEPARAS,J AND VISCARDI,G, NOVELAZOBENZENE DERIVATIVES CONTAINING A GLUCOPYRANOSIDE MOIETY. PART I: SYNTHESIS,CHARCTERISATION AND MUTAGENIC PROPERTIES, DYES PIGM. 46(1 __ ):29-36,2000"


File LuaText.lua
Functions
| LuaText:deserialize (s, name, o) | Deserialize previously serialized lua data table from s, and optionally: assign to object o. |
| LuaText:new (t) | Constructor for new instance. |
| LuaText:newClass (t) | Constructor for extending class. |
| LuaText:serialize (t) | Serialize lua data object, typically a table. |
Functions
- LuaText:deserialize (s, name, o)
-
Deserialize previously serialized lua data table from s, and optionally: assign to object o.
Parameters:
-
s
: the lua format string to deserialize. -
name
: optional chunk name in case of error. -
o
: optional table to receive deserialized key/values (I can no longer remember the reason for this).
Return value:
- lua table object
-
- LuaText:new (t)
-
Constructor for new instance.
Parameters:
-
t
:
-
- LuaText:newClass (t)
-
Constructor for extending class.
Parameters:
-
t
:
-
- LuaText:serialize (t)
-
Serialize lua data object, typically a table.
Parameters:
-
t
: the lua table or simple variable to be serialized.
Usage:
excludes the dressing needed to use said table upon deserialization, so make sure you precede it with a "return " or "myTbl = " or something.
Return value:
- serialized lua code or nil (never empty string).
-


Struct for runtime entries. More...
#include <StdUseCase.h>
Data Fields | |
| char | device_name_entry [MAX_NAME_LEN] |
| For storing device name if entered during run time. More... | |
| char | filename_entry [MAX_PATH_LEN] |
| For storing filename if entered during runtime. More... | |
| char | filename_processed [MAX_PATH_LEN] |
| For storing the processed filename. More... | |
| int32_t | password_length |
| For storing password length when calculated. More... | |
| char | password_entry [MAX_PASS] |
| For storing password if entered during run time. More... | |
| char | read_file [MAX_PATH_LEN] |
| For storing memory dump filename. More... | |
| char | verify_file_processed [MAX_PATH_LEN] |
| For storing processed filename for verify. More... | |
| char | read_mem [MAX_NAME_LEN] |
| For storing memory dump segment. More... | |
| char | exit_specs_processed [MAX_NAME_LEN] |
| For storing the processed exit_specs. More... | |
| char | read_specs_processed [MAX_NAME_LEN] |
| For storing the processed read_specs. More... | |
| char | bp_specs_processed [MAX_NAME_LEN] |
| For storing the processed breakpoint specs. More... | |
| enum FILE_TYPE | file_type |
| For storing the type of the read file. More... | |
Struct for runtime entries.
Definition at line 233 of file StdUseCase.h.
| char bp_specs_processed[MAX_NAME_LEN] |
For storing the processed breakpoint specs.
Definition at line 255 of file StdUseCase.h.
| char device_name_entry[MAX_NAME_LEN] |
For storing device name if entered during run time.
Definition at line 235 of file StdUseCase.h.
| char exit_specs_processed[MAX_NAME_LEN] |
For storing the processed exit_specs.
Definition at line 251 of file StdUseCase.h.
| enum FILE_TYPE file_type |
For storing the type of the read file.
Definition at line 257 of file StdUseCase.h.
| char filename_entry[MAX_PATH_LEN] |
For storing filename if entered during runtime.
Definition at line 237 of file StdUseCase.h.
| char filename_processed[MAX_PATH_LEN] |
For storing the processed filename.
Definition at line 239 of file StdUseCase.h.
| char password_entry[MAX_PASS] |
For storing password if entered during run time.
Definition at line 243 of file StdUseCase.h.
| int32_t password_length |
For storing password length when calculated.
Definition at line 241 of file StdUseCase.h.
| char read_file[MAX_PATH_LEN] |
For storing memory dump filename.
Definition at line 245 of file StdUseCase.h.
| char read_mem[MAX_NAME_LEN] |
For storing memory dump segment.
Definition at line 249 of file StdUseCase.h.
| char read_specs_processed[MAX_NAME_LEN] |
For storing the processed read_specs.
Definition at line 253 of file StdUseCase.h.
| char verify_file_processed[MAX_PATH_LEN] |
For storing processed filename for verify.
Definition at line 247 of file StdUseCase.h.


--- layout: post title: "An example of interaction-based testing in C#" description: "An example of using Mocks and Stubs for unit testing in C#." date: 2019-02-25 5:42 UTC tags: [Unit Testing] --- {% include JB/setup %}
{{ page.description }}
This article is an instalment in an article series about how to move from interaction-based testing to state-based testing. In this series, you'll be presented with some alternatives to interaction-based testing with Mocks and Stubs. Before we reach the alternatives, however, we need to establish an example of interaction-based testing, so that you have something against which you can compare those alternatives. In this article, I'll present a simple example, in the form of C# code.
The code shown in this article is available on GitHub.
For the example, I'll use a simplified version of the example that runs through my two Clean Coders videos, Church Visitor and Preserved in translation.
The desired functionality is simple: implement a REST API that enables one user to connect to another user. You could imagine some sort of social media platform, or essentially any sort of online service where users might be interested in connecting with, or following, other users.
In essence, you could imagine that a user interface makes an HTTP POST request against our REST API:
POST /connections/42 HTTP/1.1 Content-Type: application/json { "otherUserId": 1337 }
Let's further imagine that we implement the desired functionality with a C# method with this signature:
public IHttpActionResult Post(string userId, string otherUserId)
We'll return to the implementation later, but I want to point out a few things.
First, notice that both userId
and otherUserId
are string
arguments. While the above example encodes both IDs as numbers, essentially, both URLs and JSON are text-based. Following Postel's law, the method should also accept JSON like { "otherUserId": "1337" }
. That's the reason the Post
method takes string
arguments instead of int
arguments.
Second, the return type is IHttpActionResult
. Don't worry if you don't know that interface. It's just a way to model HTTP responses, such as 200 OK
or 400 Bad Request
.
Depending on the input values, and the state of the application, several outcomes are possible:
| Other user | ||||
|---|---|---|---|---|
| Found | Not found | Invalid | ||
| User | Found | Other user | "Other user not found." |
"Invalid ID for other user." |
| Not found | "User not found." |
"User not found." |
"User not found." |
|
| Invalid | "Invalid user ID." |
"Invalid user ID." |
"Invalid user ID." |
"foo"
that doesn't represent a number), then it doesn't matter if the other user exists. Likewise, even if the first user ID is well-formed, it might still be the case that no user with that ID exists in the database.
The assumption here is that the underlying user database uses integers as row IDs.
When both users are found, the other user should be returned in the HTTP response, like this:
HTTP/1.1 200 OK Content-Type: application/json { "id": 1337, "name": "ploeh", "connections": [{ "id": 42, "name": "fnaah" }, { "id": 2112, "name": "ndøh" }] }
The intent is that when the first user (e.g. the one with the 42
ID) successfully connects to user 1337, a user interface can show the full details of the other user, including the other user's connections.
Since there's five distinct outcomes, you ought to write at least five test cases. You could start with the happy-path case, where both user IDs are well-formed and the users exist.
All tests in this article use xUnit.net 2.3.1, Moq 4.8.1, and AutoFixture 4.1.0.
[Theory, UserManagementTestConventions] public void UsersSuccessfullyConnect( [Frozen]Mock<IUserReader> readerTD, [Frozen]Mock<IUserRepository> repoTD, User user, User otherUser, ConnectionsController sut) { readerTD .Setup(r => r.Lookup(user.Id.ToString())) .Returns(Result.Success<User, IUserLookupError>(user)); readerTD .Setup(r => r.Lookup(otherUser.Id.ToString())) .Returns(Result.Success<User, IUserLookupError>(otherUser)); var actual = sut.Post(user.Id.ToString(), otherUser.Id.ToString()); var ok = Assert.IsAssignableFrom<OkNegotiatedContentResult<User>>( actual); Assert.Equal(otherUser, ok.Content); repoTD.Verify(r => r.Update(user)); Assert.Contains(otherUser.Id, user.Connections); }
To be clear, as far as Overspecified Software goes, this isn't a bad test. It only has two Test Doubles, readerTD
and repoTD
. My current habit is to name any Test Double with the TD suffix (for Test Double), instead of explicitly naming them readerStub
and repoMock
. The latter would have been more correct, though, since the Mock<IUserReader>
object is consistently used as a Stub, whereas the Mock<IUserRepository>
object is used only as a Mock. This is as it should be, because it follows the rule that you should use Mocks for Commands, Stubs for Queries.
IUserRepository.Update
is, indeed a Command:
public interface IUserRepository { void Update(User user); }
Since the method returns void
, unless it doesn't do anything at all, the only thing it can do is to somehow change the state of the system. The test verifies that IUserRepository.Update
was invoked with the appropriate input argument.
This is fine.
I'd like to emphasise that this isn't the biggest problem with this test. A Mock like this verifies that a desired interaction took place. If IUserRepository.Update
isn't called in this test case, it would constitute a defect. The software wouldn't have the desired behaviour, so the test ought to fail.
The signature of IUserReader.Lookup
, on the other hand, implies that it's a Query:
public interface IUserReader { IResult<User, IUserLookupError> Lookup(string id); }
In C# and most other languages, you can't be sure that implementations of the Lookup
method have no side effects. If, however, we assume that the code base in question obeys the Command Query Separation principle, then, by elimination, this must be a Query (since it's not a Command, because the return type isn't void
).
For a detailed walkthrough of the IResult<S, E>
interface, see my Preserved in translation video. It's just an Either with different terminology, though. Right
is equivalent to SuccessResult
, and Left
corresponds to ErrorResult
.
The test configures the IUserReader
Stub twice. It's necessary to give the Stub some behaviour, but unfortunately you can't just use Moq's It.IsAny<string>()
for configuration, because in order to model the test case, the reader should return two different objects for two different inputs.
This starts to look like Overspecified Software.
Ideally, a Stub should just be present to 'make happy noises' in case the SUT decides to interact with the dependency, but with these two Setup
calls, the interaction is overspecified. The test is tightly coupled to how the SUT is implemented. If you change the interaction implemented in the Post
method, you could break the test.
In any case, what the test does specify is that when you query the UserReader
, it returns a Success
object for both user lookups, a 200 OK
result is returned, and the Update
method was called with user
.
If the first user ID is invalid (i.e. not an integer) then the return value should represent 400 Bad Request
and the message body should indicate as much. This test verifies that this is the case:
[Theory, UserManagementTestConventions] public void UsersFailToConnectWhenUserIdIsInvalid( [Frozen]Mock<IUserReader> readerTD, [Frozen]Mock<IUserRepository> repoTD, string userId, User otherUser, ConnectionsController sut) { Assert.False(int.TryParse(userId, out var _)); readerTD .Setup(r => r.Lookup(userId)) .Returns(Result.Error<User, IUserLookupError>( UserLookupError.InvalidId)); var actual = sut.Post(userId, otherUser.Id.ToString()); var err = Assert.IsAssignableFrom<BadRequestErrorMessageResult>(actual); Assert.Equal("Invalid user ID.", err.Message); repoTD.Verify(r => r.Update(It.IsAny<User>()), Times.Never()); }
This test starts with a Guard Assertion that userId
isn't an integer. This is mostly an artefact of using AutoFixture. Had you used specific example values, then this wouldn't have been necessary. On the other hand, had you written the test case as a property-based test, it would have been even more important to explicitly encode such a constraint.
Perhaps a better design would have been to use a domain-specific method to check for the validity of the ID, but there's always room for improvement.
This test is more brittle than it looks. It only defines what should happen when IUserReader.Lookup
is called with the invalid userId
. What happens if IUserReader.Lookup
is called with the Id
associated with otherUser
?
This currently doesn't matter, so the test passes.
The test relies, however, on an implementation detail. This test implicitly assumes that the implementation short-circuits as soon as it discovers that userId
is invalid. What if, however, you'd made some performance measurements, and you'd discovered that in most cases, the software would run faster if you Lookup
both users in parallel?
Such an innocuous performance optimisation could break the test, because the behaviour of readerTD
is unspecified for all other cases than for userId
.
What happens if the other user ID is invalid? This unit test exercises that test case:
[Theory, UserManagementTestConventions] public void UsersFailToConnectWhenOtherUserIdIsInvalid( [Frozen]Mock<IUserReader> readerTD, [Frozen]Mock<IUserRepository> repoTD, User user, string otherUserId, ConnectionsController sut) { Assert.False(int.TryParse(otherUserId, out var _)); readerTD .Setup(r => r.Lookup(user.Id.ToString())) .Returns(Result.Success<User, IUserLookupError>(user)); readerTD .Setup(r => r.Lookup(otherUserId)) .Returns(Result.Error<User, IUserLookupError>( UserLookupError.InvalidId)); var actual = sut.Post(user.Id.ToString(), otherUserId); var err = Assert.IsAssignableFrom<BadRequestErrorMessageResult>(actual); Assert.Equal("Invalid ID for other user.", err.Message); repoTD.Verify(r => r.Update(It.IsAny<User>()), Times.Never()); }
Notice how the test configures readerTD
twice: once for the Id
associated with user
, and once for otherUserId
. Why does this test look different from the previous test?
Why is the first Setup
required? Couldn't the arrange phase of the test just look like the following?
Assert.False(int.TryParse(otherUserId, out var _)); readerTD .Setup(r => r.Lookup(otherUserId)) .Returns(Result.Error<User, IUserLookupError>( UserLookupError.InvalidId));
If you wrote the test like that, it would resemble the previous test (UsersFailToConnectWhenUserIdIsInvalid
). The problem, though, is that if you remove the Setup
for the valid user, the test fails.
This is another example of how the use of interaction-based testing makes the tests brittle. The tests are tightly coupled to the implementation.
I don't want to belabour the point, so here's the two remaining tests:
[Theory, UserManagementTestConventions] public void UsersDoNotConnectWhenUserDoesNotExist( [Frozen]Mock<IUserReader> readerTD, [Frozen]Mock<IUserRepository> repoTD, string userId, User otherUser, ConnectionsController sut) { readerTD .Setup(r => r.Lookup(userId)) .Returns(Result.Error<User, IUserLookupError>( UserLookupError.NotFound)); var actual = sut.Post(userId, otherUser.Id.ToString()); var err = Assert.IsAssignableFrom<BadRequestErrorMessageResult>(actual); Assert.Equal("User not found.", err.Message); repoTD.Verify(r => r.Update(It.IsAny<User>()), Times.Never()); } [Theory, UserManagementTestConventions] public void UsersDoNotConnectWhenOtherUserDoesNotExist( [Frozen]Mock<IUserReader> readerTD, [Frozen]Mock<IUserRepository> repoTD, User user, int otherUserId, ConnectionsController sut) { readerTD .Setup(r => r.Lookup(user.Id.ToString())) .Returns(Result.Success<User, IUserLookupError>(user)); readerTD .Setup(r => r.Lookup(otherUserId.ToString())) .Returns(Result.Error<User, IUserLookupError>( UserLookupError.NotFound)); var actual = sut.Post(user.Id.ToString(), otherUserId.ToString()); var err = Assert.IsAssignableFrom<BadRequestErrorMessageResult>(actual); Assert.Equal("Other user not found.", err.Message); repoTD.Verify(r => r.Update(It.IsAny<User>()), Times.Never()); }
Again, notice the asymmetry of these two tests. The top one passes with only one Setup
of readerTD
, whereas the bottom test requires two in order to pass.
You can add a second Setup
to the top test to make the two tests equivalent, but people often forget to take such precautions. The result is Fragile Tests.
In the spirit of test-driven development, I've shown you the tests before the implementation.
public class ConnectionsController : ApiController { public ConnectionsController( IUserReader userReader, IUserRepository userRepository) { UserReader = userReader; UserRepository = userRepository; } public IUserReader UserReader { get; } public IUserRepository UserRepository { get; } public IHttpActionResult Post(string userId, string otherUserId) { var userRes = UserReader.Lookup(userId).SelectError( error => error.Accept(UserLookupError.Switch( onInvalidId: "Invalid user ID.", onNotFound: "User not found."))); var otherUserRes = UserReader.Lookup(otherUserId).SelectError( error => error.Accept(UserLookupError.Switch( onInvalidId: "Invalid ID for other user.", onNotFound: "Other user not found."))); var connect = from user in userRes from otherUser in otherUserRes select Connect(user, otherUser); return connect.SelectBoth(Ok, BadRequest).Bifold(); } private User Connect(User user, User otherUser) { user.Connect(otherUser); UserRepository.Update(user); return otherUser; } }
This is a simplified version of the code shown towards the end of my Preserved in translation video, so I'll refer you there for a detailed explanation.
The premise of Refactoring is that in order to be able to refactor, the "precondition is [...] solid tests". In reality, many development organisations have the opposite experience. When programmers attempt to make changes to how their code is organised, tests break. In xUnit Test Patterns this problem is called Fragile Tests, and the cause is often Overspecified Software. This means that tests are tightly coupled to implementation details of the System Under Test (SUT).
It's easy to inadvertently fall into this trap when you use Mocks and Stubs, even when you follow the rule of using Mocks for Commands and Stubs for Queries. In my experience, it's often the explicit configuration of Stubs that tend to make tests brittle. A Command represents an intentional side effect, and you want to verify that such a side effect takes place. A Query, on the other hand, has no side effect, so a black-box test shouldn't be concerned with any interactions involving Queries.
Yet, using an 'isolation framework' such as Moq, FakeItEasy, NSubstitute, and so on, will pull you towards overspecifying the interactions the SUT has with its Query dependencies.
How can we improve? One strategy is to move towards a more functional design, which is intrinsically testable. In the next article, you'll see how to rewrite both tests and implementation in Haskell.
Comments
Hi Mark,
I think I came to the same conclusion (maybe not the same solution), meaning you can't write solid tests when mocking all the dependencies interaction : all these dependencies interaction are implementation details (even the database system you chose). For writing solid tests I chose to write my tests like this : start all the services I can in test environment (database, queue ...), mock only things I have no choice (external PSP or Google Captcha), issue command (using MediatR) and check the result with a query. You can find some of my work here . The work is not done on all the tests but this is the way I want to go. Let me know what you think about it.
I could have launched the tests at the Controller level but I chose Command and Query handler.
Can't wait to see your solution
Rémi, thank you for writing. Hosting services as part of a test run can be a valuable addition to an overall testing or release pipeline. It's reminiscent of the approach taken in GOOS. I've also touched on this option in my Pluralsight course Outside-In Test-Driven Development. This is, however, a set of tests I would identify as belonging towards the top of a Test Pyramid. In my experience, such tests tend to run (an order of magnitude) slower than unit tests.
That doesn't preclude their use. Depending on circumstances, I still prefer having tests like that. I think that I've written a few applications where tests like that constituted the main body of unit tests.
I do, however, also find this style of testing too limiting in many situation. I tend to prefer 'real' unit tests, since they tend to be easier to write, and they execute faster.
Apart from performance and maintainability concerns, one problem that I often see with integration tests is that it's practically impossible to cover all edge cases. This tends to lead to either bug-ridden software, or unmaintainable test suites.
Still, I think that, ultimately, having enough experience with different styles of testing enables one to make an informed choice. That's my purpose with these articles: to point out that alternatives exist.


Minesweeper in Javascript
Make Flags
Validate
Cheat
Save Game
size:
8x8
12x12
16x16
mines:
10
20
40
New Game
Your saved games:


{% import "bootstrap/wtf.html" as wtf %} {% extends 'base.html' %} {% block title %}Users{% endblock %} {% block content %} Reset Password Form You will be logged out after you submit the form. Remember new password! {{ form.hidden_tag() }} {{ wtf.form_field(form.password) }} {{ wtf.form_field(form.pwconfirm) }} Submit {% endblock %}


Grzegorz Rożniecki (@xaerxess)
Java / Perl / JavaScript developer
Software reader / writer
There is more than one way to do it
Tim Toady
"The very fact that it's possible to write messy programs in Perl is also what makes it possible to write programs that are cleaner in Perl than they could ever be in a language that attempts to enforce cleanliness. The potential for greater good goes right along with the potential for greater evil."
There should be one
- and preferably only one -
obvious way to do it
"There are only two kinds of languages: the ones people complain about and the ones nobody uses"
"There are only 10
kinds of languages: the ones people complain about and the ones nobody uses"
for
loop
for (my $i = 0; $i <= 3; ++$i) {
print $i;
}
for
loop
for my $i (0..3) {
print $i;
}
for
loop
for (0..3) {
print $_;
}
for
loop
for (0..3) {
print;
}
for
loop
print for (0..3);
vs
| Edward Sapir | Benjamin Whorf |
| linguistics theory | Hopi - time & space |
| Perl | Java |
|---|---|
| created in 1987 | created in 1991 |
| Perl 5 released in 1994 | JDK 1.0 released in 1995 |
| "get things done" | "write once, run anywhere" |
| OO support in Perl 5 | OO support from the beginning |
There’s more than one way to do it
but sometimes consistency is not a bad thing either
package Foo;
sub new {
my $class = shift;
my $self = { }; # or [ ] or any arbitrary scalar value
return bless $self, $class;
}
1;
People like rules and guidelines. They like to agree with them, or to argue with them.
Inconsistency
TIMTOWTDI?
finally...
but...
final class Person {
private final String name;
private final Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
vs
case class Person(name: String, age: Int)
Java 7+: Objects
Java < 7 - Guava: Objects
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Person))
return false;
final Person other = (Person) obj;
return Objects.equals(this.name, other.name)
&& Objects.equals(this.age, other.age);
}
Better?
Guava 18+: MoreObjects.toStringHelper
Guava < 18: Objects.toStringHelper
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("age", age)
.toString();
}
Also better?
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
Lombok: @Value
@Value public class Person {
String name;
Integer age;
}
Lombok: black magic
Google AutoValue: @AutoValue
@AutoValue
abstract class Person {
public static Person create(String name, Integer age) {
return new AutoValue_Person(name, age);
}
public abstract String getName();
public abstract int getAge();
}
Good trade-off?
You should prefer List<Foo>
over Foo[]
whenever possible.
ArrayStoreException
can result at runtime.List<Class<? extends E>>
or List<Optional<T>>
). With an array you get compilation warnings and confusing runtime exceptions.equals
, hashCode
and toString
methods do what users expect; those methods on an array do anything but what you expect -- a common source of bugs.So, why would you ever use object arrays?
Ex. consistent IDE preferences
The "final
" battle
"Closures feel to me like one of these design Black Holes. (...) So, should we just give in to the force of gravity and go the rest of the way? The debate's afoot. It's going to be an entertaining year."
"Java has closures, it's just called 'anonymous inner classes' (...). [They] are the better and more 'java-way' to do closures. Adding an additional syntax for closures will only make the language more complex without solving even one real problem."
...and in 2014 (finally) instead of this:
List<Album> favs = new ArrayList<>();
for (Album a : albums) {
boolean hasFavorite = false;
for (Track t : a.tracks) {
if (t.rating >= 4) {
hasFavorite = true;
break;
}
}
if (hasFavorite) {
favs.add(a);
}
}
Collections.sort(favs, new Comparator<Album>() {
@Override public int compare(Album a1, Album a2) {
return a1.name.compareTo(a2.name);
}});
...you can do this:
List<Album> sortedFavs =
albums.stream()
.filter(a -> a.tracks.anyMatch(t -> (t.rating >= 4)))
.sorted(Comparator.comparing(a -> a.name))
.collect(Collectors.toList());
There is more than one way to do it, finally!
Please send me a feedback:
@xaerxess or xaerxess at
gmail dot
com


Calculator by Dakaro
A calculator created in Javascript and interacted with using HTML.
Addition
Subtraction
Multiplication
Division
Square Root
x^Y


Gecode license and authors
GECODE LICENSE AGREEMENT
This software and its documentation are copyrighted by the individual authors as listed in each file. All files, unless explicitly disclaimed in individual files, may be used according to the terms of the MIT license, which reads as follows:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Gecode authors
The following authors have contributed to the Gecode library and its documentation (in alphabetical order of firstname):- Christian Schulte<EMAIL_ADDRESS>- Gabor Szokoli<EMAIL_ADDRESS>- Guido Tack<EMAIL_ADDRESS>- Mikael Lagerkvist<EMAIL_ADDRESS>- Niko Paltzer<EMAIL_ADDRESS>- Patrick Pekczynski<EMAIL_ADDRESS>The above authors are grateful to the following people who have provided bugfixes:
- Alexander Samoilov
- Grégoire Dooms
- Olof Sivertsson
- Stefano Gualandi
We are also grateful for our users reporting bugs and suggesting improvements.


--- layout: compress --- {% include head.html %}
21 Glasshouse Street is a Grade II listed office building on Regent Street owned by the Crown Estate. I was a lead member working on the transformation to CAT A Office space which has now been let by Apple. The refurbishment has created 26,000 ft2 of exemplary office space with a BREEAM Excellent.
We inserted a new lift core which has enabled the relocation of the office entrance from Regent Street to Glasshouse Street unifying the existing retail street frontage that is dominant on Regent Street. I worked closely with Westminster City Council to create a unique bronze canopy that now frames the entrance. I also created the concept and brief for a carved solid stone desk that now sits in the reception and worked directly with stone sculptor Simon Hitchens from inception to completion. On the top floor we discovered an empty double height mansard which has been transformed into 4,000 ft2 of prime office space with full height glass sliding doors that lead out to terrace, meadow and dramatic views across London.
{% include overlay.html %} {% include scripts.html %}


SIAEC-Rolls Royce Application
Logout
Current WRIs
Add Work Request Input
Current WIs
Issue Work Instructions
{% block content %}{% endblock %}
{% include 'block_members.html' %}


nips nips2006 nips2006-110 nips2006-110-reference knowledge-graph by maker-knowledge-mining
Source: pdf
Author: Florian Steinke, Volker Blanz, Bernhard Schölkopf
Abstract: Establishing correspondence between distinct objects is an important and nontrivial task: correctness of the correspondence hinges on properties which are difﬁcult to capture in an a priori criterion. While previous work has used a priori criteria which in some cases led to very good results, the present paper explores whether it is possible to learn a combination of features that, for a given training set of aligned human heads, characterizes the notion of correct correspondence. By optimizing this criterion, we are then able to compute correspondence and morphs for novel heads. 1
[1] V. Blanz and T. Vetter. A morphable model for the synthesis of 3d faces. In SIGGRAPH’99 Conference Proceedings, pages 187–194, Los Angeles, 1999. ACM Press.
[2] B.D. Lucas and T. Kanade. An iterative image registration technique with an application to stereo vision. In IJCAI81, pages 674–679, 1981.
[3] B. K. P. Horn and B. G. Schunck. Determining optical ﬂow. Artif. Intell., 17(1-3):185–203, 1981.
[4] D. Beymer and T. Poggio. Image representations for visual learning. Science, 272:1905–1909, 1996.
[5] T. Vetter and T. Poggio. Linear object classes and image synthesis from a single example image. IEEE Trans. on Pattern Analysis and Machine Intelligence, 19(7):733–742, 1997.
[6] B. Allen, B. Curless, and Z. Popovic. The space of human body shapes: reconstruction and parameterization from range scans. In Proc. SIGGRAPH, pages 612–619, 2002.
[7] D. Rueckert and A. F. Frangi. Automatic construction of 3-d statistical deformation models of the brain using nonrigid registration. IEEE Trans. on Medical Imaging, 22(8):1014–1025, 2003.
[8] D. Anguelov, P. Srinivasan, H.-C. Pang, D. Koller, S. Thrun, and J. Davis. The correlated correspondence algorithm for unsupervised registration of nonrigid surfaces. In Neural Information Processing Systems 17, pages 33–40. MIT Press, 2005.
[9] M. Alexa. Recent advances in mesh morphing. Computer Graphics Forum, 21(2):173–196, 2002.
[10] B. Sch¨ lkopf, F. Steinke, and V. Blanz. Object correspondence as a machine learning problem. In o Proceedings of the 22nd International Conference on Machine Learning (ICML 05), July 2005.
[11] J.-P. Thirion and A Gourdon. Computing the differential characteristics of isointensity surfaces. Journal of Computer Vision and Image Understanding, 61(2):190–202, March 1995.
[12] N. Gelfand, N. J. Mitra, L. J. Guibas, and H. Pottmann. Robust global registration. In Proc. Eurographics Symposium on Geometry Processing, pages 197–206, 2005.
[13] K.I. Diamantaras and S.Y. Kung. Principal component neural networks: theory and applications. John Wiley & Sons, Inc., 1996.
[14] D. C. Liu and J. Nocedal. On the limited memory bfgs method for large scale optimization. Math. Program., 45(3):503–528, 1989.


BINARY KONG
We are
OFFLINE
Please go back to the cached page or try to revisit when internet comes back.


ABOUT ME
SKILLS
PROJECTS
CONTACT
Projects
Personal Projects
Rubik's Cube Solver
(C++)
Fantasy Football Schedule Analyzer
(Python)
dmolz.github.io
(HTML/CSS)


Patrick Vieira makes decision on future amid Arsenal link following Unai Emery's sacking
Unai Emery has been sacked as Arsenal manager with Freddie Ljungberg named as interim head coach. Patrick Vieira and Nuno Espirito Santo have been linked with the job
by Alex SmithPatrick Vieira has ruled out leaving Nice in the foreseeable future - despite being linked with the Arsenal job.
Gunners legend Vieira is currently in his second season as Nice manager after finishing seventh in his debut year, having previously taken charge of New York City in the MLS.
Nice are currently 15th in Ligue 1 after a disappointing start to the campaign - which saw the south coast of France outfit lose all four of their fixtures in October.
Vieira has been linked with Inter Miami, Lyon and Brazilian club Botafogo in recent times, and he would be an incredibly popular candidate to replace the ditched Unai Emery in the Gunners dugout.
But Vieira said: "At the beginning of the season it was Lyon, today there is Inter Miami and tomorrow it will be Botafogo.
"I don't know what to say to you. I do my job every day as best as I can.
"After that, you have to ask certain people what happens, but I do not feel in any danger. But, in football, we know that things move very fast."
Vieira's former Invincibles teammate Freddie Ljungberg has been named as Arsenal's interim head coach as the club begin the search for a new gaffer.
And Ray Parlour reckons ex-captain Vieira would be his choice to take over.
Parlour told talkSPORT before Emery was sacked: “They’ll have to go with Freddie Ljungberg for the moment, but I’m sure behind the scenes they’ll be sounding a few people out.
“The Wolves manager [Nuno Espirito Santo] has been mentioned as has Pochettino, but I’ve always said Patrick Viera.
 How did Pep Guardiola start his career, how did Jurgen Klopp? You need that lucky break sometimes.
“I know for a fact it would be like Frank Lampard at Chelsea – players respect Patrick, he’s been at the club and fans would give him a chance.