If we think about the kind of code we've written that used string
s, we can see that we
used several operators:
cin >> s // use the input operator to read a string cout << s // use the output operator to write a string s[i] // use the index operator to access a character s1 + s2 // use the addition operator to concatenate two strings
All these are binary operators, so that if we define them as functions, each function will
have two parameters, one of which may be implicit if the function is a member. As we
saw in §11.2.4/192, names for overloaded operators are formed by appending the operator
symbol to the word operator
. Hence, operator>>
is the name of the function that
overloads the input operator, operator[]
names the index operation, and so on.
We may as well start with the index operator, because in §11.2.4/192, we've already seen how to implement this operation, and we know that it must be a member of the class:
class Str { public: // constructors as before char& operator[](size_type i) { return data[i]; } const char& operator[](size_type i) const { return data[i]; } private: Vec<char> data; };
The index operators just forward their work to the corresponding Vec
operations. It is
worth noting that, as we did for class Vec
, we define two versions of the index
operator—one that can operate on const
objects and the other that cannot. By returning
a reference to the character, the nonconst
version gives write access to the character that
it returns. The const
version returns a reference to a const char
, thereby preventing
the user from writing to the underlying character. We return const char&
instead of a
plain char for consistency with the standard string
class.
What about the other operators? The most interesting problem in defining these functions
is deciding whether these operations should be members of the Str
class. It turns
out that answering this question involves different issues for each of these kinds of operators.
We will address input-output operators first; then, in §12.3.3/218, we'll look at the
concatenation operator.
In §9.2.2/159, we had to decide whether compare should be a member of
Student_info
. We suggested that one way to decide was to ask whether the operation
affects the state of the object. The input operator certainly changes its object's state. After
all, we use the input operator to read a new value into a preexisting object. Accordingly,
we might think that we should make the input operator a member of the Str
class. However,
doing so won't work as we might expect.
To see why, we have to remember (§11.2.4/192) how the operands of an expression are bound to the parameters of the overloaded operator function. For a binary operation, the left operand is always bound to the first parameter, and the right operand is bound to the second. In the case of member operator functions, the first parameter (the left operand) is always the one that is passed implicitly to the member function. Thus,
cin >> s;
is equivalent to
cin.operator>>(s);
which calls the overloaded >>
operator defined for the object cin
. This behavior implies
that the >>
operator must be a member of class istream
.
Of course, we do not own the definition of istream
, so we cannot add this operation
to it. If instead we make operator>>
a member of Str
, then our users would have to
invoke the operation on behalf of a Str
:
s.operator>>(cin);
or, equivalently,
s >> cin;
which would flout the conventions used throughout the library. Therefore, we can conclude that the input—and, by analogy, the output—operator must be a nonmember.
We can now update our Str
class appropriately, by adding declarations for the input
and output operators to Str.h
:
std::istream& operator>>(std::istream&, Str&); // added std::ostream& operator<<(std::ostream&, const Str&) ; // added
The output operator is easy to write: It will iterate through the Str
, writing a single character at a time:
ostream& operator<<(ostream& os, const Str& s) { for (Str::size_type i = 0; i != s.size(); ++i) os << s[i]; return os; }
The only catch is that this usage forces us to give Str
a size function:
class Str { public: size_type size() const { return data.size(); } // as before };
Despite the simple form of the output operator, we should understand it thoroughly.
Each time through the loop, we invoke the Str::operator[]
to fetch a character to
write. That operator, in turn, calls Vec::operator[]
to obtain the actual value from the
underlying vector
. Similarly, each time through the loop, we determine the size of our
Str
object by calling s.size()
, which calls the size member of the underlying Vec
object to determine that object's size.
The input operator isn't much harder to write than the output operator. It needs to read and remember characters from the input stream. Each time we call the input operator, it should read and discard any leading whitespace, and then read and remember characters until it hits whitespace or end-of-file. Our input operator is a bit simplified—it ignores some subtleties of the input-output library that are beyond the scope of this book—but it does what we need done:
// this code won't compile quite yet istream& operator>>(istream& is, Str& s) { // obliterate existing value(s) s.data.clear(); // read and discard leading whitespace char c; while (is.get(c) && isspace(c)) ; // nothing to do, except testing the condition // if still something to read, do so until next whitespace character if(is) { do s.data.push_back(c); // compile error!, data is private while (is.get(c) && !isspace(c)); // if we read whitespace, then put it back on the stream if (is) is.unget(); } return is; }
First we'll explain this function; then we'll explain why it doesn't compile.
We start by discarding any previous value that data
might have, because reading into
a Str
should obliterate whatever data were present. Next we need to read characters,
one at a time, from the given stream, until we encounter a character that is not white-
space. Because we need to be able to detect whether we just read a whitespace character,
we use the get function on the input stream. Unlike the overloaded >>
operators, which
ignore whitespace, the get function reads and returns whatever character is next in the
stream, including whitespace. Therefore, the while
loop reads characters until it finds
one that is not whitespace, or it runs out of input. If the character we read was white-
space, then there is nothing to do but read again, so the body of the while
is empty.
The if test checks whether we exited the while
because we read a nonwhitespace
character or because we ran out of input. If the former, we want to read characters until
we hit whitespace again, appending each character that we read to data
. We do so in the
next statement, which is a do while
loop (§7.4.4/136) that arranges to append to data
the character that we had already read in the previous while
loop, and then continues
reading until we run out of input or hit a whitespace character. Each time it reads a nonwhitespace
character, it uses push_back
to append that character to data
.
We could fall out of the do while
either because we can no longer read from is
, or
because we encountered a whitespace character. If the latter, we have read one character
too many, which we put back onto the input stream by calling is.unget()
. The unget
function undoes the most recent get by backspacing the input stream by one character.
After the call to unget
, the stream behaves as if the previous get had never been done.
As the comments indicate, this code fails to compile. The problem is that operator>>
is not a member of class Str
, so it cannot access the data
member of s
. We faced a similar
problem in §9.3.1/161, when the compare
function needed access to the name
member
from Student_info
objects. We solved that problem by adding an accessor function. In
this case, giving read access to data
isn't enough: The input operator needs to be able to
write data
, not just read it. The input operator is a part of our general Str
abstraction,
so giving it write access to data
is fine. On the other hand, we do not want all users to
have write access to data
, so we cannot solve our problem by adding a public
member
that would let operator>>
(and therefore any user) write to data
.
Rather than adding a (public
) access function, we can say that the input operator is a
friend of class Str
. A friend
has the same access rights as a member. By making the
input operator a friend, we can allow it, along with our member functions, to access the
private
members of class Str
:
class Str { friend std::istream& operator>>(std::istream&, Str&); // as before };
We've added a friend
declaration to class Str
. This declaration says that the version of
operator>>
that takes an istream&
and a Str&
may access the private
members of
Str
. Once we have added this declaration to Str
, our input operator will compile.
A friend
declaration may appear at any point in the class definition: It makes no difference
whether it follows a private
or public
label. Because a friend function has
special access privileges, it is part of the interface to the class. Therefore, it makes sense to
group friend
declarations at the beginning of the class definition, near the public
interface
for the class.
What remains of our work on the Str
class is to implement the +
operator. Before we can
do so, we must make several decisions: Should the operator be a member? What are its
operands' types? What type should it return? As we shall see, these questions turn out to
have subtle implications.
For now, let's make some initial guesses about the answers. First, we know that we
want to be able to concatenate values that are of type Str
. Second, we can observe that
concatenation does not change the value of either operand. These facts suggest that there
is no particular reason to decide to make the operator a member function. Finally, we
know that we want to be able to chain several concatenations into a single expression in
order to allow expressions such as
s1 + s2 + s3
where s1, s2
, and s3
all have type Str
. This usage suggests that the operator should
return a Str
.
These decisions imply that we should implement concatenation as a nonmember:
Str operator+(const Str&, const Str&);
Before we launch into implementation, a bit of thought might suggest that if we offer
operator+
, we might want to provide our users with operator+=
as well. That is,
we'd like to let our users assign to s
the value obtained by concatenating s and s1
in
either of these forms:
s = s + s1; s += s1;
It turns out that the most convenient way to implement operator+
is to implement
operator+=
first. Unlike the simple concatenation operator, the compound version
changes its left operand, so we make it a member of the Str
class. After adding definitions
for the new concatenation operations, our final Str
class looks like this:
class Str { // input operator implemented in §12.3.2/216 friend std::istream& operator>>(std::istream&, Str&); public: Str& operator+=(const Str& s) { std::copy(s.data.begin(), s.data.end(), std::back_inserter(data)); return *this; } // as before typedef Vec<char>::size_type size_type; Str() { } Str(size_type n, char c): data(n, c) { } Str(const char* cp) { std::copy(cp, cp + std::strlen(cp), std::back_inserter(data)); } template<class In> Str(In i, In j) { std::copy(i, j, std::back_inserter(data)); } char& operator[](size_type i) { return data[i]; } const char& operator[](size_type i) const { return data[i]; } size_type size() const { return data.size(); } private: Vec<char> data; }; // output operator implemented in §12.3:2/216 std::ostream& operator<<(std::ostream&, const Str&); Str operator+(const Str&, const Str&);
Because we use a Vec
for our underlying storage, implementing operator+=
is trivial:
We call copy to append a copy of the right operand to the Vec
that is the left operand. As
usual for assignment, we return a reference to the left object as our result.
Now we can implement operator+
in terms of operator+=
:
Str operator+(const Str& s, const Str& t) { Str r = s; r += t; return r; }
Recall that concatenation is a nonmember function that will create a new Str
. We create
this new Str
by initializing a local variable named r
to be a copy of s
. That initialization
uses the Str
copy constructor. Next, we invoke the +=
operator on r
to concatenate t
,
and then we return r
(again through an implicit call to the copy constructor) as the result.
We have defined the concatenation operator
to take operands of type const Str&
. What
about expressions that involve character pointers? For example, what if we wanted to use
our Str
class to implement the program from §1.2/12? That
program contained code that looked like
const std::string greeting = "Hello, " + name + "!";
where name
is a string
. Analogously, we'd like to be able to write
const Str greeting = "Hello, " + name + "!";
where name
is now a Str
.
We know that the +
operator is left-associative, which means that evaluating this
expression is equivalent to evaluating
"Hello, " + name
and applying the +
operator to the result and "!"
. In other words, the expression is
equivalent to
("Hello, " + name) + "!"
By breaking down the expression into its components, we can see that we have two different
forms of +
. In one case, we pass a string literal as the first operand and a Str
as the
second. In the other, the left operand is a Str
obtained as the result of a concatenation,
and the right operand is a string literal. Thus, in each case we are calling +
on a const char*
and a Str
in some order.
In §12.3.3/218, we defined +
with arguments of type Str
, not const char*
. However,
we know from §12.2/213 that by defining a constructor that takes a const char*
,
we also defined a conversion operator from const char*
to Str
. Evidently, our Str
class handles these expressions already. In each case, the compiler will convert the const char*
argument to type Str
, and then it will invoke operator+
.
It is important to understand the implications of conversion operations. For example,
Str greeting = "Hello, " + name + "!";
gives greeting
the same value as if we had written
Str temp1('Hello, "); // Str::Str(const char*) Str temp2 = temp1 + name; // operator*(const Str&, const Str&) Str temp3("!") // Str::Str(const char*) Str greeting = temp2 + temp3; // operator*(const Str&, const Str&)
Seeing all these temporaries, we can imagine that this approach might be expensive. In
practice, because of the perceived cost of generating temporaries, commercial string
library implementations often take the more tedious route of defining specific versions of
the concatenation operator for every combination of operands, rather than relying on
automatic conversions.
It is important to appreciate the role of conversions in the design of binary operators. If a class supports conversions, then it is usually good practice to define binary operators as nonmember functions. By doing so, we preserve symmetry between the operands.
If an operator is a member of a class, then that operator's left operand cannot be
the result of an automatic conversion. The reason for this restriction is so that when a programmer
writes an expression such as x + y
, the compiler does not have to examine every
type in the entire program to discover whether it is possible to convert x
to a type that has
a member named operator+
. Because of the restriction, the compiler (and the programmer)
has to look only at nonmember operator+
functions and at operator+
functions
that are members of the class of x
.
The left operand of a nonmember operator, and the right operand of any operator, follow
the same rules as any ordinary function argument: The operand can be of any type
that can be converted to the parameter type. If we make the binary operator a member
function, we have introduced an asymmetry with respect to its operands: The right
operand can be the result of an automatic conversion, but the left operand cannot. Such
asymmetries are fine for intrinsically asymmetric operators such as +=
, but in the context
of symmetric operands, they are confusing and error prone. It is almost always desirable
to treat both operands of such operators equivalently, which we can arrange only by making
the operator a nonmember function.
In the case of the assignment versions of binary operators, we want to constrain the left operand to be of the class type. Otherwise, what would happen? If we allowed conversions for the left operand, then we might convert that operand to the class type and assign a new value to the resulting temporary. Because that value would be a temporary object, once we completed the assignment we would have no way to access the object to which we had just assigned! Therefore, like the assignment operator itself, all of the compound- assignment operators should be members of the class.


|
Interface Summary |
| ApolloPanelHolderI |
An interface that holds ApolloPanels. |
| ApolloPanelI |
This was invented to eliminate all of the casting that
was going on. |
| ContainerViewI |
|
| DragViewI |
Defines the methods required for dragging. |
| DrawableTierManagerI |
|
| DropTargetViewI |
Interface defining methods for handling a drop in a View |
| FeatureTierManagerI |
|
| KeyViewI |
An interface representing a View object which accepts keyboard input. |
| ManagedViewI |
An interface representing a View object which has defined
extents eg a start and end base and has a tier manager to
go with it. |
| PickViewI |
An interface representing a View object which contains
selectable Drawables. |
| PixelMaskI |
A PixelMaskI can set pixels to be masked at a given level/yindex
and be queried for a masking range at a given level |
| PopupViewI |
An interface representing a View object which contains
selectable Drawables. |
| RevCompListener |
|
| SelectViewI |
|
| StrandVisibilityListener |
At the moment only for becoming visible, if need event for hiding as well
then add another method (or variable)
This is presently pase' and not used - was used by ViewMenu, but
ViewMenu.ViewMenuListener now does the same thing in an easier fashion. |
| TierViewI |
|
| ViewI |
An interface representing a View object which has defined
extents eg a start and end base. |
|
Class Summary |
| AnnotationView |
A view to display annotations in |
| ApolloLayoutManager |
An Abstract base ApolloLayoutManager class |
| ApolloPanel |
This class is a container to hold and manage the various Views
which are needed by Apollo. |
| ColumnApolloLayout |
An ApolloLayoutManager which lays out its views in a single column. |
| ContainerView |
|
| DiscreteGraphView |
This is a view for a discrete graph |
| DragView |
A FeatureView which has extra methods to handle dragging. |
| DrawableTierManager |
|
| FastClippingGraphics |
|
| FeatureTier |
A Tier to hold features. |
| FeatureTierManager |
Extended from TierManager but still abstract (no layoutTiers methods)
Implements FeatureTierManagerI which implements ControlledObjectI
extends DrawableTierManager which extends TierManager which is where the
ControlledObjectI methods are implemented. |
| FeatureView |
FeatureView is a View for displaying DrawableSeqFeatures and
DrawableFeatureSets (and maybe other Drawables),
in linear tiers. |
| GraphView |
|
| GuideLine |
|
| LaidoutViewContainer |
|
| LinearView |
A basic, non useful, implementation of the LinearViewI interface. |
| ManagedView |
An extension of LinearView for drawing analysis results. |
| NavigationBar |
This panel appears in the apollo frame and
lets the user navigate to a new region, going left or right or zooming out from
current coordinates, and selecting new chromosomes. |
| PixelMask |
Class which records which pixels in a tier have been drawn already, used in
drawing optimisation. |
| PlotUtil |
|
| ResultView |
An extension of FeatureView for drawing analysis results. |
| Rubberband |
Draws and controls the rubberband used for selections. |
| RubberbandRectangle |
A rectangular rubberband. |
| ScaleView |
Draw a scale line, BUT also draws sequence, and allows dragging of hairpins. |
| ScrollAdjustedView |
|
| Sites |
Sites holds an array of integers which are the base positions for each site
in a given frame and strand. |
| SiteTier |
|
| SiteTierManager |
|
| SiteView |
A view to display sites (start and stop codons). |
| SplitterView |
|
| StrandedZoomableApolloPanel |
The class which controls and renders the main feature display panel, containing an
AnnotationView, ResultView and SiteView for each strand. |
| TierView |
This class is the base class for FeatureView and SiteView. |
| TranslationView |
Not used - work in progress or pase? |


DOGMA A film review by Mark R. Leeper
CAPSULE: Kevin Smith has put together an extremely ambitious comedy fantasy based on Christian doctrine. The film is occasionally very clever, but too often it is heavy-handed. Ultimately this uneven theological farce fails because he has thrown too much in and often communicates it poorly to the audience. Between heavy violence and heavier ideas, between gross-out humor and bizarre satire, the film tries to be too many things. Eventually DOGMA falls apart of its own weight. Smith is not yet the filmmaker it would take to make this whole film work. Rating: 5 (0 to 10), low +1 (-4 to +4)
One of my favorite comedies of all time is Stanley Donan's BEDAZZLED featuring the writing and acting of Peter Cook and Dudley Moore. It is a retelling of the story of Faust in modern terms.  Films rarely get into humorous examinations of anything so abstract as religious belief and in the deft hands of Cook and Moore it made for a really original comedy. I hardly expected a film along these lines from relative newcomer Kevin Smith, with only the films CLERKS, MALL RATS, and CHASING AMY under his belt. None of these films indicated any inclination toward a far-out fantasy with a humorous take on religious belief, one along the lines of BEDAZZLED. When I heard that was what he had done I came hoping for a lot and I got a lot, but not the same lot. Smith wrote himself a script that a many-year veteran director might have found overly ambitious. There is just too much in the film for it to all hang together. One has the feeling that any fleeting idea Smith had stuck to the script like flypaper. Somehow feces monsters, heavy violence, deep theological discussion, fantasy, and an action thriller plot just do not all fit comfortably in the same film.
The plot is convoluted and often the viewer has to listen quick to get the concepts. Apparently two fallen angels Loki and Bartleby (played by Matt Damon and Ben Affleck) have found a loophole in God's rules so that they can get back into heaven, though they may have to destroy the world to do it. An abortion clinic worker Bethany (Linda Fiorentino) is chosen by the archangel Metatron (Alan Rickman) to stop the two angels. Soon she is traveling with Kevin Smiths repeating characters Jay and Silent Bob. In DOGMA we learn they are prophets of the Lord. This may limit their usefulness to Smith in future films. They are also joined by Rufus (Chris Rock), the 13th Apostle whom we never heard about in the New Testament because he was black. The fact that the film also suggests that Christ was also black requires some fancy explaining. What Smith should have done was drop one idea of the other and not was screen time reconciling the two ideas. There is enough explaining that has to be done in this film as it is. George Carlin has a small role as a Catholic Cardinal with a concept for popularizing religion. It is possible that the ideas for this sequence were all Smith's or perhaps he was writing a pastiche in the style of George Carlin. But the whole George Carlin Buddy Jesus sequence is very, very much in the style of Carlin and it would hardly surprise me to find out that the long-time iconoclastic comedian had a lot of input on his sequence or even wrote it himself. Tiny roles go to Bud Cort and Janeane Garofalo. It is not clear why name actors were needed in such tiny roles.
With CHASING AMY Kevin Smith showed that he could write characters with some emotional complexity. Unfortunately DOGMA does not take the time for developing characters in a meaningful way. The acting and seems much cruder in this film than in CHASING AMY. Some surprisingly crude production values betray the low budget this film must have had. Particularly noticeable early in the film words seem to fit lips very poorly as if the in studio dubbing were not competently done. The plot calls for special effects but they range from adequate to crude.
The script is full of interesting ideas but frequently they go by at lightning speed and such basic concepts as why the action is taking place now rather than at some other point of the past or future seem too quickly glossed over. Consideration should have been given how to convey the ideas better. Inconsistencies mix into Christian theology in the form of a muse from Greek mythology and the Norse god Loki. Humor is always subjective and there were members of the audience laughing, but for me much of the levity for me fell flat and was not even germane to the subject matter (e.g. Wisconsin cheese hats). Smith needs to be more selective in the humor included. Smith might well have considered letting less be more.
DOGMA comes close to subject matter I would have greatly enjoyed. A little refinement of the script could have made this like BEDAZZLED, an intelligent comedy to be savored for years. It still has a lot to offer, but I rat it only a 5 on the 0 to 10 scale and a low +1 on the -4 to +4 scale. DOGMA's reinterpretation of theology is causing the same protest that Milton or Dante might face if they were around today. The upside is that the protests appear for now to be low-key and generally ignored.
Mark R. Leeper<EMAIL_ADDRESS>Copyright 1999 Mark R. Leeper
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Cascading Style Sheets is a style sheet language used for describing the presentation of a document written in a markup language such as HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.
JS
JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.
CPP
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.
JAVA
Java is a widely used programming language expressly designed for use in the distributed environment of the internet.
PYTHON
Python is a dynamic, high level, free open source and interpreted programming language. It supports object-oriented programming as well as procedural oriented programming.


Two weeks ago I did an MSDN Briefing about Windows Communication Foundation. While we are still post-processing the recording for this briefing we wanted to make the downloads available, earlier. Here you can find the material from the briefing:
Click here to download the slides.
Click here to download the demos.
If you have any questions feel free in getting back to me.


Members
(constant) checkboxUpdate
handle checkbox changes
(constant) clearStartInput
clears the start input
(constant) clearTargetInput
clears the target input
(constant) pushStartSystemCoordinates
pushes the start system coordinates
(constant) pushTargetSystemCoordinates
pushes the target system coordinates
(constant) SubmitCoordsFailure
fired when an error is returned from the backend
(constant) submitCoordsRequest
doesn't do anything, fires whenever submitCoords is requested
(constant) submitCoordsSuccess
fired when a response is returned from the backend
Methods
AppSelectionBtn(caption, description)
Button for selecting fitting method
Parameters:
| Name | Type | Description |
|---|---|---|
caption |
string | Caption that shows the type of transformation |
description |
string | Displays more details about the transformation } |
PointsInput(onDrop)
component that holds react-dropzone to drop .txt files and handle them
Parameters:
| Name | Type | Description |
|---|---|---|
onDrop |
function | functionality when file is dropped |
PointsInputTable3D6W(systemPoints, checkboxesDisplay, handleChange, handleDeleteDataInput)
table to display the input values from PointsInput,
with checkboxes to select which points to use
Parameters:
| Name | Type | Description |
|---|---|---|
systemPoints |
Array | array of points |
checkboxesDisplay |
Object | style for checkboxes, if start-input: "display: none" |
handleChange |
function | handles checkbox clicks |
handleDeleteDataInput |
function | handles deletion of points input |
submitCoords(dispatch, getState) → {Object}
sends an axios request to the backend
Parameters:
| Name | Type | Description |
|---|---|---|
dispatch |
dispatchCallback | callback that handles dispatching of the action |
getState |
getStateCallback | callback that gets current state |
Returns:
response from backend or error message
- Type
- Object
Type Definitions
dispatchCallback()
Callback for dispatching action
getStateCallback()
Callback for getting current state


Your age:
Your weight:
Dynamic min & max
Select min ({{ dynamic_min }}):
Select max ({{ dynamic_max }}):
Slider with min & max dynamically defined above with two sliders
Deferred value update
Show value in handle
Show value in handle with deferred update
Increments with snapping
Increments with snapping, min is not zero, show value in handle, as max value for next slider
Increments with snapping, min is not zero, show value in handle, deferred value update


Sever Sent Events Demo
This data is coming from the server. It is not a timer running in the browser.


Simple client/server architecture with Docker Compose
This post builds on the previous one to create a simple client/server architecture for a web-app developed with Flask, for the back-end, and RequireJS, for the front-end. These two components will be incapsulated with Docker Compose in order to be ready for deployment.
Architecture
The web-app is composed by a back-end, made of a main Flask REST service and an additional Blueprint, and a front-end module developed with RequireJS. A Docker module will be created for both the client and the server side of the application.
The two will be linked together through Docker Compose and the final user experience will be not affected by this setup.
Source code
The source code of all the projects used in this tutorial is available on GitHub: feel free to download, fork and/or star it!
| Project | URL |
|---|---|
| Simple Flask UI | https://github.com/Kalimaha/simpleflaskui |
| Simple Flask Docker Composer | https://github.com/Kalimaha/simpleflaskdocker_composer |
RequireJS client
RequireJS is a JavaScript file and module loader that
implements the AMD.
The simple client module implemented for this example has a main.js
file,
that defines the required libraries and starts the component,
and an application.js
script that implements the business logic of the
front-end. The filesystem of the project is shown in the following schema:
simple_flask_ui/
├── css
│ ├── bootstrap.min.css
│ ├── select2.min.css
│ ├── simple-flask-ui.css
│ └── sweet-alert.css
├── html
│ └── templates.hbs
├── index.html
├── js
│ ├── application.js
│ ├── main.js
│ └── libs
│ └── 3rd Party JavaScript Libraries
└── nls
└── JavaScript files to implement I18N
As specified in the index.html
file, the application loads RequireJS and
execute the main.js
file:
<script data-main='js/main' src='js/libs/require.js'></script>
This script declares the implemented modules (in paths), loads the required
libraries (through the baseUrl
), specifies their mutual dependencies
(in shim) and starts the application.js
module:
require.config({
baseUrl: 'js/libs',
paths: {
application: '../../',
APPLICATION: '../application'
},
shim: {
bootstrap: ['jquery'],
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
highcharts: ['jquery'],
underscore: {
exports: '_'
}
}
});
require(['APPLICATION'], function(APP) {
/* Initiate components. */
var app = new APP();
/* Initiate the application. */
app.init();
});
The application.js
module loads a Handlebars template containing an input
field and two buttons: the first one will invoke the main REST service, while
the second is linked to the Blueprint. The base URL for the AJAX calls has
been set to http://localhost:5000/
, that is the address exposed by Docker
for Flask, as seen in the previous post.
The business logic of the front-end is very simple and is described in the
schema below:
Docker Compose
As per the official documentation "Compose is a tool for defining and running
multi-container applications with Docker". The
Simple Flask Docker Composer
project contains two folders, one with the definition of the front-end
Docker image, one for the back-end, and a
docker-compose.yml
file that tells
Docker Compose how to handle the two images.
The client side image is built starting from Ubuntu,
to which Apache and the source code are then added:
# Create a container from Ubuntu.
FROM ubuntu:14.04
# Update Ubuntu repositories.
RUN apt-get update
# Install Apache.
RUN apt-get -y install apache2
# Install unzip.
RUN apt-get -y install wget
RUN apt-get -y install unzip
# Get and unzip sources.
RUN wget https://github.com/Kalimaha/simple_flask_ui/archive/master.zip
RUN unzip master.zip
RUN mv simple_flask_ui-master/ /var/www/html/simple_flask_ui
The final step is the definition of the docker-compose.yml
file, in which we
specify that there are two volumes called client and server. For each module
Docker Compose will run the Docker build:
build: ./server
and
build: ./client
Each volume specifies which are the ports that need to be exposed: 5000
for
the server and 9999
for the client. In addition to that for each volume
there is a command instruction specified, that will be executed once Docker
Compose is up. Finally, the links directive tells Docker Compose to link the
server and the client volumes. The complete docker-compose.yml
file is shown
below:
server:
build: ./server
ports:
- "5000:5000"
command: "/deployment/env/bin/python /deployment/start.py"
links:
- client
client:
build: ./client
ports:
- "9999:80"
command: "/usr/sbin/apache2ctl -D FOREGROUND"
Time to build the project:
docker-compose build
and finally run it:
docker-compose up
Once the project is up and running it is possible to visit the UI at the following URL: http://localhost:9999/simpleflaskui.


Run the First JUnit Test
Goal
The goal of this lab is, that you build your first JUnit test case for a BPMN 2.0 process with the help of camunda-bpm-assert.
Short description
- Strip down the process to the happy path. Morph the user task to a manual task. Set the conditions to
true
andfalse
. - Prepare your content assist to the camunda-bpm-assert library.
- Fill the generated InMemory JUnit test and assert that a started process instance is ended right after the start.
- Have a look at the Camunda BPM Assert Library User Guide to get more information about the test library.
- Run the JUnit test to see the green bar. Check the Output of the scipts in the console.
Detailed steps
- Edit your BPMN model in the Modeler and strip down the process to the happy path. Morph the user task to a manual task. Set the conditions on the sequence flows to
${true}
and${false}
. - Two JUnit test cases have been created in
src/test/java
. Open and inspect the ‘InMemoryH2Test’. - In Eclipse go to
Window -> Preferences -> Java -> Editor -> Content Assist -> Favorites -> New Type...
and add the following type:org.camunda.bpm.engine.test.assertions.ProcessEngineTests
- Change the happy path test method that deploys the process using the @Deyployment annotation and start a process instance using the Runtime Service, which is available via
runtimeService()
- Add an assert to verify, that the process instance is ended: You can use this code:
assertThat(processInstance).isEnded();
- Have a look at the Camunda BPM Assert Library User Guide to get more information about the test library.
- Run the JUnit test (right click on the method and select
Run As -> JUnit Test
). You should get a green bar. Can you see the ouput of your script task in the console?


Atletico deny Rakitic rumours
by BeSoccerIvan Rakitic is not on Atletico Madrid's agenda. That is at least what 'Mundo Deportivo' says. According to this source, 'Los Colchoneros' have not thought about making any offer to Barca for the Croat.
The Catalan paper makes one thing clear: Rakitic is not going to end up at the Wanda Metropolitano. At least not at the moment.
Atletico will not make any attempt to sign Rakitic. The thing is not that they do not like the footballer, the problem is that they cannot sign him.
La Liga's salary cap would apparently prevent Atletico from signing anyone in January.
Featured links
- Ballon d'Or winner already been decided
- The latest football transfers news and rumours
- Possible 'Clasico' in the Spanish Supercup final
- Who has the most free-kicks goals: Messi or Cristiano?
Therefore, Atletico have apparently ruled out the arrival of reinforcements for the winter transfer window. No new faces are expected at the Metropolitano.
In addition, 'Mundo Deportivo' says that it is not Atletico's priority to sign midfielders. They have already got Thomas, Herrera, Koke, Saul and Llorente. They have that area of the field well covered.
In recent days, there was talk of Atletico putting in an offer for Barcelona's Rakitic. 'Vamos' said that the team from Madrid were willing to put in 40 million euros. However, the Catalan press strongly deny that Barcelona will be sent this offer.


--- ---
|
TGUI
v0.7-dev
|
Public Member Functions | |
| ButtonRenderer (Button *button) | |
| Constructor. More... | |
| virtual void | setProperty (std::string property, const std::string &value) override |
| Change a property of the renderer. More... | |
| virtual void | setProperty (std::string property, ObjectConverter &&value) override |
| Change a property of the renderer. More... | |
| virtual ObjectConverter | getProperty (std::string property) const override |
| Retrieve the value of a certain property. More... | |
| virtual std::map< std::string, ObjectConverter > | getPropertyValuePairs () const override |
| Get a map with all properties and their values. More... | |
| void | setTextColor (const Color &color) |
| Changes the color of the text. More... | |
| void | setTextColorNormal (const Color &color) |
| Changes the color of the text in the normal state (mouse not on button). More... | |
| void | setTextColorHover (const Color &color) |
| Changes the color of the text in the hover state (mouse on button, but not pressed). More... | |
| void | setTextColorDown (const Color &color) |
| Changes the color of the text in the down state (mouse on button and left mouse button being held down). More... | |
| void | setBackgroundColor (const Color &color) |
| Changes the color of the background. More... | |
| void | setBackgroundColorNormal (const Color &color) |
| Changes the color of the background in the normal state (mouse not on button). More... | |
| void | setBackgroundColorHover (const Color &color) |
| Changes the color of the background in the hover state (mouse on button, but not pressed). More... | |
| void | setBackgroundColorDown (const Color &color) |
| Changes the color of the background in the down state (mouse on button and left mouse button being held down). More... | |
| void | setBorderColor (const Color &color) |
| Changes the color of the borders. More... | |
| void | setNormalTexture (const Texture &texture) |
| Change the image that is displayed when the mouse is not on the button. More... | |
| void | setHoverTexture (const Texture &texture) |
| Change the image that is displayed when the mouse is located on top of the button. More... | |
| void | setDownTexture (const Texture &texture) |
| Change the image that is displayed when the mouse is held down on top of the button. More... | |
| void | setFocusTexture (const Texture &texture) |
| Change the image that is drawn on top of the button image when the button is focused. More... | |
| Public Member Functions inherited from tgui::WidgetRenderer | |
| virtual | ~WidgetRenderer () |
| Virtual destructor. | |
| Public Member Functions inherited from tgui::WidgetBorders | |
| virtual void | setBorders (const Borders &borders) |
| Changes the size of the borders. More... | |
| void | setBorders (float leftBorder, float topBorder, float rightBorder, float bottomBorder) |
| Changes the size of the borders. More... | |
| void | setBorders (float width, float height) |
| Changes the size of the borders. More... | |
| virtual Borders | getBorders () const |
| Returns the size of the borders as a tgui::Borders. More... | |
|
inline |
Constructor.
| button | The button that is connected to the renderer |
|
overridevirtual |
Retrieve the value of a certain property.
| property | The property that you would like to retrieve |
Reimplemented from tgui::WidgetRenderer.
|
overridevirtual |
Get a map with all properties and their values.
Reimplemented from tgui::WidgetRenderer.
| void tgui::ButtonRenderer::setBackgroundColor | ( | const Color & | color | ) |
Changes the color of the background.
| color | New background color |
This color will overwrite the color for any state (normal, hover and down).
Note that this color is ignored when you set an image as background.
| void tgui::ButtonRenderer::setBackgroundColorDown | ( | const Color & | color | ) |
Changes the color of the background in the down state (mouse on button and left mouse button being held down).
| color | New background color |
Note that this color is ignored when you set an image as background.
| void tgui::ButtonRenderer::setBackgroundColorHover | ( | const Color & | color | ) |
Changes the color of the background in the hover state (mouse on button, but not pressed).
| color | New background color |
Note that this color is ignored when you set an image as background.
| void tgui::ButtonRenderer::setBackgroundColorNormal | ( | const Color & | color | ) |
Changes the color of the background in the normal state (mouse not on button).
| color | New background color |
Note that this color is ignored when you set an image as background.
| void tgui::ButtonRenderer::setBorderColor | ( | const Color & | color | ) |
Changes the color of the borders.
| color | New border color |
| void tgui::ButtonRenderer::setDownTexture | ( | const Texture & | texture | ) |
Change the image that is displayed when the mouse is held down on top of the button.
| texture | The new down texture |
Pass an empty texture to unset the image.
| void tgui::ButtonRenderer::setFocusTexture | ( | const Texture & | texture | ) |
Change the image that is drawn on top of the button image when the button is focused.
| texture | The new focus texture |
Pass an empty texture to unset the image.
| void tgui::ButtonRenderer::setHoverTexture | ( | const Texture & | texture | ) |
Change the image that is displayed when the mouse is located on top of the button.
| texture | The new hover texture |
Pass an empty texture to unset the image.
| void tgui::ButtonRenderer::setNormalTexture | ( | const Texture & | texture | ) |
Change the image that is displayed when the mouse is not on the button.
| texture | The new normal texture |
When this image is set, the background color property will be ignored. Pass an empty texture to unset the image, in this case the background color property will be used again.
|
overridevirtual |
Change a property of the renderer.
| property | The property that you would like to change |
| value | The new serialized value that you like to assign to the property |
| Exception | when deserialization fails or when the widget does not have this property. |
Reimplemented from tgui::WidgetRenderer.
|
overridevirtual |
Change a property of the renderer.
| property | The property that you would like to change |
| value | The new value that you like to assign to the property. The ObjectConverter is implicitly constructed from the possible value types. |
| Exception | for unknown properties or when value was of a wrong type. |
Reimplemented from tgui::WidgetRenderer.
| void tgui::ButtonRenderer::setTextColor | ( | const Color & | color | ) |
Changes the color of the text.
| color | New text color |
This color will overwrite the color for any state (normal, hover and down).
| void tgui::ButtonRenderer::setTextColorDown | ( | const Color & | color | ) |
Changes the color of the text in the down state (mouse on button and left mouse button being held down).
| color | New text color |
| void tgui::ButtonRenderer::setTextColorHover | ( | const Color & | color | ) |
Changes the color of the text in the hover state (mouse on button, but not pressed).
| color | New text color |
| void tgui::ButtonRenderer::setTextColorNormal | ( | const Color & | color | ) |
Changes the color of the text in the normal state (mouse not on button).
| color | New text color |


This is the {{ getBrandedText('product.name') }} JavaScript web client for the REST API.
Some useful references include:
Note you can observe the REST requests made by the Javascript GUI through the developers console in many browsers.This distribution includes the following features:


I am sure no one used the SDLC method anymore after the assignment, even though it is a very important step in developing software.
Using SDLC and flowcharts, students map out how their program will function. Since they are only required to create animations in Processing, many feel there is no use for a flowchart as their program is very basic and only has one function and no inputs.
Personally, I did not use a flowchart for any of my Processing programs because they are very basic in function. However, if I were to be asked to create a more complicated program, such as one with inputs and decisions, a flowchart would definitely be helpful.


Chapter 15 Prediction and Model Comparison
15.1 Prerequisites
library("tidyverse")
library("broom")
library("modelr")
##
## Attaching package: 'modelr'
## The following object is masked from 'package:broom':
##
## bootstrap
library("stringr")
15.2 Measures of Prediction
Ideally the prediction measure should be derived from the problem at hand; There is no uniformly correct measure of accuracy, so absent other costs the the analysis should include the costs of outcomes to the [analyst(https://en.wikipedia.org/wiki/Decision_theory).
Categorical variables
- Accuracy: (True Positive) + (True Negative) / (all observations)
- Precision: (True Positives) / (Classifier Positives)
- Sensitivity (recall): (True Positive) / (All positives)
- Specificity: (True negative) / (Classifier negatives)
- F1 score which balances precision (TP / (TP + FP)) and recall (TP / (TP + FN)) as (precision * recall) / (precision + recall)
Continuous Variables
- Root Mean Squared Error (RMSE): \(\frac{1}{m} \sum_i (\hat{y}_i - y_i)^2\). This is weights large errors heavily since it uses “quadratic errors”.
- Mean Absolute Devision (MAD): \(\frac{1}{m} \sum_i \|\hat{y}_i - y_i \|\). This is robust to large errors, but sensitive to the scale of the forecasts.
- Mean Absolute Percentage Error (MAPE): \(\frac{1}{m} \sum_i \| (\hat{y}_i - y_i) / y_i \|\).
15.3 Model Comparison
For comparing models in terms of prediction we want to compare them on their expected error on future data, not their in-sample error. It is easy to minimize in-sample error, use the every-observation-is-special model—have a predictor for each observation. However, that model will have no ability to predict future observations.
The fundamental problem to estimating the expected error of the model is that we don’t have the future data to evaluate it. Even if we acquire new data that did not exist at the time of fitting the model, all that can be done is to retrospectively evaluate the model performance, perhaps giving a better estimate of the expected error of the model in the future. Yet, any errors of the model with respect to any future data will still be unknown. For example the errors of model based forecasts of the popular vote share, electoral votes, or winner of the U.S. presidential election of 2016 can be transparently evaluated since they can be made prior to the data, and short of access to a time machine, the models cannot overfit or peak on future data. After the election the models can be evaluated. However, at that point it is their expected error in the next election in 2020 which is of interest, and that is still unknown.
There are two main approaches to estimating the prediction error
- cross validation: Split the data into test and training subsets. The model is fit on the training data, and predictions are made on the test data. This is often done repeatedly.
- covariance estimates: These are analytic estimates of the expected error, usually restricted to either linear models and/or only asymptotically valid. But since they do not require resampling, they are fast.
So when do these approaches work? When do measures based on in-sample data extrapolate to non-sample errors? Like pretty much every statistical method, they work when the sample used to fit the model resembles the data on which which inference is being made.
15.4 Example: Predicting the Price of Wine
The bordeaux
dataset contains the prices of vintages of Bordeaux wines sold at auction in New York, as well as the the weather and rainfall for the years of the wine. This data was used by economist, Orley Ashenfelter, to show that the quality of a wine vintage can be as measured by its price, can largely be predicted by its age, and the weather (temperature and rainfall) of its vintage year. At the time, these prediction were not taken kindly by the wine conoisseurs.[^wine]
# devtools::install_github("jrnold/datums")
bordeaux <- datums::bordeaux %>%
mutate(lprice = log(price / 100)) %>%
dplyr::filter(!is.na(price))
The data contains 27 prices of Bordeaux wines sold at auction in New York in 1993 for vintages from 1952 to 1980; the years 1952 and 1954 were excluded because they were rarely sold. Prices are measured as an index where 100 is the price of the 1961. Since prices are 7
The dataset also includes three predictors of the price of each vintage:
time_sv
: Time since the vintage, where 0 is 1983.wrain
: Winter (October–March) rainhrain
: Harvest (August–September) raindegrees
: Average temperature in degrees centigrade from April to September in the vintage year.
The first variable to consider is the age of the vintage and the price:
ggplot(filter(bordeaux, !is.na(price), !is.na(vint)),
aes(y = log(price), x = vint)) +
geom_point() +
geom_rug() +
geom_smooth(method = "lm")
Ashenfleter, Ashmore, and Lalonde (1995) run two models. All models were estimated using OLS with log-price as the outcome variable. The predictors in the models were:
- vintage age
- vintage age, winter rain, harvest rain
We’ll start by considering these models. Since we are running several models, we’ll define the model formulae in a list
mods_f <- list(lprice ~ time_sv,
lprice ~ time_sv + wrain + hrain + degrees)
and, run each model and store the results in a data frame as list column of lm
objects:
mods_res <- tibble(
model = seq_along(mods_f),
formula = map_chr(mods_f, deparse),
mod = map(mods_f, ~ lm(.x, data = bordeaux))
)
mods_res
## # A tibble: 2 × 3
## model formula mod
## <int> <chr> <list>
## 1 1 lprice ~ time_sv <S3: lm>
## 2 2 lprice ~ time_sv + wrain + hrain + degrees <S3: lm>
Now that we have these models, extract the coefficients into a data frame with the broom function tidy
:
mods_coefs <- mods_res %>%
# Add column with the results of tidy for each model
# conf.int = TRUE adds confidence intervals to the data
mutate(tidy = map(mod, tidy, conf.int = TRUE)) %>%
# use unnest() to expand the data frame to one row for each row in the tidy
# elements
unnest(tidy, .drop = TRUE)
glimpse(mods_coefs)
## Observations: 7
## Variables: 9
## $ model <int> 1, 1, 2, 2, 2, 2, 2
## $ formula <chr> "lprice ~ time_sv", "lprice ~ time_sv", "lprice ~ ti...
## $ term <chr> "(Intercept)", "time_sv", "(Intercept)", "time_sv", ...
## $ estimate <dbl> -2.025199170, 0.035429560, -12.145333577, 0.02384741...
## $ std.error <dbl> 0.2472286519, 0.0136624941, 1.6881026571, 0.00716671...
## $ statistic <dbl> -8.191604, 2.593199, -7.194665, 3.327521, 2.420525, ...
## $ p.value <dbl> 1.522111e-08, 1.566635e-02, 3.278791e-07, 3.055739e-...
## $ conf.low <dbl> -2.534376e+00, 7.291126e-03, -1.564624e+01, 8.984546...
## $ conf.high <dbl> -1.516022230, 0.063567993, -8.644422940, 0.038710280...
walk(mods_res$mod, ~ print(summary(.x)))
##
## Call:
## lm(formula = .x, data = bordeaux)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.8545 -0.4788 -0.0718 0.4562 1.2457
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -2.02520 0.24723 -8.192 1.52e-08 ***
## time_sv 0.03543 0.01366 2.593 0.0157 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.5745 on 25 degrees of freedom
## Multiple R-squared: 0.212, Adjusted R-squared: 0.1804
## F-statistic: 6.725 on 1 and 25 DF, p-value: 0.01567
##
##
## Call:
## lm(formula = .x, data = bordeaux)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.46027 -0.23864 0.01347 0.18600 0.53446
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.215e+01 1.688e+00 -7.195 3.28e-07 ***
## time_sv 2.385e-02 7.167e-03 3.328 0.00306 **
## wrain 1.167e-03 4.820e-04 2.421 0.02420 *
## hrain -3.861e-03 8.075e-04 -4.781 8.97e-05 ***
## degrees 6.164e-01 9.518e-02 6.476 1.63e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.2865 on 22 degrees of freedom
## Multiple R-squared: 0.8275, Adjusted R-squared: 0.7962
## F-statistic: 26.39 on 4 and 22 DF, p-value: 4.058e-08
Likewise, extract model statistics such as, \(R^2\), adjusted \(R^2\), and \(\hat{\sigma}\):
mods_glance <-
mutate(mods_res, .x = map(mod, glance)) %>%
unnest(.x, .drop = TRUE)
mods_glance %>%
select(formula, r.squared, adj.r.squared, sigma)
## # A tibble: 2 × 4
## formula r.squared adj.r.squared
## <chr> <dbl> <dbl>
## 1 lprice ~ time_sv 0.2119700 0.1804488
## 2 lprice ~ time_sv + wrain + hrain + degrees 0.8275278 0.7961692
## # ... with 1 more variables: sigma <dbl>
15.5 Cross-Validation
To compare predictive models, we want to compare how well it predicts (duh), which means estimating how well it will work on new data. The problem with this is that new data is just that, …, new.
The trick is to resuse the sample data to get an estimate of how well the model will work on new data. This is done by fitting the model on a subset of the data, and predicting another subset of the data which was not used to fit the model; often this is done repeatedly. There are a variety of ways to do this, depending on the nature of the data and the predictive task. However, they all implictly assume that the sample of data that was used to fit the model is representative of future data.
… model validation is a good, simple, broadly aplicable procedure that is rarely used in social research (Fox, p. 630)
The simple idea of splitting a sample into two and then developing the hypothesis on the basis of one part and testing it on the remainder may perhaps be said to be one of the most seriously neglected ideas in statistics, if we measure the degree of neglect by the ratio of the number of cases in where a method could give help to the number where it was actually used. (Barnard 1974, p. 133, quoted in Fox, p. 630)
15.6 Out of Sample Error
k <- 20
f <- map(seq_len(k),
~ as.formula(str_c("lprice ~ poly(time_sv, ", .x, ")")))
names(f) <- seq_len(k)
mods_overfit <- map(f, ~ lm(.x, data = bordeaux))
fits <- map_df(mods_overfit, glance, .id = ".id")
fits %>%
select(.id, r.squared, adj.r.squared, df.residual) %>%
gather(stat, value, -.id) %>%
mutate(.id = as.integer(.id)) %>%
ggplot(aes(x = .id, y = value)) +
geom_point() +
geom_line() +
facet_wrap(~ stat, ncol = 2, scales = "free")
The larger the polynomial, the more wiggly the line.
library("modelr")
invoke(gather_predictions, .x = c(list(data = bordeaux), mods_overfit)) %>%
ggplot(aes(x = vint)) +
geom_point(aes(y = lprice)) +
geom_line(aes(y = pred, group = model, colour = as.numeric(model)))
Intuitively it seems that as we increase the flexibility of the model by increasing the number of variables the model is overfitting the data, but what does it actually mean to overfit? If we use \(R^2\) as the “measure of fit”, more variables always leads to better fit. Adjusted \(R^2\) does not increase, because the decrease in errors is offset by the increase in the degrees of freedom. However, there is little justification for the specific formula of \(R^2\).
The problem with over-fitting is that the model starts to fit pecularities of the sample (errors) rather than the underlying model. We’ll never know the underlying model, but what we can see is if the model predicts new data.
wine_mods_f <- list(
lprice ~ time_sv,
lprice ~ poly(time_sv, 2),
lprice ~ wrain,
lprice ~ hrain,
lprice ~ degrees,
lprice ~ wrain + hrain + degrees,
lprice ~ time_sv + wrain + hrain + degrees,
lprice ~ time_sv + wrain * hrain * degrees,
lprice ~ time_sv * (wrain + hrain + degrees),
lprice ~ time_sv * wrain * hrain * degrees,
lprice ~ time_sv * wrain * hrain * degrees + I(time_sv ^ 2)
)
15.6.1 Held-out data
A common rule of thumb is to use 70% of the data for training, and 30% of the data for testing.
In this case, let’s partition the data to use the first 70% of the observations as training data, and the remaining 30% of the data as testing.
n_test <- round(0.3 * nrow(bordeaux))
n_train <- nrow(bordeaux) - n_test
mod_train <- lm(lprice ~ time_sv + wrain + hrain + degrees,
data = head(bordeaux, n_train))
mod_train
##
## Call:
## lm(formula = lprice ~ time_sv + wrain + hrain + degrees, data = head(bordeaux,
## n_train))
##
## Coefficients:
## (Intercept) time_sv wrain hrain degrees
## -1.080e+01 1.999e-02 9.712e-04 -4.461e-03 5.533e-01
# in-sample RMSE
sqrt(mean(mod_train$residuals ^ 2))
## [1] 0.2280059
The out-of-sample RMSE is higher than the in-sample RMSE.
outsample <- augment(mod_train, newdata = tail(bordeaux, n_test))
sqrt(mean((outsample$lprice - outsample$.fitted) ^ 2))
## [1] 0.351573
This is common, but not necessarily the case. But note that this value is highly dependent on the subset of data used for testing. In some sense, we may choose as model that “overfits” the testing data.
15.6.2 Leave-One-Out Cross-Validation
For each \(i \in 1, \dots, n\)
- Estimate the model using all observations but \(i\)
- Predict \(\hat{y}_i\) using that model
- Calculate some measure(s) of model fit
Let’s create a function to fit the model on a dataset dropping a single observation.
i <- 1
f <- lprice ~ time_sv + wrain + hrain + degrees
mod <- lm(f, data = bordeaux)
mod
##
## Call:
## lm(formula = f, data = bordeaux)
##
## Coefficients:
## (Intercept) time_sv wrain hrain degrees
## -12.145334 0.023847 0.001167 -0.003861 0.616392
mod_loo1 <- lm(f, data = bordeaux[-i, ])
mod_loo1
##
## Call:
## lm(formula = f, data = bordeaux[-i, ])
##
## Coefficients:
## (Intercept) time_sv wrain hrain degrees
## -12.336504 0.025916 0.001188 -0.003832 0.625560
Unsurprisingly the fits of models fit with and without the first observation are similar, since they were fit using \(n - 1\) observations.
Now use the model fit without the first observation to
yhat_loo1 <- predict(mod_loo1, newdata = bordeaux[1, ])
yhat_loo1
## 1
## -0.7262297
bordeaux$lprice[1] - yhat_loo1
## 1
## -0.2724503
Now we want to repeat this for all observations,
fit_loo <- function(i, formula, data) {
# fit without i
m <- lm(formula, data = data[-i, ])
# predict i
yhat <- predict(m, newdata = data[i, ])
tibble(i = i, pred = yhat, resid = yhat - data[["lprice"]][[i]])
}
cv_loo <- map_df(seq_len(nrow(bordeaux)), fit_loo, formula = f, data = bordeaux)
sqrt(mean(cv_loo$resid ^ 2))
## [1] 0.3230043
15.6.3 k-fold Cross-validation
The most common approach is to to partition the data into k-folds, and use each fold once as the testing subset, where the model is fit on the other \(k - 1\) folds.
[Cross validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics) is a non-parametric method that splits the data into training and test subsets. The data is fit on the training set and then used the predict the test set.
The most common form of cross validation is 5- or 10-fold cross validation? Why this number of folds? See ISLR 5.1.4 “Bias-Variance Trade-Off for k-Fold Cross Validation”
- Larger number of folds requires more computation: a \(k\)-fold cross validation requires running the model \(k\) times
- A large number of folds has low bias because the result of \((n - 1)\) observations is approximately the same as the result of \(n\) observations
- But larger folds results in higher variance. LOOCV is averaging \(n\) models, but all those models will be similar, because they share almost all the same observations. But with fewer folds the models are fit with fewer overlapping observations and thus will have less correlated results.
cv_fold5 <- modelr::crossv_kfold(bordeaux, k = 5)
glimpse(cv_fold5)
## Observations: 5
## Variables: 3
## $ train <list> [<1952.00000, 1953.00000, 1955.00000, 1957.00000, 1958....
## $ test <list> [<1952.00000, 1953.00000, 1955.00000, 1957.00000, 1958....
## $ .id <chr> "1", "2", "3", "4", "5"
cv_fold5$train[[1]]
## <resample [21 x 7]> 1, 2, 6, 7, 8, 9, 10, 11, 12, 13, ...
cv_fold5$test[[1]]
## <resample [6 x 7]> 3, 4, 5, 15, 22, 26
as.data.frame(cv_fold5$train[[1]])
## # A tibble: 21 × 7
## vint price wrain degrees hrain time_sv lprice
## <int> <dbl> <int> <dbl> <int> <int> <dbl>
## 1 1952 36.83654 600 17.1167 160 31 -0.99868
## 2 1953 63.48288 690 16.7333 80 30 -0.45440
## 3 1959 65.83622 485 17.4833 187 24 -0.41800
## 4 1960 13.87738 763 16.4167 290 23 -1.97491
## 5 1961 100.00000 830 17.3333 38 22 0.00000
## 6 1962 33.09725 697 16.3000 52 21 -1.10572
## 7 1963 16.84730 608 15.7167 155 20 -1.78098
## 8 1964 30.59450 402 17.2667 96 19 -1.18435
## 9 1965 10.62522 602 15.3667 267 18 -2.24194
## 10 1966 47.26359 819 16.5333 86 17 -0.74943
## # ... with 11 more rows
as.data.frame(cv_fold5$test[[1]])
## # A tibble: 6 × 7
## vint price wrain degrees hrain time_sv lprice
## <int> <dbl> <int> <dbl> <int> <int> <dbl>
## 1 1955 44.57665 502 17.1500 130 28 -0.80796
## 2 1957 22.10735 420 16.1333 110 26 -1.50926
## 3 1958 17.96850 582 16.4167 187 25 -1.71655
## 4 1968 10.53803 610 16.2000 292 15 -2.25018
## 5 1975 30.06886 572 16.9500 171 8 -1.20168
## 6 1979 21.44669 717 16.1667 122 4 -1.53960
In k-fold cross-validation, each observation appears in the test-set in one fold, and is in the the training set in the remaining \(k - 1\) folds. The following plot shows this,
cv_fold5_obs <-
cv_fold5 %>%
rowwise() %>%
do(tibble(vint = c(as.data.frame(.$train)$vint,
as.data.frame(.$test)$vint),
fold = .$.id,
set = c(rep("train", dim(.$train)[1]),
rep("test", dim(.$test)[1]))))
ggplot(cv_fold5_obs, aes(y = factor(vint), x = fold, fill = set)) +
geom_raster() +
scale_fill_manual(values = c("train" = "black", "test" = "gray")) +
theme_minimal() +
theme(axis.ticks = element_blank(), legend.position = "bottom") +
labs(x = "vint", y = "CV fold", fill = "")
Example with one fold
fit_train <- lm(f, data = as.data.frame(cv_fold5$train[[1]]))
fit_train
##
## Call:
## lm(formula = f, data = as.data.frame(cv_fold5$train[[1]]))
##
## Coefficients:
## (Intercept) time_sv wrain hrain degrees
## -1.131e+01 3.114e-02 9.724e-04 -3.965e-03 5.662e-01
fit_test <- augment(fit_train, newdata = as.data.frame(cv_fold5$test[[1]])) %>%
select(vint, lprice, .fitted) %>%
mutate(.resid = .fitted - lprice)
fit_test
## vint lprice .fitted .resid
## 1 1955 -0.80796 -0.7542891 0.05367086
## 2 1957 -1.50926 -1.3926673 0.11659270
## 3 1958 -1.71655 -1.4111139 0.30543610
## 4 1968 -2.25018 -2.2342730 0.01590699
## 5 1975 -1.20168 -1.5847434 -0.38306339
## 6 1979 -1.53960 -1.8175094 -0.27790943
# could also use modelr::rmse()
mod_rmse <- sqrt(mean(sum(fit_test$.resid ^ 2)))
mod_rmse
## [1] 0.5779186
Let’s apply that to each row using map
. That way we keep the results together in the same data frame.
fit_train <- lm(f, data = as.data.frame(cv_fold5$train[[1]]))
fit_train
##
## Call:
## lm(formula = f, data = as.data.frame(cv_fold5$train[[1]]))
##
## Coefficients:
## (Intercept) time_sv wrain hrain degrees
## -1.131e+01 3.114e-02 9.724e-04 -3.965e-03 5.662e-01
fit_test <- augment(fit_train, newdata = as.data.frame(cv_fold5$test[[1]])) %>%
select(vint, lprice, .fitted) %>%
mutate(.resid = .fitted - lprice)
fit_test
## vint lprice .fitted .resid
## 1 1955 -0.80796 -0.7542891 0.05367086
## 2 1957 -1.50926 -1.3926673 0.11659270
## 3 1958 -1.71655 -1.4111139 0.30543610
## 4 1968 -2.25018 -2.2342730 0.01590699
## 5 1975 -1.20168 -1.5847434 -0.38306339
## 6 1979 -1.53960 -1.8175094 -0.27790943
# could also use modelr::rmse()
mod_rmse <- sqrt(mean(sum(fit_test$.resid ^ 2)))
mod_rmse
## [1] 0.5779186
fit_cv_fold5 <-
cv_fold5 %>%
mutate(
# fit each row using train as the data
fit_train = map(train,
~ lm(f, data = as.data.frame(.x))),
# predicted values
predict_test = map(train,
~ predict(fit_train, newdata = as.data.frame(.x))),
# calculate out-of-sample RMSE
rmse = map2_dbl(train, predict_test,
~ sqrt(mean((as.data.frame(.x)$lprice - .y) ^ 2))))
Let’s apply this to all the models. In the previous steps we kept a lot of extra information in order to understand how cross-validation worked. But really, all we care about is the average RMSE.
mod_rmse_fold <- function(f, train, test) {
fit <- lm(f, data = as.data.frame(train))
# sqrt(mean(residuals(fit, newdata = as.data.frame(test)) ^ 2))
test_data <- as.data.frame(test)
err <- test_data$lprice - predict(fit, newdata = test_data)
sqrt(mean(err ^ 2))
}
mod_rmse_fold(f, cv_fold5$train[[1]], cv_fold5$test[[1]])
## [1] 0.2359343
Now calculate this for a single model formula, averaging over all folds:
mod_rmse <- function(f, data) {
map2_dbl(data$train, data$test,
function(train, test) {
mod_rmse_fold(f, train, test)
}) %>%
mean()
}
Now we can apply this to all the models:
mod_comparison <-
tibble(formula = wine_mods_f,
.name = map_chr(formula, deparse),
.id = seq_along(wine_mods_f),
rmse = map_dbl(wine_mods_f, mod_rmse, data = cv_fold5))
mod_comparison %>% select(.name, rmse)
## # A tibble: 11 × 2
## .name rmse
## <chr> <dbl>
## 1 lprice ~ time_sv 0.6086064
## 2 lprice ~ poly(time_sv, 2) 0.6100899
## 3 lprice ~ wrain 0.6918896
## 4 lprice ~ hrain 0.5925636
## 5 lprice ~ degrees 0.5025091
## 6 lprice ~ wrain + hrain + degrees 0.3733184
## 7 lprice ~ time_sv + wrain + hrain + degrees 0.3250124
## 8 lprice ~ time_sv + wrain * hrain * degrees 0.4522841
## 9 lprice ~ time_sv * (wrain + hrain + degrees) 0.3926909
## 10 lprice ~ time_sv * wrain * hrain * degrees 1.0599623
## 11 lprice ~ time_sv * wrain * hrain * degrees + I(time_sv^2) 1.4167142
15.7 Analytic Covariance Methods
For some models, notably linear regression, analytical approximations to the expected out of sample error can be made. Each of these approximations will make some slightly different assumptions to plug in some unknown values.
Adjusted \(R^2\) is most often seen in statistical software and in papers (though often never interpreted). It intuitively penalizes a regression for a higher number of predictors; however apart from that intuitive appeal, and unlike the other measures presented here, there is no deeper justification for it (Fox, p. 609): \[ \mathrm{adj}\,R^2 = 1 - \frac{\hat{\sigma}^2}{\Var{(Y)}} = 1 - \frac{n - 1}{n - k - 1} \times \frac{\sum (y_i - \hat{y}_i^2)}{\sum (y_i - \bar{y})^2} \]
In linear regression, the LOO-CV MSE can be calculated analytically, and without simulation. It is (ISLR, p. 180): \[ \text{LOO-CV} = \frac{1}{n} \sum_{i = 1}^n {\left(\frac{y_i - \hat{y}_i}{1 - h_i} \right)}^2 = \frac{1}{n} \sum_{i = 1}^n {\left(\frac{\hat{\epsilon}_i}{1 - h_i} \right)}^2 = \frac{1}{n} \times \text{PRESS} \] where PRESS is the predictive residual sum of squares, and \(h_i\) is the hat-value of observation \(i\) (Fox, p. 270, 289) \[ h_i = \mat{X}(\mat{X}' \mat{X})^{-1} \mat{X}' \]
loocv <- function(x) {
mean((residuals(x) / (1 - hatvalues(x))) ^ 2)
}
An alternative approximation of the expected out-of-sample error is the generalized cross-validation criterion (GCV) is (Fox, 673) \[ GCV = \frac{n}{df_{res}^2} \times RSS = \frac{n}{(n - k - 1)^2} \times \sum \hat{\epsilon}^2_i \]
gcv <- function(x) {
err2 <- residuals(x) ^ 2
n <- length(err2)
(n / x[["df.residual"]] ^ 2) * sum(err2)
}
Since we generated the LOO data manually using a loop, create a LOO cross validation data frame using crossv_kfold
:
cv_loo <- crossv_kfold(bordeaux, nrow(bordeaux))
mod_comparison <-
tibble(formula = wine_mods_f,
.name = map_chr(formula, deparse),
.id = seq_along(wine_mods_f),
rmse_5fold = map_dbl(wine_mods_f, mod_rmse, data = cv_fold5),
rmse_loo = map_dbl(wine_mods_f, mod_rmse, data = cv_loo),
mod = map(formula, lm, data = bordeaux),
gcv = sqrt(map_dbl(mod, gcv)),
loocv = sqrt(map_dbl(mod, loocv))
)
mod_comparison %>% select(.name, rmse_loo, rmse_5fold, gcv, loocv)
## # A tibble: 11 × 5
## .name rmse_loo
## <chr> <dbl>
## 1 lprice ~ time_sv 0.5194518
## 2 lprice ~ poly(time_sv, 2) 0.5312953
## 3 lprice ~ wrain 0.5703790
## 4 lprice ~ hrain 0.4635317
## 5 lprice ~ degrees 0.4031840
## 6 lprice ~ wrain + hrain + degrees 0.3092453
## 7 lprice ~ time_sv + wrain + hrain + degrees 0.2767282
## 8 lprice ~ time_sv + wrain * hrain * degrees 0.3199831
## 9 lprice ~ time_sv * (wrain + hrain + degrees) 0.3128323
## 10 lprice ~ time_sv * wrain * hrain * degrees 0.7493031
## 11 lprice ~ time_sv * wrain * hrain * degrees + I(time_sv^2) 0.7287324
## # ... with 3 more variables: rmse_5fold <dbl>, gcv <dbl>, loocv <dbl>
Other measures that are also equivalent to some form of an estimate of the out-of-sample error are the AIC and BIC.
15.8 Further Resources
- Fox (2016) Chapter 22: “Model Selection, Averaging, and Validation”, p. 669.
- James et al. (2013), Ch. 5. “Resampling Methods”
- Hastie, Tibshirani, and Friedman (2009), Ch. 7. “Model Assessment and Selection”
- Rob Hyndman’s blog posts on cross validation, time series cross validation, and leave-one-out CV in linear models.
References
Fox, John. 2016. Applied Regression Analysis & Generalized Linear Models. 3rd ed. Sage.
James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2013. An Introduction to Statistical Learning with Applications in R. 6th ed. Springer.
Hastie, Trevor, Robert Tibshirani, and Jerome Friedman. 2009. The Elements of Statistical Learning. Springer-Verlag New York Inc. http://www.ebook.de/de/product/8023140/trevor_hastie_robert_tibshirani_jerome_friedman_the_elements_of_statistical_learning.html.


Preparation time
overnight
Cooking time
1 to 2 hours
Serves
Makes 30 Turkish delights
Delicately floral and nutty, Turkish delight makes an original homemade gift for friends and family. Be warned though - you will need to stir the mixture by hand for an hour.
Equipment and preparation: for this recipe you will need a sugar thermometer.
Line a 20cm/8in square baking tin on all sides with baking parchment and lightly oil with groundnut oil.
Place the sugar, lemon juice and 340ml/12fl oz water in a pan on a low heat. Stir until all the sugar is dissolved. Place a sugar thermometer in the pan and slowly, without stirring, bring the mixture up to 118C/245F – this will take about 15 minutes. (CAUTION: boiling sugar is extremely hot. Handle very carefully. Use a deep pan to avoid bubbling over.)
Meanwhile, place the cornflour, 570ml/1 pint cold water and the cream of tartar in a deep, heavy-bottomed pan. Stir continuously over a low heat, bring to the boil and beat until the mixture is smooth and resembles wallpaper paste. Use a balloon whisk to beat out any lumps, if necessary, and remove from the heat.
Place the cornflour mixture back on a low heat, and as soon as the sugar mixture has reached 118C/245F pour it over the cornflour mixture. Stir well to remove any lumps, then simmer on a low heat, stirring continuously for an hour. (Don't worry if the mixture is very lumpy at first, just keep stirring.)
Take the pan off the heat and stir in the rose syrup, pink food colouring and pistachio nuts.
Pour the mixture into the prepared tin and leave to cool and set overnight.
Once set, cut the Turkish delight into squares and dust with equal amounts of icing sugar and cornflour sifted together.


Uxbridge stabbing: Murder charge after knife awareness course attack
A teenager has been charged with murdering a man stabbed at a knife awareness course in London.
Hakim Sillah, 18, was attacked in the youth offending service department of the Hillingdon Civic Centre in Uxbridge on Thursday.
The Metropolitan Police said a group had gathered at the venue when a fight broke out. Mr Sillah was taken to hospital but died an hour later.
A 17-year-old boy will appear before Uxbridge magistrates on Saturday.
A teenage boy who sustained a knife wound to his ear was praised by detectives for "bravely" trying to break up the fight.
In a statement, Mr Sillah's family described him as "a lovely lad who cared about his family".
"He loved looking after his little brother, who had been ill," they said.
Det Ch Insp Noel McHugh said: "A young man with his whole life ahead of him has been fatally attacked and his family are absolutely devastated."


But anway there's some really good mages on a server and they keep bibgying me. But in general I just want a really good mage killer build.MOst important thing is..................
Can you please post LINKS to builds not just tell me the classes and levels. Or you can just make your on build topic on the forum two forums above this.
 _________________ Willwoms is the most super, amazing, fabulous, marvellous, exciting, dangerous and lethal dex sneak in Life vs Death.Well will be eventually. *slits your throat*.
Edited By Willwoms on 07/19/07 20:35
You do know caster types are some of the best PvP in general terms right? mage killers aren't all that easy or 100% effective, a heavy sneaker with HiPS might do the trick... sorry, no links, but try this. _________________
Quote: Posted 12/19/06 19:54 (GMT) -- FinneousPJ
Thax the Shadow Dragon sez: MONKS USE KAMAS. Just ask him.
Edited By Thaxll'ssyllia on 07/19/07 23:24
Are you looking solely for a mage killer, or do you want to be able to use this character for other purposes? If the former, then I suggest a high SR Monk build. Pure Monk is probably the way to go, picking up as many SR feats as you can. Go high WIS and Zen Archery to tackle them from range and you should be golden. _________________ It's rogue, dammit, ROGUE!!!
Probably the best mage-killer is another mage with Superior Initiative. _________________ Got Hommlet? World of Greyhawk Action Server (with 1/2 price ales on Mondays!)
Ariel, Ookla, RIDE!
You could try a str based monk28 bard2 rdd10 with some epic feats sunk into epic acid resistance.  The second level of bard actually allows you to use a crafted wand of lesser spell breach, which allows you to not only dispell him, but get the bigby off you.


Configure the Clock Tree in STM32
Almost every digital circuit needs clocks - the periodic signals that make circuits alive. Inside an MCU, there is a complex clock distribution network that drive every component and peripheral. When a device start, it should firstly setup its clock tree.
Last update: 2021-06-09 21:46:02
Table of Content
1. Clock source⚓
A clock is a device that usually generates a periodical square wave signal, with a 50% duty cycle. A clock signal oscillates between VL and VH voltage levels, which for STM32 microcontrollers are a fraction of the VDD supply voltage.
The most fundamental parameter of a clock is the frequency, which indicates how many times it switches from VL to VH in a second. The frequency is expressed in Hertz.
The majority of STM32 MCUs can be clocked by two distinct clock sources alternatively:
- an internal RC oscillator High Speed Internal (HSI); or
- an external dedicated crystal oscillator High Speed External (HSE)
There are several reasons to prefer an external crystal to the internal RC oscillator:
-
An external crystal offers a higher precision compared to the internal RC network, which is rated of a 1% accuracy, especially when PCB operative temperatures are far from the ambient temperature of 25°C
-
Some peripherals, especially high speed ones, can be clocked only by a dedicated external crystal running at a given frequency
Together with the high-speed oscillator, another clock source can be used to bias the low-speed oscillator, which in turn can be clocked by:
- an external crystal Low Speed External (LSE); or
- the internal dedicated RC oscillator Low Speed Internal (LSI)
The low-speed oscillator is used to drive the Real Time Clock (RTC) and the Independent Watchdog (IWDT) peripheral.
Using several Programmable Phase-Locked Loops (PLL) and pre-scalers, it is possible to increase/decrease the source frequency at needs, depending on the requested performances, the maximum speed for a given peripheral or bus and the overall global power consumption.
2. Clock tree⚓
The clock tree configuration is performed through a dedicated peripheral named Reset and Clock Control (RCC), and it is a process essentially composed by three steps:
-
The high-speed oscillator source is selected (HSI or HSE) and properly configured, if the HSE is used.
-
If need to feed the
SYSCLK
with a frequency higher than the one provided by the high-speed oscillator, then configure the main PLL (which provides thePLLCLK
signal). -
The System Clock Switch (SW) is configured to choose the system clock source from HSI, HSE, or
PLLCLK
. Then select the AHB, APB1 and APB2 (if available) pre-scaler settings to reach the wanted frequency of the High-speed clock (HCLK
- that is the one that feeds the core, DMAs and AHB bus), and the frequencies of Advanced Peripheral Bus 1 (APB1) and APB2 (if available) buses.
3. Master Clock Output⚓
The RCC peripheral also allows to enable the Master Clock Output (MCO), which is a pin that can be connected to a clock source. It can be used to clock another external device, allowing to save on the external crystal for this other IC. Once the MCO is enabled, it is possible to choose its clock source using the Clock Configuration view.
4. Clock Security System⚓
The Clock Security System (CSS) is a feature of the RCC peripheral used to detect malfunctions of the external HSE. The CSS is an important feature in some critical applications, and the detection of a failure is noticed through the NMI exception - a Cortex-M exception that cannot be disabled.
When the failure of HSE is detected, the MCU automatically switch to the HSI clock, which is selected as source for the SYSCLK
clock. So, if a higher core frequency is needed, it needs to perform proper initializations inside the NMI exception handler.
5. Configure Clocks⚓
After a reset:
- The device is running from the Internal High Speed oscillator (HSI 8 MHz) with Flash 0 wait state, Flash prefetch buffer is enabled, and all peripherals are off except internal SRAM, Flash and JTAG.
- There is no prescaler on High speed (AHB) and Low speed (APB) buses; all peripherals mapped on these buses are running at HSI speed.
- The clock for all peripherals is switched off, except the SRAM and FLASH.
- All GPIOs are in input floating state, except the JTAG pins which are assigned to be used for debug purpose.
Once start up, the user application has to:
- Configure the clock source to be used to drive the System clock (if the application needs higher frequency/ performance)
- Configure the System clock frequency and Flash settings
- Configure the AHB and APB buses prescalers
- Enable the clock for the peripheral(s) to be used
- Configure the clock source(s) for peripherals whose clocks are not derived from the System clock (RTC, ADC, I2C, USART, TIM, USB FS, etc.)
6. CubeMX Usage⚓
Here are two examples of setting up the clock on 2 boards - one with only internal oscillator, one with external crystals. Note that when changing the clock speed, there are some limitation of the frequency of the target buses, e.g. HCLK
, PCK1
, PCK2
.
For both HSE
and LSE
external crystals, CubeMX offers three configuration options:
- Disable: the external oscillator is not available/used, and the corresponding internal oscillator is used.
- Crystal/Ceramic Resonator: an external crystal/ceramic resonator is used and the corresponding main frequency is derived from it. This implies that
RCC_OSC_IN
andRCC_OSC_OUT
pins are used to interface the HSE, and the corresponding signal I/Os are unavailable for other usages (if use an external low-speed crystal, then the correspondingRCC_OSC32_IN
andRCC_OSC32_OUT
I/Os are used too). - BYPASS Clock Source: an external clock source is used. The clock source is generated by another active device. This means that the
RCC_OSC_OUT
is leaved unused, and it is possible to use it as regular GPIO.
User can fill in a number in a frequency node, and press Enter to let IDE automatically calculate the multiplier’s and divider’s value.
6.1. Internal RC oscillators⚓
This is an example guide on an official STM32F0 Discovery board, which only has internal RC oscillators:
-
Select PLL Source Mux is HSI
-
Set PLL Multiplier and Divider to get
PLLCLK
-
Select System Clock Mux is
PLLCLK
to getSYSCLK
-
Set divider for AHB Bus
HCLK
and APB1 BusPCLK1
6.2. External crystals⚓
This is an example guide on a custom black pill STM32F411CE board, which has external crystals:
-
Enable HSE and LSE:
In the RCC peripheral under the System Core modules, choose option Crystal/Ceramic Resonator. This will automatically setups 2 pins for HSE, and 2 pins for LSE.
-
Select PLL Source Mux is HSE
-
Set PLL Multiplier and Divider to get
PLLCLK
-
Select System Clock Mux is
PLLCLK
to getSYSCLK
-
Set divider for AHB Bus
HCLK
, APB1 BusPCLK1
, APB2 BusPCLK2
7. STM32Cube HAL Usage⚓
CubeMX is designed to generate the right code initialization for the clock tree of MCU. All the necessary code is packed inside the SystemClock_Config()
routine in the file main.c
:
- The most relevant C struct to configure the clock tree are
RCC_OscInitTypeDef
andRCC_ClkInitTypeDef
. - Use
HAL_RCC_OscConfig()
function to setup the Oscillator source, and then useHAL_RCC_ClockConfig()
function to setup the System clock (CPU) and Bus clocks (AHB, APB). - To configure the Master Clock Output, use the function
HAL_RCC_MCOConfig()
to select the clock source and its dividing factor. Note that when configuring the MCO pin as output GPIO, its speed (that is, the slew rate) affects the quality of the output clock.
Example 1 - Setting clock on F051R8, with 8 MHz HSI, to make 48 MHZ SYSCLK, and drive MCO at 48 MHz using SYSCLK:
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
in the RCC_OscInitTypeDef structure.*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL12;
RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks */
RCC_ClkInitStruct.ClockType =
RCC_CLOCKTYPE_HCLK |RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) {
Error_Handler();
}
HAL_RCC_MCOConfig(RCC_MCO, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1);
}
Example 2 - Setting clock on F411CE, with 25 MHZ HSE and 32.765KHz LSE, to make 100 MHz SYSCLK, 50 MHz APB1 Bus, 100 MHZ APB2, with CSS Enabled:
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 12;
RCC_OscInitStruct.PLL.PLLN = 96;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
{
Error_Handler();
}
/** Enables the Clock Security System
*/
HAL_RCC_EnableCSS();
}
Note that when CSS is enabled, HAL_RCC_NMI_IRQHandler()
is added into the NMI_Handler()
ISR. User should override the HAL_RCC_CSSCallback()
function to re-configure the system clocks as the same way as it only has the internal RC oscillators.


Gained exposure on the e-commerce platform - Hybris, and other web development technologies to solve business challenges. Willing to adapt and learn best practices thereby providing better solutions.
Project Name - Rodan + Fields
Framework - Hybris 1905
Team Size - ~20
Description - RNF is a Multi-Country MLM site to sell beauty and skin care products in four countries.
Project Name - John Wiley & Sons
Framework - Hybris 1808
Team Size - 4
Description - John Wiley & Sons is a B2C project to provide eCommerce solution to educational products like physical books, e-books and other media formats in the US. They have multiple websites to sell different learning materials to students and teachers.
CGPA: 7.9
Project Name - Pixburb
Framework - Spring 5
Description - Pixburb is a generic approach to handle different eCommerce organizations.
Responsibilities - Created data models and CRUD operations, Integrated JWT for authentication and Swagger for documenting web services APIs.
Analysis of age, astigmatic and tear protection rate in contact lenses selection in IEEE Conferences
Year : 2017
Pages : 1090 - 1094


The Slide Puzzle game will have three buttons: a “Reset” button that will undo any moves the player has made, a “New” button that will create a new slide puzzle, and a “Solve” button that will solve the puzzle for the player.
New Reset Solve


POS tags
| Open class words | Closed class words | Other |
|---|---|---|
| ADJ | ADP | PUNCT |
| ADV | AUX | SYM |
| INTJ | CCONJ | X |
| NOUN | DET | |
| PROPN | NUM | |
| VERB | PART | |
| PRON | ||
| SCONJ |
ADJ
: adjective
Definition
Adjectives are words that typically modify nouns and specify their properties or attributes. They may also function as predicates, as in
El cotxe és verd. “The car is green.”
In Catalan, adjectives normally follow the noun, e.g. La casa groga “The yellow house”, although sometimes they may also precede the noun, e.g. La blanca neu “The white snow”.
Adjectives in Catalan agree in number and gender with the noun they modify, e.g. la casa groga (femenine singular), les cases grogues (femenine plural).
The class of adjectives in Catalan UD also includes ordinal numbers and participial adjectives, both behaving as adjectives morphologically and syntactically. Note that participles are word forms that may share properties and usage of adjectives and verbs. Depending on context, they may be classified as either VERB or ADJ.
To conform to the UD guidelines, possessive adjectives are handled as determiners DET.
Examples
- gran “big”
- vell “old”
- verd “green”
- incomprensible “incomprehensible”
- primer “first”, segon “second”, tercer “third”
ADP
: adposition
This document is a placeholder for the language-specific documentation
for ADP
.
ADV
: adverb
Definition
Adverbs are words that typically modify verbs for such categories as time, place, direction or manner. They may also modify adjectives (as in clarament fals “clearly fake”), other adverbs (as in molt breument “very briefly”) or even nouns / pronouns (as in solament tu “only you”).
There is a closed subclass of pronominal adverbs that refer to circumstances in context, rather than naming them directly; similarly to pronouns, these can be categorized as interrogative, relative, demonstrative, etc. To conform to the UD guidelines, pronominal adverbs also get the ADV
part-of-speech tag but they are differentiated by additional features (see pronominal type).
Examples
- molt “very”
- bé “well”
- exactament “exactly”
- demà “tomorrow”
- dalt, baix “up, down”
- interrogative or exclamative adverbs: on, quan, com, per què “where, when, how, why
- demonstrative adverbs: aquí, allí, ara, després “here, there, now, then”
- totality adverbs: sempre “always”
- negative adverbs: mai “never”
AUX
: auxiliary verb
This document is a placeholder for the language-specific documentation
for AUX
.
CCONJ
: coordinating conjunction
This document is a placeholder for the language-specific documentation
for CCONJ
.
DET
: determiner
This document is a placeholder for the language-specific documentation
for DET
.
INTJ
: interjection
Definition
An interjection is a word that is used most often as an exclamation or part of an exclamation. It typically expresses an emotional reaction, is not syntactically related to other accompanying expressions, and may include a combination of sounds not otherwise found in the language.
Note that words primarily belonging to another part of speech retains their original category when used in exclamations. For example, in the phrase ¡Déu meu!, Déu is a NOUN and meu is a PRON even in exclamatory uses.
As a special case of interjections, we recognize feedback particles such as sí and no. Note that uses of sí and no syntactically related to other accompanying expressions in a sentence are recognized as ADV.
Examples
Marked as interjections:
- psst
- ai
- bravo
- hola
- sí, e.g. Sí, perque… “Yes, because…”.
- no, e.g. No, no ho crec. “No, I don’t believe it.”
Marked as adverbs:
- sí, e.g. Votarem sí. “We will vote yes”.
- no, e.g. No és veritat. “It is not true.”
NOUN
: noun
Definition
Nouns are a part of speech typically denoting a person, place, thing, animal or idea.
The NOUN
tag is intended for common nouns only. See PROPN for proper nouns and PRON for pronouns.
Spanish nouns have the lexical feature ca-feat/Gender. Furthermore, the nouns inflect for ca-feat/Number.
Examples
- noia “girl”
- gat “cat”
- arbre “tree”
- aire “air”
- bellesa “beauty”
NUM
: numeral
This document is a placeholder for the language-specific documentation
for NUM
.
PART
: particle
This document is a placeholder for the language-specific documentation
for PART
.
PRON
: pronoun
This document is a placeholder for the language-specific documentation
for PRON
.
PROPN
: proper noun
This document is a placeholder for the language-specific documentation
for PROPN
.
PUNCT
: punctuation
Definition
Punctuation marks are non-alphabetical characters and character groups used in many languages to delimit linguistic units in printed text.
Punctuation is not taken to include logograms such as $, %, and §, which are instead tagged as SYM.
Examples
- Period: .
- Comma: ,
- Parentheses: ()
SCONJ
: subordinating conjunction
This document is a placeholder for the language-specific documentation
for SCONJ
.
SYM
: symbol
This document is a placeholder for the language-specific documentation
for SYM
.
VERB
: verb
This document is a placeholder for the language-specific documentation
for VERB
.
X
: other
This document is a placeholder for the language-specific documentation
for X
.


还是跟前几个一样的题，求方案数的，有AC的代码，也有WA的代码，这个可以直接for循环递推，也可以跟前几个一样递归，但是我的只有那种一次递推完全的AC了，郁闷，到现在还没找出来其他的程序错误在哪。。。。。下面发两个递推的代码吧。
| Ways |
After making a purchase at a large department store, Mel’s
change was 17 cents. He received 1 dime, 1 nickel, and 2 pennies.
Later that day, he was shopping at a convenience store. Again his
change was 17 cents. This time he received 2 nickels and 7 pennies.
He began to wonder ‘ “How many stores can I shop in and receive 17
cents change in a different configuration of coins? After a
suitable mental struggle, he decided the answer was 6. He then
challenged you to consider the general problem.
Write a program which will determine the number of different
combinations of US coins (penny: 1c, nickel: 5c, dime: 10c,
quarter: 25c, half-dollar: 50c) which may be used to produce a
given amount of money.
Input
The input will consist of a set of numbers between 0 and 30000
inclusive, one per line in the input file.
Output
The output will consist of the appropriate statement from the
selection below on a single line in the output file for each input
value. The number m is the number your program computes,
n is the input value.
There are m ways to produce n
cents change.
There is only 1 way to produce n cents
change.
Sample
input
17
11
4
0
3000
20
200
273
623
91
23
56
Sample
output
There are 6 ways to produce 17 cents change.
There are 4 ways to produce 11 cents change.
There is only 1 way to produce 4 cents change.
There is only 1 way to produce 0 cents change.
There are 57491951 ways to produce 3000 cents change.
There are 9 ways to produce 20 cents change.
There are 2435 ways to produce 200 cents change.
There are 6664 ways to produce 273 cents change.
There are 131859 ways to produce 623 cents change.
There are 218 ways to produce 91 cents change.
There are 9 ways to produce 23 cents change.
There are 62 ways to produce 56 cents change.
AC代码：
#include<iostream>
#include<cstring>
#include<algorithm>
#include<fstream>
#define maxn 30005
using namespace std;
int coin[6]={1,5,10,25,50};
long long v[maxn][5];
int num;
void init(){
memset(v,0,sizeof(v));
for(int i=0;i<5;i++)v[0][i]=1;
for(int i=1;i<=30000;i++){
for(int j=0;j<5;j++){
if(coin[j]<=i)v[i][j]=v[i-coin[j]][j];
if(j!=0)v[i][j]+=v[i][j-1];
}
}
}
int main()
{
// freopen("test.txt","r",stdin);
init();
while(cin>>num){
if(v[num][4]==1)cout<<"There is only 1 way to produce "<<num<<" cents change."<<endl;
else cout<<"There are "<<v[num][4]<<" ways to produce "<<num<<" cents change."<<endl;
}
return 0;
}
only 1 way to produce
“<<num<<”
cents change.”<<endl;
“<<tmp<<”
ways to produce
“<<num<<”
cents change.”<<endl;


Wisconsin Guard whistleblower fighting discharge decision
MADISON, Wis. - A Wisconsin National Guard sergeant whose complaints spurred investigations into sexual misconduct in his unit is fighting his commanders' decision to discharge him.
Wisconsin Air National Guard Master Sgt. Jay Ellis complaints of sexual assault and sexual harassment within the 115th Fighter Wing has sparked two federal investigations. He alleges his superiors have retaliated by launching a review of his medical history in hopes of discharging him and denying him retirement benefits
He said last week that a medical evaluation board out of Scott Air Force Base has decided to discharge him. He said Thursday he has declined to accept the decision, triggering an appeal process. He has now been ordered to appear at a Dec. 3 hearing before a medical evaluation board at Randolph Air Force Base in Texas.


Air pollution is a persistent problem of the world, which has been around for a while and will continue to exist in the future. It is a cause of a lot of problems and has extremely adverse effects. For curbing air pollution, its analysis is first necessary. For making predictions about the air quality, domain knowledge is essential, as are data analysis skills. This problem statement tests them all.
Participating teams are invited to propose and implement a multiclass classification technique for a given data set of air quality measurements. We expect a well-structured report detailing the approach used for classification and its implementation. Teams would be provided with the training data set to be used. Teams are expected to brainstorm, ideate, experiment, and code classification techniques to get the best results. The goal of this challenge is to create awareness about the applications of data analysis and machine learning in the chemical engineering domain, especially air quality analysis for air pollution control applications among the student community and provide them a platform to showcase their ideas and innovations.
The training dataset contains 7485 instances of hourly averaged responses from an array of 5 metal oxide chemical sensors embedded in an Air Quality Chemical Multisensor Device. The device was located on the field in a significantly polluted area, at road level,within an Italian city. Data were recorded from March 2004 to February 2005 (one year)representing the longest freely available recordings of on field deployed air quality chemical sensor devices responses. Ground Truth hourly averaged concentrations for CO, Non Metanic Hydrocarbons, Benzene, Total Nitrogen Oxides (NOx) and Nitrogen Dioxide (NO2) and were provided by a co-located reference certified analyzer. Evidences of cross-sensitivities as well as both concept and sensor drifts are present as described in De Vito et al., Sens. And Act. B, Vol. 129,2,2008 (citation required) eventually affecting sensors concentration estimation capabilities. Missing values are tagged with -200 value.
CO level is given as five broad categories Very High, High, Moderate, Low and Very Low. The target is to predict this class of CO level based on all the attributes listed.
Submission guidelines can be found here.