text:
/*
 * c8_check.cpp
 */
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <unistd.h>

#include "result.h"
#include "natural_check.h"
#include "integer_check.h"
#include "rational_check.h"

/*
 * No-op test used to find timing information.
 */
auto test_nop() -> result {
    result r("nop");

    r.start_clock();
    r.stop_clock();

    r.check_pass("");
    return r;
}

/*
 * Report the usage for this test program.
 */
static auto usage(const char *name) -> void {
    std::cerr << "usage: " << name << " [OPTIONS]\n\n";
    std::cerr << "Options\n";
    std::cerr << "  -b  Generate benchmark results (optional)\n";
    std::cerr << "  -v  Verbose reporting (optional)\n\n";
}

/*
 * List of tests to run.
 */
const test tests[] = {
    test_natural_construct_0,
    test_natural_construct_1,
    test_natural_construct_2,
    test_natural_construct_3,
    test_natural_construct_4,
    test_natural_construct_5,
    test_natural_construct_6,
    test_natural_construct_7,
    test_natural_size_bits_0,
    test_natural_size_bits_1,
    test_natural_size_bits_2,
    test_natural_size_bits_3,
    test_natural_add_0a,
    test_natural_add_0b,
    test_natural_add_1a,
    test_natural_add_1b,
    test_natural_add_2a,
    test_natural_add_2b,
    test_natural_add_3a,
    test_natural_add_3b,
    test_natural_add_4a,
    test_natural_add_4b,
    test_natural_subtract_0a,
    test_natural_subtract_0b,
    test_natural_subtract_1a,
    test_natural_subtract_1b,
    test_natural_subtract_2a,
    test_natural_subtract_2b,
    test_natural_subtract_3a,
    test_natural_subtract_3b,
    test_natural_subtract_4a,
    test_natural_subtract_4b,
    test_natural_subtract_5a,
    test_natural_subtract_5b,
    test_natural_compare_0a,
    test_natural_compare_0b,
    test_natural_compare_0c,
    test_natural_compare_0d,
    test_natural_compare_0e,
    test_natural_compare_0f,
    test_natural_compare_1a,
    test_natural_compare_1b,
    test_natural_compare_1c,
    test_natural_compare_1d,
    test_natural_compare_1e,
    test_natural_compare_1f,
    test_natural_compare_2a,
    test_natural_compare_2b,
    test_natural_compare_2c,
    test_natural_compare_2d,
    test_natural_compare_2e,
    test_natural_compare_2f,
    test_natural_compare_3a,
    test_natural_compare_3b,
    test_natural_compare_3c,
    test_natural_compare_3d,
    test_natural_compare_3e,
    test_natural_compare_3f,
    test_natural_lshift_0a,
    test_natural_lshift_0b,
    test_natural_lshift_1a,
    test_natural_lshift_1b,
    test_natural_lshift_2a,
    test_natural_lshift_2b,
    test_natural_lshift_3a,
    test_natural_lshift_3b,
    test_natural_lshift_4a,
    test_natural_lshift_4b,
    test_natural_lshift_5a,
    test_natural_lshift_5b,
    test_natural_lshift_6a,
    test_natural_lshift_6b,
    test_natural_rshift_0a,
    test_natural_rshift_0b,
    test_natural_rshift_1a,
    test_natural_rshift_1b,
    test_natural_rshift_2a,
    test_natural_rshift_2b,
    test_natural_rshift_3a,
    test_natural_rshift_3b,
    test_natural_rshift_4a,
    test_natural_rshift_4b,
    test_natural_rshift_5a,
    test_natural_rshift_5b,
    test_natural_rshift_6a,
    test_natural_rshift_6b,
    test_natural_multiply_0a,
    test_natural_multiply_0b,
    test_natural_multiply_1a,
    test_natural_multiply_1b,
    test_natural_multiply_2a,
    test_natural_multiply_2b,
    test_natural_multiply_3a,
    test_natural_multiply_3b,
    test_natural_multiply_4a,
    test_natural_multiply_4b,
    test_natural_multiply_5a,
    test_natural_multiply_5b,
    test_natural_divide_0a,
    test_natural_divide_0b,
    test_natural_divide_0c,
    test_natural_divide_1a,
    test_natural_divide_1b,
    test_natural_divide_1c,
    test_natural_divide_2a,
    test_natural_divide_2b,
    test_natural_divide_2c,
    test_natural_divide_3a,
    test_natural_divide_3b,
    test_natural_divide_3c,
    test_natural_divide_4a,
    test_natural_divide_4b,
    test_natural_divide_4c,
    test_natural_divide_5a,
    test_natural_divide_5b,
    test_natural_divide_5c,
    test_natural_divide_6a,
    test_natural_divide_6b,
    test_natural_divide_6c,
    test_natural_divide_7a,
    test_natural_divide_7b,
    test_natural_divide_7c,
    test_natural_divide_8a,
    test_natural_divide_8b,
    test_natural_divide_8c,
    test_natural_gcd_0,
    test_natural_gcd_1,
    test_natural_gcd_2,
    test_natural_gcd_3,
    test_natural_gcd_4,
    test_natural_to_unsigned_long_long_0,
    test_natural_to_unsigned_long_long_1,
    test_natural_to_unsigned_long_long_2,
    test_natural_to_unsigned_long_long_3,
    test_natural_to_unsigned_long_long_4,
    test_natural_print_0,
    test_natural_print_1,
    test_natural_print_2,
    test_natural_print_3,
    test_natural_print_4,
    test_natural_print_5,
    test_natural_print_6,
    test_natural_print_7,
    test_integer_construct_0,
    test_integer_construct_1,
    test_integer_construct_2,
    test_integer_construct_3,
    test_integer_construct_4,
    test_integer_construct_5,
    test_integer_construct_6,
    test_integer_construct_7,
    test_integer_construct_8,
    test_integer_construct_9,
    test_integer_construct_10,
    test_integer_construct_11,
    test_integer_add_0a,
    test_integer_add_0b,
    test_integer_add_1a,
    test_integer_add_1b,
    test_integer_add_2a,
    test_integer_add_2b,
    test_integer_add_3a,
    test_integer_add_3b,
    test_integer_subtract_0a,
    test_integer_subtract_0b,
    test_integer_subtract_1a,
    test_integer_subtract_1b,
    test_integer_subtract_2a,
    test_integer_subtract_2b,
    test_integer_subtract_3a,
    test_integer_subtract_3b,
    test_integer_compare_0a,
    test_integer_compare_0b,
    test_integer_compare_0c,
    test_integer_compare_0d,
    test_integer_compare_0e,
    test_integer_compare_0f,
    test_integer_compare_1a,
    test_integer_compare_1b,
    test_integer_compare_1c,
    test_integer_compare_1d,
    test_integer_compare_1e,
    test_integer_compare_1f,
    test_integer_compare_2a,
    test_integer_compare_2b,
    test_integer_compare_2c,
    test_integer_compare_2d,
    test_integer_compare_2e,
    test_integer_compare_2f,
    test_integer_compare_3a,
    test_integer_compare_3b,
    test_integer_compare_3c,
    test_integer_compare_3d,
    test_integer_compare_3e,
    test_integer_compare_3f,
    test_integer_lshift_0a,
    test_integer_lshift_0b,
    test_integer_lshift_1a,
    test_integer_lshift_1b,
    test_integer_lshift_2a,
    test_integer_lshift_2b,
    test_integer_lshift_3a,
    test_integer_lshift_3b,
    test_integer_lshift_4a,
    test_integer_lshift_4b,
    test_integer_rshift_0a,
    test_integer_rshift_0b,
    test_integer_rshift_1a,
    test_integer_rshift_1b,
    test_integer_rshift_2a,
    test_integer_rshift_2b,
    test_integer_rshift_3a,
    test_integer_rshift_3b,
    test_integer_rshift_4a,
    test_integer_rshift_4b,
    test_integer_multiply_0a,
    test_integer_multiply_0b,
    test_integer_multiply_1a,
    test_integer_multiply_1b,
    test_integer_multiply_2a,
    test_integer_multiply_2b,
    test_integer_multiply_3a,
    test_integer_multiply_3b,
    test_integer_divide_0a,
    test_integer_divide_0b,
    test_integer_divide_1a,
    test_integer_divide_1b,
    test_integer_divide_2a,
    test_integer_divide_2b,
    test_integer_divide_3a,
    test_integer_divide_3b,
    test_integer_divide_4a,
    test_integer_divide_4b,
    test_integer_magnitude_0,
    test_integer_magnitude_1,
    test_integer_magnitude_2,
    test_integer_to_long_long_0,
    test_integer_to_long_long_1,
    test_integer_to_long_long_2,
    test_integer_to_long_long_3,
    test_integer_to_long_long_4,
    test_integer_print_0,
    test_integer_print_1,
    test_integer_print_2,
    test_integer_print_3,
    test_integer_print_4,
    test_integer_print_5,
    test_integer_print_6,
    test_integer_print_7,
    test_rational_construct_0,
    test_rational_construct_1,
    test_rational_construct_2,
    test_rational_construct_3,
    test_rational_construct_4,
    test_rational_construct_5,
    test_rational_construct_6,
    test_rational_construct_7,
    test_rational_construct_8,
    test_rational_construct_9,
    test_rational_construct_10,
    test_rational_add_0a,
    test_rational_add_0b,
    test_rational_add_1a,
    test_rational_add_1b,
    test_rational_add_2a,
    test_rational_add_2b,
    test_rational_add_3a,
    test_rational_add_3b,
    test_rational_subtract_0a,
    test_rational_subtract_0b,
    test_rational_subtract_1a,
    test_rational_subtract_1b,
    test_rational_subtract_2a,
    test_rational_subtract_2b,
    test_rational_subtract_3a,
    test_rational_subtract_3b,
    test_rational_compare_0a,
    test_rational_compare_0b,
    test_rational_compare_0c,
    test_rational_compare_0d,
    test_rational_compare_0e,
    test_rational_compare_0f,
    test_rational_compare_1a,
    test_rational_compare_1b,
    test_rational_compare_1c,
    test_rational_compare_1d,
    test_rational_compare_1e,
    test_rational_compare_1f,
    test_rational_compare_2a,
    test_rational_compare_2b,
    test_rational_compare_2c,
    test_rational_compare_2d,
    test_rational_compare_2e,
    test_rational_compare_2f,
    test_rational_compare_3a,
    test_rational_compare_3b,
    test_rational_compare_3c,
    test_rational_compare_3d,
    test_rational_compare_3e,
    test_rational_compare_3f,
    test_rational_multiply_0a,
    test_rational_multiply_0b,
    test_rational_multiply_1a,
    test_rational_multiply_1b,
    test_rational_multiply_2a,
    test_rational_multiply_2b,
    test_rational_multiply_3a,
    test_rational_multiply_3b,
    test_rational_divide_0a,
    test_rational_divide_0b,
    test_rational_divide_1a,
    test_rational_divide_1b,
    test_rational_divide_2a,
    test_rational_divide_2b,
    test_rational_divide_3a,
    test_rational_divide_3b,
    test_rational_divide_4a,
    test_rational_divide_4b,
    test_rational_to_double_0,
    test_rational_to_double_1,
    test_rational_to_double_2,
    test_rational_to_double_3,
    test_rational_to_double_4,
    test_rational_to_parts_0,
    test_rational_to_parts_1,
    test_rational_print_0,
    test_rational_print_1,
    test_rational_print_2,
    test_rational_print_3,
    test_rational_print_4,
    test_rational_print_5,
    test_rational_print_6,
    test_rational_print_7,
    nullptr
};

/*
 * Entry point.
 */
auto main(int argc, char **argv) -> int {
    bool verbose = false;
    std::size_t loops = 1;

    /*
     * Parse the command line options.
     */
    int ch;
    while ((ch = getopt(argc, argv, "bv?")) != -1) {
        switch (ch) {
        case 'b':
            loops = 10000;
            break;

        case 'v':
            verbose = true;
            break;

        case '?':
            usage(argv[0]);
            exit(-1);
        }
    }

    /*
     * Run a prolonged no-op test to warm up any power-saving modes to move
     * into a higher performance state.  We do this by running the no-op test
     * repeatedly for 2 seconds.
     */
    std::vector<std::chrono::nanoseconds> nop_durations;
    nop_durations.reserve(1000);

    std::time_t t = std::time(nullptr);
    std::time_t s;

    do {
        for (std::size_t i = 1; i < 1000; i++) {
            result r = test_nop();
            nop_durations.push_back(r.get_elapsed());
        }

        s = std::time(nullptr);
    } while ((s - t) < 2);

    /*
     * Take the 0.01% value - we need to make sure we've picked up one after everything
     * is running in a performance state.
     */
    std::nth_element(nop_durations.begin(), nop_durations.begin() + (nop_durations.size() / 10000), nop_durations.end());
    auto nop_duration = nop_durations[nop_durations.size() / 10000];

    /*
     * Run the tests.
     */
    bool res = true;

    const test *p = tests;
    while (*p) {
        std::vector<std::chrono::nanoseconds> durations;
        durations.reserve(loops);

        /*
         * Run one test every time.  This gives the pass/fail status.
         */
        result r = (*p)();
        bool rp = r.get_pass();
        durations.push_back(r.get_elapsed());

        /*
         * Run more tests if we're running a benchmark.
         */
        for (std::size_t i = 1; i < loops; i++) {
            result l = (*p)();
            durations.push_back(l.get_elapsed());
        }

        /*
         * If we're being verbose then print the results.  We print the 20th percentile result if
         * this is a benchmark test.  Lower than the 10th percentile we can see some rather
         * odd timing results and greater than the 50th percentile we can run into problems
         * related to scheduling.  The 20th percentile number is an empirical choice.
         */
        if (verbose) {
            std::nth_element(durations.begin(), durations.begin() + (durations.size() / 5), durations.end());
            std::cout << std::setw(14) << std::left << r.get_name() << " | ";
            auto d = durations[durations.size() / 5] - nop_duration;
            std::cout << std::setw(10) << std::right << d.count() << " | " << (rp ? "pass" : "FAIL");
            std::cout << " | " << r.get_stream().str();
            if (!rp) {
                std::cout << " (" << r.get_expected() << ')';
            }

            std::cout << '\n';
        }

        res &= rp;
        p++;
    }

    if (!res) {
        std::cout << "TESTS FAILED!\n";
        exit(-1);
    }

    std::cout << "All tests passed\n";
    return 0;
}


text:
In the previous chapter, you already saw how NativeScript leverages the concept of 'modules' to include bits of code that are kept in the `tns_modules` folder. Using `require()`, you can include these snippets ad hoc in your code when you need to use them, similar to the way you use npm to import node libraries. Let's take a closer look at these modules and what they can do for your app.

>If you dig a bit into the tns_modules folder and find the http folder, you can see how a NativeScript module is constructed. It includes:
- a package.json file that sets the name of the module and includes the base file that defines the module.
- a file containing android native code (http-request.android.js).
- a file containing ios native code (http-request.ios.js).
- a generic file (http.js) that abstracts the platform-specific code above into a platform-agnostic API so that you can make HTTP calls on both platforms using a single JavaScript API.

>A note about platform-specific files: Any file, whether XML, CSS, or JavaScript, in NativeScript can have a platform-specific file and will be named accordingly. These files are included on an ad hoc basis when NativeScript compiles an app - for an iOS app, the ios file is included, and for Android, the android version is included. These files contain native code to manage device-specific actions, but a platform-specific file written in XML or CSS might contain code to make the presentation layer behave or look differently on a different platform. We'll explore this method in detail below.

More information on modules can be found [here](http://developer.telerik.com/featured/nativescript-works/).

### Connecting the model to the back end with the http module

You probably noticed, if you created your own user on the registration page, that data was passing magically...somewhere. There's actually no magic involved; there is a config file that contains an API Key to [Telerik BackEnd Services](http://www.telerik.com/backend-services), where we are storing our users' information. You don't have to use Telerik Backend Services; you can connect to any back end endpoint you like! The Groceries app just happens to use the Telerik endpoint.

Take a look at `app/shared/config.js`. There's only a small code snippet there, but it includes a hard-coded API Key that we use throughout the app to access the back end (in real life, you would of course use your own API Key):

```
module.exports = {
	apiUrl: "http://api.everlive.com/v1/GWfRtXi1Lwt4jcqK/"
};
```

Take a look in `app/shared/models`. Normally, models use a service to connect to and communicate with a back end. In this case, the connection code is added directly into the model for simplicity. You can see this demonstrated in the registration function.

Note that the config file is used in all the model files, for example in User model: `app/shared/models/User.js`:

```
var config = require("../../shared/config");
```

    Exercise: Complete the login in the model

To complete the login of a user, in `app/shared/Models/Users.js`, under the line where you require `config`, you need to require [the http module](http://docs.nativescript.org/ApiReference/http/README.html). This module allows the app to communicate with an external endpoint over HTTP.

```
var http = require("http");
```

Now you can build out the login function. Paste in the following code in between the login function brackets:

```
	var that = this;
	return new Promise(function(resolve, reject) {
		http.request({
			url: config.apiUrl + "oauth/token",
			method: "POST",
			content: JSON.stringify({
				username: that.get("email_address"),
				password: that.get("password"),
				grant_type: "password"
			}),
			headers: {
				"Content-Type": "application/json"
			}
		}).then(function(data) {
			config.token = data.content.toJSON().Result.access_token;
			resolve();
		}).catch(function() {
			reject();
		});
	});
```
What's going on here?

- First, you alias the `this` variable by assigning it to a private variable, `that`. This allows you to continue to access the original value of `this` in inner functions

- Second, you return a new Promise, which primarily allows the caller ofthis function to execute code after the asynchronous login either completes successfully or fails.

>**Promises**: [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) are a part of ECMAScript 6 (the scripting language of which JavaScript is an implementation) that have been implemented in Google's V8 engine and JavaScriptCore framework (which provides a JavaScript engine for WebKit) and are thereby available in NativeScript apps.

- Next, you use the http module's [`request()` method](http://docs.nativescript.org/ApiReference/http/HttpRequestOptions.html) to POST data to the `apiUrl` that is set up in config. The username, password and grant_type are sent to this endpoint as a JSON string. Telerik Backend Services [uses the parameter of grant_type](http://docs.telerik.com/platform/backend-services/development/rest-api/users/authenticate-user) for login.

- Finally, the endpoint's response is handled. `Http.request()` returns a Promise, which this code uses to either resolve or reject its own Promise. When the request is successful, the code saves a reference to the user's authentication token to be used on subsequent requests.

### Dialog module

The dialog module can be used to show [several types](http://docs.nativescript.org/ApiReference/ui/dialogs/HOW-TO.html) of popup UIs in your app, including action, confirm, alert, login, and prompt dialogs. It is a highly customizable module so that you can provide good prompts to your users, and it allows you to control the buttons you include int he alert, their text, and the messaging in the alert itself. Its code is found in the tns_modules/ui folder with other UI widgets.

	Exercise: Handle an error with a dialog window

Allow the view model to invoke the login function that you just added to the model. In  `app/views/login/login.js` rewrite your `signIn()` function to look like this:

```
exports.signIn = function() {
	user.login()
		.then(function() {

		}).catch(function() {
			dialogs.alert({
				message: "Unfortunately we could not find your account.",
				okButtonText: "OK"
			});
		});
};
```

What's happening here? In this case, the `login()` function uses the Promise approach that is returned by the login prototype in `app/shared/models/User.js` to handle both a successful and an unsuccessful login. If the login is unsuccessful, we show a dialog with a popup button stating that your account can't be found.

Now that you are able to handle an unsuccessful login, you need to allow people to view their grocery list after they successfully login. Once the user logs in, you can use the "list" page to facilitate adding and removing groceries to and from a list. To do that, you need a module that will show items in a list, which is exactly what the ListView does.

### ListView

Let's use another UI module to craft a page to actually hold our grocery data. This is the page we want users to navigate to once they login, so let's add a line in `app/views/login/login.js` to allow this navigation to happen. In the `signIn()` function you edited above, add the following line after `.then(function(){`:

```
frameModule.topmost().navigate("./views/list/list");
```

Now, if you rebuild and run your app in an emulator, you can login either using your credentials that you created earlier, or TJ's:

![login 6](images/login-stage6-ios.png)
![login 6](images/login-stage6-android.png)

You'll find that after you login, you're sent to a blank screen. You're going to build a list to hold grocery data next.

    Exercise: Construct the list view

In `app/views/list/list.xml`, let's get started using the ListView module by creating a list where our groceries will reside:

```
<Page navigatedTo="navigatedTo">
	<GridLayout>
		<ListView items="{{ groceryList }}">
			<ListView.itemTemplate>
				<Label text="{{ name }}" horizontalAlignment="left" verticalAlignment="center"/>
			</ListView.itemTemplate>
		</ListView>
	</GridLayout>
</Page>
```

>navigatedTo: The navigatedTo function that is called during the navigation event allows data to pass from one page to another when navigation is occurring. In this case, the navigatedTo function in `app/views/list/list.js` will set the page title for iOS, sets up the deletion module, sets up binding, and empties and reloads the list. You'll build this functionality below.

Note the use of the ListView module. In this case, we're not requiring a tns_module from the ui folder, but are rather using the ui widget within the xml code. This is a different way to use these modules.

If you wanted to, you could construct a ListView in pure JavaScript code behind the scenes as shown in [this example](http://docs.nativescript.org/ApiReference/ui/list-view/HOW-TO.html). However for now, you can simply use xml to build the ListView and thereby follow the pattern you use in the login and register screens.

Finally, note the ListView's use of an itemTemplate. Using an itemTemplate gives you more control over how the actual items look within the list.

>Tip: Other modules
There are several modules that come out of the box with your NativeScript install, including a location service, a file-system helper, timer, camera, and even a color module that helps navigate the ways various colors are handled cross-platform. If you are interested in helping build and distribute more modules for the community, there's a [good guide](http://developer.telerik.com/featured/building-your-own-nativescript-modules-for-npm/) available on how to do this.

If you were to run this code as it stands, you wouldn't see any items in the grocery list. You need to build out a way to manage data within the ListView module.

### Working with arrays

To be able to manage data in the grocery list, you need to build a connection between the presentation tier and the database as you did for login. Go ahead and build out these pieces in your grocery list.

    Exercise: Populate the list view

In app/views/list/list.js, add:

```
var GroceryList = require("../../shared/models/GroceryList");

var page;
var pageData = new observable.Observable();
var groceryList = []; // create an empty array
var tmpList = ["eggs","bread","cereal"];

for (var i = 0, size = tmpList.length; i < size ; i++) {
		groceryList.push({id: i, name: tmpList[i]});
	}

pageData.set("groceryList", groceryList);

exports.navigatedTo = function(args) {
	page = args.object;
	page.bindingContext = pageData;

};

```

Here, you're creating a new empty grocery array and, for the moment, populating it with some grocery items. You can see how this data is pulled into the page when you navigate to this page via the pageData observable object.

Now if you were to run this code in the emulator, you would see a list of your hard-coded values:

<>images

You need, however, to load up any grocery items that exist in the database to which you just logged in, however, so edit the code above to change the hard-coded values into an object that references the model:

```
var GroceryList = require("../../shared/models/GroceryList");

var page;
var pageData = new observable.Observable();
var groceryList = new GroceryList();

pageData.set("groceryList", groceryList);

exports.navigatedTo = function(args) {
	page = args.object;
	page.bindingContext = pageData;

	groceryList.empty();
	groceryList.load();
};
```

In this code, groceryList is now referencing the grocery list model and in the navigatedTo function, the groceryList object is emptied and then reloaded from the database so that the data remains current.

Now you should build out the `empty()` and `load()` functions in the model so that we can get this data from the database.

In `app/shared/models/GroceryList.js`, grab any Grocery data that might exist in the back end and push it into the grocery array:

```
GroceryList.prototype.load = function() {
	var that = this;
	http.getJSON({
		url: config.apiUrl + "Groceries",
		method: "GET",
		headers: {
			"Authorization": "Bearer " + config.token
		}
	}).then(function(data) {
		data.Result.forEach(function(grocery) {
			that.push({
				name: grocery.Name,
				id: grocery.Id
			});
		});
	});
};
GroceryList.prototype.empty = function() {
	while (this.length) {
		this.pop();
	}
};
```

In the load function above, you are pulling down the list associated to the user's credentials. In the empty function, you clear out the array and get ready to reload it. If you rebuild, run the app, and login as tj.vantoll@gmail.com, you'll find a list of groceries pulled from Backend Services in the Groceries data type. It will look something like this:

![list ios](images/list-ios.png)
![list android](images/list-android.png)

It's great that you can see data already in the database, but you also need to add some items. Go ahead and build that functionality.

    Exercise: Add the ability to create a Grocery item

First, add another parameter to the pageData observable object as an empty placeholder in `app/views/list/list.js` above the line: `pageData.set("groceryList", groceryList);`:

```
pageData.set("grocery", "");
```

Edit the list view xml to allow for a two column layout with a text field and a button to add grocery items. Change the GridLayout in `app/views/list/list.xml` initial tag to account for this layout:

```
<GridLayout rows="auto, *" columns="*, *, *">
```
>This layout will include two rows, one auto-sized according to its children's dimensions, and the other stretchable to allow for the expanding list. It will have three auto-stretching columns as the text field will occupy two columns and the button one column.

Add a text field and a button to have a place to enter grocery items. The text field will have the id 'grocery' and is bound to the grocery object, has a hint that will show on the front end to help the user, will occupy one row and two columns. The button will have a tap event - `tap` and will occupy the initial row as well and the third column - remember numbering of rows and columns starts at zero. Add these two lines after the GridLayout initial tag:

```
	<TextField id="grocery" text="{{ grocery }}" hint="Enter a grocery item" row="0" colspan="2" />
	<Button text="Add" tap="add" row="0" col="2"></Button>
```
Finally, edit the `<ListView>` tag to ensure that it will expand across the new columns you created:

```
<ListView items="{{ groceryList }}" id="groceryList" row="1" colSpan="3">
```

Now you are ready to build the add tap event.

In app/views/list/list.js, add a function to respond to the 'add' tap event that you just added. You'll put this underneath the navigatedTo function.

```
exports.add = function() {
	//check for empty submission
	if (groceryList.isValidItem(pageData.get("grocery"))) {
		//dismiss the keyboard
		view.getViewById(page, "grocery").dismissSoftInput();
		groceryList.add(pageData.get("grocery"))
			.catch(function() {
				dialogs.alert({
					message: "An error occurred adding to your list.",
					okButtonText: "OK"
				});
			});
		//empty the input field
		pageData.set("grocery", "");
	} else {
		dialogs.alert({
			message: "Please enter a grocery item",
			okButtonText: "OK"
		});
	}
};
```
In this function, you test for an empty value, and if this test passes, dismiss the keyboard, then get the 'grocery' item from the input field and add it to the groceryList object.

Finally, let the manipulation of this new data be handled in the model by adding the following function under the 'empty' function in /app/shared/models/GroceryList.js:

```
GroceryList.prototype.add = function(grocery) {
	var that = this;
	return new Promise(function(resolve, reject) {
		http.request({
			url: config.apiUrl + "Groceries",
			method: "POST",
			content: JSON.stringify({
				Name: grocery
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		}).then(function() {
			that.push({ name: grocery });
			resolve();
		}).catch(function() {
			reject();
		});
	});
};
```

If you build and rerun your app now, you'll find that you can add a grocery item and it will appear immediately in your list.

Now that you have login, registration, and list routines complete, you can enhance the app's functionality as a grocery list management tool. You can use the NativeScript Social Sharing plugin to get the data you input into an email so you can send yourself a reminder to pick up your groceries.

redpajama_set_name: RedPajamaGithub


text:
namespace p09___PairsByDifference
{
    using System;
    using System.Linq;

    public class PairsByDifference
    {
        public static void Main()
        {
            var numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int difference = int.Parse(Console.ReadLine());

            int count = 0;

            for (int i = 0; i < numbers.Length; i++)
            {
                for (int j = i+1; j < numbers.Length; j++)
                {
                    if (Math.Abs(numbers[i] - numbers[j]) == difference && i < j)
                    {
                        count++;
                    }
                }
            }
            Console.WriteLine(count);
        }
    }
}


text:
package com.baidubce.services.as.model.asgroup;

import com.baidubce.services.as.model.zone.ZoneInfo;

import java.util.List;

/**
 * The information of the asGroup.
 */
public class AsGroup {
    /**
     * The id of specified auto scaling group.
     */
    private String groupId;

    /**
     * The name of specified auto scaling group.
     */
    private String groupName;

    /**
     * The region where the auto scaling group is located
     */
    private String region;

    /**
     * Current status of the auto scaling group
     */
    private AsGroupStatus status;

    /**
     * The if of vpc
     */
    private String vpcId;

    /**
     * Number of nodes in the auto scaling group
     */
    private int nodeNum;

    private String createTime;

    private List<ZoneInfo> zoneInfo;

    /**
     * The spec of auto scaling group
     */
    private GroupConfig groupConfig;

    private String blbId;

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public AsGroupStatus getStatus() {
        return status;
    }

    public void setStatus(AsGroupStatus status) {
        this.status = status;
    }

    public String getVpcId() {
        return vpcId;
    }

    public void setVpcId(String vpcId) {
        this.vpcId = vpcId;
    }

    public int getNodeNum() {
        return nodeNum;
    }

    public void setNodeNum(int nodeNum) {
        this.nodeNum = nodeNum;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public List<ZoneInfo> getZoneInfo() {
        return zoneInfo;
    }

    public void setZoneInfo(List<ZoneInfo> zoneInfo) {
        this.zoneInfo = zoneInfo;
    }

    public GroupConfig getGroupConfig() {
        return groupConfig;
    }

    public void setGroupConfig(GroupConfig groupConfig) {
        this.groupConfig = groupConfig;
    }

    public String getBlbId() {
        return blbId;
    }

    public void setBlbId(String blbId) {
        this.blbId = blbId;
    }

    @Override
    public String toString() {
        return "AsGroup{" +
                "groupId='" + groupId + '\'' +
                ", groupName='" + groupName + '\'' +
                ", region='" + region + '\'' +
                ", status=" + status +
                ", vpcId='" + vpcId + '\'' +
                ", nodeNum=" + nodeNum +
                ", createTime='" + createTime + '\'' +
                ", zoneInfo=" + zoneInfo +
                ", groupConfig=" + groupConfig +
                ", blbId='" + blbId + '\'' +
                '}';
    }
}


text:
import { ClientMiddlewareParameters, ClientMiddleware } from '../middleware'
import { readJSONOrText } from '../utils'

const parseResponse = async (
  response: Response,
  params: ClientMiddlewareParameters
) => {
  const result = await readJSONOrText<{ data: any }>(response)

  if (typeof result === 'string') {
    return result
  }

  const { deserializer } = params
  if (
    typeof deserializer === 'function' &&
    result != null &&
    result.data != null
  ) {
    result.data = deserializer(result.data)
  }
  params.end({
    result,
    headers: response.headers,
  })
}

export const createParseResponseMiddleware = (): ClientMiddleware<Response> =>
  parseResponse.bind(null)


text:
<?php

namespace Knax\TestingBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * UserdataRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserdataRepository extends EntityRepository
{
}


text:
/* eslint-disable quotes */
'use strict';

let babel = require('babel-core');
let devExpressionWithCodes = require('../dev-expression-with-codes');

function transform(input) {
  return babel.transform(input, {
    plugins: [devExpressionWithCodes],
  }).code;
}

function compare(input, output) {
  var compiled = transform(input);
  expect(compiled).toEqual(output);
}

var oldEnv;

describe('dev-expression', () => {
  beforeEach(() => {
    oldEnv = process.env.NODE_ENV;
    process.env.NODE_ENV = '';
  });

  afterEach(() => {
    process.env.NODE_ENV = oldEnv;
  });

  it('should replace __DEV__ in if', () => {
    compare(
      `
if (__DEV__) {
  console.log('foo')
}`,
      `
if (process.env.NODE_ENV !== 'production') {
  console.log('foo');
}`
    );
  });

  it('should replace warning calls', () => {
    compare(
      "warning(condition, 'a %s b', 'c');",
      "process.env.NODE_ENV !== 'production' ? warning(condition, 'a %s b', 'c') : void 0;"
    );
  });

  it("should add `reactProdInvariant` when it finds `require('invariant')`", () => {
    compare(
      "var invariant = require('invariant');",
      `var _prodInvariant = require('reactProdInvariant');

var invariant = require('invariant');`
    );
  });

  it('should replace simple invariant calls', () => {
    compare(
      "invariant(condition, 'Do not override existing functions.');",
      "var _prodInvariant = require('reactProdInvariant');\n\n" +
        '!condition ? ' +
        "process.env.NODE_ENV !== 'production' ? " +
        "invariant(false, 'Do not override existing functions.') : " +
        `_prodInvariant('16') : void 0;`
    );
  });

  it('should only add `reactProdInvariant` once', () => {
    var expectedInvariantTransformResult =
      '!condition ? ' +
      "process.env.NODE_ENV !== 'production' ? " +
      "invariant(false, 'Do not override existing functions.') : " +
      `_prodInvariant('16') : void 0;`;

    compare(
      `var invariant = require('invariant');
invariant(condition, 'Do not override existing functions.');
invariant(condition, 'Do not override existing functions.');`,
      `var _prodInvariant = require('reactProdInvariant');

var invariant = require('invariant');
${expectedInvariantTransformResult}
${expectedInvariantTransformResult}`
    );
  });

  it('should support invariant calls with args', () => {
    compare(
      "invariant(condition, 'Expected %s target to be an array; got %s', 'foo', 'bar');",
      "var _prodInvariant = require('reactProdInvariant');\n\n" +
        '!condition ? ' +
        "process.env.NODE_ENV !== 'production' ? " +
        "invariant(false, 'Expected %s target to be an array; got %s', 'foo', 'bar') : " +
        `_prodInvariant('7', 'foo', 'bar') : void 0;`
    );
  });

  it('should support invariant calls with a concatenated template string and args', () => {
    compare(
      "invariant(condition, 'Expected a component class, ' + 'got %s.' + '%s', 'Foo', 'Bar');",
      "var _prodInvariant = require('reactProdInvariant');\n\n" +
        '!condition ? ' +
        "process.env.NODE_ENV !== 'production' ? " +
        "invariant(false, 'Expected a component class, got %s.%s', 'Foo', 'Bar') : " +
        `_prodInvariant('18', 'Foo', 'Bar') : void 0;`
    );
  });

  it('should warn in non-test envs if the error message cannot be found', () => {
    spyOn(console, 'warn');
    transform("invariant(condition, 'a %s b', 'c');");

    expect(console.warn.calls.count()).toBe(1);
    expect(console.warn.calls.argsFor(0)[0]).toBe(
      'Error message "a %s b" ' +
        'cannot be found. The current React version ' +
        'and the error map are probably out of sync. ' +
        'Please run `yarn build -- --extractErrors` to build React with the error map in sync.'
    );
  });

  it('should not warn in test env if the error message cannot be found', () => {
    process.env.NODE_ENV = 'test';

    spyOn(console, 'warn');
    transform("invariant(condition, 'a %s b', 'c');");

    expect(console.warn.calls.count()).toBe(0);

    process.env.NODE_ENV = '';
  });
});


text:
import dataset
import datetime

# create a database and a table
db = dataset.connect('mysql://root@localhost/kickstarter')
table = db['campaign_basics']

def now():
    return datetime.datetime.now()

# insert time-stamped campaign info into the database
def insert_campaign(campaign_info):
    campaign_info['date_observed'] = now()
    table.insert(campaign_info)


text:
class UnshiftUint16Base {
protected:
	SourceBase<Uint16> *source;
public:
	UnshiftUint16Base(SourceBase<Uint16>& i)
		{
			source=&i;
		}
	virtual size_t read(void)			= 0;
	virtual const Uint16 *getBuffer(void) 		= 0;
	virtual size_t getBufferCount(void) const	= 0;
	virtual int good(void) const	{ return source && source->good(); }
};

class UnshiftUint16General : public UnshiftUint16Base {
	Uint16 *buffer;
	size_t bufsize;
	size_t length;
	Uint16 mask;
	unsigned short rightshift;
public:
	UnshiftUint16General(SourceBase<Uint16>& i,unsigned short bitsstored,unsigned short highbit)
			:UnshiftUint16Base(i)
		{
			buffer=0;
			bufsize=0;
			length=0;

			mask=(Uint16)(((Uint32)1<<bitsstored)-1);
			rightshift=highbit+1-bitsstored;

			// sign extension not implemented yet
		}

	~UnshiftUint16General()
		{
			Assert((!bufsize && !buffer) || (bufsize && buffer));
			if (buffer) delete[] buffer;
		}

	size_t read(void)
		{
			Assert(source);
			if (source->read()) {
				length=source->getBufferCount();

				if (bufsize < length) {
					Assert((!bufsize && !buffer) || (bufsize && buffer));
					if (buffer) delete[] buffer;
					bufsize=length;
					buffer=new Uint16[bufsize];
				}

				const Uint16 *src=source->getBuffer();
				Uint16 *dst=buffer;
				size_t n=length;
				while (n--) *dst++=(*src++>>rightshift)&mask;
			}
			else length=0;
			return length;
		}

	const Uint16 *getBuffer(void)		{ return buffer; }
	size_t getBufferCount(void) const	{ return length; }
};

// These are the classes that are actually used as filters ...

class UnshiftUint16 : public FilterSourceToSinkBase<Uint16,Uint16> {
	UnshiftUint16Base *convertor;
public:
	UnshiftUint16(SourceBase<Uint16>& i,
			unsigned short bitsallocated,unsigned short bitsstored,unsigned short highbit)
		: FilterSourceToSinkBase<Uint16,Uint16>(i)
		{
			Assert(bitsallocated <= 16u);
			Assert(bitsstored <= bitsallocated);
			Assert(highbit <= bitsallocated-1u);

			// no optimizations yet ...
			convertor=new UnshiftUint16General(i,bitsstored,highbit);

			Assert(convertor);
		}

	size_t read(void)			{ return convertor->read(); }
	const Uint16 *getBuffer(void) 		{ return convertor->getBuffer(); }
	size_t getBufferCount(void) const	{ return convertor->getBufferCount(); }
	int good(void) const			{ return convertor->good(); }
};

#endif // __Header_FromShift__


text:
export const DELETE_DECK_COMMENT_REQUEST = 'DELETE_DECK_COMMENT_REQUEST';
export const DELETE_DECK_COMMENT_SUCCESS = 'DELETE_DECK_COMMENT_SUCCESS';
export const DELETE_DECK_COMMENT_FAILURE = 'DELETE_DECK_COMMENT_FAILURE';


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('galleries', '0018_auto_20190104_1502'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='gallerymedia',
            name='gallery',
        ),
        migrations.RemoveField(
            model_name='gallerymedia',
            name='media',
        ),
        migrations.DeleteModel(
            name='GalleryMedia',
        ),
    ]