text:
---
layout: pages
route: /books/habits-by-william-james
title: Habit
tags: [books]
systemTags: never-archive
category: books
---

## BY WILLIAM JAMES
### The Principles of Psychology (1890)
#### Chapter IV

WHEN we look at living creatures
from an outward point of view,
one of the first things that strike
us is that they are bundles of habits. In
wild animals, the usual round of daily behavior seems a necessity implanted at birth
in animals domesticated, and especially in
man, it seems, to a great extent, to be the
result of education. The habits to which
there is an innate tendency are called instincts;
some of those due to education would
by most persons be called acts of reason. It
thus appears that habit covers a very large
part of life, and that one engaged in studying
the objective manifestations of mind is
bound at the very outset to define clearly
just what its limits are.

The moment one tries to define what habit
is, one is led to the fundamental properties
of matter. The laws of Nature are nothing
but the immutable habits which the different
elementary sorts of matter follow in their
actions and reactions upon each other. In
the organic world, however, the habits are
more variable than this. Even instincts
vary from one individual to another of a
kind; and are modified in the same individual,
as we shall later see, to suit the exigencies of
the case. The habits of an elementary particle of matter cannot change (on the principles of the atomistic philosophy), because
the particle is itself an unchangeable thing;
but those of a compound mass of matter can
change, because they are in the last instance
due to the structure of the compound, and
either outward forces or inward tensions can,

from one hour to another, turn that structure
into something different from what it was.
That is, they can do so if the body be plastic
enough to maintain its integrity, and be not
disrupted when its structure yields. The
change of structure here spoken of need not
involve the outward shape; it may be invisible and molecular, as when a bar of iron
becomes magnetic or crystalline through the
action of certain outward causes, or Indiarubber becomes friable, or plaster 'sets.'
All these changes are rather slow; the material in question opposes a certain resistance to
the modifying cause, which it takes time to
overcome, but the gradual yielding whereof
often saves the material from being disintegrated altogether. When the structure has
yielded, the same inertia becomes a condition
of its comparative permanence in the new
form, and of the new habits the body then
manifests. Plasticity, then, in the wide sense of the word, means the possession of a
structure weak enough to yield to an influence, but strong enough not to yield all at
once. Each relatively stable phase of equilibrium in such a structure is marked by what
we may call a new set of habits. Organic
matter, especially nervous tissue, seems endowed with a very extraordinary degree of
plasticity of this sort; so that we may without hesitation lay down as our first proposition the following, that the phenomena of
habit in living beings are due to the plasticity 1
of the organic materials of which their bodies
are composed.

But the philosophy of habit is thus, in the
first instance, a chapter in physics rather
than in physiology or psychology. That it
is at bottom a physical principle is admitted
by all good recent writers on the subject.

1 In the sense above explained, which applies to inner structure
as well as to outer form.

They call attention to analogues of acquired
habits exhibited by dead matter. Thus
M. Leon Dumont, whose essay on habit is
perhaps the most philosophical account yet
published, writes:

"Every one knows how a garment, after
having been worn a certain time, clings to
the shape of the body better than when it
was new; there has been a change in the
tissue, and this change is a new habit of cohesion. A lock works better after being
used some time; at the outset more force was
required to overcome certain roughnesses in
the mechanism. The overcoming of their
resistance is a phenomenon of habituation.
It costs less trouble to fold a paper when it
has been folded already. This saving of
trouble is due to the essential nature of habit,
which brings it about that, to reproduce the
effect, a less amount of the outward cause is required. The sounds of a violin improve by
use in the hands of an able artist, because the
fibres of the wood at last contract habits of
vibration conformed to harmonic relations.
This is what gives such inestimable value to
instruments that have belonged to great
masters. Water, in flowing, hollows out for
itself a channel, which grows broader and
deeper; and, after having ceased to flow, it
resumes, when it flows again, the path
traced by itself before. Just so, the impressions of outer objects fashion for themselves in the nervous system more and more
appropriate paths, and these vital phenomena
recur under similar excitements from without, when they have been interrupted a certain time." 1

Not in the nervous system alone.
A sprained ankle, a dislocated arm, are in
danger of being sprained or dislocated again;
joints that have once been attacked by
rheumatism or gout, mucous membranes
that have been the seat of catarrh, are with
each fresh recurrence more prone to a relapse,
until often the morbid state chronically substitutes itself for the sound one. And if we
ascend to the nervous system, we find how
many so-called functional diseases seem to
keep themselves going simply because they
happen to have once begun; and how the
forcible cutting short by medicine of a few
attacks is often sufficient to enable the physiological forces to get possession of the field
again, and to bring the organs back to functions of health. Epilepsies, neuralgias, convulsive affections of various sorts, insomnias,
are so many cases in point. And, to take what are more obviously habits, the success
with which a * weaning' treatment can often
be applied to the victims of unhealthy indulgence of passion, or of mere complaining or
irascible disposition, shows us how much the
morbid manifestations themselves were due
to the mere inertia of the nervous organs,
when once launched on a false career.

Can we now form a notion of what the
inward physical changes may be like, in
organs whose habits have thus struck into
new paths? In other words, can we say just
what mechanical facts the expression 'change
of habit ' covers when it is applied to a nervous system? Certainly we cannot in anything like a minute or definite way. But our
usual scientific custom of interpreting hidden
molecular events after the analogy of visible
massive ones enables us to frame easily an
abstract and general scheme of processes

HABIT 11

which the physical changes in question may
be like. And when once the possibility of
some kind of mechanical interpretation is
established, Mechanical Science, in her present mood, will not hesitate to set her brand
of ownership upon the matter, feeling sure
that it is only a question of time when the
exact mechanical explanation of the case
shall be found out.

If habits are due to the plasticity of materials to outward agents, we can immediately
see to what outward influences, if to any, the
brain-matter is plastic. Not to mechanical
pressures, not to thermal changes, not to any
of the forces to which all the other organs of
our body are exposed; for nature has carefully shut up our brain and spinal cord in
bony boxes, where no influences of this sort
can get at them. She has floated them in
fluid so that only the severest shocks can
give them a concussion, and blanketed and wrapped them about in an altogether exceptional way. The only impressions that can
be made upon them are through the blood,
on the one hand, and through the sensory
nerve-roots, on the other; and it is to the
infinitely attenuated currents that pour in
through these latter channels that the hemispherical cortex shows itself to be so peculiarly susceptible. The currents, once in,
must find a way out. In getting out they
leave their traces in the paths which they
take. The only thing they can do, in short,
is to deepen old paths or to make new ones;
and the whole plasticity of the brain sums
itself up in two words when we call it an
organ in which currents pouring in from the
sense-organs make with extreme facility
paths which do not easily disappear. For,
of course, a simple habit, like every other
nervous event the habit of snuffling, for
example, or of putting one's hands into one's pockets, or of biting one's nails is, mechanically, nothing but a reflex discharge; and
its anatomical substratum must be a path
in the system. The most complex habits,
as we shall presently see more fully, are, from
the same point of view, nothing but concatenated discharges in the nerve-centres, due
to the presence there of systems of reflex
paths, so organized as to wake each other up
successively the impression produced by
one muscular contraction serving as a stimulus to provoke the next, until a final impression inhibits the process and closes the chain.
The only difficult mechanical problem is to
explain the formation de novo of a simple
reflex or path in a pre-existing nervous
system. Here, as in so many other cases,
it is only the premier pas qui coute.  A path once traversed by
a nerve-current might be expected to follow
the law of most of the paths we know, and
to be scooped out and made more permeable
than before; ' and this ought to be repeated
with each new passage of the current.
Whatever obstructions may have kept it at
first from being a path should then, little by
little, and more and more, be swept out of
the way, until at last it might become a
natural drainage-channel. This is what happens where either solids or liquids pass over
a path; there seems no reason why it should
not happen where the thing that passes is a
mere wave of rearrangement in matter that
does not displace itself, but merely changes
chemically or turns itself round in place,
or vibrates across the line. The most
plausible views of the nerve-current make it

iSome paths, to be sure, are banked up by bodies moving
through them under too great pressure, and made impervious.
These special cases we disregard.

out to be the passage of some such wave of
rearrangement as this. If only a part of the
matter of the path were to 'rearrange' itself,
the neighboring parts remaining inert, it is
easy to see how their inertness might oppose
a friction which it would take many waves of
rearrangement to break down and overcome.
If we call the path itself the 'organ, ' and the
wave of rearrangement the 'function, ' then
it is obviously a case for repeating the celebrated French formula of 'Lajondion fait
Tor gam J

So nothing is easier than to imagine how,
when a current once has traversed a path,
it should traverse it more readily still a
second time. But what made it ever tra-

1 We cannot say the will, for, though many, perhaps most,
human habits were once voluntary actions, no action, as we
shall see in a later chapter, can be primarily such. While an
habitual action may once have been voluntary, the voluntary
action must before that, at least once, have been impulsive or
reflex. It is this very first occurrence of all that we consider in
the text.

verse it the first time? 1 In answering this
question we can only fall back on our general
conception of a nervous system as a mass of
matter whose parts, constantly kept in states
of different tension, are as constantly tending
to equalize their states. The equalization
between any two points occurs through whatever path may at the moment be most pervious. But, as a given point of the system
may belong, actually or potentially, to many
different paths, and, as the play of nutrition
is subject to accidental changes, blocks may
from time to time occur, and make currents
shoot through unwonted lines. Such an
unwonted line would be a new-created path,
which if traversed repeatedly, would become
the beginning of a new reflex arc. All this
is vague to the last degree, and amounts to
little more than saying that a new path may
be formed by the sort of chances that in
nervous material are likely to occur. But,

HABIT 17

vague as it is, it is really the last word of our
wisdom in the matter. 1

It must be noticed that the growth of
structural modification in living matter may
be more rapid than in any lifeless mass
because the incessant nutritive renovation of
which the living matter is the seat tends often
to corroborate and fix the impressed modification, rather than to counteract it by renewing
the original constitution of the tissue that
has been impressed. Thus, we notice after
exercising our muscles or our brain in a new
way, that we can do so no longer at that time;

1 Those who desire a more definite formulation may consult
J. FiskeV Cosmic Philosophy,' vol. II. pp.142 146, and Spencer's
' Principles of Biology,' sections 302 and 303, and the part entitled
'Physical Synthesis' of his 'Principles of Psychology.' Mr.
Spencer there tries, not only to show how new actions may arise
in nervous systems and form new reflex arcs therein, but even
how nervous tissue may actually be born by the passage of new
waves of isometric transformation through an originally indifferent mass. I cannot help thinking that Mr. Spencer's data,
under a great show of precision, conceal vagueness and improbability, and even self-contradiction.

18 HABIT

but after a day or two of rest, when we resume
the discipline, our increase in skill not seldom surprises us. I have often noticed this
in learning a tune; and it has led a German
author to say that we learn to swim during
the winter and to skate during the summer.
Dr. Carpenter writes: 1

"It is a matter of universal experience
that every kind of training for special aptitudes is both far more effective, and leaves
a more permanent impress, when exerted on
the growing organism than when brought to
bear on the adult. The effect of such training is shown in the tendency of the organ to
'grow to' the mode in which it is habitually
exercised; as is evidenced by the increased
size and power of particular sets of muscles,
and the extraordinary flexibility of joints,
which are acquired by such as have been

'Mental Physiology' (1874), pp. 339-345.

HABIT 19

early exercised in gymnastic performances.
. . . There is no part of the organism of
man in which the reconstructive activity is so
great, during the whole period of life, as it
is in the ganglionic substance of the brain.
This is indicated by the enormous supply of
blood which it receives. ... It is, moreover, a fact of great significance that the
nerve-substance is specially distinguished by
its reparative power. For while injuries of
other tissues (such as the muscular) which
are distinguished by the speciality of their
structure and endowments, are repaired by
substance of a lower or less specialized type
those of nerve-substance are repaired by a
complete reproduction of the normal tissue;
as is evidenced in the sensibility of the newly
forming skin which is closing over an open
wound, or in the recovery of the sensibility
of a piece of 'transplanted' skin, which has
for a time been rendered insensible by the

20 HABIT

complete interruption of the continuity of
its nerves. The most remarkable example
of this reproduction, however, is afforded by
the results of M. Brown-Se'quard's l experiments upon the gradual restoration of the
functional activity of the spinal cord after
its complete division; which takes place in
a way that indicates rather a reproduction
of the whole, or the lower part of the cord
and of the nerves proceeding from it, than a
mere reunion of divided surfaces. This
reproduction is but a special manifestation
of the reconstructive change which is always
taking place in the nervous system; it being
not less obvious to the eye of reason that the
'waste' occasioned by its functional activity
must be constantly repaired by the production of new tissue, than it is to the eye of
sense that such reparation supplies an

1 [See, later, Masius in Van Benedens' and Van Bambckc's
'Archives de Biologic' vol I (Li6ge 1880) W. J.J

HABIT 21

actual loss of substance by disease or
injury.

"Now, in this constant and active reconstruction of the nervous system, we recognize
a most marked conformity to the general
plan manifested in the nutrition of the organism as a whole. For, in the first place, it is
obvious that there is a tendency to the production of a determinate type of structure;
which type is often not merely that of the
species, but some special modification of it
which characterized one or both of the
progenitors. But this type is peculiarly
liable to modification during the early period
of life; in which the functional activity of the
nervous system (and particularly of the
brain) is extraordinarily great, and the reconstructive process proportionally active. And
this modifiability expresses itself in the
formation of the mechanism by which those
secondarily automatic modes of movement

22 HABIT

come to be established, which, in man, take
the place of those that are congenital in most
of the animals beneath him; and those modes
of sense-perception come to be acquired
which are elsewhere clearly instinctive. For
there can be no reasonable doubt that, in
both cases, a nervous mechanism is developed
in the course of this self-education, corresponding with that which the lower animals
inherit from their parents. The plan of that
rebuilding process, which is necessary to maintain the integrity of the organism generally,
and which goes on with peculiar activity in
this portion of it, is thus being incessantly
modified; and in this manner all that portion
of it which ministers to the external life of
sense and motion that is shared by man with
the animal kingdom at large, becomes at adult
age the expression of the habits which the
individual has acquired during the period of
growth and development. Of these habits,

HABIT 23

some are common to the race generally, while
others are peculiar to the individual; those
of the former kind (such as walking erect)
being universally acquired, save where physical inability prevents; while for the latter a
special training is needed, which is usually
the more effective the earlier it is begun as
is remarkably seen in the case of such feats
of dexterity as require a conjoint education
of the perceptive and of the motor powers.
And when thus developed during the period
of growth, so as to have become a part of
the constitution of the adult, the acquired
mechanism is thenceforth maintained in the
ordinary course of the nutritive operations,
so as to be ready for use when called upon,
even after long inaction.

"What is so clearly true of the nervous
apparatus of animal life can scarcely be
otherwise than true of that which ministers
to the automatic activity of the mind. For,

24 HABIT

as already shown, the study of psychology
has evolved no more certain result than that
there are uniformities of mental action which
are so entirely conformable to those of bodily
action as to indicate their intimate relation
to a 'mechanism of thought and feeling,'
acting under the like conditions with that of
sense and motion. The psychical principles
of association, indeed, and the physiological
principles of nutrition, simply express the
former in terms of mind, the latter in terms
of brain the universally admitted fact that
any sequence of mental action which has
been frequently repeated tends to perpetuate
itself; so that we find ourselves automatically
prompted to think, feel, or do what we have
been before accustomed to think, feel, or do,
under like circumstances, without any consciously formed purpose, or anticipation of
results. For there is no reason to regard the
cerebrum as an exception to the general

HABIT 25

principle that, while each part of the organism tends to form itself in accordance with
the mode in which it is habitually exercised,
this tendency will be especially strong in the
nervous apparatus, in virtue of that incessant
regeneration which is the very condition of its
functional activity. It scarcely, indeed, admits of doubt that every state of ideational
consciousness which is either Very strong or
is habitually repeated leaves an organic impression on the cerebrum; in virtue of which
that same state may be reproduced at any
future time, in respondence to a suggestion
fitted to excite it. . . . The * strength of early
association' is a fact so universally recognized
that the expression of it has become proverbial; and this precisely accords with the
physiological principle that, during the period
of growth and development, the formative
activity of the brain will be most amenable
to directing influences. It is in this way that

26 HABIT

what is early 'learned by heart* becomes
branded in (as it were) upon the cerebrum;
so that its ' traces * are never lost, even though
the conscious memory of it may have completely faded out. For, when the organic
modification has been once fixed in the growing brain, it becomes a part of the normal
fabric, and is regularly maintained by nutritive substitution; so that it may endure to
the end of life, like the scar of a wound."

Dr. Carpenter's phrase that our nervous
system grows to the modes in which it has been
exercised expresses the philosophy of habit in
a nutshell. We may now trace some of the
practical applications of the principle to
human life.

The first result of it is that habit simplifies
the movements required to achieve a given result,
makes them more accurate and diminishes
fatigue.

HABIT 27

"The beginner at the piano not only moves
his finger up and down in order to depress the
key, he moves the whole hand, the forearm
and even the entire body, especially moving
its least rigid part, the head, as if he would
press down the key with that organ too.
Often a contraction of the abdominal muscles
occurs as well. Principally, however, the
impulse is determined to the motion of the
hand and of the single finger. This is, in the
first place, because the movement of the
finger is the movement thougkt o/, and, in
the second place, because its movement and
that of the key are the movements we try
to perceive, along with the results of the latter
on the ear. The more often the process
is repeated, the more easily the movement
follows, on account of the increase in permeability of the nerves engaged.

"But the more easily the movement occurs,
the slighter is the stimulus required to set it

28 HABIT

up; and the slighter the stimulus is, the more
its effect is confined to the fingers alone.

"Thus, an impulse which originally spread
its effects over the whole body, or at least
over many of its movable parts, is gradually
determined to a single definite organ, in
which it effects the contraction of a few
limited muscles. In this change the thoughts
and perceptions which start the impulse
acquire more and more intimate causal relations with a particular group of motor nerves.

"To recur to a simile, at least partially
apt, imagine the nervous system to represent
a drainage-system, inclining, on the whole,
toward certain muscles, but with the escape
thither somewhat clogged. Then streams of
water will, on the whole, tend most to fill the
drains that go toward these muscles and to
wash out the escape. In case of a sudden
'flushing/ however, the whole system of
channels will fill itself, and the water overflow everywhere before it escapes. But a
moderate quantity of water invading the system will flow through the proper escape alone.
"Just so with the piano-player. As soon
as his impulse, which has gradually learned
to confine itself to single muscles, grows extreme, it overflows into larger muscular
regions. He usually plays with his fingers,
his body being at rest. But no sooner does
he get excited than his whole body becomes
1 animated, ' and he moves his head and trunk,
in particular, as if these also were organs with
which he meant to belabor the keys." 1

Man is born with a tendency to do more
things than he has ready-made arrangements
for in his nerve-centres. Most of the performances of other animals are automatic.
But in him the number of them is so enormous, that most of them must be the fruit
of painful study. If practice did not make
perfect, nor habit economize the expense of
nervous and muscular energy, he would therefore be in a sorry plight. As Dr. Maudsley
says: 1

"If an act became no easier after being
done several times, if the careful direction
of consciousness were necessary to its accomplishment on each occasion, it is evident that
the whole activity of a lifetime might be
confined to one or two deeds that no progress could take place in development. A
man might be occupied all day in dressing
and undressing himself; the attitude of his
body would absorb all his attention and
energy; the washing of his hands or the
fastening of a button would be as difficult
to him on each occasion as to the child on

1 'Physiology of Mind,' p. 155.

HABIT 31

its first trial; and he would, furthermore, be
completely exhausted by his exertions. Think
of the pains necessary to teach a child to
stand, of the many efforts which it must
make, and of the ease with which it at last
stands, unconscious of any effort. For while
secondarily automatic acts are accomplished
with comparatively little weariness in this
regard approaching the organic movements,
or the original reflex movements the conscious effort of the will soon produces exhaustion.  It is impossible for an individual to
realize how much he owes to its automatic
agency until disease has impaired its functions. "

The next result is that habit diminishes
the conscious attention with which our acts
are performed.

32 HABIT

One may state this abstractly thus: If
an act require for its execution a chain,
A, B, C, D, E y F, G, etc., of successive
nervous events, then in the first performances
of the action the conscious will must choose;
each of these events from a number of wrong
alternatives that tend to present themselves;
but habit soon brings it about that each
event calls up its own appropriate successor
without any alternative offering itself, and
without any reference to the conscious will,
until at last the whole chain, A, B, C, D, E,
F, G, rattles itself off as soon as A occurs,
just as if A and the rest of the chain were
fused into a continuous stream. When we
are learning to walk, to ride, to swim, skate,
fence, write, play, or sing, we interrupt ourselves at every step by unnecessary movements and false notes. When we are proficients, on the contrary, the results not only
follow with the very minimum of muscular

HABIT 33

action requisite to bring them forth, they also
follow from a single instantaneous 'cue.'
The marksman sees the bird, and, before he
knows it, he has aimed and shot. A gleam
in his adversary's eye, a momentary pressure
from his rapier, and the fencer finds that he
has instantly made the right parry and return. A glance at the musical hieroglyphics,
and the pianist's fingers have ripped through
a cataract of notes. And not only is it the
right thing at the right time that we thus
involuntarily do, but the wrong thing also,
if it be an habitual thing. Who is there that
has never wound up his watch on taking off
his waistcoat in the daytime, or taken his
latch-key out on arriving at the door-step of
a friend? Very absent-minded persons in
going to their bedroom to dress for dinner
have been known to take off one garment
after another and finally to get into bed,
merely because that was the habitual issue

34 HABIT

of the first few movements when performed
at a later hour. The writer well remembers
how, on revisiting Paris after ten years'
absence, and, finding himself in the street in
which for one winter he had attended school,
he lost himself in a brown study, from which
he was awakened by finding himself upon the
stairs which led to the apartment in a house
many streets away in which he had lived
during that earlier time, and to which his
steps from the school had then habitually
led. We all of us have a definite routine
manner of performing certain daily offices
connected with the toilet, with the opening
and shutting of familiar cupboards, and the
like. Our lower centres know the order of
these movements, and show their knowledge
by their 'surprise' if the objects are altered
so as to oblige the movement to be made in
a different way. But our higher thought-centres know hardly anything about the

HABIT 35

matter. Few men can tell off-hand which
sock, shoe, or trousers-leg they put on first.
They must first mentally rehearse the act;
and even that is often insufficient the act
must be performed. So of the questions,
Which valve of my double door opens first?
Which way does my door swing? etc. I
cannot tell the answer; yet my hand never
makes a mistake. No one can describe the
order in which he brushes his hair or teeth;
yet it is likely that the order is a pretty fixed
one in all of us.

These results may be expressed as
follows:

In action grown habitual, what instigates
each new muscular contraction to take place
in its appointed order is not a thought or a
perception, but the sensation occasioned by
the muscular contraction just finished. A
strictly voluntary act has to be guided by
idea, perception, and volition, throughout

36 HABIT

its whole course. In an habitual action,
mere sensation is a sufficient guide, and the
upper regions of brain and mind are set
comparatively free. A diagram will make
the matter clear:

Let A, B,C, Z), , F, G represent an habitual chain of muscular contractions, and let
a, b, c, d, e, f stand for the respective sensations which these contractions excite in us
when they are successfully performed. Such
sensations will usually be of the muscles,
skin, or joints of the parts moved, but they
may also be effects of the movement upon
the eye or the ear. Through them, and
through them alone, we are made aware

HABIT 37

whether the contraction has or has not
occurred. When the series, A, B,C, D, E y F,
G, is being learned, each of these sensations
becomes the object of a separate perception
by the mind. By it we test each movement,
to see if it be right before advancing to the
next. We hesitate, compare, choose, revoke,
reject, etc., by intellectual means; and the
order by which the next movement is discharged is an express order from the ideational centres after this deliberation has
been gone through.

In habitual action, on the contrary, the only
impulse which the centres of idea or perception need send down is the initial impulse,
the'commandto start. This is represented in
the diagram by V; it may be a thought of the
first movement or of the last result, or a mere
perception of some of the habitual conditions
of the chain, the presence, e.g., of the keyboard near the hand. In the present case,

38 HABIT

no sooner has the conscious thought or
volition instigated movement A, than A,
through the sensation a of its own occurrence,
awakens B reflexly ; B then excites C through
b, and so on till the chain is ended, when the
intellect generally takes cognizance of the
final result. The process, in fact, resembles
the passage of a wave of ' peristaltic ' motion
down the bowels. The intellectual perception at the end is indicated in the diagram by
the effect of G being represented, at G 1 , in
the ideational centres above the merely
sensational line. The sensational impressions, a, J, c, d, c, /, are all supposed to have
their seat below the ideational lines. That
our ideational centres, if involved at all by
a, I, c, d, e,f, are involved in a minimal degree,
is shown by the fact that the attention may
be wholly absorbed elsewhere. We may say
our prayers, or repeat the alphabet, with our
attention far away.

HABIT 39

"A musical performer will play a piece
which has become familiar by repetition
while carrying on an animated conversation
or while continuously engrossed by some train
of deeply interesting thought; the accus-
tomed sequence of movements being directly
prompted by the sight of the notes, or by the
remembered succession of the sounds (if
the piece is played from memory), aided in
both cases by the guiding sensations derived
from the muscles themselves. But, further,
a higher degree of the same 'training' (acting
on an organism specially fitted to profit by
it) enables an accomplished pianist to play
a difficult piece of music at sight; the move-
ments of the hands and fingers following so
immediately upon the sight of the notes that
it seems impossible to believe that any but
the very shortest and most direct track
can be the channel of the nervous communi-
cation through which they are called forth.

40 HABIT

The following curious example of the same
class of acquired aptitudes, which differ from
instincts only in being prompted to action
by the will, is furnished by Robert Houdin:
"'With a view of cultivating the rapidity
of visual and tactile perception, and the
precision of respondent movements, which
are necessary for success in every kind of
prestidigitation, Houdin early practised the
art of juggling with balls in the air; and hav-
ing, after a month's practice, become thor-
ough master of the art of keeping up four
balls at once, he placed a book before him,
and, while the balls were in the air, accus-
tomed himself to read without hesitation.
'This,' he says, 'will probably seem to my
readers very extraordinary; but I shall sur-
prise them still more when I say that I have
just amused myself with repeating this curi-
ous experiment.  (Autobiography, p. 26.) *

We have called a, b, c, d, e, /, the antece-
dents of the successive muscular attractions,
by the name of sensations. Some authors
seem to deny that they are even this. If not
even this, they can only be centripetal nerve-
currents, not sufficient to arouse feeling,
but sufficient to arouse motor response. 2 It
may be at once admitted that they are not
distinct Volitions. The will, if any will be
present, limits itself to a permission that
they exert their motor effects. Dr. Car-
penter writes:

"There may still be metaphysicians who

Carpenter's 'Mental Physiology' (1874), pp. 217, 218.

2 Von Hartmann devotes a chapter of his 'Philosophy of the
Unconscious' (English translation, vol. I. p. 72) to proving that
they must be both ideas and unconscious.

42 HABIT

maintain that actions which were originally
prompted by the will with a distinct inten-
tion, and which are still entirely under its
control, can never cease to be volitional;
and that either an infinitesimally small
amount of will is required to sustain them
when they have been once set going, or that
the will is in a sort of pendulum-like oscilla-
tion between the two actions the mainte-
nance of the train of thought, and the mainte-
nance of the train of movement. But if only
an infinitesimally small amount of will is
necessary to sustain them, is not this tanta-
mount to saying that they go on by a force
of their own? And does not the experience
of the perfect continuity of our train of thought
during the performance of movements that
have become habitual, entirely negative the
hypothesis of oscillation? Besides, if such
an oscillation existed, there must be intervals
in which each action goes on of itself; so that

HABIT 43

its essentially automatic character is vir-
tually admitted. The physiological explana-
tion, that the mechanism of locomotion, as
of habitual movements, grows to the mode
in which it is early exercised, and that it then
works automatically under the general con-
trol and direction of the will, can scarcely
be put down by any assumption of an hypo-
thetical necessity, which rests only on the
basis of ignorance of one side of our composite
nature. " l

But if not distinct acts of will, these im-
mediate antecedents of each movement of
the chain are at any rate accompanied by con-
sciousness of some kind. They are sensa-
tions to which we are usually inattentive, but
which immediately call our attention if they
go wrong. Schneider's account of these
sensations deserves to be quoted. In the

1 'Mental Physiology,' p. 20.

44 HABIT

act of walking, he says, even when our atten-
tion is entirely off,

"we are continuously aware of certain mus-
cular feelings; and we have, moreover, a
feeling of certain impulses to keep our
equilibrium and to set down one leg after
another. It is doubtful whether we could
preserve equilibrium if no sensation of our
body's attitude were there, and doubtful
whether we should advance our leg if we had
no sensation of its movement as executed,
and not even a minimal feeling of impulse
to set it down. Knitting appears altogether
mechanical, and the knitter keeps up her
knitting even while she reads or is engaged in
lively talk. But if we ask her how this be
possible, she will hardly reply that the
knitting goes on of itself. She will rather
say that she has a feeling of it, that she
feels in her hands that she knits and

HABIT 45

how she must knit, and that therefore
the movements of knitting are called forth
and regulated by the sensations associated
therewithal even when the attention is
called away.

"So of every one who practises, apparently
automatically, a long-familiar handicraft.
The smith turning his tongs as he smites the
iron, the carpenter wielding his plane, the
lace-maker with her bobbin, the weaver at
his loom, all will answer the same question
in the same way by saying that they have a
feeling of the proper management of the
implement in their hands.

" In these cases, the feelings which are con-
ditions of the appropriate acts are very faint.
But none the less are they necessary.
Imagine your hands not feeling; your move-
ments could then only be provoked by ideas,
and if your ideas were then diverted away,
the movements ought to come to a standstill,

46 HABIT

which is a consequence that seldom
occurs." 1

Again:

"An idea makes you take, for example, a
violin into your left hand. But it is not
necessary that your idea remain fixed on the
contraction of the muscles of the left hand
and fingers in order that the violin may con-
tinue to be held fast and not let fall. The
sensations themselves which the holding of
the instrument awakens in the hand, since
they are associated with the motor impulse
of grasping, are sufficient to cause this im-
pulse, which then lasts as long as the feeling
itself lasts, or until the impulse is inhibited
by the idea of some antagonistic motion."
And the same may be said of the man-
ner in which the right hand holds the
bow:

1# Der mcnschliche Wille,' pp. 447, 448.

HABIT, 47

"It sometimes happens, in beginning these
simultaneous combinations, that one move-
ment or impulse will cease if the conscious-
ness turn particularly toward another, be-
cause at the outset the guiding sensations
must all be strongly felt. The bow will per-
haps slip from the fingers, because some of
the muscles have relaxed. But the slipping
is a cause of new sensations starting up in
the hand, so that the attention is in a moment
brought back to the grasping of the bow.

"The following experiment shows this
well : When one begins to play on the violin,
to keep him from raising his right elbow in
playing a book is placed under his right arm-
pit, which he is ordered to hold fast by keep-
ing the upper arm tight against his body.
The muscular feelings, and feelings of con-
tact connected with the book, provoke an im-
pulse to press it tight. But often it happens
that the beginner, whose attention gets

48 HABIT

absorbed in the production of the notes, lets
drop the book. Later, however, this never
happens; the faintest sensations of contact
suffice to awaken the impulse to keep it in
its place, and the attention may be wholly
absorbed by the notes and the fingering with
the left hand. The simultaneous combina-
tion of movements is thus in the first instance
conditioned by the facility with which in us,
alongside of intellectual processes, processes of
inattentive feeling may still go on." 1

This brings us by a very natural transition
to the ethical implications of the law of habit.
They are numerous and momentous. Dr.
Carpenter, from whose 'Mental Physiology'
we have quoted, has so prominently enforced
the principle that our organs grow to the way
in which they have been exercised, and dwelt

1 'Der menschliche Wille,' p. 439. The last sentence is rather,
freely translated the sense is unaltered.

HABIT 49

upon its consequences, that his book almost
deserves to be called a work of edification, on
this account alone. We need make no
apology, then, for tracing a few of these
consequences ourselves:

"Habit a second nature! Habit is ten
times nature," the Duke of Wellington is
said to have exclaimed; and the degree to
which this is true no one can probably appre-
ciate as well as one who is a veteran soldier
himself. The daily drill and the years of
discipline end by fashioning a man complete-
ly over again, as to most of the possibilities
of his conduct.

"There is a story, which is credible enough
though it may not be true, of a practical
joker, who, seeing a discharged veteran carry-
ing home his dinner, suddenly called out,
'Attention!' whereupon the man instantly
brought his hands down, and lost his mutton

50 HABIT

and potatoes in the gutter. The drill had
been thorough, and its effects had become
embodied in the man's nervous structure." l

Riderless cavalry-horses, at many a battle,
have been seen to come together and go
through their customary evolutions at the
sound of the bugle-call. Most trained domes-
tic animals, dogs and oxen, and omnibus- and
car-horses, seem to be machines almost pure
and simple, undoubtingly, unhesitatingly
doing from minute to minute the duties
they have been taught, and giving no sign
that the possibility of an alternative ever
suggests itself to their mind. Men grown
old in prison have asked to be readmitted
after being once set free. In a railroad acci-
dent to a travelling menagerie in the United
States some time in 1 884, a tiger, whose cage
had broken open, is said to have emerged,

Huxley's 'Elementary Lessons in Physiology,' lesson XII.

HABIT 51

but presently crept back again, as if too
much bewildered by his new responsibilities,
so that he was without difficulty secured.

Habit is thus the enormous fly-wheel of
society, its most precious conservative agent.
It alone is what keeps us all within the bounds
of ordinance, and saves the children of for-
tune from the envious uprisings of the poor.
It alone prevents the hardest and most
repulsive walks of life from being deserted
by those brought up to tread therein. It
keeps the fisherman and the deck-hand at
sea through the winter; it holds the miner
in his darkness, and nails the countryman to
his log cabin and his lonely farm through all
the months of snow; it protects us from in-
vasion by the natives of the desert and the
frozen zone. It dooms us all to fight out the
battle of life upon the lines of our nurture
or our early choice, and to make the best
of a pursuit that disagrees, because there is

52 HABIT

no other for which we are fitted, and it is
too late to begin again. It keeps different
social strata from mixing. Already at the
age of twenty-five you see the professional
mannerism settling down on the young com-
mercial traveller, on the young doctor, on
the young minister, on the young counsellor-
at-law. You see the little lines of cleavage
running through the character, the tricks of
thought, the prejudices, the ways of the
'shop,' in a word, from which the man can
by-and-by no more escape than his coat-
sleeve can suddenly fall into a new set of
folds. On the whole, it is best he should
not escape. It is well for the world that
in most of us, by the age of thirty, the char-
acter has set like plaster, and will never soften
again.

If the period between twenty and thirty
is the critical one in the formation of intellec-
tual and professional habits, the period below

HABIT 53

twenty is more important still for the fixing
of personal habits, properly so called, such as
vocalization and pronunciation, gesture, mo-
tion, and address. Hardly ever is a language
learned after twenty spoken without a foreign
accent; hardly ever can a youth transferred
to the society of his betters unlearn the
nasality and other vices of speech bred in
him by the associations of his growing years.
Hardly ever, indeed, no matter how much
money there be in his pocket, can he even
learn to dress like a gentleman-born. The
merchants offer their wares as eagerly to
him as to the veriest * swell,' but he simply
cannot buy the right things. An invisible
law, as strong as gravitation, keeps him
within his orbit, arrayed this year as he was
the last; and how his better-bred acquaint-
ances contrive to get the things they wear
will be for him a mystery till his dying
day.

54 HABIT

The great thing, then, in all education, is
to ma\e our nervous system our ally instead
of our enemy. It is to fund and capitalize
our acquisitions, and live at ease upon the
interest of the fund. For this we must mafe
automatic and habitual, as early as possible,
as many useful actions as we can, and guard
against the growing into ways that are likely
to be disadvantageous to us, as we should
guard against the plague. The more of the
details of our daily life we can hand over to
the effortless custody of automatism, the
more our higher powers of mind will be set
free for their own proper work. There is
no more miserable human being than one in
whom nothing is habitual but indecision, and
for whom the lighting of every cigar, the
drinking of every cup, the time of rising and
going to bed every day, and the beginning
of every bit of work, are subjects of express
volitional deliberation. Full half the time

HABIT 55

of such a man goes to the deciding, or regret-
ting, of matters which ought to be so in-
grained in him as practically not to exist for
his consciousness at all. If there be such
daily duties not yet ingrained in any one of
my readers, let him begin this very hour to
set the matter right.

In Professor Bain's chapter on 'The Moral
Habits' there are some admirable practical
remarks laid down. Two great maxims
emerge from his treatment. The first is that
in the acquisition of a new habit, or the leav-
ing off of an old one, we must take care to
launch ourselves with as strong and decided
an initiative as possible. Accumulate all
the possible circumstances which shall re-
enforce the right motives ; put yourself assidu-
ously in conditions that encourage the new
way; make engagements incompatible with
the old; take a public pledge, if the case
allows; in short, envelop your resolution with

56 HABIT

every aid you know. This will give your
new beginning such a momentum that the
temptation to break down will not occur as
soon as it otherwise might; and every day
during which a breakdown is postponed
adds to the chances of its not occurring
at all.

The second maxim is: Never suffer an
exception to occur till the new habit is securely
rooted in your life. Each lapse is like the
letting fall of a ball of string which one is
carefully winding up; a single slip undoes
more than a great many turns will wind
again. Continuity of training is the great
means of making the nervous system
act infallibly right. As Professor Bain
says:

"The peculiarity of the moral habits, con-
tradistinguishing them from the intellectual
acquisitions, is the presence of two hostile

HABIT 57

powers, one to be gradually raised into the
ascendant over the other. It is necessary,
above all things, in such a situation, never
to lose a battle. Every gain on the wrong
side undoes the effect of many conquests on
the right. The essential precaution, there-
fore, is so to regulate the two opposing powers
that the one may have a series of uninter-
rupted successes, until repetition has forti-
fied it to such a degree as to enable it to cope
with the opposition, under any circumstances.
This is the theoretically best career of mental
progress."

The need of securing success at the outset
is imperative. Failure at first is apt to
dampen the energy of all future attempts,
whereas past experience of success nerves
one to future vigor. Goethe says to a man
who consulted him about an enterprise but
mistrusted his own powers: "Ach! you

58 HABIT

need only blow on your hands!" And the
remark illustrates the effect on Goethe's
spirits of his own habitually successful career.
Prof. Baumann, from whom I borrow the
anecdote, 1 says that the collapse of barbarian
nations when Europeans come among them
is due to their despair of ever succeeding as
the new-comers do in the larger tasks of life.
Old ways are broken and new ones not
formed.

The question of ' tapering-off , ' in abandon-
ing such habits as drink and opium-indul-
gence, comes in here, and is a question about
which experts differ within certain limits, and
in regard to what may be best for an individ-
ual case. In the main, however, all expert
opinion would agree that abrupt acquisition
of the new habit is the best way, // there be a
real possibility of carrying it out. We must

1 See the admirable passage about success at the outset, in
his 'Handbuch der Moral* (1378), pp. 38-43.

HABIT 59

be careful not to give the will so stiff a task
as to insure its defeat at the very outset;
but, provided one can stand it, a sharp period
of suffering, and then a free time, is the best
thing to aim at, whether in giving up a habit
like that of opium, or in simply changing
one's hours of rising or of work. It is sur-
prising how soon a desire will die of inanition
if it be never fed.

"One must first learn, unmoved, looking
neither to the right nor left, to walk firmly
on the straight and narrow path, before one
can begin 'to make one's self over again.'
He who every day makes a fresh resolve
is like one who, arriving at the edge of the
ditch he is to leap, forever stops and returns
for a fresh run. Without unbroken advance
there is no such thing as accumulation of the
ethical forces possible, and to make this
possible, and to exercise us and habituate us

60 HABIT

in it, is the sovereign blessing of regular
work/ 1 l

A third maxim may be added to the pre-
ceding pair: Seize the Very first possible
opportunity to act on every resolution you make,
and on every emotional prompting you may
experience in the direction of the habits you
aspire to gain. It is not in the moment of
their forming, but in the moment of their
producing motor effects, that resolves and
aspirations communicate the new 'set' to
the brain. As the author last quoted
remarks:

"The actual presence of the practical
opportunity alone furnishes the fulcrum
upon which the lever can rest, by means of
which the moral will may multiply its

1 J. Bahnsen: 'Beitrage zu Charakterologie' (1867), vol.
I. p. 209.

HABIT 61

strength, and raise itself aloft. He who has
no solid ground to press against will never
get beyond the stage of empty gesture-
making.' '

No matter how full a reservoir of maxims
one may possess, and no matter how good
one's sentiments may be, if one have not
taken advantage of every concrete oppor-
tunity to ad, one's character may remain
entirely unaffected for the better.  And this is an obvious consequence
of the principles we have laid down. A
'character, ' as J. S. Mill says, 'is a completely
fashioned will'; and a will, in the sense in
which he means it, is an aggregate of ten-
dencies to act in a firm and prompt and defi-
nite way upon all the principal emergencies
of life. A tendency to act only becomes effec-
tively ingrained in us in proportion to the

62 HABIT

uninterrupted frequency with which the
actions actually occur, and the brain 'grows'
to their use. Every time a resolve or a fine
glow of feeling evaporates without bearing
practical fruit is worse than a chance lost;
it works so as positively to hinder future reso-
lutions and emotions from taking the normal
path of discharge. There is no more con-
temptible type of human character than that
of the nerveless sentimentalist and dreamer,
who spends his life in a weltering sea of
sensibility and emotion, but who never does
a manly concrete deed. Rousseau, inflam-
ing all the mothers of France, by his elo-
quence, to follow Nature and nurse their
babies themselves, while he sends his own
children to the foundling hospital, is the
classical example of what I mean. But
every one of us in his measure, whenever,
after glowing for an abstractly formulated
Good, he practically ignores some actual

HABIT 63

case, among the squalid 'other particulars'
of which that same Good lurks disguised,
treads straight on Rousseau's path. All
Goods are disguised by the vulgarity of their
concomitants, in this work-a-day world; but
woe to him who can only recognize them
when he thinks them in their pure and
abstract form ! The habit of excessive novel-
reading and theatre-going will produce true
monsters in this line. The weeping of a
Russian lady over the fictitious personages
in the play, while her coachman is freezing
to death on his seat outside, is the sort of
thing that everywhere happens on a less
glaring scale. Even the habit of excessive
indulgence in music, for those who are
neither performers themselves nor musically
gifted enough to take it in a purely intellec-
tual way, has probably a relaxing effect upon
the character. One becomes filled with
emotions which habitually pass without

64 HABIT

prompting to any deed, and so the inertly
sentimental condition is kept up. The
remedy would be, never to suffer one's self
to have an emotion at a concert, without
expressing it afterward in some active way. 1
Let the expression be the least thing in the
world speaking genially to one's aunt, or
giving up one's seat in a horse-car, if nothing
more heroic offers but let it not fail to take
place.

These latter cases make us aware that it
is not simply particular lines of discharge, but
also general forms of discharge, that seem to
be grooved out by habit in the brain. Just
as, if we let our emotions evaporate, they get
into a way of evaporating; so there is reason
to suppose that if we often flinch from making
an effort, before we know it the effort-making
capacity will be gone; and that, if we suffer

1 See for remarks on this subject a readable article by Miss V.
Scudder on 'Musical Devotees and Morals,' in the Andover
Review for January, 1887.

HABIT 65

the wandering of our attention, presently it
will wander all the time. Attention and
effort are, as we shall see later, but two names
for the same psychic fact. To what brain-
processes they correspond we do not know.
The strongest reason for believing that they
do depend on brain-processes at all, and are
not pure acts of the spirit, is just this fact,
that they seem in some degree subject to the
law of habit, which is a material law. As a
final practical maxim, relative to these habits
of the will, we may, then, offer something
like this: Keep the faculty of effort alive in
you by a little gratuitous exercise every day.
That is, be systematically ascetic or heroic
in little unnecessary points, do every day or
two something for no other reason than that
you would rather not do it, so that when the
hour of dire need draws nigh, it may find you
not unnerved and untrained to stand the
test. Asceticism of this sort is like the insur-

66 HABIT

ance which a man pays on his house and
goods. The tax does him no good at the
time, and possibly may never bring him a
return. But if the fire does come, his having
paid it will be his salvation from ruin. So
with the man who has daily inured himself
to habits of concentrated attention, ener-
getic volition, and self-denial in unnecessary
things. He will stand like a tower when
everything rocks around him, and when his
softer fellow-mortals are winnowed like chaff
in the blast.

The physiological study of mental con-
ditions is thus the most powerful ally of
hortatory ethics. The hell to be endured
hereafter, of which theology tells, is no worse
than the hell we make for ourselves in this
world by habitually fashioning our charac-
ters in the wrong way. Could the young
but realize how soon they will become mere
walking bundles of habits, they would give

HABIT 67

more heed to their conduct while in the plas-
tic state. We are spinning our own fates,
good or evil, and never to be undone. Every
smallest stroke of virtue or of vice leaves its
never so little scar. The drunken Rip Van
Winkle, in Jefferson's play, excuses himself
for every fresh dereliction by saying, *I
won't count this time!' Well! he may not
count it, and a kind Heaven may not count
it; but it is being counted none the less.
Down among his nerve-cells and fibres the
molecules are counting it, registering and
storing it up to be used against him when the
next temptation comes. Nothing we ever do
is, in strict scientific literalness, wiped out.
Of course, this has its good side as well as
its bad one. As we become permanent
drunkards by so many separate drinks, so
we become saints in the moral, and author-
ities and experts in the practical and scien-
tific spheres, by so many separate acts and

68 HABIT

hours of work. Let no youth have any
anxiety about the upshot of his education,
whatever the line of it may be. If he keep
faithfully busy each hour of the working-day,
he may safely leave the final result to itself.
He can with perfect certainty count on
waking up some fine morning, to find himself
one of the competent ones of his generation,
in whatever pursuit he may have singled out.
Silently, between all the details of his busi-
ness, the power of judging in all that class of
matter will have built itself up within him as
a possession that will never pass away.
Young people should know this truth in
advance. The ignorance of it has probably
engendered more discouragement and faint-
heartedness in youths embarking on ardu-
ous careers than all other causes put together.

mf

gha_language: TypeScript


text:
# Demo: Components

For more details regarding this feature you can read the
[Kustomize Components KEP](https://github.com/kubernetes/enhancements/blob/master/keps/sig-cli/1802-kustomize-components/README.md).

_This example requires Kustomize ``v3.7.0`` or newer_

Suppose you've written a very simple Web application:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
spec:
  template:
    spec:
      containers:
      - name: example
        image: example:1.0
```

You want to deploy a **community** edition of this application as SaaS, so you
add support for persistence (e.g. an external database), and bot detection
(e.g. Google reCAPTCHA).

You've now attracted **enterprise** customers who want to deploy it
on-premises, so you add LDAP support, and disable Google reCAPTCHA. At the same
time, the **devs** need to be able to test parts of the application, so they
want to deploy it with some features enabled and others not.

Here's a matrix with the deployments of this application and the features
enabled for each one:

|            | External DB        | LDAP               | reCAPTCHA          |
|------------|:------------------:|:------------------:|:------------------:|
| Community  | :heavy_check_mark: |                    | :heavy_check_mark: |
| Enterprise | :heavy_check_mark: | :heavy_check_mark: |                    |
| Dev        | :white_check_mark: | :white_check_mark: | :white_check_mark: |

So, you want to make it easy to deploy your application in any of the above
three environments. This seems like a work for [variants], so you try to create
three overlays; a `community/`, an `enterprise/` and a `dev/` overlay, that each
provides the appropriate features for their audience, i.e., public, customers and
developers, respectfully.

## Variants example

Here's the common and most simplistic approach to solve this problem. As we will
soon see, this approach does not scale well in more complex scenarios. However,
it will help you get a better grasp of the problem we are about to tackle and
demonstrate where there is room for improvement.

First, define a place to work:

```shell
DEMO_HOME=$(mktemp -d)
```

Define a common **base** that has a `Deployment` and a simple `ConfigMap`, that
is mounted on the application's container.

```shell
BASE=$DEMO_HOME/base
mkdir $BASE

cat <<EOF >$BASE/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- deployment.yaml

configMapGenerator:
- name: conf
  literals:
    - main.conf=|
        color=cornflower_blue
        log_level=info
EOF

cat <<EOF >$BASE/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
spec:
  template:
    spec:
      containers:
      - name: example
        image: example:1.0
        volumeMounts:
        - name: conf
          mountPath: /etc/config
      volumes:
        - name: conf
          configMap:
            name: conf
EOF
```

Define a **community** overlay that:

- generates `Secrets` for external DB's password and reCAPTCHA's keys
- patches the `ConfigMap` of the common base with configurations for external DB
  and reCAPTCHA
- patches the `Deployment` of the common base to mount the generated `Secrets`
  for external DB and reCAPTCHA

```shell
COMMUNITY=$DEMO_HOME/overlays/community
mkdir -p $COMMUNITY

cat <<EOF >$COMMUNITY/kustomization.yaml
kind: Kustomization

resources:
  - ../../base

secretGenerator:
  - name: dbpass
    files:
      - dbpass.txt
  - name: recaptcha
    files:
      - site_key.txt
      - secret_key.txt

patchesStrategicMerge:
  - configmap.yaml

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$COMMUNITY/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: dbpass
    secret:
      secretName: dbpass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/db/
    name: dbpass
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: recaptcha
    secret:
      secretName: recaptcha
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/recaptcha/
    name: recaptcha
EOF

cat <<EOF >$COMMUNITY/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
data:
  db.conf: |
    endpoint=<IP_ADDRESS>:1234
    name=app
    user=admin
    pass=/var/run/secrets/db/dbpass.txt
  recaptcha.conf: |
    enabled=true
    site_key=/var/run/secrets/recaptcha/site_key.txt
    secret_key=/var/run/secrets/recaptcha/secret_key.txt
EOF
```

Create local input files for external DB's password and reCAPTCHA's keys:

```shell

cat <<EOF >$COMMUNITY/dbpass.txt
dbpass
EOF

cat <<EOF >$COMMUNITY/site_key.txt
sitekey
EOF

cat <<EOF >$COMMUNITY/secret_key.txt
secretkey
EOF
```

Define a **enterprise** overlay that:

- generates `Secrets` for LDAP's password and external DB's password
- patches the `ConfigMap` of the common base with configurations for LDAP and
  external DB
- patches the `Deployment` of the common base to mount the generated `Secrets`
  for LDAP and external DB

```shell
ENTERPRISE=$DEMO_HOME/overlays/enterprise
mkdir -p $ENTERPRISE

cat <<EOF >$ENTERPRISE/kustomization.yaml
kind: Kustomization

resources:
  - ../../base

secretGenerator:
  - name: ldappass
    files:
      - ldappass.txt
  - name: dbpass
    files:
      - dbpass.txt

patchesStrategicMerge:
  - configmap.yaml

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$ENTERPRISE/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: dbpass
    secret:
      secretName: dbpass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/db/
    name: dbpass
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: ldappass
    secret:
      secretName: ldappass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/ldap/
    name: ldappass
EOF

cat <<EOF >$ENTERPRISE/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
data:
  db.conf: |
    endpoint=<IP_ADDRESS>:1234
    name=app
    user=admin
    pass=/var/run/secrets/db/dbpass.txt
  ldap.conf: |
    endpoint=ldap://ldap.example.com
    bindDN=cn=admin,dc=example,dc=com
    pass=/var/run/secrets/ldap/ldappass.txt
EOF
```

Create local input files for LDAP's password and external DB's password:

```shell

cat <<EOF >$ENTERPRISE/ldappass.txt
ldappass
EOF

cat <<EOF >$ENTERPRISE/dbpass.txt
dbpass
EOF
```

Define a **dev** overlay that supports all three features(ExternalDB, LDAP,
reCAPTCHA) and conditionally enables some or all of them. In this example, we
define a dev overlay that supports all the features, but has disabled the LDAP
support, by doing the following::

- generates `Secrets` for external DB's password and reCAPTCHA's keys
- patches the `ConfigMap` of the common base with configurations for external DB
  and reCAPTCHA
- patches the `Deployment` of the common base to mount the generated `Secrets`
  for external DB and reCAPTCHA

```shell
DEV=$DEMO_HOME/overlays/dev
mkdir -p $DEV

cat <<EOF >$DEV/kustomization.yaml
kind: Kustomization

resources:
  - ../../base

secretGenerator:
  # - name: ldappass              <-- Commenting to disable LDAP support
  #   files:
  #     - ldappass.txt
  - name: dbpass
    files:
      - dbpass.txt
  - name: recaptcha
    files:
      - site_key.txt
      - secret_key.txt

patchesStrategicMerge:
  - configmap.yaml

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$DEV/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: dbpass
    secret:
      secretName: dbpass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/db/
    name: dbpass
# - op: add                             <-- Commenting to disable LDAP support
#   path: /spec/template/spec/volumes/0
#   value:
#     name: ldappass
#     secret:
#       secretName: ldappass
# - op: add
#   path: /spec/template/spec/containers/0/volumeMounts/0
#   value:
#     mountPath: /var/run/secrets/ldap/
#     name: ldappass
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: recaptcha
    secret:
      secretName: recaptcha
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/recaptcha/
    name: recaptcha

EOF

cat <<EOF >$DEV/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
data:
  db.conf: |
    endpoint=<IP_ADDRESS>:1234
    name=app
    user=admin
    pass=/var/run/secrets/db/dbpass.txt
  # ldap.conf: |                          <-- Commenting to disable LDAP support
  #   endpoint=ldap://ldap.example.com
  #   bindDN=cn=admin,dc=example,dc=com
  #   pass=/var/run/secrets/ldap/ldappass.txt
  recaptcha.conf: |
    enabled=true
    site_key=/var/run/secrets/recaptcha/site_key.txt
    secret_key=/var/run/secrets/recaptcha/secret_key.txt
EOF
```

Create local input files for external DB's password and reCAPTCHA's keys:

```shell

cat <<EOF >$DEV/dbpass.txt
dbpass
EOF

cat <<EOF >$DEV/site_key.txt
sitekey
EOF

cat <<EOF >$DEV/secret_key.txt
secretkey
EOF
```

The above commands result in the following structure:

```shell
├── base
│   ├── deployment.yaml
│   └── kustomization.yaml
└── overlays
    ├── community
    │   ├── configmap.yaml
    │   ├── dbpass.txt
    │   ├── deployment.yaml
    │   ├── kustomization.yaml
    │   ├── secret_key.txt
    │   └── site_key.txt
    ├── dev
    │   ├── configmap.yaml      <-- Refers to multiple features and might contain comments
    │   ├── dbpass.txt
    │   ├── deployment.yaml     <-- Refers to multiple features and might contain comments
    │   ├── kustomization.yaml  <-- Refers to multiple features and might contain comments
    │   ├── secret_key.txt
    │   └── site_key.txt
    └── enterprise
        ├── configmap.yaml
        ├── dbpass.txt
        ├── deployment.yaml
        ├── kustomization.yaml
        └── ldappass.txt
```

The main issues observed with this solution are:

1. Since some features are repeated in the `community/`, `enterprise/` and
   `dev/` overlays, one needs to manually define patches with content that is
   partially identical to patches of different overlays, that also enable this
   feature.
2. The `dev/` overlay is dynamic, i.e., supports multiple optional features. To
   enable/disable any single feature one needs to uncomment/comment many lines
   of YAML which is cumbersome and hard to maintain. Alternatively, one needs
   to maintain a multitude of overlays and track all possible combinations of
   features.
3. Overlays that combine more than one features define patches for resources
   whose content is not dedicated to a single feature. That is, there is no
   semantic isolation per feature, everything gets mixed into a single,
   multi-feature, resource-specific patch.

The variants approach may solve this simple example but it won't scale in the
long run, as the number of features and deployments grow. What if you have `N`
opt-in features and `M` real-world deployment scenarios that ship with `0-N` of
these features?

Ideally, you want to move each feature under a separate, reusable overlay and
enable them on-demand per deployment, i.e., in kustomization files of top-level
overlays. Enter components.

## Components example

Here's an alternative and more [DRY] approach that solves this issue by using a
Kustomize feature called "components". Each opt-in feature gets packaged as a
component, so that it can be referred to from higher-level overlays.

First, define a place to work:

```shell
DEMO_HOME=$(mktemp -d)
```

Define a common **base** that has a `Deployment` and a simple `ConfigMap`, that
is mounted on the application's container.

```shell
BASE=$DEMO_HOME/base
mkdir $BASE

cat <<EOF >$BASE/kustomization.yaml
resources:
- deployment.yaml

configMapGenerator:
- name: conf
  literals:
    - main.conf=|
        color=cornflower_blue
        log_level=info
EOF

cat <<EOF >$BASE/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
spec:
  template:
    spec:
      containers:
      - name: example
        image: example:1.0
        volumeMounts:
        - name: conf
          mountPath: /etc/config
      volumes:
        - name: conf
          configMap:
            name: conf
EOF
```

Define an `external_db` component, using `kind: Component`, that creates a
`Secret` for the DB password and a new entry in the `ConfigMap`:

```shell
EXT_DB=$DEMO_HOME/components/external_db
mkdir -p $EXT_DB

cat <<EOF >$EXT_DB/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1  # <-- Component notation
kind: Component

secretGenerator:
- name: dbpass
  files:
    - dbpass.txt

patchesStrategicMerge:
  - configmap.yaml

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$EXT_DB/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: dbpass
    secret:
      secretName: dbpass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/db/
    name: dbpass
EOF

cat <<EOF >$EXT_DB/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
data:
  db.conf: |
    endpoint=<IP_ADDRESS>:1234
    name=app
    user=admin
    pass=/var/run/secrets/db/dbpass.txt
EOF
```

Define an `ldap` component, that creates a `Secret` for the LDAP password
and a new entry in the `ConfigMap`:

```shell
LDAP=$DEMO_HOME/components/ldap
mkdir -p $LDAP

cat <<EOF >$LDAP/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component

secretGenerator:
- name: ldappass
  files:
    - ldappass.txt

patchesStrategicMerge:
  - configmap.yaml

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$LDAP/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: ldappass
    secret:
      secretName: ldappass
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/ldap/
    name: ldappass
EOF

cat <<EOF >$LDAP/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
data:
  ldap.conf: |
    endpoint=ldap://ldap.example.com
    bindDN=cn=admin,dc=example,dc=com
    pass=/var/run/secrets/ldap/ldappass.txt
EOF
```

Define a `recaptcha` component, that creates a `Secret` for the reCAPTCHA
site/secret keys and a new entry in the `ConfigMap`:

```shell
RECAPTCHA=$DEMO_HOME/components/recaptcha
mkdir -p $RECAPTCHA

cat <<EOF >$RECAPTCHA/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component

secretGenerator:
- name: recaptcha
  files:
    - site_key.txt
    - secret_key.txt

# Updating the ConfigMap works with generators as well.
configMapGenerator:
- name: conf
  behavior: merge
  literals:
    - recaptcha.conf=|
        enabled=true
        site_key=/var/run/secrets/recaptcha/site_key.txt
        secret_key=/var/run/secrets/recaptcha/secret_key.txt

patchesJson6902:
- target:
    group: apps
    version: v1
    kind: Deployment
    name: example
  path: deployment.yaml
EOF

cat <<EOF >$RECAPTCHA/deployment.yaml
- op: add
  path: /spec/template/spec/volumes/0
  value:
    name: recaptcha
    secret:
      secretName: recaptcha
- op: add
  path: /spec/template/spec/containers/0/volumeMounts/0
  value:
    mountPath: /var/run/secrets/recaptcha/
    name: recaptcha
EOF
```

Define a `community` variant, that bundles the external DB and reCAPTCHA
components:

```shell
COMMUNITY=$DEMO_HOME/overlays/community
mkdir -p $COMMUNITY

cat <<EOF >$COMMUNITY/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

components:
  - ../../components/external_db
  - ../../components/recaptcha
EOF
```

Define an `enterprise` overlay, that bundles the external DB and LDAP
components:

```shell
ENTERPRISE=$DEMO_HOME/overlays/enterprise
mkdir -p $ENTERPRISE

cat <<EOF >$ENTERPRISE/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

components:
  - ../../components/external_db
  - ../../components/ldap
EOF
```

Define a `dev` overlay, that points to all the components and has LDAP
disabled:

```shell
DEV=$DEMO_HOME/overlays/dev
mkdir -p $DEV

cat <<EOF >$DEV/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

components:
  - ../../components/external_db
  #- ../../components/ldap
  - ../../components/recaptcha
EOF
```

Now the workspace has following directories:

```shell
├── base
│   ├── deployment.yaml
│   └── kustomization.yaml
├── components
│   ├── external_db
│   │   ├── configmap.yaml
│   │   ├── dbpass.txt
│   │   ├── deployment.yaml
│   │   └── kustomization.yaml
│   ├── ldap
│   │   ├── configmap.yaml
│   │   ├── deployment.yaml
│   │   ├── kustomization.yaml
│   │   └── ldappass.txt
│   └── recaptcha
│       ├── deployment.yaml
│       ├── kustomization.yaml
│       ├── secret_key.txt
│       └── site_key.txt
└── overlays
    ├── community
    │   └── kustomization.yaml
    ├── dev
    │   └── kustomization.yaml
    └── enterprise
        └── kustomization.yaml
```

With this structure, you can create the YAML files for each deployment as
follows:

```shell
kustomize build overlays/community
kustomize build overlays/enterprise
kustomize build overlays/dev
```

## Takeaway

At the end of the day, Kustomize components provide a more flexible way to
enable/disable features and configurations for applications directly from the
kustomization file. This results in more readable, concise and intuitive
overlays.

[variants]: multibases/README.md
[DRY principle]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

repository: kubernetes-sigs/kustomize

branch_name: refs/heads/master

extension: md

gha_language: Go

license_type: permissive

repo_name: kubernetes-sigs/kustomize


text:
# WIDESIGHT backend

This is the backend component of Widesight Service application.
It is a django app based on [Django REST Framework](https://www.django-rest-framework.org/) that exposes a REST interface for creating and mantaining a street level  images and derived objects database

## Install:

Manually install GDAL and related python library for your platform.
local clone the repository than install the remaining needed python library requirements:

```
pip install -r requirements.txt
```

configure `ws/settings.py` specifying database backend (demo on spatialite backend) then migrate database from scratch.

```
python manage.py makemigrations wide_sight

python manage.py migrate
```

run development service:

```
python manage.py runserver
```

## REST API interface

The service manage listing , creation and editing of three five sets of objects:

- main

  - sequences: panorama containers

  - panoramas: geolocated equirectangular images with support informations

  - image objects: geolocated user recognized image objects (tags, spots, stereo measurements, etc...)

- support

  - image objects types: custom image objects categories

  - userkey: userkeys user capabilities (geofencing, allowed appkeys)

  - appkeys: allowed application keys (needed for GET method without user authorization)

the complete API reference is available at [docs/API.html](https://app.swaggerhub.com/apis-docs/enricofer/Widesight/1.0.0)

## Web interface
https://github.com/enricofer/wide_sight_frontend

## Uploading utilities
https://github.com/enricofer/wide_sight_utils


text:
# what i travel with

Food is not included in the list. I eat what i find in dumpsters, on the trees around, and if that doesn't work i buy food, too. I tend to buy nuts or sunflower seeds before a hitchhiking stretch (best energy/weight ratio). Food contained in my backpack varies a lot. Generally i don't cook outdoors.

## papers
- yoga - papers with printed excerpts from Yoga by Milan Polášek (Slovakian yoga teacher)
- calendar - diy calendar for 1 year (2 weeks per page A5
- plastic containers for papers - 3-4
- white papers
- various papers with notes
- diary (7 folded white pages, to be sewn together when finished. Very lightweight)
- map of Europe
- hipster pda

## society, legal
- hitchhiking belt (to carry passport and money when not feeling safe)
- passport
- money (i like having as little as possible)

## various
- plastic tape - for paper and much more
- black electric tape
- teaspoon (for eating, cleaning tongue, measuring bubble-making ingredients)
- pencils
- small ball of wax (make strings stronger by waxing)
- pack thread - a strong string
- earplugs with a box
- black and white thread
- 2-3 needles
- black drawing ink,
- pen for drawing ink - it is dipped to the ink
- micro screwdriver - for those small screws in laptops etc
- tweezer
- paper clip binders (2-4)
- eraser

## health
- plaster tape - Leukoplast - to fix small wounds
- propolis
- medical charcoal
- disinfectant
- manicure scissors
- white petroleum jelly (dry skin care)
- vitamin b12 (1 tablet weekly)

## bags
- backpack 75 liters (Gemma Expedition)
- fabric handbag
- straps to attach violin case to backpack

## electronics
- laptop - asus eee pc 1001px
- laptop cables
- headphones
- 3 flash drives
- bag for computer (simple, diy)
- ebook reader
- usb charger
- usb-microusb cable

## camping
- various plastic bottles for drinking water (0.5 - 1 l) total volume of 1 - 2 l
- hammock with mosquito net
- sleeping mat
- plastic sheet 2x3m worn out - to cover my backpack at night, to do yoga on, a floor for various activity, not usable as rain protection anymore
- tarp 2x3m - a cheap 3-euro plastic sheet from woven plastic, with metal holes on sides and corners
- plastic clothes-line to build plastic sheet (tarp) between trees
- strings to attach tarp to the ground
- plastic and metal sticks (10 pieces) to attach tarp strings to the ground
- sleeping bag
- headlight
- pocket knife
- yellow piece of rope (get rid of?)
- raincoat - poncho

## hitchhiking
- oil pastels to draw hitchhiking signs (bought in Tiger (oliekridt))
- yellow reflex vest attached to backpack - hitchhiking safety

## busking
- a green money container for busking (a woven flowerpot cover found in Geneve)
- a soap bubble ingredient
- green plastic bowl
- small plastic bottle for measuring liquid volume
- red plastic bowl (busking, washing, ...)
- 5l plastic canister (busking, showering, not suitable for drinking water)
- bubble-making strings (busking)

## clothes
- @todo

## music
- violin, violin bow (a fixed bad violin, low quality but good enoough sound)
- tuner
- colophonium
- violin case

## hygiene
- towel (a small piece of fast drying cloth)
- toothbrush
- hairbrush
- soap
- strap for sharping razor
- toothpaste, preferably without fluoride
- alum
- dental floss
- razor
- bag for hygienic stuff

## miscellaneous

license: MIT

repository: mrkvon/stuff

gha_license_id: MIT

repo_name: mrkvon/stuff


text:
# StretchScrollView

[![CI Status](http://img.shields.io/travis/anton-plebanovich/StretchScrollView.svg?style=flat)](https://travis-ci.org/anton-plebanovich/StretchScrollView)
[![Version](https://img.shields.io/cocoapods/v/StretchScrollView.svg?style=flat)](http://cocoapods.org/pods/StretchScrollView)
[![License](https://img.shields.io/cocoapods/l/StretchScrollView.svg?style=flat)](http://cocoapods.org/pods/StretchScrollView)
[![Platform](https://img.shields.io/cocoapods/p/StretchScrollView.svg?style=flat)](http://cocoapods.org/pods/StretchScrollView)

StretchScrollView provides functionality to enlarge title image and hide overlays when scrolling down. When scrolling up it allows to animate background of navigation bar.

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## GIF animation

## Installation

#### CocoaPods

StretchScrollView is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'StretchScrollView'
```

## Usage

Assign `StretchScrollView` class to your UIScrollView in storyboard.

Set needed outlets and options.

You are done!

Please note that you have to make your navigation bar fully transparent if you want to change it's background color. See example project for more details.

## Contributions

Any contribution is more than welcome! You can contribute through pull requests and issues on GitHub.

## Author

Anton Plebanovich<EMAIL_ADDRESS>
## License

StretchScrollView is available under the MIT license. See the LICENSE file for more info.

repository: carabina/StretchScrollView

repo_name: carabina/StretchScrollView


text:
---
home: true
heroImage: /logo.png
actionText: Get Started →
actionLink: /en/introduction
features:
  - title: RISK FREE TO JOIN
    details: No Joining Fees. No Membership fees. No Monthly Purchase Obligations. No Automatic Reordering. No Auto-Ship
  - title: MASSTIGE PRODUCT
    details: Atomy's slogan is Absolute Quality. Absolute Price. This means you are getting the highest quality products at the lowest price possible.
  - title: WORLDWIDE BUSINESS WITH A VALID PASS
    details: Atomy took 8 years to open new markets in KOREA,USA, CANADA, JAPAN, TAIWAN, SINGAPORE, PHILIPPINE, CAMBODIA AND now MALAYSIA. Once you're a member of Atomy you can refer anyone in any of the opened countries and place them in your group under you. So the income potential is amazing!
  - title: PASSIVE INCOME INVESTMENT AT ZERO COST
    details: With Atomy expansion plans around the world you can start building up your very own soure of passive income simply by joining at no cost! Imagine starting a business without the need for any capital expenditure and being given your very own online shopping mall and virtual office. That is essentially what Atomy is!
  - title: HOUSEHOLD NAME WORLDWIDE
    details: Atomy has the backing of kolmar "the leading manufacture of cosmetics, skin care, home care and many other products since 1921" and KEAERY "Korea Atomy Energy Research Institute" - They are a government institution that developed HemoHim after 8 years of research in a quest to help boost the immune system for their scientists working with radiation
  - title: STRESS FREE CULTURE
    details: We never sell products & force people to buy as we know nobody like to sell products. But we buy products at low prices from Atomy, then simply share our experience to others. This is how Atomy work.

footer: MIT Licensed | Copyright © 2019 - present TEAW LI LI
---

## Contact

- 🏀 [Wechat](https://i.imgur.com/1RDF4lM.jpg)
- ⚽ [WhatsApp](https://i.imgur.com/BKj4ROo.png)
- 🏓 [Facebook-Messenger](https://i.imgur.com/bBV2O1n.png)
- 🏈 [Line](https://i.imgur.com/iRngVkz.jpg)
- 🏸 [SMS](https://i.imgur.com/MWKdd7N.png)

## Follow

- 👦 [Facebook](https://)
- 📸 [Instagram](https://)
- 🎬 [Youtube](https://)
- 📌 [Pinterest](https://)
- 📚 [Medium](https://)

## My-Webside

- 🏠 [My-blog](https://)
- 🛠 [DIY](https://)
- 🍙 [Recipes](https://)
- 📡 [XOX](https://)
- ♻ [Zero-waste](https://)
- 💰 [e-commerce](https://)

## Buy me a coffee

-  ☕ [Wechat-pay](https://i.imgur.com/i3IUBSj.png)
- 🍕 [Paypal-pay](https://i.imgur.com/OuFAvpD.png)
- 🍰[Touch ‘n Go](https://i.imgur.com/KF9Rji9.jpg)

repository: teawlili/atomy

repo_name: teawlili/atomy


text:
Demonstrating interactions between AEAs and and an instance of Aries Cloud Agent (ACA).

### Discussion

This demo illustrates how an AEA may connect to an Aries Cloud Agent (ACA).

Hyperledger Aries Cloud Agent is a foundation for building self-sovereign identity/decentralized identity services using verifiable credentials. You can read more about Hyperledger here and the Aries project here.

In this demo, you will learn how an AEA could connect with an ACA, to send it administrative commands (e.g. issue verifiable credential to another AEA) and receive DID related notifications (e.g. receive a request for a credential proof from another AEA).

## Preparation instructions

### Dependencies

Follow the Preliminaries and Installation sections from the AEA quick start.

## ACA

### Install ACA

Install Aries cloud-agents (run `pip install aries-cloudagent` or see here) if you do not have it on your machine.

## Run the demo test

Run the following test file using PyTest:

``` bash
pytest tests/test_examples/test_http_client_connection_to_aries_cloud_agent.py
```

You should see that the two tests pass.

## Demo code

Take a look at the test file you ran above `tests/test_examples/test_http_client_connection_to_aries_cloud_agent.py`.

The main class is `TestAEAToACA`. The `setup_class` method initialises the scenario.

``` python
@pytest.mark.asyncio
class TestAEAToACA:
    """End-to-end test for an AEA connecting to an ACA via the http client connection."""

    @classmethod
    def setup_class(cls):
        """Initialise the class."""
        cls.aca_admin_address = "<IP_ADDRESS>"
        cls.aca_admin_port = 8020
```

The address and port fields `cls.aca_admin_address` and `cls.aca_admin_port` specify where the ACA should listen to receive administrative commands from the AEA.

The following runs an ACA:

``` python
cls.process = subprocess.Popen(  # nosec
            [
                "aca-py",
                "start",
                "--admin",
                cls.aca_admin_address,
                str(cls.aca_admin_port),
                "--admin-insecure-mode",
                "--inbound-transport",
                "http",
                "<IP_ADDRESS>",
                "8000",
                "--outbound-transport",
                "http",
            ]
        )
```

Now take a look at the following method. This is where the demo resides. It first creates an AEA programmatically.

``` python
    @pytest.mark.asyncio
    async def test_end_to_end_aea_aca(self):
        # AEA components
        ledger_apis = LedgerApis({}, FetchAICrypto.identifier)
        wallet = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(FetchAICrypto.identifier),
            default_address_key=FetchAICrypto.identifier,
        )
        http_client_connection = HTTPClientConnection(
            address=self.aea_address,
            provider_address=self.aca_admin_address,
            provider_port=self.aca_admin_port,
        )
        resources = Resources()

        # create AEA
        aea = AEA(identity, [http_client_connection], wallet, ledger_apis, resources)
```

It then adds the HTTP protocol to the AEA. THe HTTP protocol defines the format of HTTP interactions (e.g. HTTP Request and Response).

``` python
        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    )
                )
            )
        )
        http_protocol = Protocol(http_protocol_configuration, HttpSerializer())
        resources.add_protocol(http_protocol)
```

Then, the request message and envelope is created:

``` python
        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(
                self.aca_admin_address, self.aca_admin_port
            ),
            headers="",
            version="",
            bodyy=b"",
        )
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HTTP_PROTOCOL_PUBLIC_ID,
            message=HttpSerializer().encode(request_http_message),
        )
```

Note that the `performative` is set to `HttpMessage.Performative.REQUEST`, the method `GET` corresponds with HTTP GET method, and `url` is where the request is sent. This is the location the ACA is listening for administrative commands.

In the following part, the AEA is started in another thread `t_aea = Thread(target=aea.start)`, the HTTP request message created above is placed in the agent's outbox `aea.outbox.put(request_envelope)` to be sent to the ACA, and the received response is checked for success (e.g. `assert aea_handler.handled_message.status_text == "OK"`).

``` python
        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (
                aea_handler.handled_message.performative
                == HttpMessage.Performative.RESPONSE
            )
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
```

Note that the response from the ACA is caught by the `AEAHandler` class which just saves the handled message.

In the above interaction, and in general, the HTTP client connection the added to the AEA, takes care of the translation between messages and envelopes in the AEA world and the HTTP request/response format in the HTTP connection with the ACA.

repository: yangjue-han/agents-aea

repo_name: yangjue-han/agents-aea


text:
---
layout: post
title: Downtown Emergency Service Center (DESC)
subtitle: data science volunteer to help Seattle's homelessness crisis
---

Since summer of 2017 I have been volunteering at [DESC](https://www.desc.org), an incredible local non-profit that runs 17 buildings throughout Seattle where they provide permanent supportive housing to the most vulnerable of Seattle's homeless population.  Their client database includes detailed information going back decades, including residency data as well as data from clinical programs (e.g. mental health, chemical dependency).  I lead a team of two data science volunteers.  Some of the projects we have worked on:

- built a deep learning model that incorporates caseworker notes via natural language processing (NLP), along with hand-crafted features, to predict clients at risk of costly incidents involving police, ambulance, or property damage. (gensim, keras)

- wrote and presented a 27-page white paper analyzing DESC's residency data (seaborn, matplotlib)

- conducted statistical analysis on client intake assessment data, to identify gender and assessor biases


text:
---
id: plugin-relay
title: graphql-compose-relay
sidebar_label: Relay plugin
---

This is a plugin for [graphql-compose](https://github.com/graphql-compose/graphql-compose), which wraps GraphQL types with Relay specific things, like `Node` type and interface, `globalId`, `clientMutationId`.

Live demo: [https://graphql-compose.herokuapp.com/](https://graphql-compose.herokuapp.com/)

[CHANGELOG](https://github.com/graphql-compose/graphql-compose-relay/blob/master/CHANGELOG.md)

## Installation

```bash
npm install graphql graphql-compose graphql-compose-relay --save
```

Modules `graphql` and `graphql-compose` are in `peerDependencies`, so should be installed explicitly in your app. They have global objects and should not have ability to be installed as submodule.

## Example

`ObjectTypeComposer` is a [graphql-compose](https://github.com/graphql-compose/graphql-compose) utility, that wraps GraphQL types and provide bunch of useful methods for type manipulation.

```js
import composeWithRelay from 'graphql-compose-relay';
import { ObjectTypeComposer } from 'graphql-compose';
import { RootQueryType, UserType } from './my-graphq-object-types';

const rootQueryTypeComposer = new ObjectTypeComposer(RootQueryType);
const userTypeComposer = new ObjectTypeComposer(UserType);

// If passed RootQuery, then will be added only `node` field to this type.
// Via RootQuery.node you may find objects by globally unique ID among all types.
composeWithRelay(rootQueryTypeComposer);

// Other types, like User, will be wrapped with middlewares that:
// - add relay's id field. Field will be added or wrapped to return Relay's globally unique ID.
// - for mutations will be added clientMutationId to input and output objects types
// - this type will be added to NodeInterface for resolving via RootQuery.node
composeWithRelay(userTypeComposer);
```

That's all!

All mutations resolvers' arguments will be placed into `input` field, and added `clientMutationId`. If `input` fields already exists in resolver, then  `clientMutationId` will be added to it, rest argument stays untouched. Accepted value via `args.input.clientMutationId` will be transfer to `payload.clientMutationId`, as Relay required it.

To all wrapped Types with Relay, will be added `id` field or wrapped, if it exist already. This field will return globally unique ID among all types in the following format `base64(TypeName + ':' + recordId)`.

For `RootQuery` will be added `node` field, that will resolve by globalId only that types, which you wrap with `composeWithRelay`.

All this annoying operations is too fatigue to do by hands. So this middleware done all Relay magic implicitly for you.

## Requirements

Method `composeWithRelay` accept `ObjectTypeComposer` as input argument. So `ObjectTypeComposer` should meet following requirements:

- has defined `recordIdFn` (function that from object of this type, returns you id for the globalId construction)
- should have `findById` resolver (that will be used by `RootQuery.node`)

If something is missing `composeWithRelay` throws error.

## License

[MIT](https://github.com/graphql-compose/graphql-compose-relay/blob/master/LICENSE.md)

repository: graphql-compose/graphql-compose

repo_name: graphql-compose/graphql-compose


text:
# Installation
> `npm install --save @types/node-notifier`

# Summary
This package contains type definitions for node-notifier ( https://github.com/mikaelbr/node-notifier ).

# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-notifier

Additional Details
 * Last updated: Mon, 11 Mar 2019 18:27:03 GMT
 * Dependencies: @types/node
 * Global values: none

# Credits
These definitions were written by Qubo <https://github.com/tkQubo>, Lorenzo Rapetti <https://github.com/loryman>.

repository: CarlosETB/Pokedex

gha_language: Java

repo_name: CarlosETB/Pokedex


text:
---
########### THIS FILE IS AUTO GENERATED - ANY CHANGES WILL BE VOID ###########
title: itm
description: OpenBB Telegram Command
---

# itm

This command allows the user to retrieve a list of In-the-Money options for the stock ticker symbol sorted by expiry date. The command compares the amount of Calls and Puts In-the-Money vs Out-the-Money and gives a total.

### Usage

```python wordwrap
/itm ticker
```

---

## Parameters

| Name | Description | Optional | Choices |
| ---- | ----------- | -------- | ------- |
| ticker | Stock Ticker | False | None |

---

## Examples

```
/itm AMD
```

---

repository: conrad-strughold/GamestonkTerminal

branch_name: refs/heads/main

repo_name: conrad-strughold/GamestonkTerminal


text:
[![Throughput Graph](https://graphs.waffle.io/Longri/cachebox3.0/throughput.svg)](https://waffle.io/Longri/cachebox3.0/metrics/throughput)

[![Waffle.io - Columns and their card count](https://badge.waffle.io/Longri/cachebox3.0.svg?columns=all)](https://waffle.io/Longri/cachebox3.0)
[![Build Status](https://travis-ci.org/Longri/cachebox3.0.svg?branch=master)](https://travis-ci.org/Longri/cachebox3.0)


text:
[![Build Status](https://travis-ci.org/rust-vmm/kvm-bindings.svg?branch=master)](https://travis-ci.org/rust-vmm/kvm-bindings)
[![Crates.io](https://img.shields.io/crates/v/kvm-bindings.svg)](https://crates.io/crates/kvm-bindings)
![](https://img.shields.io/crates/l/kvm-bindings.svg)
# kvm-bindings
Rust FFI bindings to KVM generated using
[bindgen](https://crates.io/crates/bindgen). It currently has support for the
following target architectures:
- x86
- x86_64
- arm
- arm64

# Usage
First, add the following to your `Cargo.toml`:
```toml
kvm-bindings = "0.1"
```
Next, add this to your crate root:
```rust
extern crate kvm_bindings;
```
By default `kvm-bindings` will export a wrapper over the latest available kernel
version (4.20), but you can select a different version by specifying it in your
toml:
```toml
kvm-bindings = { version = "0.1", features = ["kvm_v4_20_0"]}
```
In the `kvm-bindings` crate each feature maps to exactly one Linux version
as follows:
- `kvm_v4_14_0` contains the bindings for the Linux kernel version 4.14
- `kvm_v4_20_0` contains the bindings for the Linux kernel version 4.20

repository: princeton-sns/kvm-bindings

gha_language: Rust

repo_name: princeton-sns/kvm-bindings