# get the solution

Page 1 of 4123...Last »

## An Introduction to create exams with the R exams package

on Regards: R;

The exams package for the R statistics software provides functions to create exams. You can export your exams to different formats, like pdf, docx or moodle import files. The exams are written in Sweave files (.Rnw), which combine R code and Latex code. If you don’t like Latex, you can also use Markdown (.Rmd). It is much easier to start with the exams package if you write small exercises instead of exam tasks.

In this article I want to give you a short introduction on how to write such exams and exercises. I will be focusing on Rnw files, which use Latex. You can write these files the way you like, but you have to use some special commands and environments. These are needed to give the interpreter of the exams package the necessary information to create the exams and export them correctly.

## Basic structure

Every exam consists of a question and a solution. You need to encapsulate these two in Latex environments like this:

\begin{question}
What is the sum of 3 and 5?
\end{question}
\begin{solution}
The sum of 3 and 5 is 8.
\end{solution}

There are different types of questions/answers: like multiple choice questions (with multiple correct answers) or single choice questions. For the question above we would expect a single number as answer. For multiple choice or single choice questions you should use the answerlist function in the question and solution environment. The exam can then be displayed differently in a Moodle platform or in a PDF file. See this example:

\begin{question}
What is the sum of 3 and 5?
<<echo=FALSE, results=tex>>=
@
\end{question}
\begin{solution}
The sum of 3 and 5 is 8. Hence the answer options were
<<echo=FALSE, results=tex>>=
@
\end{solution}

Basically you can use every R and Latex command you like to design your exam.

If you use the exams2pdf(“myfile.Rnw”) command to export the exam as a PDF, the file is read by Sweave. The R commands will be executed and the result is a latex file. Then a template is applied on the Latex file. If you want to export the exam to an other format, an other template may be used. For exams2pdf the template plain.tex is used. If you want to see it, you could download the source of the exams package and have a look at the exams/inst/tex/ directory. In this template you can also see how the solution and question evironment is declared. If you are more interested at the different files created in the export process, use the verbose parameter of exams2pdf.

Last but not least, you have to define some special commands, to store information about your exam. For instance, which answers are correct or what question type you used. These commands are typically at the bottom of your Rnw file:

%% META-INFORMATION
%% \extype{schoice}
%% \exsolution{1000}
%% \exname{Simple addition}

This were the basic commands you should use to design your exams. It is also recommended to use commands like mchoice2string etc from the exams package in the meta information section. You will learn about these commands if you read a lot of examples and tutorials on r-exams.org. Unfortunately these commands sometimes make the exams quite hard to read.

But I didn’t mention the real power of such exams yet: you can use random numbers for your exam/exercise. For instance, you could pick two random numbers and ask for the sum of them.

<<echo=FALSE, results=tex>>=
firstNumber = sample(1:20, 1);
secondNumber = sample(1:20, 1);
sum = firstNumber + secondNumber;
@
\begin{question}
What is the sum of \Sexpr{firstNumber} and \Sexpr{secondNumber}?
\end{question}
\begin{solution}
The sum of \Sexpr{firstNumber} and \Sexpr{secondNumber} is \Sexpr{sum}.
\end{solution}
%% META-INFORMATION
%% \extype{num}
%% \exsolution{\Sexpr{sum}}
%% \exname{Simple addition}

It is also recommended to change the order of the answers when using multiple/single choice questions.

Page 1 of 4123...Last »

## Storing hierarchical data structures in repositories

on Regards: PHP;

For the project Lenex2html a performance optimization was done for this Lenex library. The performance gain was significant: an example file had a reduced parsing time of 0,41 seconds instead of 7,3 seconds.

The lenex file format has a hierarchical structure. For instance: A Meet element has a subset of Sessions, which have a subset of Events. Events contain Agegroups and these contain Rankings. But the results themselves are stored at the Athlete entries (orange line), which are a subset of the Clubs, which are a subset of the Meet.

This can lead to difficult search operations, when you want to display the data in an other order than the hierarchical data structure. Here I present a proposal to store such data structures without loosing any information.

I created a generic repository called “ObjectRepository” (possibly there exist better names). This repository can also store indexes using a private array named “index”. The addIndex method converts the criteria parameter to a string using json_encode, as PHP does not support any other index data types than int or string. Then the result parameter is associated in the private “index” array of the class to the criteria as string. The findBy method then uses this private array. It looks if there exists a result for the specified criteria in the private array. It can be understood as a cache. If there are no cached results, the method searches for corresponding objects.
This implementation also allows you to create relations of objects on properties, which do not exist at all.

All in all: The simple idea of storing the parent-child relations in an index allows you to store hierarchical data structures simplified without loosing any information.

Page 1 of 4123...Last »

## Webseite für das Reparaturcafe Feldkirch gesponsert

on Regards: Other;

Wir freuen uns, bekanntgeben zu dürfen, dass wir die Webseite für das Reparaturcafe in Feldkirch gesponsert haben. Wir möchten damit einen Beitrag zur Bekämpfung der Wegwerfgesellschaft beitragen, indem dieses Reparaturcafe bekannter gemacht wird. Im Reparaturcafe werden defekte Geräte gemeinsam mit Experten repariert.

Das Design wurde von Norbert Pfleger entworfen. Aus einem Konzept für Printmedien entwickelte sich in der Zusammenarbeit eine schlicht gehaltene Webseite, die auch auf mobilen Platformen lesbar ist. Eine Vorgängerversion können Sie hier ansehen. Die endgültige Version können Sie auf http://www.reparaturcafe-feldkirch.at einsehen.

Page 1 of 4123...Last »

## Add Token Authorization to AngularJS and WebApi

on Regards: .NET Framework; C#;

### Protection and authorization for a Single Web Application and a RESTFul Service

#### Introduction

There exists some ways to implement an authentication into RESTFul Service. For this article I will focus on the HTTP Token Header technique, because its really easy to implement with the JsonWebTokenHandler.(RESTful Authentication, 22.08.2015, http://stackoverflow.com/questions/319530/restful-authentication?lq=1  ).

To keep it short we focus on the practical aspect. The demonstration contains a Single Web Application with AngularJS which is hosted on an ASP.NET MVC page. The RESTFul Service will be represented by an ASP.NET WebApi project. I want to mention that most of the code was built from code snippets which I researched from other blogs or stackoverflow to reduce time. So the example project consists of several code snippets and some custom coding.

As you know the RESTFul Service is stateless. We need to achieve that the WebApi can correctly identify our current requests to a user. There the token, or precisely the Json Web Token, comes into play. Because the returned data is formatted as JSON the term Json Web Token is more common in that subject.

When sending a valid login request to the WebApi, it will issue a token for the logged in user. The SWA will catch the returned token from the login. From now the SWA will add the token to each call into the HTTP Header. The WebApi will check if there exists a JWT and extract the containing user information. This process is visualized in the graphic below.

After associating a user to the request we can permit or deny the request.

{"iss":"Identity Provider","name":"John Doe","admin":true}

The Json Web Token is a JSON-based open standard which contains the user payload a signature and the following important header information’s (JSON Web Token, https://en.wikipedia.org/wiki/JSON_Web_Token, 22.08.2015).

• Issuer (iss) : The Service which created the jwt
• Subject (sub) : The subject regarding the token
• Audience (aud) : Which application can use the token
• Expiration time (exp): When expires the token
• Not before (nbf): Don’t use the token before
• Issued at (iat): When was the token created
• JWT ID (jti) : The ID of the token

(“JSON Web Token (JWT)”, https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html, 22.08.2015 )

#### Frontend – AngularJS

Our AngularJS web application has got an Authentication service which can initiate the login process. It sends the logon and the password to the webapi and saves the returned token. The token will be set to the default Authorization HTTP Header of the httpService (“Setting angularjs $http headers globally“, http://stackoverflow.com/questions/27134840/setting-angularjs-http-headers-globally, 22.08.2015). In order to prevent the user from navigating to any other page of our application, we add a callback to the angular module. When navigating between pages the callback checks if the user is logged in our Authentication service. This is done by registering the “$locationChangeStart” event which will be fired on any page navigation. If the user is not logged in we force a redirect to the login page. A logout can be done by refreshing the whole page, the state of the SWA will then be lost.

After a successful login we forward the user from the login- to the home view. The corresponding homeController makes an authenticated webapi request which will then return the current users privileges.

#### Backend – WebApi

Let’s switch to the WebApi’s PostUser action method. It is used to login a user and issue a security json web token.

First of all we check if the delivered user credentials are correct. Normally this is done by querying the database or another resource. The user and the roles are implemented with the claims-based identity of the Windows Identify Foundation. So if you never heard of claims you should definitely check Andras Nemes blog series about that topic (“Introduction to Claims based security in .NET4.5 with C# Part 4: authorisation with claims”, http://dotnetcodr.com/2013/02/21/introduction-to-claims-based-security-in-net4-5-with-c-part-4-authorisation-with-claims/, 22.08.2015 ).

For creating JSON Web Tokens Microsoft published the JwtSecurityTokenHandler class which can be found in the NuGet Package System.IdentityModel.Tokens.Jwt.

We create the ClaimsIdentity for the user which we wish to log in by adding his claims. After that we can create the token with tokenHandler.CreateToken(issuer: “http://localhost”, audience: “http://localhost”, subject: claimsIdentity, expires: expires, signingCredentials: new X509SigningCredentials(cert));

So as you see the issuer and audience value are equal because we create the token and at the same time consume it. With the expire parameter we can determine how long the token is valid and with the signing credentials we sign our token against manipulation. The returned encoded token is a base64 string.

The Json Web Token will be signed when issuing it with a private key. When a token will be “read”, it will be validated against the public key.

In this project I deposit the private and the public key as files, which is not recommended regarding security issues. In a real world example it would be stored in the certificate manager and for a convenient project start up I skipped that part. By the way, I used the following self-signed certificate tool http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net.

We should not only be able to create tokens, but also to read and “extract” the information from it. This can be done with a DelegatingHandler which intercepts every web request of the WebApi.

Vittorio Bertocci wrote an excellent article http://www.cloudidentity.com/blog/2013/01/09/using-the-jwt-handler-for-implementing-poor-man-s-delegation-actas/on that topic a while ago. The JwtSecurityTokenHandler has changed since the article was released.

What does the TokenValidationHandler do in particular?

First of all it intercept the web request before the concerning action method gets executed. It checks if the request contains a HTTP Header with the key Authorization. If not, the request will be forwarded to the action method. If you wish to protect the action method you can add a claimsauthorization attribute (details about that later).

If there exists a JWT token it will be validated against the TokenValidationParameters and the public key. With ValidateToken the user information from the token will be extracted and set the current user of the HttpContext and Thread. If the validation didn’t fail the request will be forwarded to the action method. Otherwise we abort the current request and return an unauthorized status code.

If for specific action methods certain claims are necessary we can use the ClaimsAuthorization attribute. Before the action method gets executed, it checks if the current HttpContext.User got the required claims.

#### Remarks

The solution is configured in a way that you can easily execute the project. Make sure you installed Visual Studio 2013 with the Web Development Tools and the latest updates. Also The Web Essential Tools should be installed with the latest TypeScript Version. You can Download the project from Github.

Press F5 to start the Web Project and navigate to http://localhost:5118/Default/Index/to start the SWA. Then switch to Visual Studio and right click on the WebApi Project and select Debug àStart new Instance. Create some breakpoints and try to login with the user martin in the web application and step through the program to see what’s happening.

Because the web projects are hosted under different domains (http://localhost:5118vs http://localhost:5117) we run into the CORS issue. To solve that I installed the CORS NuGet Package from Microsoft and enabled it with the EnableCors attribute. You may also want to check http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api.

I hope I could show you that it is really is easy to implement an authentication mechanism in AngularJS and ASP.NET WebApi. If you have any questions or suggestion feel free to comment or write me on twitter.