text:
/**
 * Created by Luigi Ilie Aron on 27.01.15.
 * email: luigi@kreditech.com
 */
'use strict';
var Errors = require('waterline-errors').adapter,
    Connection = require('./connection'),
    Collection = require('./collection'),
    fs = require('fs'),
    util = require('util'),
    async = require('async'),
    _ = require('lodash');

module.exports = (function () {
    // Keep track of all the connections used by the app
    var connections = {},
        db = null;

    var adapter = {
        // Which type of primary key is used by default
        pkFormat: 'string',
        // to track schema internally
        syncable: true,
        identity: "waterline-cbes",
        schema: false,
        // Default configuration for connections
        defaults: {
            // couch base
            cb: {
                //Server
                version: '3.0.3',
                host: 'localhost',
                port: 8091,
                user: 'root',
                pass: 'root123',
                operationTimeout: 1000 * 10, // 10 seconds

                //bucket
                bucket: {
                    name: 'testCbes',
                    pass: ''
                }
            },
            // elastic search
            es: {
                host: ['192.168.33.10:9200'],
                log: 'error',
                index: 'test_cbes',
                numberOfShards: 5,
                numberOfReplicas: 1,
                requestTimeout: 30000,
                ttlInterval: 5000 //milliseconds
            }
        },

        /**
         * @param connection
         * @param collections
         * @param cb
         * @returns {*}
         */
        registerConnection: function (connection, collections, cb) {
            if (!connection.identity) return cb(Errors.IdentityMissing);
            if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);

            // Store the connection
            connections[connection.identity] = {
                config: connection,
                collections: {}
            };

            // Create new connection
            new Connection(connection, collections,function(_err, connectionObject) {
                if (_err) {
                    return cb((function _createError() {
                        var msg = util.format('Failed to connect to the Couchbase/ElasticSearch clients', util.inspect(_err, false, null));
                        var err = new Error(msg);
                        err.originalError = _err;
                        return err;
                    })());
                }

                connections[connection.identity].connection = connectionObject;
                Object.keys(collections).forEach(function(key) {
                    connections[connection.identity].collections[key] = new Collection(collections[key], key, connectionObject);
                });

                cb();
            });
        },

        /**
         * Fired when a model is unregistered, typically when the server
         * is killed. Useful for tearing-down remaining open connections,
         * etc.
         *
         * @param  {Function} cb [description]
         * @return {[type]}      [description]
         */
        teardown: function (conn, cb) {
            if (typeof conn == 'function') {
                cb = conn;
                conn = null;
            }

            if (!conn) {
                connections = {};
                return cb();
            }

            if (!connections[conn]) return cb();
            delete connections[conn];

            cb();
        },

        describe: function (connection, collection, cb) {
            // Add in logic here to describe a collection (e.g. DESCRIBE TABLE logic)
            return cb();
        },

        /**
         *
         * REQUIRED method if integrating with a schemaful
         * (SQL-ish) database.
         *
         */
        define: function (connection, collection, definition, cb) {
            // Add in logic here to create a collection (e.g. CREATE TABLE logic)
            return cb();
        },

        /**
         *
         * REQUIRED method if integrating with a schemaful
         * (SQL-ish) database.
         *
         */
        drop: function (connection, collection, relations, cb) {
            // Add in logic here to delete a collection (e.g. DROP TABLE logic)
            return cb();
        },

        /**
         * @param connection
         * @param collection
         * @param options
         * @param callback
         */
        find: function (connection, collection, options, callback) {
            var db = require('./db')(connections[connection].connection);

            db.find(collection, options, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });
        },

        /**
         * @param connection
         * @param collection
         * @param values
         * @param callback
         */
        create: function (connection, collection, values, callback) {
            var db = require('./db')(connections[connection].connection),
                originalVals = _.cloneDeep(values),
                _values = [],
                schema = connections[connection].collections[collection].schema;

            if (!Array.isArray(values)) {
                values = [values];
            }

            var uniqueFields = (function() {
                var unique = [];

                for (var key in schema) {
                    val = schema[key];

                    if (val.hasOwnProperty("unique") && val["unique"] === true) {
                        if (key != "id") {
                            unique.push(key);
                        }
                    }
                }

                return unique
            })();

            function create() {
                if (schema.hasOwnProperty('_ttl') &&
                    schema._ttl.hasOwnProperty('defaultsTo') &&
                    typeof schema._ttl.defaultsTo == 'number')
                {
                    if (val.hasOwnProperty('_ttl') && typeof val._ttl == 'number') {
                        _ttl = val._ttl;
                    } else {
                        _ttl = schema._ttl.defaultsTo;
                    }
                }

                db.create(collection, val, _ttl, function(err, _vals){
                    if (err){
                        return callback(err, false);
                    }

                    _values.push(_vals);

                    if ((i + 1) == values.length) {
                        callback(null, Array.isArray(originalVals) ? _values : _values[i]);
                    }
                });
            }

            for (var i in values) {
                var _ttl = 0,
                    val = values[i];

                if (uniqueFields.length > 0) {
                    var _termData = [],
                        q = {where: {or: []}};

                    for (var j in uniqueFields) {
                        var _field = uniqueFields[j],
                            _term  = {term: {}};

                        if (val[_field] && val[_field] != "undefined" && val[_field] != "") {
                            _term.term[_field] = val[_field];
                            _termData.push(_term)
                        }
                    }

                    q.where.or = _termData;

                    db.find(collection, q, function(err, res){
                        if (err) {
                            return callback(err, null);
                        }

                        if (res.length > 0) {
                            return callback(new Error("Unique field already exist!"), null);
                        }

                        create();
                    });
                } else {
                    create();
                }
            }
        },

        /**
         * @param connection
         * @param collection
         * @param options
         * @param values
         * @param callback
         */
        update: function (connection, collection, options, values, callback) {
            var db = require('./db')(connections[connection].connection);

            db.update(collection, options, values, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });
        },

        /**
         * @param connection
         * @param collection
         * @param options
         * @param callback
         */
        destroy: function (connection, collection, options, callback) {
            if (
                options &&
                typeof options == 'object' &&
                Object.keys(options).length == 1 &&
                options.hasOwnProperty('where') &&
                options.where instanceof Object &&
                options.where !== null &&
                Object.keys(options.where).length == 1 &&
                options.where.hasOwnProperty('id')
            ) {
                options.where = {
                    bool: {
                        must: [
                            {
                                term: {
                                    _id: options.where.id
                                }
                            }
                        ]
                    }
                };
            }

            var db = require('./db')(connections[connection].connection);
            db.destroy(collection, options, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });
        },

        /**
         * @param connection
         * @param collection
         * @param options
         * @param callback
         */
        count: function (connection, collection, options, callback) {
            var db = require('./db')(connections[connection].connection);
            db.count(collection, options, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });
        },

        /**
         * get raw data from couchbase view
         * @param connection
         * @param collection
         * @param callback
         */
        getRawCollection: function (connection, collection, callback) {
            var db = require('./db')(connections[connection].connection);

            db.getCollection(collection, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });
        },

        /**
         *
         * @param connection
         * @param collection
         * @param callback
         */
        reindex : function(connection, collection, callback) {
            var db = require('./db')(connections[connection].connection),
                schema = connections[connection].collections[collection].schema,
                _ttl = null;

            if (schema.hasOwnProperty('_ttl') &&
                schema._ttl.hasOwnProperty('defaultsTo') &&
                typeof schema._ttl.defaultsTo == 'number')
            {
                _ttl = {
                    "enabled": true,
                    "default": schema._ttl.defaultsTo
                };
            }

            db.reindex(collection, this.mapping, _ttl, callback);
        },

        reindexAll: function(connectionName, collection, callback) {
            var collections = connections[connectionName].collections,
                db = require('./db')(connections[connectionName].connection);

            function iterator(colName, next) {
                var schema = collections[colName].schema,
                    mapping = collections[colName].mapping,
                    _ttl = null;

                if (schema.hasOwnProperty('_ttl') &&
                    schema._ttl.hasOwnProperty('defaultsTo') &&
                    typeof schema._ttl.defaultsTo == 'number')
                {
                    _ttl = {
                        "enabled": true,
                        "default": schema._ttl.defaultsTo
                    };
                }

                db.reindex(colName, mapping, _ttl, function(err) {
                    if (err) {
                        return next(err, false);
                    }

                    next(false, false);
                });
            }

            async.each(Object.keys(collections), iterator, callback);
        },

        aggregate : function(connection, collection, options, callback) {
            var db = require('./db')(connections[connection].connection);

            db.aggregate(collection, options, function(err, res){
                if (err) {
                    return callback(err, false);
                }

                callback(null, res);
            });

        },

        /**
         * @param connectionName
         * @param collectionName
         * @param options
         * @param callback
         */
        backup: function(connectionName, collectionName, options, callback) {
            var db = require('./db')(connections[connectionName].connection);

            db.backup(options, callback);
        },

        /**
         * @param connectionName
         * @param collectionName
         * @param options
         * @param reindexDelay
         * @param callback
         */
        restore: function(connectionName, collectionName, options, reindexDelay, callback) {
            var db = require('./db')(connections[connectionName].connection),
                self = this;

            db.restore(options, function(err, res) {
                if (err) {
                    return callback(err, res);
                }

                setTimeout(function() {
                    var collections = connections[connectionName].collections;

                    function iterator(colName, next) {
                        var schema = collections[colName].schema,
                            mapping = collections[colName].mapping,
                            _ttl = null;

                        if (schema.hasOwnProperty('_ttl') &&
                            schema._ttl.hasOwnProperty('defaultsTo') &&
                            typeof schema._ttl.defaultsTo == 'number')
                        {
                            _ttl = {
                                "enabled": true,
                                "default": schema._ttl.defaultsTo
                            };
                        }

                        db.reindex(colName, mapping, _ttl, function(err) {
                            if (err) {
                                return next(err, false);
                            }

                            next(false, false);
                        });
                    }

                    async.each(Object.keys(collections), iterator, callback);

                }, reindexDelay);
            });
        }
    };

    return adapter;
})();


text:
using System.Numerics;
using OpenSage.Data.Ini;

namespace OpenSage.Logic.Object
{
    /// <summary>
    /// Allows the use of StartDive within UnitSpecificSounds section of the object.
    /// </summary>
    public sealed class DeliverPayloadAIUpdateModuleData : AIUpdateModuleData
    {
        internal new static DeliverPayloadAIUpdateModuleData Parse(IniParser parser) => parser.ParseBlock(FieldParseTable);

        private new static readonly IniParseTable<DeliverPayloadAIUpdateModuleData> FieldParseTable = AIUpdateModuleData.FieldParseTable
            .Concat(new IniParseTable<DeliverPayloadAIUpdateModuleData>
            {
                { "DoorDelay", (parser, x) => x.DoorDelay = parser.ParseInteger() },
                { "MaxAttempts", (parser, x) => x.MaxAttempts = parser.ParseInteger() },
                { "DropOffset", (parser, x) => x.DropOffset = parser.ParseVector3() },
                { "DropDelay", (parser, x) => x.DropDelay = parser.ParseInteger() },
                { "PutInContainer", (parser, x) => x.PutInContainer = parser.ParseAssetReference() },
                { "DeliveryDistance", (parser, x) => x.DeliveryDistance = parser.ParseInteger() }
            });

        public int DoorDelay { get; private set; }
        public int MaxAttempts { get; private set; }
        public Vector3 DropOffset { get; private set; }
        public int DropDelay { get; private set; }
        public string PutInContainer { get; private set; }
        public int DeliveryDistance { get; private set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.recommendationengine.v1beta1.samples;

// [START recommendationengine_v1beta1_generated_catalogserviceclient_importcatalogitems_stringstringinputconfigimporterrorsconfig_sync]
import com.google.cloud.recommendationengine.v1beta1.CatalogName;
import com.google.cloud.recommendationengine.v1beta1.CatalogServiceClient;
import com.google.cloud.recommendationengine.v1beta1.ImportCatalogItemsResponse;
import com.google.cloud.recommendationengine.v1beta1.ImportErrorsConfig;
import com.google.cloud.recommendationengine.v1beta1.InputConfig;

public class SyncImportCatalogItemsStringStringInputconfigImporterrorsconfig {

  public static void main(String[] args) throws Exception {
    syncImportCatalogItemsStringStringInputconfigImporterrorsconfig();
  }

  public static void syncImportCatalogItemsStringStringInputconfigImporterrorsconfig()
      throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) {
      String parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString();
      String requestId = "requestId693933066";
      InputConfig inputConfig = InputConfig.newBuilder().build();
      ImportErrorsConfig errorsConfig = ImportErrorsConfig.newBuilder().build();
      ImportCatalogItemsResponse response =
          catalogServiceClient
              .importCatalogItemsAsync(parent, requestId, inputConfig, errorsConfig)
              .get();
    }
  }
}
// [END recommendationengine_v1beta1_generated_catalogserviceclient_importcatalogitems_stringstringinputconfigimporterrorsconfig_sync]


text:
(function () {
  'use strict';

  angular
    .module('organisators')
    .factory('OrganisatorsService', OrganisatorsService);

  OrganisatorsService.$inject = ['$resource'];

  function OrganisatorsService($resource) {
    return $resource('api/organisators/:organisatorId', {
      organisatorId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
})();


text:
package metrics

import (
	"testing"

	dto "github.com/prometheus/client_model/go"

	apimachineryversion "k8s.io/apimachinery/pkg/version"
)

type testCustomCollector struct {
	BaseStableCollector
}

var (
	currentVersion = apimachineryversion.Info{
		Major:      "1",
		Minor:      "17",
		GitVersion: "v1.17.0-alpha-1.12345",
	}
	alphaDesc = NewDesc("metric_alpha", "alpha metric", []string{"name"}, nil,
		ALPHA, "")
	stableDesc = NewDesc("metric_stable", "stable metrics", []string{"name"}, nil,
		STABLE, "")
	deprecatedDesc = NewDesc("metric_deprecated", "stable deprecated metrics", []string{"name"}, nil,
		STABLE, "1.17.0")
	hiddenDesc = NewDesc("metric_hidden", "stable hidden metrics", []string{"name"}, nil,
		STABLE, "1.16.0")
)

func (tc *testCustomCollector) DescribeWithStability(ch chan<- *Desc) {
	ch <- alphaDesc
	ch <- stableDesc
	ch <- deprecatedDesc
	ch <- hiddenDesc
}

func (tc *testCustomCollector) CollectWithStability(ch chan<- Metric) {
	ch <- NewLazyConstMetric(
		alphaDesc,
		GaugeValue,
		1,
		"value",
	)
	ch <- NewLazyConstMetric(
		stableDesc,
		GaugeValue,
		1,
		"value",
	)
	ch <- NewLazyConstMetric(
		deprecatedDesc,
		GaugeValue,
		1,
		"value",
	)
	ch <- NewLazyConstMetric(
		hiddenDesc,
		GaugeValue,
		1,
		"value",
	)

}

func getMetric(metrics []*dto.MetricFamily, fqName string) *dto.MetricFamily {
	for _, m := range metrics {
		if *m.Name == fqName {
			return m
		}
	}

	return nil
}

func TestBaseCustomCollector(t *testing.T) {
	var tests = []struct {
		name         string
		d            *Desc
		shouldHidden bool
		expectedHelp string
	}{
		{
			name:         "alpha metric should contains stability metadata",
			d:            alphaDesc,
			shouldHidden: false,
			expectedHelp: "[ALPHA] alpha metric",
		},
		{
			name:         "stable metric should contains stability metadata",
			d:            stableDesc,
			shouldHidden: false,
			expectedHelp: "[STABLE] stable metrics",
		},
		{
			name:         "deprecated metric should contains stability metadata",
			d:            deprecatedDesc,
			shouldHidden: false,
			expectedHelp: "[STABLE] (Deprecated since 1.17.0) stable deprecated metrics",
		},
		{
			name:         "hidden metric should be ignored",
			d:            hiddenDesc,
			shouldHidden: true,
			expectedHelp: "[STABLE] stable hidden metrics",
		},
	}

	registry := newKubeRegistry(currentVersion)
	customCollector := &testCustomCollector{}

	if err := registry.CustomRegister(customCollector); err != nil {
		t.Fatalf("register collector failed with err: %v", err)
	}

	metrics, err := registry.Gather()
	if err != nil {
		t.Fatalf("failed to get metrics from collector, %v", err)
	}

	for _, test := range tests {
		tc := test
		t.Run(tc.name, func(t *testing.T) {
			m := getMetric(metrics, tc.d.fqName)
			if m == nil {
				if !tc.shouldHidden {
					t.Fatalf("Want metric: %s", tc.d.fqName)
				}
			} else {
				if m.GetHelp() != tc.expectedHelp {
					t.Fatalf("Metric(%s) HELP(%s) not contains: %s", tc.d.fqName, *m.Help, tc.expectedHelp)
				}
			}

		})
	}
}


text:
try:
    from ..settings import *
except ImportError:
    import sys, django
    django.utils.six.reraise(RuntimeError, *sys.exc_info()[1:])  # use RuntimeError to extend the traceback
except:
    raise

DEBUG = False  # this setting file will not work on "runserver" -- it needs a server for static files

ADMINS = (
    ('Adam', 'adam@ehealthafrica.org'),
)

MANAGERS = ADMINS

# override to set the actual location for the production static and media directories
MEDIA_ROOT = '/var/formhub-media'
STATIC_ROOT = "/srv/formhub-static"
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, "static"),
)

# your actual production settings go here...,.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'formhub',
        'USER': 'formhub_prod',
        'PASSWORD': os.environ['FORMHUB_PROD_PW'],  # the password must be stored in an environment variable
        'HOST': os.environ.get("FORMHUB_DB_SERVER", 'dbserver.yourdomain.org'), # the server name may be in env
        'OPTIONS': {
            'autocommit': True,   # note: this option obsolete starting with django 1.6
        }
    },
    'gis': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'phis',
        'USER': 'staff',
        'PASSWORD': os.environ['PHIS_PW'],  # the password must be stored in an environment variable
        'HOST': os.environ.get("FORMHUB_DB_SERVER", 'dbserver.yourdomain.org'), # the server name may be in env
        'OPTIONS': {
            'autocommit': True,
        }
    }
}

#
ALLOWED_HOSTS = ['.eocng.org', '.eocng.org.', '.ehealth.org.ng' ,'forms.ehealthafrica.org', '']

DATABASE_ROUTERS = ['formhub.preset.dbrouter.GisRouter']

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
#TIME_ZONE = 'America/New_York'
TIME_ZONE = 'Africa/Lagos'

EMAIL_HOST = 'smtp.gmail.com'  #The host to use for sending email.

EMAIL_HOST_PASSWORD = os.environ.get("FORMHUB_EMAIL_PASSWORD", "12345678")
#Password to use for the SMTP server defined in EMAIL_HOST.
EMAIL_HOST_USER = 'do.not.reply@ehealthnigeria.org'

EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "do.not.reply@ehealthnigeria.org"

TOUCHFORMS_URL = 'http://localhost:9000/'

MONGO_DATABASE = {
    'HOST': 'localhost',
    'PORT': 27017,
    'NAME': 'formhub',
    'USER': '',
    'PASSWORD': ''
}
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'mlfs33^s1l4xf6a36$0#j%dd*sisfo6HOktYXB9y'


text:
[![Build status][cibadge]][ci] [![NuGet][nugetbadge]][nuget]

The **Cyotek.Windows.Forms.ColorPickers** library contains a
series of custom controls and utility classes for Windows Forms
applications that work with colours. Controls are available to
allow colour selection via a HSL `ColorWheel`, a `ColorGrid`
with many customisation options, a `ColorEditor` for entering
colours via RGB or HSL, and a `ScreenColorPicker` for capturing
colours from running applications.

Color palettes can be loaded and saved in a number of different
formats, including Adobe PhotoShop Color Swatch files, JASC
Palettes, Gimp Palettes and more (see Color Palettes and
External Palette Files below).

For more information on these controls, see the [articles tagged
with `colorpicker`][blogtag] at cyotek.com.

## Getting the library

The easiest way of obtaining the library is via [NuGet][nuget].

> `Install-Package Cyotek.Windows.Forms.ColorPicker`

If you don't use NuGet, pre-compiled binaries can be obtained
from the [GitHub Releases page][ghrel].

Of course, you can always grab [the source][ghsrc] and build it
yourself!

## Controls

There are three primary controls (`ColorGrid`, `ColorWheel` and
`ColorEditor`), along with 5 utility controls
(`ScreenColorPicker`, `RgbaColorSlider`, `HueColorSlider`,
`LightnessColorSlider` and `SaturationColorSlider`), a
management component (`ColorEditorManager`) and one dialog
(`ColorPickerDialog`). Combined together, these provide a decent
array of tools for colour selection.

### ColorGrid Control

![ColorGrid control demonstration][colorgridscreen]

This control displays a grid of colours, and supports both a
primary palette, and a custom colour palette. Several properties
are available for configuring the appearing of the control, and
there are behaviour options too, such as built in editing of
colours and support for automatically adding new colours not in
the primary palette.

### ColorWheel Control

![ColorWheel control demonstration][colorwheelscreen]

This control displays a radial wheel of RGB colours and allows
selection from any point in the wheel. The `ShowAngleArrow`,
`ShowCenterLines` and `ShowSaturationRing` properties can be
used to display useful adornments, while the `Lightness` and
`Alpha` properties can be used to compose the final colour while
not being directly editable on the wheel.

The `SecondaryColors` and `SecondarySelectionSize` properties
allow you to display additional colours on the wheel, for
example for showing relationships.

### ColorSlider Controls

![ColorSlider controls demonstration][colorsliderscreen]

A bunch of controls (inheriting from a single base) that allow
selection of values via a colourful bar. Similar to the
`TrackBar` control you have a few options for specifying the
drag handle's position and bar orientation. You can also
customise the fill and outline colour, or replace it completely
with a custom image.

### ColorEditor Control

![ColorEditor control demonstration][coloreditorscreen]

This control allows the editing of a RGB or HSL colour via a
standard interface. You can also enter colours via 6 or 8
character hexadecimal notation, or choose from named web and
system colors.

Use of the alpha channel can be configured via the
`ShowAlphaChannel` and `PreserveAlphaChannel` properties. The
`ShowHex`, `ShowHsl` and `ShowRgb` properties can be used to
show or hide groups of editors.

Alternatively, the `NubSize`, `NubColor` and `NubOutlineColor`
properties can be used to customise the appearance of the
sliders.

### ScreenColorPicker Control

![ScreenColorPicker control demonstration][screenpickerscreen]

This control allows the user to pick a colour from any pixel
displayed on the screen. The user can either trigger the
operation by clicking and dragging the control, or it can be
done programmatically via the `CaptureMouse` method, allowing
selections to be triggered via other actions, for example a hot
key. The `Zoom` property can be used set the grid size of the
preview.

### ColorPickerDialog Form

![ColorPickerDialog form demonstration][colordialogscreen]

This form puts together the previous controls in a ready to use
dialog.

Custom colours are supported via the `CustomColors` property,
and users can also load or save external palette files into
these. You can use the `ShowLoad` and `ShowSave` properties to
enable or disable this, and the `CustomColorsLoading` and
`CustomColorsSaving`events to override the built-in behaviour
and provide your own logic.

### ColorEditorManager

![ColorEditorManager compnent demonstration][coloreditormanagerscreen]

This is a non-GUI component that you can drop onto a form, and
bind to other controls in this library. When the `Color`
property of one control changes, it is reflected in the others
without having to lift a finger. Useful if you're creating
composite displays from multiple controls.

## Color Palettes and External Palette Files

The `ColorGrid` control has `Colors` and `CustomColors`
properties which return a `ColorCollection`. These two
properties make it easier as a developer to keep separate a
primary palette whilst having the flexibility of custom colours,
although it does complicate the control's internal logic a bit!
The grid will automatically populate custom colours if you try
and set the control's `Color` to a value not currently defined.

As well as manually populating `ColorCollection` instances, you
can also load in external palette files. The following palette
formats are supported:

* Adobe Color Table (*.act)
* Adobe PhotoShop Color Swatch (*.aco)
* GIMP (*.gpl)
* Deluxe Paint (*.bbm; *.lbm) [read only]
* JASC (*.pal)
* Paint.NET (*.txt)
* Raw RGB Triplets (*.pal)

With the exception of the ILBM image format, all other formats
can be exported as well as imported.

Additional palette serializers can be easily created by adding a
class which implements `IPaletteSerializer`. The
`ColorPickerDialog` (or any custom code using
`PaletteSerializer` static methods) will automatically detect
and make available custom palettes via reflection.

## Keyboard Support

All GUI components, with the exception of the
`ScreenColorPicker` include full keyboard/focus support. Many
controls support `SmallChange` and `LargeChange` properties
which influence how navigation keys are processed. Although in
the case of the `ColorWheel` it's not really a bonus... but
that's what the `ColorEditor` control is best suited for!

## Requirements

.NET Framework 3.5 or later.

Pre-built binaries are available via a signed [NuGet
package][nuget] containing the following targets.

* .NET 3.5
* .NET 4.0
* .NET 4.5.2
* .NET 4.6.2
* .NET 4.7.2
* .NET 4.8
* .NET 5.0

## Contributing to this code

Contributions accepted!

* Found a problem? [Raise an issue][ghissue]
* Want to improve the code? [Make a pull request][ghpull]

Alternatively, if you make use of this software and it saves you
some time, donations are welcome.

[![PayPal Donation][paypalimg]][paypal]

[![By Me a Coffee Donation][bmacimg]][bmac]

## Known Issues

* XML documentation comments are incomplete

## Related Reading

* [Reading Photoshop Color Swatch (aco) files using C#]
* [Writing Photoshop Color Swatch (aco) files using C#]
* [Loading the color palette from a BBM/LBM image file using C#]
* [Hosting a ColorGrid control in a ToolStrip]

## Acknowledgements

* Inspiration (and some code!) was taken from [Color Picker with
  Color Wheel and Eye Dropper]
* The eye dropper png graphic is from the [Momentum Glossy
  Icons]
* [DawnBringer 16 color palette]
* [DawnBringer 32 color palette]
* The Atari 800 XL color palette by [Space Monster Games]
* [Arne Palette v20]

[Color Picker with Color Wheel and Eye Dropper]: http://www.codeproject.com/Articles/21965/Color-Picker-with-Color-Wheel-and-Eye-Dropper
[Momentum Glossy Icons]: http://www.iconfinder.com/icondetails/84569/32/eyedropper_icon
[DawnBringer 16 color palette]: http://www.pixeljoint.com/forum/forum_posts.asp?TID=12795
[DawnBringer 32 color palette]: http://www.pixeljoint.com/forum/forum_posts.asp?TID=16247
[Space Monster Games]: http://www.spacemonsters.co.uk/2011/10/the-atari-colour-palette/
[Arne Palette v20]: http://androidarts.com/palette/16pal.htm

[Reading Photoshop Color Swatch (aco) files using C#]: http://cyotek.com/blog/reading-photoshop-color-swatch-aco-files-using-csharp
[Writing Photoshop Color Swatch (aco) files using C#]: http://cyotek.com/blog/writing-photoshop-color-swatch-aco-files-using-csharp
[Loading the color palette from a BBM/LBM image file using C#]: http://cyotek.com/blog/loading-the-color-palette-from-a-bbm-lbm-image-file-using-csharp
[Hosting a ColorGrid control in a ToolStrip]: http://www.cyotek.com/blog/hosting-a-colorgrid-control-in-a-toolstrip

[blogtag]: http://www.cyotek.com/blog/tag/colorpicker

[icon]: res/icon-32.png
[colorgridscreen]: res/cp-colorgridcontrol.png
[colorwheelscreen]: res/cp-colorwheelcontrol.png
[colorsliderscreen]: res/cp-colorslidercontrols.png
[coloreditorscreen]: res/cp-coloreditorcontrol.png
[screenpickerscreen]: res/cp-screencolorpickercontrol.png
[colordialogscreen]: res/cp-colorpickerdialog.png
[coloreditormanagerscreen]: res/cp-coloreditormanager.gif

[nuget]: https://www.nuget.org/packages/Cyotek.Windows.Forms.ColorPicker/
[nugetbadge]: https://img.shields.io/nuget/vpre/Cyotek.Windows.Forms.ColorPicker

[ci]: https://ci.appveyor.com/project/cyotek/cyotek-windows-forms-colorpicker
[cibadge]: https://img.shields.io/appveyor/build/cyotek/cyotek-windows-forms-colorpicker

[ghissue]: https://github.com/cyotek/Cyotek.Windows.Forms.ColorPicker/issues
[ghpull]: https://github.com/cyotek/Cyotek.Windows.Forms.ColorPicker/pulls
[ghrel]: https://github.com/cyotek/Cyotek.Windows.Forms.ColorPicker/releases
[ghsrc]: https://github.com/cyotek/Cyotek.Windows.Forms.ColorPicker

[paypal]: https://www.paypal.me/cyotek
[paypalimg]: https://static.cyotek.com/assets/images/donate.gif
[bmac]: https://www.buymeacoffee.com/cyotek
[bmacimg]: https://static.cyotek.com/assets/images/bmac.png


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NerdDinner.Helpers
{
    public class FileNotFoundResult : ActionResult
    {
        public string Message {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context) {
            throw new HttpException(404, Message);
        }
    }
}


text:
using Common.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Ipfs.CoreApi;
using System.Globalization;

namespace Ipfs.Http
{

    class DagApi : IDagApi
    {
        IpfsClient ipfs;

        internal DagApi(IpfsClient ipfs)
        {
            this.ipfs = ipfs;
        }

        public async Task<Cid> PutAsync(
            JObject data,
            string contentType = "dag-cbor",
            string multiHash = MultiHash.DefaultAlgorithmName,
            string encoding = MultiBase.DefaultAlgorithmName,
            bool pin = true,
            CancellationToken cancel = default(CancellationToken))
        {
            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, new UTF8Encoding(false), 4096, true) { AutoFlush = true })
                using (var jw = new JsonTextWriter(sw))
                {
                    var serializer = new JsonSerializer
                    {
                        Culture = CultureInfo.InvariantCulture
                    };
                    serializer.Serialize(jw, data);
                }
                ms.Position = 0;
                return await PutAsync(ms, contentType, multiHash, encoding, pin, cancel);
            }
        }

        public async Task<Cid> PutAsync(
            object data,
            string contentType = "dag-cbor",
            string multiHash = MultiHash.DefaultAlgorithmName,
            string encoding = MultiBase.DefaultAlgorithmName,
            bool pin = true,
            CancellationToken cancel = default(CancellationToken))
        {
            using (var ms = new MemoryStream(
                Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)),
                false))
            {
                return await PutAsync(ms, contentType, multiHash, encoding, pin, cancel);
            }
        }

        public async Task<Cid> PutAsync(
            Stream data,
            string contentType = "dag-cbor",
            string multiHash = MultiHash.DefaultAlgorithmName,
            string encoding = MultiBase.DefaultAlgorithmName,
            bool pin = true,
            CancellationToken cancel = default(CancellationToken))
        {
            var json = await ipfs.UploadAsync("dag/put", cancel,
                data, null,
                $"format={contentType}",
                $"pin={pin.ToString().ToLowerInvariant()}",
                $"hash={multiHash}",
                $"cid-base={encoding}");
            var result = JObject.Parse(json);
            return (Cid)(string)result["Cid"]["/"];
        }

        public async Task<JObject> GetAsync(
            Cid id,
            CancellationToken cancel = default(CancellationToken))
        {
            var json = await ipfs.DoCommandAsync("dag/get", cancel, id);
            return JObject.Parse(json);
        }

        public async Task<JToken> GetAsync(
            string path,
            CancellationToken cancel = default(CancellationToken))
        {
            var json = await ipfs.DoCommandAsync("dag/get", cancel, path);
            return JToken.Parse(json);
        }

        public async Task<T> GetAsync<T>(Cid id, CancellationToken cancel = default(CancellationToken))
        {
            var json = await ipfs.DoCommandAsync("dag/get", cancel, id);
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}


text:
"""
nwid.terminal.screen
~~~~~~~~~~~~~~~~~~~~

This module contains functions responsible for clearing the screen and getting
its size.
"""

from __future__ import absolute_import

from . import codes as code
from nwid import Size

def size():
    """Returns the size of the window as a Size object (rows, cols).
    Note that this is the actual size; in order to get the bottom right corner,
    you must subtract 1 from both the rows and the columns."""
    try:
        from struct import unpack
        from fcntl import ioctl
        from termios import TIOCGWINSZ
        from os import ctermid

        with open(ctermid()) as fd:
            size = unpack('hh', ioctl(fd, TIOCGWINSZ, '----'))
            return Size(size[0], size[1])

    except ImportError:
        from os import environ
        try:
            return Size(environ['COLUMNS'], environ['LINES'])
        except KeyError:
            return Size(25, 80)  # just send back a best guess

def clear():
    """Clears the entire screen."""
    code.CLEAR_SCREEN()

def clear_down():
    """Clears the screen from the cursor down."""
    code.CLEAR_DOWN()

def clear_up():
    """Clears the screen from the cursor down."""
    code.CLEAR_UP()

def clear_line():
    """Clears the entire line."""
    code.CLEAR_LINE()

def clear_line_forward():
    """Clears the line from the cursor forward."""
    # TODO: inclusive or exclusive?
    code.CLEAR_LINE_FORWARD()

def clear_line_backward():
    """Clears the line from the cursor backward."""
    # TODO: inclusive or exclusive?
    code.CLEAR_LINE_BACKWARD()

def reset():
    """Clears the entire screen and places cursor at top left corner."""
    code.CLEAR_SCREEN()
    code.CURSOR_SET_POSITION(0, 0)


text:
package challenge

const (
	ACMEChallengePrefix = "_acme-challenge"
	DNSChallenge        = "dns-01"
	HTTPChallenge       = "http-01"
)


text:
titus.util.uniqueRecordName
===========================

.. autofunction:: titus.util.uniqueRecordName


text:
/*----------------------------------------------
Programmer: Alberto Bobadilla (labigm@gmail.com)
Date: 2017/05
----------------------------------------------*/
#ifndef __BASICXDEFINITIONS_H_
#define __BASICXDEFINITIONS_H_

// Include standard headers
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <assert.h>
#include <math.h>
#include <vector>
#include <locale>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <random>
#include <vector>
#include <map>
#include <set>

// Include GLM
#include <glm\glm.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>
#include <glm\gtx\transform.hpp>
#include <glm\ext.hpp>
#include <glm\gtc\quaternion.hpp>

#ifdef EXP_STL
#	define BasicXDLL __declspec(dllexport)
#	define EXPIMP_TEMPLATE
#else
#	define BasicXDLL __declspec(dllimport)
#	define EXPIMP_TEMPLATE extern
#endif

namespace BasicX
{
	typedef unsigned int uint;
	typedef std::string String;
	typedef glm::vec2 vector2;
	typedef glm::vec3 vector3;
	typedef glm::vec4 vector4;
	typedef glm::mat3 matrix3;
	typedef glm::mat4 matrix4;
	typedef glm::quat quaternion;
/*
USAGE: will safely delete the input pointer and initialize it to nullptr, DOES NOT WORK WITH POINTER ARRAY
*/
#define SafeDelete(p){ if(p) { delete p; p = nullptr; } }
////https://stackoverflow.com/questions/10240161/reason-to-pass-a-pointer-by-reference-in-c/20188970#20188970
//template<typename T>
//void SafeDelete(T*& p)
//{
//	if(p != nullptr)
//	{
//		delete p;
//		p = nullptr;
//	}
//}
#define PI 3.14159265358979323846
#define IDENTITY_M4 matrix4(1.0f)
#define IDENTITY_QUAT quaternion();
#define ZERO_V3 vector3(0.0f, 0.0f, 0.0f)
#define DEFAULT_V3NEG vector3(-1.0f, -1.0f, -1.0f)

#define C_BLACK vector3(0.0f, 0.0f, 0.0f)
#define C_WHITE vector3(1.0f, 1.0f, 1.0f)
#define C_GRAY vector3(0.3f, 0.3f, 0.3f)

#define C_RED vector3(1.0f, 0.0f, 0.0f)
#define C_MAGENTA vector3(1.0f, 0.0f, 1.0f)
#define C_BROWN vector3(0.6f,0.3f,0.0f)

#define C_GREEN vector3(0.0f, 1.0f, 0.0f)
#define C_GREEN_DARK vector3(0.0f, 5.0f, 0.0f)
#define C_GREEN_LIME vector3(0.33f,0.90f,0.33f)

#define C_BLUE vector3(0.0f, 0.0f, 1.0f)
#define C_BLUE_CORNFLOWER vector3(0.4f, 0.6f, 0.9f)
#define C_CYAN vector3(0.0f,1.0f,1.0f)

#define C_INDIGO vector3(0.30f, 0.0f, 0.52)

#define C_YELLOW vector3(1.0f, 1.0f, 0.0f)
#define C_ORANGE vector3(1.0f,0.5f,0.0f)
#define C_VIOLET vector3(0.54f,0.16f,0.88f)
#define C_PURPLE vector3(0.50f,0.0f,0.50f)

#define AXIS_X vector3(1.0f, 0.0f, 0.0f)
#define AXIS_XY vector3(1.0f, 1.0f, 0.0f)
#define AXIS_XZ vector3(1.0f, 0.0f, 1.0f)
#define AXIS_Y vector3(0.0f, 1.0f, 0.0f)
#define AXIS_YZ vector3(0.0f, 1.0f, 1.0f)
#define AXIS_Z vector3(0.0f, 0.0f, 1.0f)

//-----------------------------------------------------------------------------------------------------------
// Enumerations
//-----------------------------------------------------------------------------------------------------------
enum BTO_OPTIONS
{
	OPT_NO = 0,
	OPT_YES = 1,
	OPT_ASK = 2,
	OPT_OPENGL3X = 3,
};
enum BTO_OUTPUT
{
	OUT_ERR_NONE,
	OUT_ERR_GENERAL,
	OUT_ERR_FILE_MISSING,
	OUT_ERR_CONTEXT,
	OUT_ERR_MEMORY,
	OUT_ERR_NAME,
	OUT_ERR_NOT_INITIALIZED,
	OUT_ERR_FILE,
	OUT_ERR_NO_EXTENSION,
	OUT_DONE,
	OUT_RUNNING,
};
enum BTO_AXIS
{
	AX_NONE = 0,
	AX_XY = 1,
	AX_XZ = 2,
	AX_YZ = 4,
};
enum BTO_DISPLAY
{
	BD_NONE = 0,//...
	BD_BS = 1, //Bounding Sphere
	BD_OB = 2, //Oriented Bounding Box
	BD_AB = 4, //Axis (Re)Aligned Bounding Box
};
enum BTO_RENDER
{
	RENDER_NONE = 0,
	RENDER_SOLID = 1,
	RENDER_WIRE = 2,
};
enum BTO_CAMERAMODE
{
	CAM_PERSP = 0,
	CAM_ORTHO_X = 1,
	CAM_ORTHO_Y = 2,
	CAM_ORTHO_Z = 3,
};
enum BTO_FORMAT
{
	FORMAT_ATO = 0,
	FORMAT_BTO = 1,
};
enum BTO_RESOLUTIONS
{
	//Resolution | Aspect Ratio | Name
	RES_WINDOWED,
	//Common resolutions
	RES_C_720x480_4x3_NTSC,
	RES_C_1280x720_16x9_HD,
	RES_C_1920x1080_16x9_FULLHD,

	RES_CV_480x720_3x4_NTSC,
	RES_CV_720x1280_9x16_HD,
	RES_CV_1080x1920_9x16_FULLHD,

	//Monitor Resolutions
	RES_M_640x480_4x3_VGA,
	RES_M_1600x900_16x9_WXGA,
	RES_M_1920x1200_16x10_WUXGA,
	RES_M_2560x1080_21x9_UWUXGA,

	RES_MV_480x640_3x4_VGA,
	RES_MV_900x1600_9x16_WXGA,
	RES_MV_1200x1920_10x16_WUXGA,
	RES_MV_1080x2560_9x21_UWUXGA,

	//Other Resolutions
	RES_O_800x600_4x3_SVGA,
	RES_O_1024x768_4x3_XGA,
	RES_O_1280x800_16x10_WXGA,
	RES_O_1600x1200_4x3_UXGA,
	RES_O_2048x1080_17x9_2K,
	RES_O_3840x2160_17x9_4K,
};

struct BasicXDLL MeshOptions
{
	matrix4 m_m4Transform;
	int m_nRender;
	MeshOptions():m_m4Transform(IDENTITY_M4), m_nRender(RENDER_SOLID) {};
	MeshOptions(matrix4 a_m4Transform, int a_nRender):m_m4Transform(a_m4Transform), m_nRender(a_nRender){};
};
/*
USAGE: Will translate all characters in the string to upper case and return a copy string
ARGUMENTS:
	String a_sInput -> input string
OUTPUT: output
*/
static String ToUpperCase(String a_sInput)
{
	String output = a_sInput;
	std::transform(output.begin(), output.end(), output.begin(), ::toupper);
	return output;
}
/*
USAGE: Will trim the input string when the first token is found
ARGUMENTS:
	String a_sInput -> input string
	char a_sToken -> token to be used as divider
OUTPUT: trimmed output
*/
static String CopyUntilToken(String a_sInput, char a_sToken)
{
	char* szOutput = new char[a_sInput.size() + 1];
	uint counter = 0;
	uint charCount = a_sInput.size();
	while (a_sInput[counter] != a_sToken && counter < charCount)
	{
		szOutput[counter] = a_sInput[counter];
		++counter;
	}
	szOutput[counter] = '\0';
	String output = szOutput;
	if (szOutput)
	{
		delete[] szOutput;
		szOutput = nullptr;
	}
	return output;
}
/*
USAGE: Will trim the input string from when the first token is found till the end
ARGUMENTS:
String a_sInput -> input string
char a_sToken -> token to be used as divider
OUTPUT: trimmed output
*/
static String CopyAfterToken(String a_sInput, char a_sToken)
{
	uint counter = 0;
	uint charCount = a_sInput.size();
	while (a_sInput[counter] != a_sToken && counter < charCount)
	{
		++counter;
	}
	if (counter == charCount)
		return a_sInput;

	char* szOutput = new char[a_sInput.size() + 1];
	int nSecond = 0;
	++counter;
	while (counter < charCount)
	{
		szOutput[nSecond] = a_sInput[counter];
		++counter;
		++nSecond;
	}
	szOutput[nSecond] = '\0';
	String output = szOutput;
	if (szOutput)
	{
		delete[] szOutput;
		szOutput = nullptr;
	}
	return output;
}

/*
USAGE: Will map a value from an original scale to a new scale
ARGUMENTS:
T valueToMap -> input value
T originalScale_min ->  Start of the original scale
T originalScale_max -> End of the original scale
T mappedScale_min -> Start of the new scale
T mappedScale_max -> end of the new scale
OUTPUT: returns the mapped value
*/
template <class T>
static T MapValue(T valueToMap, T originalScale_min, T originalScale_max, T mappedScale_min, T mappedScale_max)
{
	return (valueToMap - originalScale_min) * (mappedScale_max - mappedScale_min) / (originalScale_max - originalScale_min) + mappedScale_min;
}

/*
MapVector
USAGE: Will return a vector mapped in the mappedScale range from a value vectorToMap in the OriginalScale range
ARGUMENTS:
vector3 vectorToMap -> input vector
vector3 originalScaleVectorMin -> Start of the original vector
vector3 originalScaleVectorMax -> End of the original vector
vector3 mappedScaleVectorMin -> Start of the new vector
vector3 mappedScaleVectorMax -> End of the new vector
OUTPUT: returns the mapped vector
*/
static vector3 MapVector(vector3 vectorToMap, vector3 originalScaleVectorMin, vector3 originalScaleVectorMax,
	vector3 mappedScaleVectorMin, vector3 mappedScaleVectorMax)
{
	vector3 v3Output;
	v3Output.x = MapValue(vectorToMap.x, originalScaleVectorMin.x, originalScaleVectorMax.x, mappedScaleVectorMin.x, mappedScaleVectorMax.x);
	v3Output.y = MapValue(vectorToMap.y, originalScaleVectorMin.y, originalScaleVectorMax.y, mappedScaleVectorMin.y, mappedScaleVectorMax.y);
	v3Output.z = MapValue(vectorToMap.z, originalScaleVectorMin.z, originalScaleVectorMax.z, mappedScaleVectorMin.z, mappedScaleVectorMax.z);
	return v3Output;
}
/*
ToMatrix4
USAGE: Will take a glm::quat and return a glm::mat4 wrapping glm::mat4_cast
ARGUMENTS:
quaternion a_qInput -> quaternion to translate from
OUTPUT: matrix4 conversion of a_qInput
*/
static matrix4 ToMatrix4(quaternion a_qInput)
{
	return glm::mat4_cast(a_qInput);
}

/*
USAGE: Will generate random numbers limited to the cap (inclusive)
ARGUMENTS:
uint a_uMin -> lower cap (exclusive)
uint a_uMax -> upper cap (exclusive)
OUTPUT: random number between 0 and a_uMax
*/
static double GenerateRandom(double a_uMin, double a_uMax)
{
	//Old way
	//srand((unsigned)time(0));
	//return (rand() % a_uMax);

	if (a_uMin >= a_uMax)
		a_uMax = a_uMin + 1;

	//C++11 way
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_real_distribution<> dist(a_uMin, a_uMax);
	return dist(gen);
}

}

#endif //__REDEFINITIONS_H__


text:
from vif_plug_linux_bridge import constants as lb_constants
from vif_plug_ovs import constants as ovs_constants

from os_vif import exception
from os_vif import objects
from os_vif.tests.unit import base

class TestHostInfo(base.TestCase):

    def setUp(self):
        super(TestHostInfo, self).setUp()

        objects.register_all()

        self.host_info = objects.host_info.HostInfo(
            plugin_info=[
                objects.host_info.HostPluginInfo(
                    plugin_name=lb_constants.PLUGIN_NAME,
                    vif_info=[
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFBridge",
                            min_version="1.0",
                            max_version="3.0"
                        ),
                    ]),
                objects.host_info.HostPluginInfo(
                    plugin_name=ovs_constants.PLUGIN_NAME,
                    vif_info=[
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFBridge",
                            min_version="2.0",
                            max_version="7.0"
                        ),
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFOpenVSwitch",
                            min_version="1.0",
                            max_version="2.0"
                        ),
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFVHostUser",
                            min_version="1.0",
                            max_version="2.0"
                        ),
                    ])
            ])
        # https://bugs.launchpad.net/oslo.versionedobjects/+bug/1563787
        self.host_info.obj_reset_changes(recursive=True)

    def test_serialization(self):
        json = self.host_info.obj_to_primitive()
        self.assertEqual("os_vif", json["versioned_object.namespace"])

        host_info = objects.host_info.HostInfo.obj_from_primitive(json)
        # Copied from test_vif.py:
        #
        # The __eq__ function works by using obj_to_primitive()
        # and this includes a list of changed fields. Very
        # occassionally the ordering of the list of changes
        # varies, causing bogus equality failures. This is
        # arguably a bug in oslo.versionedobjects since the
        # set of changes fields should not affect equality
        # comparisons. Remove this hack once this is fixed:
        #
        # https://bugs.launchpad.net/oslo.versionedobjects/+bug/1563787
        host_info.obj_reset_changes(recursive=True)

        self.assertEqual(self.host_info, host_info)

    def test_plugin_existance(self):
        self.assertTrue(self.host_info.has_plugin(ovs_constants.PLUGIN_NAME))
        self.assertFalse(self.host_info.has_plugin("fishfood"))

    def test_plugin_fetch(self):
        plugin = self.host_info.get_plugin(ovs_constants.PLUGIN_NAME)
        self.assertEqual(ovs_constants.PLUGIN_NAME, plugin.plugin_name)

        self.assertRaises(exception.NoMatchingPlugin,
                          self.host_info.get_plugin,
                          "fishfood")

    def test_vif_existance(self):
        plugin = self.host_info.get_plugin(ovs_constants.PLUGIN_NAME)
        self.assertTrue(plugin.has_vif("VIFOpenVSwitch"))
        self.assertFalse(plugin.has_vif("VIFFishFood"))

    def test_vif_fetch(self):
        plugin = self.host_info.get_plugin(ovs_constants.PLUGIN_NAME)

        vif = plugin.get_vif("VIFOpenVSwitch")
        self.assertEqual("VIFOpenVSwitch", vif.vif_object_name)

        self.assertRaises(exception.NoMatchingVIFClass,
                          plugin.get_vif,
                          "VIFFishFood")

    def test_common_version_no_obj(self):
        info = objects.host_info.HostVIFInfo(
            vif_object_name="VIFFishFood",
            min_version="1.0",
            max_version="1.8")

        self.assertRaises(exception.NoMatchingVIFClass,
                          info.get_common_version)

    def test_common_version_no_version(self):
        info = objects.host_info.HostVIFInfo(
            vif_object_name="VIFOpenVSwitch",
            min_version="1729.0",
            max_version="8753.0")

        self.assertRaises(exception.NoSupportedVIFVersion,
                          info.get_common_version)

    def test_common_version_ok(self):
        info = objects.host_info.HostVIFInfo(
            vif_object_name="VIFOpenVSwitch",
            min_version="1.0",
            max_version="10.0")

        ver = info.get_common_version()
        self.assertEqual(objects.vif.VIFOpenVSwitch.VERSION,
                         ver)

    def test_filtering(self):
        host_info = objects.host_info.HostInfo(
            plugin_info=[
                objects.host_info.HostPluginInfo(
                    plugin_name=lb_constants.PLUGIN_NAME,
                    vif_info=[
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFBridge",
                            min_version="1.0",
                            max_version="3.0"
                        ),
                    ]),
                objects.host_info.HostPluginInfo(
                    plugin_name=ovs_constants.PLUGIN_NAME,
                    vif_info=[
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFBridge",
                            min_version="2.0",
                            max_version="7.0"
                        ),
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFOpenVSwitch",
                            min_version="1.0",
                            max_version="2.0"
                        ),
                        objects.host_info.HostVIFInfo(
                            vif_object_name="VIFVHostUser",
                            min_version="1.0",
                            max_version="2.0"
                        ),
                    ])
            ])

        host_info.filter_vif_types(["VIFBridge", "VIFOpenVSwitch"])

        self.assertEqual(len(host_info.plugin_info), 2)

        plugin = host_info.plugin_info[0]
        self.assertEqual(len(plugin.vif_info), 1)
        self.assertEqual(plugin.vif_info[0].vif_object_name,
                         "VIFBridge")

        plugin = host_info.plugin_info[1]
        self.assertEqual(len(plugin.vif_info), 2)
        self.assertEqual(plugin.vif_info[0].vif_object_name,
                         "VIFBridge")
        self.assertEqual(plugin.vif_info[1].vif_object_name,
                         "VIFOpenVSwitch")

        host_info.filter_vif_types(["VIFOpenVSwitch"])

        self.assertEqual(len(host_info.plugin_info), 1)

        plugin = host_info.plugin_info[0]
        self.assertEqual(len(plugin.vif_info), 1)
        self.assertEqual(plugin.vif_info[0].vif_object_name,
                         "VIFOpenVSwitch")


text:
<!DOCTYPE html>

    <title>Dropbuttons demo 1</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="https://rawgit.com/lbacas/dropbuttons/master/jquery.dropbuttons.css">

            <button type="button" class="btn btn-default">Default</button>
            <button type="button" class="btn btn-primary always-visible">Primary</button>
            <button type="button" class="btn btn-success">Success</button>
            <button type="button" class="btn btn-info">Info</button>
            <button type="button" class="btn btn-warning">Warning</button>
            <button type="button" class="btn btn-danger always-dropdown">Danger</button>
            <button type="button" class="btn btn-link">Link</button>
            <button type="button" class="btn btn-default">Default 2</button>
            <button type="button" class="btn btn-primary always-visible">Primary 2</button>
            <button type="button" class="btn btn-success">Success 2</button>
            <button type="button" class="btn btn-info">Info 2</button>
            <button type="button" class="btn btn-warning">Warning 2</button>
            <button type="button" class="btn btn-danger always-dropdown">Danger 2</button>
            <button type="button" class="btn btn-link">Link 2</button>
            <button type="button" class="btn btn-default">Default 3</button>
            <button type="button" class="btn btn-primary always-visible" data-dropbuttons-class="bg-primary">Primary 3</button>
            <button type="button" class="btn btn-success" data-dropbuttons-class="bg-success">Success 3</button>
            <button type="button" class="btn btn-info" data-dropbuttons-class="bg-info">Info 3</button>
            <button type="button" class="btn btn-warning" data-dropbuttons-class="bg-warning">Warning 3</button>
            <button type="button" class="btn btn-danger always-dropdown" data-dropbuttons-class="bg-danger">Danger 3</button>
            <button type="button" class="btn btn-link">Link 3</button>

                <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Dropdown

                </button>


text:
define("dojox/mobile/ScrollablePane",["dojo/_base/array","dojo/_base/declare","dojo/sniff","dojo/_base/window","dojo/dom-construct","dojo/dom-style","./common","./_ScrollableMixin","./Pane","./_maskUtils"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a){
return _2("dojox.mobile.ScrollablePane",[_9,_8],{roundCornerMask:false,radius:0,baseClass:"mblScrollablePane",buildRendering:function(){
var c=this.containerNode=_5.create("div",{className:"mblScrollableViewContainer",style:{width:this.scrollDir==="v"?"100%":""}});
this.inherited(arguments);
if(this.srcNodeRef){
for(var i=0,_b=this.srcNodeRef.childNodes.length;i<_b;i++){
this.containerNode.appendChild(this.srcNodeRef.firstChild);
}
}
if(this.roundCornerMask&&(_3("mask-image"))){
var _c=this.containerNode;
var _d=this.maskNode=_5.create("div",{className:"mblScrollablePaneMask"});
_d.appendChild(_c);
c=_d;
}
this.domNode.appendChild(c);
_7.setSelectable(this.containerNode,false);
},resize:function(){
this.inherited(arguments);
if(this.roundCornerMask){
this.createRoundMask();
}
_1.forEach(this.getChildren(),function(_e){
if(_e.resize){
_e.resize();
}
});
},isTopLevel:function(e){
var _f=this.getParent&&this.getParent();
return (!_f||!_f.resize);
},createRoundMask:function(){
if(_3("mask-image")){
if(this.domNode.offsetHeight==0){
return;
}
this.maskNode.style.height=this.domNode.offsetHeight+"px";
var _10=this.getChildren()[0],c=this.containerNode,_11=_10?_10.domNode:(c.childNodes.length>0&&(c.childNodes[0].nodeType===1?c.childNodes[0]:c.childNodes[1]));
var r=this.radius;
if(!r){
var _12=function(n){
return parseInt(_6.get(n,"borderTopLeftRadius"));
};
if(_10){
r=_12(_10.domNode);
if(!r){
var _13=_10.getChildren()[0];
r=_13?_12(_13.domNode):0;
}
}else{
r=_12(_11);
}
}
var pw=this.domNode.offsetWidth,w=_11.offsetWidth,h=this.domNode.offsetHeight,t=_6.get(_11,"marginTop"),b=_6.get(_11,"marginBottom"),l=_6.get(_11,"marginLeft");
_a.createRoundMask(this.maskNode,l,t,0,b,w,h-b-t,r,r);
}
}});
});


text:
"""This is the main public API of Morepath.

Additional public APIs can be imported from the :mod:`morepath.error`
and :mod:`morepath.pdbsupport` modules. For custom directive
implementations that interact with core directives for grouping or
subclassing purposes, or that need to use one of the Morepath
registries, you may need to import from :mod:`morepath.directive`.

The other submodules are considered private. If you find yourself
needing to import from them in application or extension code, please
report an issue about it on the Morepath issue tracker.
"""

from dectate import commit
from .app import App, dispatch_method
from .core import (excview_tween_factory as EXCVIEW,
    poisoned_host_header_protection_tween_factory as HOST_HEADER_PROTECTION,
    model_predicate, name_predicate, request_method_predicate,
    body_model_predicate)
from .core import body_model_predicate as LAST_VIEW_PREDICATE
from .view import render_json, render_html, redirect
from .request import Request, Response
from .autosetup import scan, autoscan
from .authentication import Identity, IdentityPolicy, NO_IDENTITY
from .converter import Converter
from .reify import reify
from .run import run


text:
namespace MordorsCrueltyPlan
{
    using System;

    public class StartUp
    {
        public static void Main()
        {
            var foodFactory = new FoodFactory();
            var moodFactory = new MoodFactory();
            var gandalf = new Gandalf();
            var input = Console.ReadLine().Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var foodStr in input)
            {
                var food = foodFactory.GetFood(foodStr);
                gandalf.Eat(food);
            }

            var totalHappinessPoints = gandalf.GetHappinessPoints();
            var currentMood = moodFactory.GetMood(totalHappinessPoints);
            Console.WriteLine(totalHappinessPoints);
            Console.WriteLine(currentMood);
        }
    }
}


text:
<?php

namespace Qumonto\UserSys\Http\Controllers;

use Event;
use App\User;
use App\Http\Requests\Request;
use App\Http\Controllers\Controller;

use Qumonto\UserSys\AuthenticationTrait;
use Qumonto\UserSys\Events\UserRegistered;
use Qumonto\UserSys\Http\Requests\UserLoginRequest;
use Qumonto\UserSys\Http\Requests\UserRegisterRequest;

class AuthController extends Controller
{
	use AuthenticationTrait;

	/**
	 * Create a new AuthController instance.
	 *
	 * @return void
	 **/
	public function __construct()
	{
		$this->middleware('guest', ['except' => 'getLogout']);
	}

	/**
	 * Show login form.
	 *
	 * @return Illuminate\Http\Response
	 **/
	public function getLogin()
	{
		if(is_null(config('usersys.login_view'))){
			return view('usersys::login');
		}
		else{
			return view(config('usersys.login_view'));
		}
	}

	/**
	 * Handle login request.
	 *
	 * @param Illuminate\Http\Request $request
	 * @return Illuminate\Http\Response
	 **/
	public function postLogin(UserLoginRequest $request)
	{
		$credentials = $this->getCredentials($request);

		if (\Auth::attempt($credentials, $request->has('remember'))) {
            // clear the login attempts if throttle is set to true.

            // if email_verification is active
			if (config('usersys.email_verification')) {
	            // check if the account is activated
	            if (!\Auth::user()->verification_token) {
	            	return redirect()->intended(config('usersys.redirect_after_login'));
	            }
	            else {

	            	\Auth::logout();	// email not verified

	            	return redirect(config('usersys.redirect_after_fail'))
	            			->withInput($request->only($this->getUsernameColumnAndField(),'remember'))
	            			->withErrors([
	            				$this->getUsernameColumnAndField() => $this->getFailedLoginMessage('forActivation'),
	            			]);
	            }
			}
        }
        else{

	        // increment the throttle count.

	        return redirect(config('usersys.redirect_after_fail'))
			        ->withInput($request->only($this->getUsernameColumnAndField(), 'remember'))
			        ->withErrors([
			            $this->getUsernameColumnAndField() => $this->getFailedLoginMessage('forCredentials'),
			        ]);
        }

	    return redirect()->intended(config('usersys.redirect_after_login'));
	}

	/**
	 * Log the user out.
	 *
	 * @return Illuminate\Http\Response
	 **/
	public function getLogout()
	{
		\Auth::logout();

		        session()->flash(config('usersys.session_identifier'), 'You have been logged out!');

        return redirect(config('usersys.redirect_after_logout'));
	}

	/**
	 * Show the registration form
	 *
	 * @return Illuminate\Http\Response
	 **/
	public function getRegister()
	{
		if(is_null(config('usersys.register_view'))){
			return view('usersys::register');
		}
		else{
			return view(config('usersys.register_view'));
		}
	}

	/**
	 * Handle the registration request.
	 *
	 * @param Illuminate\Http\Request $request
	 * @return Illuminate\Http\Response
	 **/
	public function postRegister(UserRegisterRequest $request)
	{
		$user = $this->createNewUser($request->all());

		if(config('usersys.log_user_after_registration')){
			\Auth::login($user);
			return redirect(config('usersys.redirect_after_login'));
		}
		else{
			return redirect(config('usersys.redirect_after_logout'));
		}
	}

	public function getVerify($verification_token)
    {
    	if( ! $this->tokenExists($verification_token))
        {
            throw new Exception("Invalid Confirmation Code", 1);
        }

        $user = User::where('verification_token', '=', $verification_token)->first();

        if(!$user) {
        	throw new Exception("Invalid Confirmation Code", 1);

        }

        $user->verification_token = null;
        $user->save();

        session()->flash(config('usersys.session_identifier'),config('usersys.email_verification_success'));

        return redirect(config('usersys.redirect_after_verification'));
    }
}


text:
title:  Teacher Comments
date:   08/12/2017
---

### The Lesson in Brief

**Key Text**: Romans 9

**The Student Will**:

- **Know**: Grasp the reality that God has not forsaken Israel and that He wants to save all—both Jews and Gentiles.
- **Feel**: Develop a convincing sense that while God desires to save all, He alone chooses who carries out particular missions in His kingdom.
- **Do**: Seek to clarify the difference between whom God saves and whom He appoints as His saving agents.

### Learning Outline:

1. Know: How God Redeems the Lost
+ Why was it that Israel so obviously had misunderstood its divine destiny?
+ Why has God never made an unconditional covenant to save any people or religious group?

2. Feel: Sense God's Patience With the Failures of Israel.
+ The Jewish rejection and crucifixion of Christ could have brought rejection by God, so why has God not fully rejected Israel?
+ Have you ever really blown an important job opportunity yet gotten a second chance? Please share your reaction to this special blessing.

3. Do: Yield to God's Will.
+ Why might someone be jealous of another's ministry?
+ How does the fact that God determines who receives what when it comes to "spiritual gifts" speak to God's service appointments?

**Summary**: It is important to seek to understand God's will to save both Jew and Gentile and to clarify how He chooses whomever He will to reach the lost.

#### Learning Cycle

##### STEP 1—Motivate

**Spotlight on Scripture**: Romans 9

**Key Concept for Spiritual Growth**: It is critically important to understand that God does not predetermine anyone's eternal salvation. But He does determine who will do His bidding when it comes to mission assignments and spiritual gifting. In such a life of Christian witness and service, there is a great blessing in being a part of God's redemptive purposes.

**Just for Teachers**: God does not predetermine anyone's personal salvation. But He has been quite sovereign when it comes to Israel's destiny as God's chosen mission witnesses to the lost human race. So, this week's key question is: How does God relate to the failures of His Old Testament people in the context of His desire for the salvation of both Jews and Gentiles?

**Opening Discussion**: Recall the first time that you ever read Romans 9. What questions immediately came to your mind regarding God's seemingly irresistible predestination, especially as it related to questions addressing personal salvation from sin and eternal death?

**Questions for Discussion**:

1. What is it in God's nature that assures us that He is not a Being who irresistibly predetermines everyone's eternal destiny?
2. Why does Paul seem so burdened regarding the salvation of the Jews?
3. Consider Paul's obvious preoccupation with what has been called "the Jewish question" in Romans 9. What contributed to Paul's anxious puzzlement over the fact that the Jews were resisting the gospel, while a great number of Gentiles gladly flocked into the churches and freely embraced it?

##### STEP 2—Explore

**Just for Teachers**: While we seek to justify God's desire to save all sinful humans, the key question that Romans 9 addresses is: How does God intend ultimately to redeem the Israelite (Jewish) people, in spite of their past failures? In other words, as part of our search, we need to follow carefully Paul's argument that seeks to justify God's redemptive providences in saving all, both Jew and Gentile.

**Bible Commentary**

**I. Paul's Burden and Purpose for Both Jews and Gentiles** (Review Romans 9:1–13 with your class.)

In these verses, Paul seeks to demonstrate that God's plan to use Israel has not totally failed, as it is still producing a "remnant" of the seed of Abraham. So, while God has been selective, His will to save the lost is slowly but surely being effected. For instance, Abraham, the father of the Jewish nation, was chosen, and he (by faith in God's promises and power) begot a son named Isaac; then Isaac by faith begot Jacob, the direct progenitor of the tribes of Israel. Therefore, though God has been suffering setbacks, He is steadily, persistently, and providentially raising up a faithful "seed," or redeemed children. And these miracle children are becoming His progenitors of Israel and agents of salvation in a world racked by sin and hopelessness.

**Consider This**: Even though God has been selective in choosing His special servants, what evidence do we have that God has, or has not, been arbitrary in whom He saves?

**II. God's Elected Messengers to the World** (Review Romans 9:14–24 with your class.)

Paul now continues his argument by citing Exodus 33:19 and 9:16 in order to make the point that God will have "mercy on whomever" He chooses. And He will show His "compassion" and His "power . . . in all the earth" (Rom. 9:15, 17, NKJV). Paul also sets forth God's sovereign "power" in the illustration of the divine Potter, whose prerogative it is to shape the clay as He chooses (Rom. 9:19–24). So, clearly God is the One who is in charge when it comes to deciding who will do His missionary will on the earth.

**Discussion Question**: God is in charge of choosing His missionary agencies. Does this fact negate His ability to impart to humans the right to choose to accept or reject their eternal salvation? Why, or why not?

**III. God Is in Charge of His Mission to Save the World.** (Review Romans 9:25–33 with your class.)

Spend a few moments going over the Old Testament passages cited by Paul that prophesy about God's mission to the Gentiles (such as Hos. 2:23; 1:10; Isa. 10:22, 23; 1:9, and 13:19).

**Consider This**: What evidence is given in these verses that points to God's passion to save both Jews and Gentiles?

**IV. A Universal Offer of Salvation** (Review 1 Timothy 2:3, 4; 4:10; John 3:16; Titus 2:11; and 2 Peter 3:9 with your class.)

The texts for review clearly witness to a universal offer of salvation. But how do they, in turn, relate to Paul's thesis of God's sovereign choice of Israel to do His missionary bidding?

In answer to this question, let's ponder these five texts, which seem to clearly speak of a free-grace, freewill version of salvation:

1. "God our Savior, who desires all men to be saved" (1 Tim. 2:3, 4, NKJV); compared with
2. "God, who is the Savior of all men, especially of those who believe" (1 Tim. 4:10, NKJV);
3. " 'For God so loved the world that He gave His only begotten Son, that whoever believes in Him should not perish but have everlasting life' " (John 3:16, NKJV);
4. "For the grace of God that brings salvation has appeared to all men" (Titus 2:11, NKJV); and
5. "The Lord . . . is longsuffering toward us, not willing that any should perish but that all should come to repentance" (2 Pet. 3:9, NKJV).

**Consider This**: Recall the question that commenced this section: What are we to make of these verses? By way of answering, ponder the following rationale: If Paul means in Romans 9 that God has irresistibly predetermined the salvation of all men, regardless of their freely given, grace-and faith-based response to the gospel, then we have caught the Scriptures in a gross contradiction. What is to be made of this supposed conundrum? It then would seem "logical" to conclude that the great controversy theme is effectually shorn of its interpretive power to explain the origin of sin and suffering. The terrible result of this conclusion would be that God is left as the sole cause of evil and the Bestower of an arbitrary salvation from the wages of sin. How does a correct understanding of Bible truth in Romans 9 overturn this false assumption?

##### STEP 3—Apply

**Just for Teachers**: Invite your class to ponder the last question posed regarding the dynamics of the great controversy theme in the previous step, and then tackle the following questions:

**Application Questions**:

1. There is a theme that is often referred to in philosophy and theology as "theodicy." Namely, it is the question of how we can go about vindicating or properly "judging" God in the face of the problem of seemingly unmitigated human suffering and sorrow. How have you struggled to make sense of the problem of evil?
2. How does our explanation of Romans 9 make contextual sense in the unfolding argument of Paul in Romans? Or have we improperly imported a "freewill, free-grace" theme that is alien to Paul's overall thought? Discuss.
3. Is it fair to Paul to place him in the larger narrative of the biblical canon when it comes to the numerous freewill, free-grace passages cited above?
4. How does the great controversy provide a satisfactory explanation of the problem of evil and the inconceivable amount of human suffering and loss manifested in the history of this world?

##### STEP 4—Create

**Just for Teachers**: As your class wrestles with Romans 9 and Paul's struggle with the Judaizers, seek to lead them into a sympathetic identity with Paul and his missionary burdens for both Jews and Gentiles.

**Activities**:

1. Ask the class to reread reflectively Paul's anguished, even "hand-wringing," confession of concern for the salvation of the Jews in Romans 9:1–4. Then ponder the second activity listed.
2. After reflecting on your experience of Christian witness and service, ask yourselves (first individually, then as a class) if you have ever reached the point where you were willing to die either "with" (as Moses) or "for" (as Paul) the Christians and the non-Christians in your life.
3. As Paul ponders the differing ways that "Israel" (particularly first-century "Jews") and the "Gentiles" have related to the gospel in Romans 9:30–33, he then compares the two contrasting experiences of those who pursue "the law of righteousness" (Rom. 9:31). He identifies these two experiences as (a) "the righteousness of faith" (Rom. 9:30, NKJV) and (b) "works of the law" (Rom. 9:32). What would be some key characteristics that could help the followers of Christ to discern the distinctions between experiences that have been based on "faith" as opposed to those based on "works of the law"?


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class IoAndroidCamera extends React.Component<IconBaseProps> { }
export = IoAndroidCamera;


text:
import Tile from './Tile.js';
import TilePosition from './TilePosition.js';

export default class TilePuzzle {

    /**
     * Constructor.
     */
    constructor() {
        this.tiles = [];
        this.rows = [];
        this.win = false;

        this.TILES_PER_ROW = 4;
        this.TILES_NUMBER = 15;

        this.switchTiles.bind(this);
        this.init.bind(this);
        this.get.bind(this);
        this.toRows.bind(this);
    }

    /**
     * Initializes TilePuzzle game.
     */
    init() {
        for (let i = 1; i <= this.TILES_NUMBER; ++i) {
            let tile = new Tile(i);
            tile.addOnSwitchListener(this);
            this.tiles.push(tile);
        }
        this.tiles.push(new Tile(null)); // Empty tile

        this._shuffle();

        let rowNumber = 1;
        let rowPosition = 1;
        this.tiles.forEach((tile) => {
            tile.setPosition(new TilePosition(rowNumber, rowPosition++));
            if (rowPosition > this.TILES_PER_ROW) {
                rowPosition = 1;
                rowNumber++;
            }
        });
    }

    /**
     * Shuffles the tiles.
     * @private
     */
    _shuffle() {
        var j, x, i;
        for (i = this.tiles.length; i; i -= 1) {
            j = Math.floor(Math.random() * i);
            x = this.tiles[i - 1];
            this.tiles[i - 1] = this.tiles[j];
            this.tiles[j] = x;
        }
    }

    /**
     * Returns array of all rows containing Tiles.
     * @returns {Array}
     */
    toRows() {
        let rows = [];
        let currentRow = [];
        let currentRowNumber = 1;
        this.tiles.forEach((tile) => {
            if (tile.tilePosition.rowNumber != currentRowNumber) {
                rows.push(currentRow);
                currentRow = [];
                currentRowNumber = tile.tilePosition.rowNumber;
            }
            currentRow.push(tile);
        });
        rows.push(currentRow);

        return rows;
    }

    /**
     * Returns tile with given rowNumber and rowPosition.
     * @param rowNumber
     * @param rowPosition
     * @returns {number|null}
     */
    get(rowNumber, rowPosition) {
        let index = this._getIndexForPosition(new TilePosition(rowNumber, rowPosition));
        return index < this.tiles.length && index >= 0 ? this.tiles[index] : null;
    }

    /**
     * Switches given tile with empty tile in its neighborhood.
     * If there isn't the empty tile nearby, nothing happens.
     * Checks for win conditions after switching.
     * @param {Tile} tile
     */
    switchTiles(tile) {
        let otherTile = null;
        let otherTilePositions = [
            new TilePosition(tile.tilePosition.rowNumber + 1, tile.tilePosition.rowPosition),
            new TilePosition(tile.tilePosition.rowNumber, tile.tilePosition.rowPosition + 1),
            new TilePosition(tile.tilePosition.rowNumber - 1, tile.tilePosition.rowPosition),
            new TilePosition(tile.tilePosition.rowNumber, tile.tilePosition.rowPosition - 1)
        ];
        while (otherTilePositions.length > 0 && !otherTile) {
            let otherTilePosition = otherTilePositions.shift();
            otherTile = this.get(otherTilePosition.rowNumber, otherTilePosition.rowPosition);
            if (otherTile && !otherTile.isEmpty()) {
                otherTile = null;
            }
        }
        if (otherTile) {
            let otherTilePosition = this._getIndexForPosition(otherTile.tilePosition);
            let tilePosition = this._getIndexForPosition(tile.tilePosition);
            this.tiles[otherTilePosition] = tile;
            this.tiles[tilePosition] = otherTile;
            tile.switchPositions(otherTile);
            this._checkWin();
        }
    }

    /**
     * Return index in tiles for TilePosition.
     * @param {TilePosition} tilePosition
     * @returns {number}
     * @private
     */
    _getIndexForPosition(tilePosition) {
        return (tilePosition.rowNumber - 1) * this.TILES_PER_ROW + (tilePosition.rowPosition - 1);
    }

    /**
     * Checks win conditions.
     * If all the tiles are in numerically ascending order, the player wins.
     * @private
     */
    _checkWin() {
        let lastNumber = 0;

        for (let i = 0; i < this.tiles.length; ++i) {
            let tile = this.tiles[i];
            if (tile.number != null) {
                if (tile.number > lastNumber) {
                    lastNumber = tile.number;
                } else {
                    return false;
                }
            }
        }
        this.win = true;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Generate PDF with PHP</title>

 Please download  your results in PDF Version .

<form action="index.php"  method="post" class="registration_form">
  <fieldset>
    <legend>Personal Information </legend>

      Name :
      <input type="text" name="name" value="Hyder Bangash" size="25" />

      E-mail :
      <input type="text" name="e-mail" value="admin@youhack.me" size="25" />

      Address :
      <input type="text" name="Address" value="Henrietta Rd" size="25" />

      City  :
      <input type="text" name="City" value="Vacoas" size="25" />

      Country  :
      <input type="text" name="Country" value="Mauritius" size="25" />

  </fieldset>

  <fieldset>
    <legend>Results  </legend>

      <input type="text" name="subjects[]" value="Maths" size="25" />
      <input type="text" name="Marks[]" value="50" size="10" />

      <input type="text" name="subjects[]" value="English" size="25" />
      <input type="text" name="Marks[]" value="10" size="10" />

     <input type="text" name="subjects[]" value="French" size="25" />
     <input type="text" name="Marks[]" value="65" size="10" />

    <input type="text" name="subjects[]" value="Science" size="25" />
    <input type="text" name="Marks[]" value="80" size="10" />

        <input type="hidden" value="submitted" />
	<button type="submit">Submit</button>

  </fieldset>
</form>


text:
var TableExtension = MediumEditor.extensions.anchor.extend({
  name: 'table',
  action: 'createTable',
  aria: 'table',
  tagNames: ['table'],
  contentDefault: 'T',
  contentFA: '',

  doFormSave: function () {
    var columnCount = this.getColumnsInput().value,
    rowCount = this.getRowsInput().value,
    table = this.createTable(columnCount, rowCount);

    // Restore Medium Editor's selection before pasting HTML
    this.base.restoreSelection();

    // Paste newly created table.
    this.base.pasteHTML(table.innerHTML);

    // Update toolbar -> hide this form
    this.base.checkSelection();
  },

  createTable: function (cols, rows) {
    var doc = this.base.options.ownerDocument,
    table = doc.createElement('table'),
    header = doc.createElement('thead'),
    headerRow = doc.createElement('tr'),
    body = doc.createElement('tbody'),
    wrap = doc.createElement('div'),
    h, r, c, headerCol, bodyRow, bodyCol;

    for (h = 1; h <= cols; h++) {
      headerCol = doc.createElement('th');
      headerCol.innerHTML = '...';
      headerRow.appendChild(headerCol);
    }

    header.appendChild(headerRow);

    for (r = 1; r <= rows; r++) {
      bodyRow = doc.createElement('tr');
      for (c = 1; c <= cols; c++) {
        bodyCol = doc.createElement('td');
        bodyCol.innerHTML = '...';
        bodyRow.appendChild(bodyCol);
      }
      body.appendChild(bodyRow);
    }

    table.appendChild(header);
    table.appendChild(body);
    wrap.appendChild(table);

    return wrap;
  },

  // Called when the button the toolbar is clicked
  // Overrides DefaultButton.handleClick
  handleClick: function (evt) {
    evt.preventDefault();
    evt.stopPropagation();

    if (!this.isDisplayed()) {
      this.showForm();
    }

    return false;
  },

  hideForm: function () {
    this.getColumnsInput().value = '';
    this.getRowsInput().value = '';
    this.getForm().style.display = 'none';
  },

  showForm: function () {
    var colsInput = this.getColumnsInput(),
    rowsInput = this.getRowsInput();

    this.base.saveSelection();
    this.hideToolbarDefaultActions();
    this.getForm().style.display = 'block';
    this.setToolbarPosition();

    colsInput.focus();
  },

  createForm: function () {
    var doc = this.base.options.ownerDocument,
    form = doc.createElement('div'),
    close = doc.createElement('a'),
    save = doc.createElement('a'),
    columnInput = doc.createElement('input'),
    rowInput = doc.createElement('input');

    form.className = 'medium-editor-toolbar-form';
    form.id = 'medium-editor-toolbar-form-table-' + this.base.id;

    // Handle clicks on the form itself
    this.base.on(form, 'click', this.handleFormClick.bind(this));

    // Add columns textbox
    columnInput.setAttribute('type', 'text');
    columnInput.className = 'medium-editor-toolbar-input medium-editor-toolbar-input-columns';
    columnInput.setAttribute('placeholder', 'Column Count');
    form.appendChild(columnInput);

    // Add rows textbox
    rowInput.setAttribute('type', 'text');
    rowInput.className = 'medium-editor-toolbar-input medium-editor-toolbar-input-rows';
    rowInput.setAttribute('placeholder', 'Row Count');
    form.appendChild(rowInput);

    // Handle typing in the textboxes
    this.base.on(columnInput, 'keyup', this.handleTextboxKeyup.bind(this));
    this.base.on(rowInput, 'keyup', this.handleTextboxKeyup.bind(this));

    // Add save buton
    save.setAttribute('href', '#');
    save.className = 'medium-editor-toolbar-save';
    save.innerHTML = this.base.options.buttonLabels === 'fontawesome' ?
    '' :
    '✓';
    form.appendChild(save);

    // Handle save button clicks (capture)
    this.base.on(save, 'click', this.handleSaveClick.bind(this), true);

    // Add close button
    close.setAttribute('href', '#');
    close.className = 'medium-editor-toolbar-close';
    close.innerHTML = this.base.options.buttonLabels === 'fontawesome' ?
    '' :
    '×';
    form.appendChild(close);

    // Handle close button clicks
    this.base.on(close, 'click', this.handleCloseClick.bind(this));

    return form;
  },

  getColumnsInput: function () {
    return this.getForm().querySelector('input.medium-editor-toolbar-input-columns');
  },

  getRowsInput: function () {
    return this.getForm().querySelector('input.medium-editor-toolbar-input-rows');
  }
})


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_margin="15dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:id="@+id/hourly_date_text"/>

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/hourly_forecast_img"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:gravity="center"
        android:id="@+id/hourly_info_text"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:gravity="right"
        android:id="@+id/hourly_text"/>

</LinearLayout>


text:
Cron string parser for node and the browser

[![npm version](https://badge.fury.io/js/cron-converter.svg)](https://badge.fury.io/js/cron-converter)
[![Build status](https://github.com/roccivic/cron-converter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/roccivic/cron-converter/actions/workflows/build.yml)
[![Coverage Status](https://coveralls.io/repos/roccivic/cron-converter/badge.svg?branch=master&service=github)](https://coveralls.io/github/roccivic/cron-converter?branch=master)

Try the [online demo](https://cron-converter-demo.netlify.app/) and check the [source code](https://github.com/roccivic/cron-converter-demo) for the integration.

# Install

```bash
yarn add cron-converter
```

or

```bash
npm install cron-converter --save
```

# Compatibility

Versions `2.x.x` of `cron-converter` are not backwards compatible with versions `1.x.x`.

| | `2.x.x`  | `1.x.x` |
| ---- | ------------- | ------------- |
| API | Functional | Object-oriented |
| Loader | ESM and CommonJS | CommonJS only |
| Type definitions | Bundled | Install [`@types/cron-converter`](https://www.npmjs.com/package/@types/cron-converter) |
| Date/time | [`Luxon`](https://moment.github.io/luxon/) | [`Moment.js`](https://momentjs.com/) |
| Tree-shaking | ✅ | ❌ |

# Import

```ts
import { stringToArray, arrayToString, getSchedule, getUnits } from "cron-converter";
```

# Usage

## Convert a string to an array

```ts
// Every 10 mins between 9am and 5pm on the 1st of every month
const arr = stringToArray("*/10 9-17 1 * *");

// Prints:
// [
//   [ 0, 10, 20, 30, 40, 50 ],
//   [ 9, 10, 11, 12, 13, 14, 15, 16, 17 ],
//   [ 1 ],
//   [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ],
//   [ 0, 1, 2, 3, 4, 5, 6 ]
// ]
console.log(arr);
```

## Convert an array to a string

```ts
const str = arrayToString([[0], [1], [1], [5], [0, 2, 4, 6]]);

// Prints: '0 1 1 5 */2'
console.log(str);
```

## Formatting options

### outputMonthNames

Default: `false`

```ts
const arr = [[1], [1], [1], [1, 2, 3], [1, 2, 3]];
const str = arrayToString(arr, { outputMonthNames: true });

// Prints: '1 1 1 JAN-MAR 1-3'
console.log(str);
```

### outputWeekdayNames

Default: `false`

```ts
const arr = [[1], [1], [1], [1, 2, 3], [1, 2, 3]];
const str = arrayToString(arr, { outputWeekdayNames: true });

// Prints: '1 1 1 1-3 MON-WED'
console.log(str);
```

### outputHashes

Default: `false`

```ts
const arr = [[1], [1], [1], [1, 6, 11], [0, 1, 2, 3, 4, 5, 6]];

// Prints: '1 1 1 H/5 H'
console.log(arrayToString(arr, { outputHashes: true }));
```

## Get the schedule execution times

```ts
// Convert a string to an array
const arr = stringToArray("*/5 * * * *");

// Get the iterator, initialised to now
let schedule = getSchedule(arr);

// Optionally pass a reference `Date` and a `timezone`
let reference = new Date(2013, 2, 8, 9, 32);
const schedule = getSchedule(arr, reference, "Europe/London");

// Calls to `.next()` and `.prev()` return a Luxon `DateTime` object

// Prints: '2013-03-08T09:35:00+00:00''
console.log(schedule.next().format());
// Prints: '2013-03-08T09:40:00+00:00''
console.log(schedule.next().format());

// Reset
schedule.reset();

// Prints: '2013-03-08T09:30:00+00:00''
console.log(schedule.prev().format());
// Prints: '2013-03-08T09:25:00+00:00''
console.log(schedule.prev().format());
```

## Get the units configuration
This is useful if you are creating a user interface. See [units.ts](./src/units.ts).
```ts
const units = getUnits();
```

## Test and build

```bash
git clone https://github.com/roccivic/cron-converter
cd cron-converter
yarn
yarn build
yarn test
yarn coverage
```


text:
/*
 @ 0xCCCCCCCC
*/

#include <iostream>
#include <random>

#include <pthread.h>

int g_seq[2];

pthread_barrier_t barrier;

void* ThreadFunc(void* arg)
{
    std::random_device rd;
    auto seq = rd();
    auto idx = reinterpret_cast<long>(arg);

    std::cout << "thread " << idx << " is done and ready to wait\n";
    pthread_barrier_wait(&barrier);

    g_seq[idx] = seq;

    return reinterpret_cast<void*>(0);
}

int main()
{
    pthread_barrier_init(&barrier, nullptr, 2);

    constexpr int kThreadNum = 2;
    pthread_t threads[kThreadNum];

    for (int i = 0; i < kThreadNum; ++i) {
        pthread_create(&threads[i], nullptr, ThreadFunc, reinterpret_cast<void*>(i));
    }

    for (int i = 0; i < kThreadNum; ++i) {
        pthread_join(threads[i], nullptr);
    }

    std::cout << "Generated seq are: " << g_seq[0] << "\t" << g_seq[1] << "\n";

    pthread_barrier_destroy(&barrier);

    return 0;
}


text:
require 'spec_helper'

describe Catarse::OmniauthCallbacksController do
  before do
    @request.env["devise.mapping"] = Devise.mappings[:user]
  end

  let(:return_to){ nil }
  let(:user){ FactoryGirl.create(:user, authorizations: [ FactoryGirl.create(:authorization, uid: oauth_data[:uid], oauth_provider: facebook_provider ) ]) }
  let(:facebook_provider){ FactoryGirl.create :oauth_provider, name: 'facebook' }
  let(:oauth_data){
    Hashie::Mash.new({
      credentials: {
        expires: true,
        expires_at: 1366644101,
        token: "AAAHuZCwF61OkBAOmLTwrhv52pZCriPnTGIasdasdasdascNhZCZApsZCSg6POZCQqolxYjnqLSVH67TaRDONx72fXXXB7N7ZBByLZCV7ldvagm"
      },
      extra: {
        raw_info: {
          bio: "I, simply am not there",
          email: "diogob@gmail.com",
          first_name: "Diogo",
          gender: "male",
          id: "547955110",
          last_name: "Biazus",
          link: "http://www.facebook.com/diogo.biazus",
          locale: "pt_BR",
          name: "Diogo, Biazus",
          timezone: -3,
          updated_time: "2012-08-01T18:22:50+0000",
          username: "diogo.biazus",
          verified: true
        },
      },
      info: {
        description: "I, simply am not there",
        email: "diogob@gmail.com",
        first_name: "Diogo",
        image: "http://graph.facebook.com/547955110/picture?type:, square",
        last_name: "Biazus",
        name: "Diogo, Biazus",
        nickname: "diogo.biazus",
        urls: {
          Facebook: "http://www.facebook.com/diogo.biazus"
        },
        verified: true
      },
      provider: "facebook",
      uid: "547955110"
    })
  }

  subject{ response }
  describe "GET facebook" do

    before do
      user
      session[:return_to] = return_to
      request.env['omniauth.auth'] = oauth_data
      get :facebook
    end

    context "when there is no such user and we do not have an email address" do
      let(:oauth_data){
        Hashie::Mash.new({
          info: {
            image: "http://graph.facebook.com/547955110/picture?type:, square",
            name: "Diogo, Biazus",
            nickname: "diogo.biazus",
            urls: {
              Facebook: "http://www.facebook.com/diogo.biazus"
            },
            verified: true
          },
          provider: "facebook",
          uid: "547955110"
        })
      }

      let(:user){ nil }
      describe "assigned user" do
        subject{ assigns(:user) }
        its(:email){ should be_nil }
        its(:name){ should == "Diogo, Biazus" }
      end
      it{ should render_template 'users/set_email' }
    end

    context "when there is no such user but we retrieve the email from omniauth" do
      let(:user){ nil }
      describe "assigned user" do
        subject{ assigns(:user) }
        its(:email){ should == "diogob@gmail.com" }
        its(:name){ should == "Diogo, Biazus" }
      end
      it{ should redirect_to root_path }
    end

    context "when there is a valid user with this provider and uid and session return_to is /foo" do
      let(:return_to){ '/foo' }
      it{ assigns(:user).should == user }
      it{ should redirect_to '/foo' }
    end

    context "when there is a valid user with this provider and uid and session return_to is nil" do
      it{ assigns(:user).should == user }
      it{ should redirect_to root_path }
    end
  end
end


text:
/* Include file for the GAPS map class */

#ifndef __RN__MAP__H__
#define __RN__MAP__H__

/* Library initialization functions */

int RNInitMap();
void RNStopMap();

/* Support class  */

template <class KeyType>
struct RNMapComparator {
    public:
        RNMapComparator(int (*compare_function)(KeyType, KeyType) = NULL) : compare_function(compare_function) {};
        bool operator()(KeyType a, KeyType b) const {
            if (compare_function) { return ((*compare_function)(a, b) < 0) ? true: false; }
            else { return a < b; }
        };
    private:
        int (*compare_function)(KeyType, KeyType);
};

/* Class definition */

template <class KeyType, class ValueType>
class RNMap {
    public:
        // Constructor/destructor functions
        RNMap(void);
        RNMap(int (*compare)(KeyType, KeyType));
        RNMap(const RNMap<KeyType,ValueType>& map);
        ~RNMap(void);

        // Property functions/operations
        int NEntries(void) const;

        // Data access functions/operators
        RNBoolean Find(KeyType key, ValueType *value = NULL) const;

        // Manipulation functions
        void Empty(void);
        void Insert(KeyType key, ValueType value);
        void Replace(KeyType key, ValueType value);
        void Remove(KeyType key);

        // Manipulation operators
        RNMap<KeyType, ValueType>& operator=(const RNMap<KeyType,ValueType>& map);

    public:
        std::map<KeyType, ValueType, RNMapComparator<KeyType> > *m;
};

/* Templated member functions */

#include "RNMap.cpp"

/* A useful derived class definition */

template <class ValueType>
class RNSymbolTable : public RNMap<std::string, ValueType> {
    public:
        // Constructor/destructor functions
        RNSymbolTable(void) : RNMap<std::string, ValueType>() {};
};

#endif