text:
var path = require('path');
var viewPath = path.join( __dirname + "/");
var fs = require('fs');
var multer = require('multer');
var Logger = require( __configs + "loggingConfig");

var _ = require('lodash');
var url = require('url');

var preferencesDB = require(__components + 'Preferences/preferenceDB.js');
var profileDB = require(__components + 'StudentProfile/studentProfileDB.js');
var defaultTool = require(__components + 'Preferences/setupDefaultToolType.js');

var sanitization = require(__configs + 'sanitization');
var validator = require('validator');

var event = require(__components + "InteractionEvents/buildEvent.js" );
var tracker = require(__components + "InteractionEvents/trackEvents.js" );

var surveyTests = require(__components +  "Survey/helpers/prePostSurvey");
const async = require('async');
var dbcfg = require(__configs + "databaseConfig");
var db = require(__configs + "database");
var dbHelpers = require(__components + "Databases/dbHelpers");

// multer config
var limits = { fileSize: 51200 };
var fileFilter = function(req, file, cb) {
    var filetype = /png/;
    var mimetype = filetype.test(file.mimetype);
    var extension = filetype.test(path.extname(file.originalname).toLowerCase());
    if (mimetype && extension) {
        return cb(null, true);
    } else {
        cb("Error: Only " + filetype + "files are allowed.", false);
    }
};
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        var userId = req.user.id;
        var basepath = 'app/shared/img/user/';
        var submissionFolder = path.join(basepath, req.user.id.toString());
        cb(null, submissionFolder);
    },
    filename: function(req, file, cb) {
        cb(null, 'avatar.png');
    },
});
var upload = multer({
    storage: storage,
    limits: limits,
    fileFilter: fileFilter
});

// POST/GET requests
module.exports = function(app, iosocket) {
    app.get('/preferences', function(req,res,next) {
        var err = false;
        var msg = "";
        if (req.query.err === 'name' || req.query.err === 'bio') {
                msg = "Illegal characters in " + req.query.err + ". Please try again.";
                err = true;
        } else if (req.query.success) {
            msg = "Success! Your changes have been saved.";
        }
        res.render(viewPath + "preferences", {title: 'Preferences', message: msg, err: err})
    });

    app.get('/preferences/data.json', function(req, res) {
        var preferencesFile = './config/preferencesList.json';
        fs.readFile(preferencesFile, 'utf-8', function(err, data) {
            if(err) {
                //Unable to get support tools file, larger problem here.
                Logger.error(err);
                res.end();
            } else {
                var jsonObj = JSON.parse(data);
                var preferences = jsonObj['preferences'];

                preferencesDB.getStudentPreferencesByToolType(req.user.id, "Option", function(err, preferencesDB) {
                    if(!err)
                        updateJsonWithDbValues(preferencesDB, preferences.options);

                    profileDB.getStudentProfile(req.user.id, function(perr, profile ) {
                        setupProfile(preferences.options, profile);
                        res.json(preferences);
                    });
                });
            }
        });
    });

    /**
     * [description] This function updates the user preference changes.
     *                 It validates answers and returns the user to the tool page or survey page.
     * @param  {[type]} req   [description]
     * @param  {[type]} res   [description]
     * @param  {[type]} next) {                   var userId [description]
     * @return {[type]}       [description]
     */
    app.post('/preferences/profile', upload.single('student-avatar'), function(req, res, next) {

        var userId = req.user.id;
        var pref = req.body["pref-toolSelect"];
        var tipsOn = req.body["pref-tipsAllowed"] ? req.body["pref-tipsAllowed"] : "off";
        var studentName = req.body['student-name'];
        var studentBio = req.body['student-bio'];
        var studentYearofStudy = req.body['student-yearOfStudy'] || '0' ;
        var studentAge = req.body["student-age"] || '0';
        var studentGender = req.body["student-gender"];
        var error = false;

        if (!sanitization.validateText(studentName, 'title')) {
            res.redirect(url.format({
                pathname:"/preferences",
                query: { err: "name" }
            }));
            error = true;
        }
        if (!sanitization.validateText(studentBio, 'par') && !error) {
            res.redirect(url.format({
                pathname: "/preferences",
                query: { err: "bio" }
            }));
            error = true;
        }

        if(pref && !error) {
            preferencesDB.setStudentPreferences(userId, "Option", "pref-toolSelect", pref , function(err,result){
                preferencesDB.setStudentPreferences(userId, "Option", "pref-tipsAllowed",tipsOn, function(err1,result1) {

                    tracker.trackEvent( iosocket, event.changeEvent(req.user.sessionId, req.user.id, "pref-toolSelect", pref));
                    tracker.trackEvent( iosocket, event.changeEvent(req.user.sessionId, req.user.id, "pref-tipsAllowed", tipsOn));

                    if(!err) {
                        defaultTool.setupDefaultTool(req, pref);
                    }

                    profileDB.setStudentProfile(userId, studentName, studentBio, studentYearofStudy, studentAge, studentGender, function(err, presult) {

                        tracker.trackEvent( iosocket, event.changeEvent(req.user.sessionId, req.user.id, "studentName", studentName));
                        tracker.trackEvent( iosocket, event.changeEvent(req.user.sessionId, req.user.id, "studentBio", studentBio));

                        if(err)
                            Logger.log("ERROR SETTING STUDENT PROFILE");
                        else {
                            async.series([
                                function(callback) {
                                    var q = "select completedSetup from " + dbcfg.user_registration_table + " where userId = ?";
                                    db.query(q, [req.user.id], function(err, data) {
                                        callback(null,data);
                                    });
                                },
                                function(callback) {
                                    var q = dbHelpers.buildUpdate(dbcfg.user_registration_table)
                                                    + 'SET completedSetup = ? WHERE userId = ?';
                                    db.query(q, [1, req.user.id], function(err, data) {
                                        callback(null,data);
                                    });
                                }
                            ],
                            function (err, results ){
                                if(results && results.length >= 1 && results[0].length >=1 && results[0][0].completedSetup == 0) {
                                    surveyTests.completedRecentSurveyTest(req.user.id, function(err,data){
                                        if(err) {
                                            res.redirect('/tool');
                                        }
                                        else
                                            res.redirect('/surveysRequest');
                                    });
                                }
                                else
                                    res.redirect('/tool');
                            });
                        }

                    });
                });
            });
        } else {
            Logger.log("ERROR IN POSTING PROFILE PREFERENCES");
            res.end();
        }
    });

    /**
     * Update default preferences with DB values for specific user.
     * @param  {[type]} preferencesDB      [description]
     * @param  {[type]} preferencesOptions [description]
     * @return {[type]}                    [description]
     */
    function updateJsonWithDbValues( preferencesDB, preferencesOptions) {
        var prefPrefix = "pref-"
        for(var i = 0; i < preferencesDB.length; i++) {
            var optionName = preferencesDB[i].toolName;

            if(_.startsWith(optionName,prefPrefix)) {
                var r = _.find(preferencesOptions,_.matchesProperty('name',optionName));
                 if(r){
                    if(r.type == "checkbox")
                        r['prefValue'] = preferencesDB[i].toolValue == "on";
                    else if(r.type == "select")
                        r['prefValue'] = preferencesDB[i].toolValue;
                }
            }
        }
    }

    /**
     * Setup student profile with basic information name, bio, img
     * @param  {[type]} preferenceOptions [description]
     * @param  {[type]} profile           [description]
     * @return {[type]}                   [description]
     */
    function setupProfile(preferenceOptions, profile) {
        if(profile && profile.length > 0) {
            var prefix = "student-"
            var keys = ['name', 'avatarFileName','bio', 'age', 'yearOfStudy', 'gender'];
            for(var i = 0; i < keys.length; i++) {
                var r = _.find(preferenceOptions,_.matchesProperty('name',prefix+keys[i]));
                if(r && r.type) {
                    r['prefValue'] =  profile[0][keys[i]] != null ? profile[0][keys[i]] : "";
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Authlete
  module Model
    class Base
      include Authlete::ParamInitializer

      public

      def self.parse(hash)
        hash.kind_of?(Hash) ? self.new(hash) : nil
      end
    end
  end
end


text:
#pragma once

#include <algorithm>
#include <array>
#include <memory>
#include "util/error.hpp"
#include "util/global_config.hpp"
#include "geometry/geom.hpp"
#include "constants.hpp"
#include "position.hpp"

namespace mocc {
/**
 * \brief Enumeration of different mesh treatments.
 *
 * Different clients will want to interact with the mesh in different ways. For
 * instance, MoC wants a radially fine mesh, but may wish to homogenize planes,
 * whereas an Sn sweeper wants to operate on a pin-homogenized mesh, with finer
 * axial treatment.
 */
enum class MeshTreatment : unsigned char {
    /// Fully conformal to the mesh as described. No homogenization is made.
    TRUE,
    /// Pin-homogenized mesh. Planes are not homogenized.
    PIN,
    /// Pins are not homogenized. Planes are homogenized as desired
    PLANE,
    /// Pin- and macroplane-homogenized mesh. Good for getting coarse results
    /// from and MoC sweeper
    PIN_PLANE
};

/**
 * This defines a base \ref Mesh type, which provides some basic
 * information. For now, the mesh is restricted to a structured grid of
 * cells, which in the case of the derived \ref CoreMesh class are filled
 * with \ref Pin objects, but in the case of the base \ref Mesh type are
 * more abstract in nature. In lieu of a standalone coarse mesh (for things
 * like CMFD and 2D/3D), the Mesh itself provides method for interacting
 * with homogeneous regions and their interface surfaces.
 *
 * \todo the unit test for Mesh is not really done. Its got some stuff in
 * there for my testing, but it needs some serious work.
 */
class Mesh {
public:
    typedef std::array<std::array<Boundary, 2>, 3> BCArray_t;

    Mesh(){};

    /**
     * \brief Construct a \ref Mesh using cell boundaries specified
     * externally.
     *
     * \param n_reg The total expected number of regions
     * \param n_xsreg The total expected number of XS mesh regions
     * \param hx a vector containing the inter-pin boundaries for the X
     * dimension. Starts at 0.0, ends at the farthest extent of the mesh
     * \param hy a vector containing the inter-pin boundaries for the Y
     * dimension. Starts at 0.0, ends at the farthest extent of the mesh
     * \param hz a vector containing the inter-pin boundaries for the Z
     * dimension. Starts at 0.0, ends at the farthest extent of the mesh
     * \param bc an array containing the boundary conditions to be imposed on
     * each surface of the global domain
     */
    Mesh(size_t n_reg, size_t n_xsreg, const VecF &hx, const VecF &hy,
         const VecF &hz, std::array<Boundary, 6> bc);

    /**
     * \brief Return the total number of regions in the computational mesh.
     *
     * This is not necessarily the number of pins. For a MoC/CoreMesh this
     * is the number of flat source regions.
     *
     * \todo change name to n_regions()
     */
    virtual size_t n_reg(MeshTreatment treatment) const
    {
        assert((treatment == MeshTreatment::PIN) ||
               (treatment == MeshTreatment::PIN_PLANE));
        if (treatment == MeshTreatment::PIN) {
            return nx_ * ny_ * nz_;
        } else {
            return nx_ * ny_ * (macroplane_index_.back() + 1);
        }
    }

    /**
     * \brief Return the number of pins along the X dimension
     */
    size_t nx() const
    {
        return nx_;
    }

    /**
     * \brief Return the number of pins along the Y dimension
     */
    size_t ny() const
    {
        return ny_;
    }

    /**
     * \brief Return the number of planes in the Z dimension
     */
    size_t nz() const
    {
        return nz_;
    }

    /**
    * \brief Return a vector containing the core boundary conditions.
    */
    const std::array<Boundary, 6> &boundary() const
    {
        return bc_;
    }

    /**
     * \brief Return the boundary condition associated with the given \ref
     * Surface of the mesh
     */
    Boundary boundary_condition(Surface surf) const
    {
        assert((int)surf >= (int)Surface::EAST);
        assert((int)surf <= (int)Surface::BOTTOM);

        return bc_[(int)surf];
    }

    /**
     * \brief Return a nifty array of the boundary conditions, organized by
     * normal direction and sense.
     *
     * This returns a 2-dimensional array of the boundary conditions,
     * organized in such a way that makes BC determination for a given
     * normal direction and directional sense. For example \c
     * bc[Normal::X_NORM][0] would give the boundary condition on the west
     * bounday, \c bc[Normal::Z_NORM][1] would give the boundary condition
     * on the top.
     */
    BCArray_t boundary_array() const
    {
        BCArray_t bc;

        bc[(int)Normal::X_NORM][0] = bc_[(int)Surface::WEST];
        bc[(int)Normal::X_NORM][1] = bc_[(int)Surface::EAST];
        bc[(int)Normal::Y_NORM][0] = bc_[(int)Surface::SOUTH];
        bc[(int)Normal::Y_NORM][1] = bc_[(int)Surface::NORTH];
        bc[(int)Normal::Z_NORM][0] = bc_[(int)Surface::BOTTOM];
        bc[(int)Normal::Z_NORM][1] = bc_[(int)Surface::TOP];

        return bc;
    }

    /**
    * \brief Return the total core length along the x dimension
    */
    real_t hx_core() const
    {
        return hx_;
    }

    /**
    * \brief Return the total core length along the y dimension
    */
    real_t hy_core() const
    {
        return hy_;
    }

    /**
     * \brief Return the pin/coarse cell thickness in the x dimension at the
     * specified x position.
     */
    inline real_t dx(int ix) const
    {
        return dx_vec_[ix];
    }

    /**
     * \brief Return the pin/coarse cell thickness in the y dimension at the
     * specified y position.
     */
    inline real_t dy(int iy) const
    {
        return dy_vec_[iy];
    }

    /**
     * \brief Return the pin/coarse cell thickness in the z dimension at the
     * specified z position.
     */
    inline real_t dz(int iz) const
    {
        return dz_vec_[iz];
    }

    /**
     * \brief Return the indexed plane boundary.
     *
     * The 0-th value should be 0.0, and the last value should be to total
     * height of the domain.
     */
    inline real_t z(int iz) const
    {
        return z_vec_[iz];
    }

    /**
    * \brief Return the pin widths along the x dimension
    */
    const VecF &pin_dx() const
    {
        return dx_vec_;
    }

    /**
    * \brief Return the pin widths along the y dimension
    */
    const VecF &pin_dy() const
    {
        return dy_vec_;
    }

    /**
    * \brief Return the pin heights along the y dimension
    */
    const VecF &pin_dz() const
    {
        return dz_vec_;
    }

    /**
     * \brief Return a vector of all of the inter-pin boundary locations along
     * the x dimension
     */
    const VecF &x_divisions() const
    {
        return x_vec_;
    }

    /**
     * \brief Return a vector of all of the inter-pin boundary locations along
     * the y dimension
     */
    const VecF &y_divisions() const
    {
        return y_vec_;
    }

    /**
     * \brief Return a vector of all of the inter-plane boundaries
     */
    const VecF &z_divisions() const
    {
        return z_vec_;
    }

    real_t coarse_volume(int cell) const
    {
        return coarse_vol_[cell];
    }

    const VecF &coarse_volume() const
    {
        return coarse_vol_;
    }

    /**
     * \brief Return the cell thickness in the direction indicated.
     *
     * \param cell the index of the cell
     * \param norm the \ref Normal direction
     *
     * Given a cell index and a \ref Normal, returns the thickness of the
     * indexed cell in the specified direction. For instance, if \ref
     * Normal::X_NORM is passed, this returns the thickness of the indexed
     * cell in the x direction.
     *
     */
    real_t cell_thickness(int cell, Normal norm) const
    {
        assert(cell < this->n_pin());
        assert((norm == Normal::X_NORM) || (norm == Normal::Y_NORM) ||
               (norm == Normal::Z_NORM));
        auto pos = this->coarse_position(cell);
        real_t h = 0;
        switch (norm) {
        case Normal::X_NORM:
            h = dx_vec_[pos.x];
            break;
        case Normal::Y_NORM:
            h = dy_vec_[pos.y];
            break;
        case Normal::Z_NORM:
            h = dz_vec_[pos.z];
            break;
        }
        return h;
    }

    /**
     * \brief Return the total number of pin regions in the mesh.
     *
     * This includes plane separations. This is essentially the number of
     * coarse mesh regions.
     */
    int n_pin() const
    {
        return nx_ * ny_ * nz_;
    }

    /**
     * \brief Return the number of coarse surfaces.
     *
     * \param nz the number of planes to consider (default: nz_). This might be
     * specified to use a coarser axial mesh for certain things (CMFD)
     */
    size_t n_surf() const
    {
        return (nx_ + 1) * ny_ * nz_ + (ny_ + 1) * nx_ * nz_ +
               (nz_ + 1) * nx_ * ny_;
    }

    /**
     * \brief Return a vector containing the x-, y-, z-dimensions of the
     * mesh.
     */
    VecI dimensions() const
    {
        VecI d = {(int)nx_, (int)ny_, (int)nz_};
        return d;
    }

    /**
     * \brief Return the lowest coarse cell index in a given plane
     */
    int plane_cell_begin(int plane) const
    {
        return nx_ * ny_ * plane;
    }

    /**
     * \brief Return the highest coarse cell index in a given plane, plus 1
     */
    int plane_cell_end(int plane) const
    {
        return nx_ * ny_ * (plane + 1);
    }

    /**
     * \brief Return the lowest coarse surface index in a given plane.
     *
     * It should be considered possible for the return value to be of any
     * direction normal (e.g. X, Y, or Z). Under the current indexing
     * scheme, it will always be Z-normal, but this could change.
     *
     * \sa plane_surf_xy_begin()
     */
    int plane_surf_begin(int plane) const
    {
        return n_surf_plane_ * plane;
    }

    /**
     * \brief Return the highest coarse surface index in a given plane, plus
     * 1
     */
    int plane_surf_end(int plane) const
    {
        return n_surf_plane_ * (plane + 1);
    }

    /**
     * \brief Return the lowest coarse surface index of the x- and y-normal
     * surfaces in a given plane.
     *
     * Iterating from here to \ref plane_surf_end() is safe, since the x/y
     * surfaces are guaranteed contiguous.
     *
     * \sa plane_surf_begin()
     * \sa plane_surf_end()
     */
    int plane_surf_xy_begin(int plane) const
    {
        return n_surf_plane_ * plane + nx_ * ny_;
    }

    /**
     * \brief Return the number of coarse cells per plane
     */
    size_t n_cell_plane() const
    {
        return nx_ * ny_;
    }

    /**
     * \brief Return the number of surfaces in each plane
     *
     * The "number of surfaces in each plane" can be a little confusing.
     * This really means the number of surfaces you need to offset one
     * surface index by to end up with the same plane-local surface, but in
     * the plane above. This means that \c n_surf_plane does not include the
     * "top" surfaces of each plane. For a concrete example, a 3x3 array of
     * regions per plane would yield an \c n_surf_plane of 33.
     */
    size_t n_surf_plane() const
    {
        return n_surf_plane_;
    }

    /**
     * \brief Return the coarse cell index given a pin \ref Position.
     *
     * Cell indexing is natural in x, y z. This can return invalid indices,
     * so in applications where an invalid Position might passed, check that
     * the return value is in [0,n_pin).
    */
    inline int coarse_cell(Position pos) const
    {
        return pos.z * nx_ * ny_ + pos.y * nx_ + pos.x;
    }

    /**
     * \brief Return the coarse cell index corresponding to the \ref Point2
     * passed.
     */
    int coarse_cell_point(Point2 p) const;

    /**
     * \brief Return the coarse cell index corresponding to the \ref Point3
     * passed.
     */
    int coarse_cell_point(Point3 p) const;

    /**
     * \brief Return the \ref Position of a coarse mesh cell index.
    */
    Position coarse_position(size_t cell) const
    {
        return Position(cell % nx_, (cell % (nx_ * ny_)) / nx_,
                        cell / (nx_ * ny_));
    }

    /**
     * \brief Return a coarse surface index given a cell index and Surface
     * direction.
     *
     * Surface indexing is more complicated than cell indexing, so listen
     * up, dear readers...
     *
     * Imagine that you are in the bottom plane of the mesh. Start by
     * numbering all of the bottom faces of the plane, starting in the lower
     * left, then moving right and up. You will have nx_*ny_ bottom surfaces
     * indexed, from 0 to nx_*ny_-1. Now start numbering all of the x-normal
     * faces, again starting with the bottom-leftmost, proceeding right,
     * then up.  Now you should be at nx_*ny_ + (nx_+1)*ny_ - 1. Do a
     * similar thing for the y-normal faces, except proceed up first, then
     * right. Lastly, number the surfaces above you, again starting at the
     * southwest, proceeding east, then north. This entire plane is now
     * indexed. Move up to the next plane above you and repeat the process,
     * keeping in mind that the surfaces below you already have numbers.
    */
    int coarse_surf(int i, Surface surf) const
    {
        assert(i >= 0);
        assert(i < this->n_pin());
        return coarse_surf_[i * 6 + (int)surf];
    }

    /**
     * \brief Determine the surface of a coarse cell that a point is on.
     *
     * If the point is on a corner, things get weird. Read on...
     *
     * This is useful for performing the coarse ray trace, and has to
     * consider a number of concerns related to current and surface flux
     * calculations, mostly when a point is in the vicinity of a mesh
     * corner. In such a case, potentially two surfaces are crossed and both
     * must be returned. The conventions for handling this are described
     * in \ref coarseraypage.
     */
    size_t coarse_norm_point(Point2 p, int octant, Surface (&s)[2]) const;

    /**
     * \brief Return the cell index that a point on the boundary of the mesh
     * should be considered within.
     *
     * This follows the conventions described in \ref coarseraypage.
     */
    int coarse_boundary_cell(Point2 p, int octant) const;

    /**
     * \brief Return the number of surfaces coincident with the passed
     * \ref Point2 and determine the index(s) of the surface(s) crossed.
     *
     * \param[in] p the \ref Point2 to check for surface.
     * \param[in] cell the index of a cell that the point should be
     * bordering.
     * \param[out] s an std::array<int, 2> to store the indices of the
     * surface(s) crossed.
     *
     * This will return the number of surfaces that a point lies on, either
     * 0, 1 or 2.
     *
     * Since this is primarily used for ray tracing, it is fundamentally 2-D
     * in nature, so the passed cell index will be %-ed by the number of CM
     * cells per plane, and the surface indices are returned as if they were
     * in the bottom-most plane; the code using the resulting indices is
     * therefore required to offset them to the appropriate plane.
    */
    int coarse_surf_point(Point2 p, int cell, std::array<int, 2> &s) const;

    /**
     * \brief Return the \ref Surface of the domain that a point is on, if
     * any.
     *
     * This returns an std::array<Surface, 3>, since it is possible for the
     * point to be outside of multiple bounds.
     */
    std::array<Surface, 3> boundary_surface(Point3 p, Direction dir) const
    {
        std::array<Surface, 3> surf = {
            {Surface::INTERNAL, Surface::INTERNAL, Surface::INTERNAL}};
        if ((p.x < REAL_FUZZ) && (dir.ox < 0.0)) {
            surf[0] = Surface::WEST;
        } else if ((p.y < REAL_FUZZ) && (dir.oy < 0.0)) {
            surf[0] = Surface::SOUTH;
        }
        if ((p.z < REAL_FUZZ) && (dir.oz < 0.0)) {
            surf[1] = Surface::BOTTOM;
        } else if ((p.x / hx_ > 1.0 - REAL_FUZZ) && (dir.ox > 0.0)) {
            surf[1] = Surface::EAST;
        }
        if ((p.y / hy_ > 1.0 - REAL_FUZZ) && (dir.oy > 0.0)) {
            surf[2] = Surface::NORTH;
        } else if ((p.z / hz_ > 1.0 - REAL_FUZZ) && (dir.oz > 0.0)) {
            surf[2] = Surface::TOP;
        }
        return surf;
    }

    /**
     * \brief Return the coarse cell indices straddling the surface
     * indicated.
     *
     * \param surf the index of the coarse surface to find neighboring
     * cells.
     *
     * \note The cells are always given in the order of increasing
     * position. This makes it easy to tell which cell is to the "right"
     * of the other. The first cell in the pair is always "left" of the
     * surface and the second is always "right." Positive current always
     * flows "right."
     *
     */
    std::pair<int, int> coarse_neigh_cells(size_t surf) const
    {
        std::pair<int, int> cells;

        switch (this->surface_normal(surf)) {
        case Normal::X_NORM: {
            // iz and iy are the cell positions, ix is the surface
            // position.
            int iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            int iy = (surf - nx_ * ny_) / (nx_ + 1);
            int ix = (surf - nx_ * ny_) % (nx_ + 1);

            if (ix > 0) {
                cells.first = this->coarse_cell(Position(ix - 1, iy, iz));
                assert(cells.first < this->n_pin());
            } else {
                cells.first = -1;
            }
            if (ix < nx_) {
                cells.second = this->coarse_cell(Position(ix, iy, iz));
                assert(cells.second < this->n_pin());
            } else {
                cells.second = -1;
            }
        } break;
        case Normal::Y_NORM: {
            // iz and ix are the cell positions, iy is the surface
            // position.
            int iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            surf -= nx_ * ny_ + (nx_ + 1) * ny_;
            int iy = surf % (ny_ + 1);
            int ix = surf / (ny_ + 1);

            if (iy > 0) {
                cells.first = this->coarse_cell(Position(ix, iy - 1, iz));
                assert(cells.first < this->n_pin());
            } else {
                cells.first = -1;
            }
            if (iy < ny_) {
                cells.second = this->coarse_cell(Position(ix, iy, iz));
                assert(cells.second < this->n_pin());
            } else {
                cells.second = -1;
            }
        } break;
        case Normal::Z_NORM: {
            // ix and iy are the cell positions, iz is the surface
            // position.
            int iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            int iy = surf / nx_;
            int ix = surf % nx_;

            if (iz > 0) {
                cells.first = this->coarse_cell(Position(ix, iy, iz - 1));
                assert(cells.first < this->n_pin());
            } else {
                cells.first = -1;
            }
            if (iz < nz_) {
                cells.second = this->coarse_cell(Position(ix, iy, iz));
                assert(cells.second < this->n_pin());
            } else {
                cells.second = -1;
            }
        } break;
        }
        return cells;
    }

    /**
     * \brief Return an index offset to the zero-th coarse cell in a given
     * plane.
     */
    int coarse_cell_offset(size_t plane) const
    {
        return nx_ * ny_ * plane;
    }

    /**
     * \brief Return an index offset to the zero-th coarse surface in a
     * given plane.
     *
     * Plane indexing is wonkier than cell indexing, espectially when
     * talking about planes, since we need to take into consideration the
     * surfaces between the planes. Since surface indexing starts with the
     * bottom-facing Z-normal faces, surface "zero" for any plane is a
     * surface looking "down" into the plane below. Stuff that wants to
     * interact with X- and Y-normal faces (e.g. 2-D MoC) should expect
     * this.
     */
    int coarse_surf_offset(size_t plane) const
    {
        return n_surf_plane_ * plane;
    }

    /**
     * \brief Return the surface index between two cells and the \ref
     * Surface of \p cell1 that makes the interface.
     *
     * This returns a \c std::pair containing the surface index and a \ref
     * Surface enumeration. The surface index is self-explainatory. The \ref
     * Surface enumeration is a little more complicated; it is the \ref
     * Surface of \p cell1 that makes the interface between \p cell1 and \p
     * cell2. If \p cell2 is to the north of \p cell1, then the \ref Surface
     * will be \ref Surface::NORTH. If the cell indices were passed in the
     * reverse order, the \ref Surface would be \ref Surface::SOUTH.
     * Therefore, it is important which order the cells are provided.
     */
    std::pair<size_t, Surface> coarse_interface(size_t cell1,
                                                size_t cell2) const
    {
        // Stupid search
        for (auto is : AllSurfaces) {
            if (this->coarse_neighbor(cell1, is) == (int)cell2) {
                return std::pair<size_t, Surface>(this->coarse_surf(cell1, is),
                                                  is);
            }
        }

        throw EXCEPT("Cells do not appear to be neighbors");
    }
    /**
     * \brief Return the surface area of the indexed cell and direction.
     */
    real_t coarse_area(size_t cell, Surface surf) const
    {
        auto pos    = this->coarse_position(cell);
        real_t area = 0.0;
        switch (surf) {
        case (Surface::EAST):
            area = dy_vec_[pos.y] * dz_vec_[pos.z];
            break;
        case (Surface::WEST):
            area = dy_vec_[pos.y] * dz_vec_[pos.z];
            break;
        case (Surface::NORTH):
            area = dx_vec_[pos.x] * dz_vec_[pos.z];
            break;
        case (Surface::SOUTH):
            area = dx_vec_[pos.x] * dz_vec_[pos.z];
            break;
        case (Surface::TOP):
            area = dx_vec_[pos.x] * dy_vec_[pos.y];
            break;
        case (Surface::BOTTOM):
            area = dx_vec_[pos.x] * dy_vec_[pos.y];
            break;
        default:
            assert(false);
            area = -1;
        }
        return area;
    }

    /**
     * \brief Return the surface area of the indexed coarse surface.
     */
    real_t coarse_area(size_t surf) const
    {
        real_t area;
        switch (this->surface_normal(surf)) {
        case Normal::X_NORM: {
            // iz and iy are the cell positions, ix is the surface
            // position.
            size_t iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            size_t iy = (surf - nx_ * ny_) / (nx_ + 1);

            area = dy_vec_[iy] * dz_vec_[iz];
        } break;
        case Normal::Y_NORM: {
            // iz and ix are the cell positions, iy is the surface
            // position.
            size_t iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            surf -= nx_ * ny_ + (nx_ + 1) * ny_;
            size_t ix = surf / (ny_ + 1);

            area = dx_vec_[ix] * dz_vec_[iz];
        } break;
        case Normal::Z_NORM: {
            // ix and iy are the cell positions, iz is the surface
            // position.
            size_t iz = surf / n_surf_plane_;
            surf -= iz * n_surf_plane_;
            size_t iy = surf / nx_;
            size_t ix = surf % nx_;

            area = dx_vec_[ix] * dy_vec_[iy];
        } break;
        }
        return area;
    }

    /**
     * \brief Return the neighboring coarse cell index of the passed cell
     * index in the passed direction.
     *
     * If the neighbor is out of bounds, return -1;
     */
    int coarse_neighbor(size_t cell, Surface surf) const
    {
        auto pos = this->coarse_position(cell);
        switch (surf) {
        case Surface::NORTH:
            if (pos.y < ny_ - 1) {
                return cell + nx_;
            } else {
                return -1;
            }
        case Surface::SOUTH:
            if (pos.y > 0) {
                return cell - nx_;
            } else {
                return -1;
            }
        case Surface::EAST:
            if (pos.x < nx_ - 1) {
                return cell + 1;
            } else {
                return -1;
            }
        case Surface::WEST:
            if (pos.x > 0) {
                return cell - 1;
            } else {
                return -1;
            }
        case Surface::TOP:
            if (pos.z < nz_ - 1) {
                return cell + nx_ * ny_;
            } else {
                return -1;
            }
        case Surface::BOTTOM:
            if (pos.z > 0) {
                return cell - nx_ * ny_;
            } else {
                return -1;
            }
        default:
            return -5;
        }
    }

    /**
     * \brief Return the plane index for the given axial position
     *
     * \param z the axial location
     * \param oz a direction in the z direction to be used to disabmiguate
     * between planes, if the value \p z lies directly on a plane interface.
     * Defaults to zero, and gives the following behavior:
     *  - If zero: Throw an exception if \p z lies on a plane interface.
     *  - If negative: Return the lower plane index if \p z lies on a plane
     *  interface.
     *  - If positive: Return the higher plane index if \p z lies on a plane
     *  interface.
     */
    int plane_index(real_t z, real_t oz = 0.0) const
    {
        int iz = std::distance(
            z_vec_.begin(),
            std::lower_bound(z_vec_.begin(), z_vec_.end(), z, fuzzy_lt));

        if (fp_equiv(z, z_vec_[iz])) {
            if (oz == 0.0) {
                throw EXCEPT(
                    "Ambiguous plane index, without valid "
                    "z-direction.");
            } else {
                iz = (oz > 0.0) ? iz + 1 : iz;
            }
        }

        return std::max(0, std::min(iz - 1, nz_ - 1));
    }

    /**
     * \brief Return the surface normal of the given surface.
     */
    Normal surface_normal(int surface) const
    {
        // Number of surfaces per plane
        int nsurfz = nx_ * ny_ + (nx_ + 1) * ny_ + (ny_ + 1) * nx_;

        if ((surface % nsurfz) < nx_ * ny_) {
            return Normal::Z_NORM;
        }
        if ((surface % nsurfz) < (nx_ * ny_ + (nx_ + 1) * ny_)) {
            return Normal::X_NORM;
        }
        return Normal::Y_NORM;
    }

    /**
     * \brief Trace a ray through the coarse surfaces.
    */
    void trace(std::vector<Point2> &p) const;

    /**
     * \brief Return a const reference to the collection of \ref Line
     * objects.
     */
    const std::vector<Line> lines() const
    {
        return lines_;
    }

    const VecI &macroplane_index() const
    {
        return macroplane_index_;
    }
    int macroplane_index(int iz) const
    {
        return macroplane_index_[iz];
    }

    int n_macroplanes() const
    {
        return macroplane_index_.back() + 1;
    }

protected:
    /**
     * This method pre-computes the surface indices for each coarse cell.
     * This must be done after we know what the overall dimensions of the
     * Mesh are since there is an empty constructor, allowing for mesh
     * dimensions to be deferred (namely by the CoreMesh), these dimensions
     * need to be determined at the end.
    */
    void prepare_surfaces();

    /// Total number of FSRs in the entire geometry
    size_t n_reg_;
    /// Total number of XS regions in the entire geometry
    size_t n_xsreg_;
    // Numbers of pins/planes in each dimension
    int nx_;
    int ny_;
    int nz_;

    /// Total core size in the x dimension
    real_t hx_;

    /// Total core size in the y dimension
    real_t hy_;

    /// Total core size in the z dimension
    real_t hz_;

    /// List of pin boundaries in the x dimension (starts at 0.0)
    VecF x_vec_;

    /// List of pin boundaries in the y dimension (starts at 0.0)
    VecF y_vec_;

    /// Sequence of plane boundaries in the z dimension (starts at 0.0)
    VecF z_vec_;

    /// Sequence of pin x pitches
    VecF dx_vec_;

    /// Sequence of pin y pitches
    VecF dy_vec_;

    /// Sequence of plane heights
    VecF dz_vec_;

    /// Coarse cell volumes
    VecF coarse_vol_;

    /// Vector of \ref Line objects, representing internal pin boundaries. This
    /// greatly simplifies the ray trace.
    std::vector<Line> lines_;

    /// Bounding box of the domain, also useful for tracing/particle tracking.
    Box bounding_box_;

    /// Number of surfaces per plane (doesn't consider the top surface)
    size_t n_surf_plane_;

    /// Vector of the macroplane indices corresponding to each axial height of
    /// the mesh.
    VecI macroplane_index_;

    /// Boundary condition for each side of the mesh
    std::array<Boundary, 6> bc_;

private:
    /// Vector storing densely-packed coarse mesh surface indices for each
    /// cell.
    VecI coarse_surf_;
};

typedef std::shared_ptr<Mesh> SP_Mesh_t;
}


text:
Create config like

~~~
module.exports = {
  channels: ['channel1']
  server: 'irc.gitter.im',
  botName: YOURNAME,
  password: YOURTOKEN
};
~~~

## Abilities

![links](https://raw.githubusercontent.com/afiodorov/myircbot/master/links%20today.png)

## Running

~~~.shell
node run.js
~~~

## TODO

Add some abstractions for events


text:
void MaybeSetMappingName(void *Mapping, size_t Size, const char *Name) {
#ifdef ANDROID
  prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, Mapping, Size, Name);
#endif // ANDROID
  // Anonymous mapping names are only supported on Android.
  return;
}

namespace gwp_asan {
void *GuardedPoolAllocator::mapMemory(size_t Size, const char *Name) const {
  void *Ptr =
      mmap(nullptr, Size, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  Check(Ptr != MAP_FAILED, "Failed to map guarded pool allocator memory");
  MaybeSetMappingName(Ptr, Size, Name);
  return Ptr;
}

void GuardedPoolAllocator::unmapMemory(void *Ptr, size_t Size,
                                       const char *Name) const {
  Check(munmap(Ptr, Size) == 0,
        "Failed to unmap guarded pool allocator memory.");
  MaybeSetMappingName(Ptr, Size, Name);
}

void GuardedPoolAllocator::markReadWrite(void *Ptr, size_t Size,
                                         const char *Name) const {
  Check(mprotect(Ptr, Size, PROT_READ | PROT_WRITE) == 0,
        "Failed to set guarded pool allocator memory at as RW.");
  MaybeSetMappingName(Ptr, Size, Name);
}

void GuardedPoolAllocator::markInaccessible(void *Ptr, size_t Size,
                                            const char *Name) const {
  // mmap() a PROT_NONE page over the address to release it to the system, if
  // we used mprotect() here the system would count pages in the quarantine
  // against the RSS.
  Check(mmap(Ptr, Size, PROT_NONE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1,
             0) != MAP_FAILED,
        "Failed to set guarded pool allocator memory as inaccessible.");
  MaybeSetMappingName(Ptr, Size, Name);
}

size_t GuardedPoolAllocator::getPlatformPageSize() {
  return sysconf(_SC_PAGESIZE);
}

void GuardedPoolAllocator::installAtFork() {
  auto Disable = []() {
    if (auto *S = getSingleton())
      S->disable();
  };
  auto Enable = []() {
    if (auto *S = getSingleton())
      S->enable();
  };
  pthread_atfork(Disable, Enable, Enable);
}

} // namespace gwp_asan


text:
from zeit.cms.checkout.interfaces import CheckinCheckoutError
from zeit.cms.checkout.interfaces import ICheckinManager, ICheckoutManager
from zeit.cms.checkout.interfaces import IValidateCheckinEvent
import copy
import datetime
import mock
import zeit.cms.checkout.helper
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.cms.repository.interfaces
import zeit.cms.testing
import zeit.cms.workingcopy.interfaces
import zope.component

class IContent(zeit.cms.interfaces.ICMSContent):
    pass

class Content(object):

    zope.interface.implements(
        IContent, zope.annotation.interfaces.IAttributeAnnotatable)
    uniqueId = u'testcontent://'
    __name__ = u'karlheinz'

@zope.component.adapter(IContent)
@zope.interface.implementer(zeit.cms.checkout.interfaces.ILocalContent)
def local_content(context):
    local = copy.copy(context)
    local.are_you_local = True
    zope.interface.alsoProvides(
        local, zeit.cms.checkout.interfaces.ILocalContent)
    return local

@zope.component.adapter(IContent)
@zope.interface.implementer(zeit.cms.checkout.interfaces.IRepositoryContent)
def repository_content(context):
    content = copy.copy(context)
    content.are_you_local = False
    zope.interface.noLongerProvides(
        content, zeit.cms.checkout.interfaces.ILocalContent)
    return content

class ManagerTest(zeit.cms.testing.ZeitCmsTestCase):

    def setUp(self):
        super(ManagerTest, self).setUp()
        self.content = Content()
        gsm = zope.component.getGlobalSiteManager()
        gsm.registerAdapter(local_content)
        gsm.registerAdapter(repository_content)

    def tearDown(self):
        self._tear_down_adapters()
        super(ManagerTest, self).tearDown()

    def _tear_down_adapters(self):
        gsm = zope.component.getGlobalSiteManager()
        gsm.unregisterAdapter(local_content)
        gsm.unregisterAdapter(repository_content)

    def test_checkout_without_ILocalContent_adapter_should_raise(self):
        self._tear_down_adapters()
        manager = ICheckoutManager(self.content)
        self.assertFalse(manager.canCheckout)
        self.assertRaises(CheckinCheckoutError, manager.checkout)

    def test_checkout_needs_adapter_to_ILocalContent(self):
        manager = ICheckoutManager(self.content)
        checked_out = manager.checkout()
        self.assertTrue(checked_out.are_you_local)

    def test_checkin_without_IRepositoryContent_adapter_should_raise(self):
        manager = ICheckoutManager(self.content)
        checked_out = manager.checkout()
        self._tear_down_adapters()
        manager = ICheckinManager(checked_out)
        self.assertTrue(manager.canCheckin)
        self.assertRaises(LookupError, manager.checkin)

    def test_checkin_needs_adapter_to_IRepositoryContent(self):
        manager = ICheckoutManager(self.content)
        checked_out = manager.checkout()
        manager = ICheckinManager(checked_out)
        checked_in = manager.checkin()
        self.assertFalse(checked_in.are_you_local)

    def test_delete_issues_events_and_deletes_context(self):
        manager = ICheckoutManager(self.content)
        checked_out = manager.checkout()
        parent = checked_out.__parent__
        name = checked_out.__name__
        manager = ICheckinManager(checked_out)
        with mock.patch('zope.event.notify', mock.Mock()) as notify:
            manager.delete()
            self.assertNotIn(name, parent.keys())
            self.assertEqual(2, len(notify.call_args_list))
            before, after = notify.call_args_list
            self.assertTrue(
                zeit.cms.checkout.interfaces.IBeforeDeleteEvent.providedBy(
                    before[0][0]))
            self.assertTrue(
                zeit.cms.checkout.interfaces.IAfterDeleteEvent.providedBy(
                    after[0][0]))

    def test_checkin_does_not_unlock_while_publishing(self):
        manager = ICheckoutManager(self.repository['testcontent'])
        checked_out = manager.checkout()
        manager = ICheckinManager(checked_out)
        manager.checkin(publishing=True)
        lockable = zope.app.locking.interfaces.ILockable(
            self.repository['testcontent'])
        self.assertTrue(lockable.locked())

class ValidateCheckinTest(zeit.cms.testing.ZeitCmsTestCase):

    def setUp(self):
        super(ValidateCheckinTest, self).setUp()
        zope.component.getSiteManager().registerHandler(
            self.provoke_veto, (IValidateCheckinEvent,))

        self.workingcopy = zeit.cms.workingcopy.interfaces.IWorkingcopy(
            self.principal)

        manager = ICheckoutManager(self.repository['testcontent'])
        self.checked_out = manager.checkout()

    def tearDown(self):
        zope.component.getSiteManager().unregisterHandler(
            self.provoke_veto, (IValidateCheckinEvent,))
        super(ValidateCheckinTest, self).tearDown()

    def provoke_veto(self, event):
        event.veto('provoked veto')

    def test_veto_in_event_makes_canCheckin_return_false(self):
        manager = ICheckinManager(self.checked_out)
        self.assertFalse(manager.canCheckin)

    def test_veto_message_is_available_on_manager(self):
        manager = ICheckinManager(self.checked_out)
        manager.canCheckin
        self.assertEqual('provoked veto', manager.last_validation_error)

    def test_checkin_with_veto_should_raise(self):
        self.assertEqual(1, len(self.workingcopy))
        lsc = zeit.cms.content.interfaces.ISemanticChange(
            self.repository['testcontent'])
        changed = lsc.last_semantic_change

        manager = ICheckinManager(self.checked_out)
        self.assertRaisesRegexp(
            CheckinCheckoutError, '.*provoked veto.*', manager.checkin)

        self.assertEqual(1, len(self.workingcopy))

        lsc = zeit.cms.content.interfaces.ISemanticChange(
            self.repository['testcontent'])
        self.assertEqual(changed, lsc.last_semantic_change)

    def test_event_is_not_sent_for_temporary_workingcopy(self):
        # thus, no validation is performed during publishing, for example
        # XXX this needs to be conceptualized more clearly, see #12701

        # undo setUp, since it doesn't apply for this test
        manager = ICheckinManager(self.checked_out)
        manager.delete()

        manager = ICheckoutManager(self.repository['testcontent'])
        checked_out = manager.checkout(temporary=True)
        manager = ICheckinManager(checked_out)
        self.assertTrue(manager.canCheckin)

class SemanticChangeTest(zeit.cms.testing.ZeitCmsTestCase):

    def setUp(self):
        super(SemanticChangeTest, self).setUp()
        self.content = self.repository['testcontent']
        self.sc = zeit.cms.content.interfaces.ISemanticChange(self.content)

    def test_content_has_no_semantic_change_by_default(self):
        self.assertIsNone(self.sc.last_semantic_change)

    def test_checkin_with_semantic_change_sets_lsc_date(self):
        with zeit.cms.checkout.helper.checked_out(
                self.content, semantic_change=True):
            pass
        self.assertIsInstance(self.sc.last_semantic_change, datetime.datetime)

    def test_checkin_without_semantic_change_does_not_change_lsc_date(self):
        old = self.sc.last_semantic_change
        with zeit.cms.checkout.helper.checked_out(
                self.content, semantic_change=False):
            pass
        self.assertEqual(old, self.sc.last_semantic_change)

    def test_checkin_without_explicit_sc_uses_sc_flag_on_content_object(self):
        with zeit.cms.checkout.helper.checked_out(
                self.content, semantic_change=None) as co:
            sc = zeit.cms.content.interfaces.ISemanticChange(co)
            sc.has_semantic_change = True
        self.assertIsInstance(self.sc.last_semantic_change, datetime.datetime)

class DeleteWorkingCopy(zeit.cms.testing.ZeitCmsTestCase):

    def test_new_content_is_deleted_in_repo_when_wc_is_deleted(self):
        content = self.repository['testcontent']
        co_manager = zeit.cms.checkout.interfaces.ICheckoutManager(content)
        co = co_manager.checkout()
        zeit.cms.repository.interfaces.IAutomaticallyRenameable(
            co).renameable = True
        ci_manager = zeit.cms.checkout.interfaces.ICheckinManager(co)
        ci_manager.delete()
        with self.assertRaises(TypeError):
            zeit.cms.interfaces.ICMSContent('http://xml.zeit.de/testcontent')

    def test_checked_out_content_is_left_in_repo_when_wc_is_deleted(self):
        content = self.repository['testcontent']
        co_manager = zeit.cms.checkout.interfaces.ICheckoutManager(content)
        co = co_manager.checkout()
        zeit.cms.repository.interfaces.IAutomaticallyRenameable(
            co).renameable = False
        ci_manager = zeit.cms.checkout.interfaces.ICheckinManager(co)
        ci_manager.delete()
        with self.assertNothingRaised():
            zeit.cms.interfaces.ICMSContent('http://xml.zeit.de/testcontent')


text:
external help file: AutomatedLabWorker-help.xml
Module Name: AutomatedLabWorker
online version: https://automatedlab.org/en/latest/AutomatedLabWorker/en-us/Start-LWVMWareVM
schema: 2.0.0
---

# Start-LWVMWareVM

## SYNOPSIS
Start a VMWare VM

## SYNTAX

```
Start-LWVMWareVM [-ComputerName] <String[]> [[-DelayBetweenComputers] <Int32>] [<CommonParameters>]
```

## DESCRIPTION
Start a VMWare VM

## EXAMPLES

### Example 1
```powershell
PS C:\> Start-LWVMWareVM Host1,Host2
```

Start Host1 and Host2 in parallel

## PARAMETERS

### -ComputerName
The hosts to start

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -DelayBetweenComputers
The delay in minutes between each start

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### System.Object
## NOTES

## RELATED LINKS


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record id="hr.employee_niv" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Designer, UI Expert</field>
        </record>

        <record id="hr.employee_fp" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Lean Management Expert</field>
        </record>

        <record id="hr.employee_qdp" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Designer, UI Expert</field>
        </record>

        <record id="hr.employee_fpi" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Customer Service Oriented</field>
        </record>

        <record id="hr.employee_al" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Like Coding</field>
        </record>

        <record id="hr.employee_jgo" model="hr.employee">
            <field name="website_published" eval="True"/>
            <field name="public_info">Driven by Customer Satisfaction</field>
        </record>

    </data>
</openerp>


text:
package sorting;

import java.util.ArrayList;

import graphics.ArrayCanvas;
import graphics.PaintableArray;
import utils.CanvasUtils;
import utils.Constants;

public class RadixSort
    {
        public static void sort(ArrayCanvas ac)
            {
                radixSort(ac);
            }

        /**
        	 * Finds the largest element, and calls counting sort for all the places up until that so that the array becomes properly sorted
        	 */
        public static void radixSort(ArrayCanvas ac)
            {
                ArrayList<Integer> list = ac.getArray().list;
                int maxDecimalPlaces = (maxVal(list) + "").length();
                for (int i = 1; i <= maxDecimalPlaces; i++) {
                    auxSort(ac, i);
                }
                Sorter.isSorted(ac.getArray(), true);
            }

        /**
         * Sorts an array so that all elements are in accending order according to the value of that decimal place, 1 being the 1's place, etc.
         */
        private static void auxSort(ArrayCanvas ac, int place)
            {
                PaintableArray pa = ac.getArray();
                ArrayList<Integer> list = pa.list;
                int[] counts = new int[10];
                for (int val : list) {
                    counts[getPlace(val, place)]++;
                }
                for (int i = 1; i < counts.length; i++) {
                    counts[i] += counts[i - 1];
                }
                PaintableArray ret = pa.subArray(0, pa.list.size());
                for (int i = 0; i < pa.list.size(); i++) {
                    ret.list.set(i, 0);
                }
                for (int i = list.size() - 1; i >= 0; i--) {
                    int j = list.get(i);
                    int k = counts[getPlace(j, place)];
                    ret.addHighlight(k - 1, Constants.COLOR_POINTER1);
                    ret.list.set(k - 1, list.get(i));
                    counts[getPlace(j, place)]--;
                    ret.removeHighlights(k - 1);
                }
                for (int i = 0; i < list.size(); i++) {
                    CanvasUtils.sleep(1);
                    list.set(i, ret.list.get(i));
                }
                ret.remove(ac.getGraphicsContext2D());
            }

        /**
         * Returns the number at the given place in a value. ex getPlace(345,1) would return 5
         */
        public static int getPlace(int a, int place)
            {
                for (int i = 0; i < place - 1; i++) {
                    a /= 10;
                }
                return a % 10;
            }

        /**
         * Returns the maximum value in an array, used to get the number of times that radix sort should run counting sort
         */
        public static int maxVal(ArrayList<Integer> a)
            {
                int max = Integer.MIN_VALUE;
                for (int val : a) {
                    if (val > max) {
                        max = val;
                    }
                }
                return max;
            }
    }


text:
  <video #test class="player" autoplay></video>

		<video #remote *ngIf="stream" class="player" [srcObject]="stream" autoplay></video>

		<video #local *ngIf="myStream" class="player" [srcObject]="myStream" autoplay muted></video>

    {{duration | amTimeElapsed}}

    {{duration | amTimeElapsed}}


text:
'use strict';

var ThaliMobile = require('thali/NextGeneration/thaliMobile');
if (global.NETWORK_TYPE === ThaliMobile.networkTypes.WIFI) {
  return;
}

var express = require('express');
var net = require('net');
var Promise = require('lie');
var testUtils = require('../lib/testUtils.js');

if (typeof Mobile === 'undefined') {
  return;
}

var platform = require('thali/NextGeneration/utils/platform');
var thaliMobileNativeWrapper =
  require('thali/NextGeneration/thaliMobileNativeWrapper');
var thaliMobileNativeTestUtils = require('../lib/thaliMobileNativeTestUtils');
var validations = require('thali/validations');
var tape = require('../lib/thaliTape');
var uuid = require('node-uuid');

var peerIdsToBeClosed = [];

var test = tape({
  setup: function (t) {
    t.end();
  },
  teardown: function (t) {
    thaliMobileNativeWrapper.stop()
      .then(function () {
        t.equals(thaliMobileNativeWrapper._isStarted(), false,
          'must be stopped');
        thaliMobileNativeTestUtils.stopListeningAndAdvertising()
          .then(function () {
            if (!platform.isAndroid) {
              return thaliMobileNativeTestUtils.killAllMultiConnectConnections(peerIdsToBeClosed);
            }
          })
          .catch(function (err) {
            t.fail(err);
          })
          .then(function () {
            peerIdsToBeClosed = [];
            thaliMobileNativeWrapper._registerToNative();
            t.end();
          });
      })
      .catch(function (err) {
        t.fail('teardown failed with ' + JSON.stringify(err));
        t.end();
      });
  }
});

var testIdempotentFunction = function (t, functionName) {
  thaliMobileNativeWrapper.start(express.Router())
  .then(function () {
    return thaliMobileNativeWrapper[functionName]();
  })
  .then(function (error) {
    t.notOk(error, 'no errors');
    return thaliMobileNativeWrapper[functionName]();
  })
  .then(function (error) {
    t.notOk(error, 'still no errors');
    t.end();
  })
  .catch(function (error) {
    t.fail('testIdempotentFunction failed with ' + JSON.stringify(error));
    t.end();
  });
};

var testFunctionBeforeStart = function (t, functionName) {
  thaliMobileNativeWrapper[functionName]()
  .then(function () {
    t.fail('call should not succeed');
    t.end();
  })
  .catch(function (error) {
    t.equal(error.message, 'Call Start!', 'specific error should be returned');
    t.end();
  });
};

test('#startListeningForAdvertisements should fail if start not called',
  function (t) {
    testFunctionBeforeStart(t, 'startListeningForAdvertisements');
  }
);

test('#startUpdateAdvertisingAndListening should fail if start not called',
  function (t) {
    testFunctionBeforeStart(t, 'startUpdateAdvertisingAndListening');
  }
);

test('should be able to call #stopListeningForAdvertisements many times',
  function (t) {
    testIdempotentFunction(t, 'stopListeningForAdvertisements');
  }
);

test('should be able to call #startListeningForAdvertisements many times',
  function (t) {
    testIdempotentFunction(t, 'startListeningForAdvertisements');
  }
);

test('should be able to call #startUpdateAdvertisingAndListening many times',
  function (t) {
    testIdempotentFunction(t, 'startUpdateAdvertisingAndListening');
  }
);

test('should be able to call #stopAdvertisingAndListening many times',
  function (t) {
    testIdempotentFunction(t, 'stopAdvertisingAndListening');
  }
);

test('can get the network status before starting', function (t) {
  thaliMobileNativeWrapper.getNonTCPNetworkStatus()
  .then(function (networkChangedValue) {
    t.doesNotThrow(function () {
      var requiredProperties = [
        'wifi',
        'bluetooth',
        'bluetoothLowEnergy',
        'cellular'
      ];
      requiredProperties.forEach(function (requiredProperty) {
        validations.ensureNonNullOrEmptyString(
          networkChangedValue[requiredProperty]
        );
      });
    }, 'network status should have certain non-empty properties');
    t.end();
  });
});

test('error returned with bad router', function (t) {
  thaliMobileNativeWrapper.start('bad router')
  .then(function () {
    t.fail('should not succeed');
    t.end();
  })
  .catch(function (error) {
    t.equals(error.message, 'Bad Router', 'specific error expected');
    t.end();
  });
});

var testPath = '/test';
function trivialEndToEndTestScaffold(t, pskIdtoSecret, pskIdentity, pskKey,
                                     testData, callback) {
  var router = express.Router();
  router.get(testPath, function (req, res) {
    res.send(testData);
  });

  var end = function (peerId, fail) {
    peerIdsToBeClosed.push(peerId);
    return callback ? callback(peerId, fail) : t.end();
  };

  thaliMobileNativeTestUtils.getSamePeerWithRetry(testPath, pskIdentity, pskKey)
    .then(function (response) {
      t.equal(response.httpResponseBody, testData,
        'response body should match testData');
      end(response.peerId);
    })
    .catch(function (error) {
      t.fail('fail in trivialEndtoEndTestScaffold - ' + error);
      end(null, error);
    });

  thaliMobileNativeWrapper.start(router, pskIdtoSecret)
    .then(function () {
      return thaliMobileNativeWrapper.startListeningForAdvertisements();
    })
    .then(function () {
      return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
    });
}

var pskIdentity = 'I am me!';
var pskKey = new Buffer('I am a reasonable long string');
var testData = 'foobar';
function trivialEndToEndTest(t, callback) {
  function pskIdToSecret(id) {
    // There is a race condition where we could still get an incoming
    // request even after we think we are done with the test. This will cause
    // us to do a test but it will be a test called after we called end and
    // thus causes an unexpected error. To prevent this race condition we will
    // pre-vet the result and only if it's wrong will we call t.fail. That
    // way any extraneous connections won't cause us to fail just because we
    // did a test after we had called end.
    if (id !== pskIdentity) {
      t.fail('Should only get expected id');
    }
    return id === pskIdentity ? pskKey : null;
  }

  trivialEndToEndTestScaffold(
    t, pskIdToSecret, pskIdentity, pskKey, testData, callback
  );
}

var connectionTester = function(port, reversed) {
  return new Promise(function(resolve, reject) {
    var connection = net.createConnection(port, function () {
      connection.destroy();
      if (reversed) {
        reject(new Error('Unexpectedly successful connection'));
      } else {
        resolve();
      }
    });
    connection.on('error', function (error) {
      connection.destroy();
      if (reversed) {
        resolve();
      } else {
        reject(error);
      }
    });
  });
};

test('all services are started when we call start', function (t) {
  var serversManagerLocalPort = 0;
  var routerServerPort = 0;
  var connections = [];
  thaliMobileNativeWrapper.start(express.Router())
  .then(function () {
    return thaliMobileNativeWrapper.startListeningForAdvertisements();
  })
  .then(function () {
    return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
  })
  .then(function () {
    routerServerPort = thaliMobileNativeWrapper._getRouterServerPort();

    connections.push(connectionTester(routerServerPort));

    if (platform.isAndroid) {
      serversManagerLocalPort =
        thaliMobileNativeWrapper._getServersManagerLocalPort();
      connections.push(connectionTester(serversManagerLocalPort));
    }

    return Promise.all(connections);
  })
  .then(function (connection) {
    t.pass('all connection succeed');
    t.end();
  })
  .catch(function (error) {
    t.fail(error);
    t.end();
  });
});

test('TCP Servers Manager should be null when we call start on iOS',
testUtils.skipOnAndroid,
function (t) {
  thaliMobileNativeWrapper.start(express.Router())
  .then(function () {
    return thaliMobileNativeWrapper.startListeningForAdvertisements();
  })
  .then(function () {
    return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
  })
  .then(function () {
    var serversManager = thaliMobileNativeWrapper._getServersManager();
    t.equals(serversManager, null, 'TCP Servers Manager doesn\'t exists');
    t.end();
  })
  .catch(function (error) {
    t.fail(error);
    t.end();
  });
});

test('all services are stopped when we call stop', function (t) {
  var stopped = false;
  var serversManagerLocalPort = 0;
  var routerServerPort = 0;
  var connections = [];
  thaliMobileNativeWrapper.start(express.Router())
  .then(function () {
    return thaliMobileNativeWrapper.startListeningForAdvertisements();
  })
  .then(function () {
    return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
  })
  .then(function() {
    var discoveryStopped = false;
    var advertisingStopped = false;
    var stateChangeHandler = function (state) {
      discoveryStopped = !state.discoveryActive;
      advertisingStopped = !state.advertisingActive;
      if (discoveryStopped && advertisingStopped) {
        thaliMobileNativeWrapper.emitter.removeListener(
          'discoveryAdvertisingStateUpdateNonTCP',
          stateChangeHandler
        );
        var doConnectTest = function () {
          // It is possible that the state changes
          // are emitted before the stop call has been
          // completed so don't proceed with the checks
          // until the stop has been done.
          if (stopped === false) {
            setImmediate(doConnectTest);
            return;
          }

          routerServerPort = thaliMobileNativeWrapper._getRouterServerPort();

          connections.push(connectionTester(routerServerPort, true));

          if (platform.isAndroid) {
            serversManagerLocalPort =
              thaliMobileNativeWrapper._getServersManagerLocalPort();
            connections.push(connectionTester(serversManagerLocalPort, true));
          }

          Promise.all(connections)
          .then(function (response) {
            t.pass('connection should fail after stopping');
            t.end();
          })
          .catch(function () {
            t.fail('connection should fail after stopping');
            t.end();
          });

        };
        doConnectTest();
      }
    };
    thaliMobileNativeWrapper.emitter.on(
      'discoveryAdvertisingStateUpdateNonTCP',
      stateChangeHandler
    );
    thaliMobileNativeWrapper.stop()
    .then(function () {
      t.equals(thaliMobileNativeWrapper._isStarted(), false,
        'is stopped after calling stop');
      stopped = true;
      // stateChangeHandler above should get called
    });
  });
});

var verifyCallWithArguments = function (t, callName, parameters) {
  var mockServersManager = {};
  var spy = this.spy();
  var serversManagerEquivalentCallName = callName === '_terminateConnection' ?
    'terminateIncomingConnection' : 'terminateOutgoingConnection';
  mockServersManager[serversManagerEquivalentCallName] = function () {
    spy.apply(this, arguments);
    return Promise.resolve();
  };
  var oldServersManager = thaliMobileNativeWrapper._getServersManager();
  thaliMobileNativeWrapper._setServersManager(mockServersManager);
  thaliMobileNativeWrapper[callName].apply(this, parameters)
  .then(function () {
    t.equals(
      JSON.stringify(parameters),
      JSON.stringify(spy.args[0]),
      'called with right arguments'
    );
    thaliMobileNativeWrapper._setServersManager(oldServersManager);
    t.end();
  });
};

test('make sure terminateConnection is properly hooked up',
  testUtils.skipOnIOS,
  tape.sinonTest(function (t) {
    verifyCallWithArguments.call(this, t, '_terminateConnection', ['connection-id']);
  })
);

test('make sure terminateConnection is return error if we get called on iOS',
  testUtils.skipOnAndroid,
  function (t) {
    var error = 'Not connect platform';

    thaliMobileNativeWrapper._terminateConnection()
    .then(function() {
      t.fail('should not succeed on iOS');
      t.end();
    })
    .catch(function(err) {
      t.equal(err.message, error, 'error description matches');
      t.end();
    });
  }
);

test('make sure terminateListener is properly hooked up',
  testUtils.skipOnIOS,
  tape.sinonTest(function (t) {
    verifyCallWithArguments.call(this, t, '_terminateListener', ['peer-id', 8080]);
  })
);

test('make sure terminateListener is return error if we get called on iOS',
  testUtils.skipOnAndroid,
  function (t) {
    var error = 'Not connect platform';

    thaliMobileNativeWrapper._terminateListener()
    .then(function() {
      t.fail('should not succeed on iOS');
      t.end();
    })
    .catch(function(err) {
      t.equal(err.message, error, 'error description matches');
      t.end();
    });
  }
);

test('make sure we actually call kill connections properly', function (t) {
  thaliMobileNativeWrapper.killConnections()
  .then(function () {
    if (platform.isAndroid) {
      t.fail('should not succeed on Android');
      t.end();
    } else {
      // TODO: Do right checks on iOS.
      // Also implement the right behavior in the Wifi-based mock.
      t.ok(true, 'IMPLEMENT ME!!!!!!');
      t.end();
    }
  })
  .catch(function (error) {
    if (platform._isRealIOS) {
      t.fail('should not fail on iOS');
      t.end();
    } else {
      t.equals(error.message, 'Not Supported', 'specific error expected');
      t.end();
    }
  });
});

test('thaliMobileNativeWrapper is stopped when routerPortConnectionFailed ' +
  'is received',
  testUtils.skipOnIOS,
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      var routerServerPort = thaliMobileNativeWrapper._getRouterServerPort();
      var errorDescription = 'Dummy Error';
      thaliMobileNativeWrapper.emitter.once(
        'incomingConnectionToPortNumberFailed',
        function (routerFailureReason) {
          t.equals(
            routerFailureReason.reason,
            thaliMobileNativeWrapper.routerFailureReason.APP_LISTENER,
            'failure reason is as expected'
          );
          t.equals(
            routerFailureReason.errors[0].message,
            errorDescription,
            'error description is as expected'
          );
          t.equals(thaliMobileNativeWrapper._isStarted(), false,
            'must be stopped');
          t.end();
        }
      );
      thaliMobileNativeWrapper._getServersManager().emit(
        'routerPortConnectionFailed',
        {
          routerPort: routerServerPort,
          error: new Error(errorDescription)
        }
      );
    });
  }
);

test('We fire failedNativeConnection event when we get failedConnection from ' +
  'thaliTcpServersManager',
  testUtils.skipOnIOS,
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      var peerIdentifier = 'some-identifier';
      var errorDescription = 'Dummy Error';
      thaliMobileNativeWrapper.emitter.once(
        'failedNativeConnection',
        function (failedConnection) {
          t.equals(failedConnection.peerIdentifier, peerIdentifier,
            'peerIdentifier matches');
          t.equals(failedConnection.error.message, errorDescription,
            'error description matches');
          t.equals(
            failedConnection.connectionType,
            thaliMobileNativeWrapper.connectionTypes.BLUETOOTH,
            'connection type is tcp');
          t.end();
        }
      );
      thaliMobileNativeWrapper._getServersManager().emit(
        'failedConnection',
        {
          peerIdentifier: peerIdentifier,
          error: new Error(errorDescription)
        }
      );
    });
  }
);

test('We fire failedNativeConnection event when we get failedConnection from ' +
  'multiConnectConnection',
  function() {
    // this test uses mock ability to fire events from native layer and it cant
    // work on real devices
    return platform._isRealMobile;
  },
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      var peerIdentifier = 'some-identifier';
      var errorDescription = 'Dummy Error';
      thaliMobileNativeWrapper.emitter.once(
        'failedNativeConnection',
        function (failedConnection) {
          t.equals(failedConnection.peerIdentifier, peerIdentifier,
            'peerIdentifier matches');
          t.equals(failedConnection.error, errorDescription,
            'error description matches');
          t.equals(
            failedConnection.connectionType,
            thaliMobileNativeWrapper.connectionTypes.
              MULTI_PEER_CONNECTIVITY_FRAMEWORK,
            'connection type is MPCF');
          t.end();
        }
      );
      Mobile.fireMultiConnectConnectionFailure({
        peerIdentifier: peerIdentifier,
        error: errorDescription
      });
    });
  }
);

test('We fire nonTCPPeerAvailabilityChangedEvent event when we get ' +
  'failedConnection from multiConnectConnection',
  function() {
    // We no longer do it, see discussion in #1924
    return true;
  },
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      var peerIdentifier = 'some-identifier';
      var callCounter = 0;
      var errorMessage = 'Connection could not be established';
      var peer = {
        peerIdentifier: peerIdentifier,
        peerAvailable: true,
        generation: 5,
        portNumber: null
      };

      var peerAvailabilityHandler = function (peer) {
        ++callCounter;

        switch (callCounter) {
          case 1: {
            t.equal(peer.peerIdentifier, peerIdentifier, 'peerIds match');
            Mobile.fireMultiConnectConnectionFailure({
              peerIdentifier: peerIdentifier,
              error: errorMessage
            });
            return;
          }
          case 2: {
            t.equal(peer.peerIdentifier, peerIdentifier, 'peerIds match');
            t.equal(peer.peerAvailable, false, 'peer is unavailable');
            return;
          }
          case 3: {
            t.equal(peer.peerIdentifier, peerIdentifier, 'peerIds match');
            t.equal(peer.peerAvailable, true, 'peer should be available');
            t.equal(peer.recreated, true, 'peer is recreated');
            return cleanUp();
          }
        }
      };

      var cleanUpCalled = false;

      function cleanUp() {
        if (cleanUpCalled) {
          return;
        }
        cleanUpCalled = true;
        thaliMobileNativeWrapper.emitter.removeListener(
          'nonTCPPeerAvailabilityChangedEvent', peerAvailabilityHandler);
        t.end();
      }

      thaliMobileNativeWrapper.emitter.on('nonTCPPeerAvailabilityChangedEvent',
        peerAvailabilityHandler);

      thaliMobileNativeWrapper._handlePeerAvailabilityChanged(peer);
    });
  }
);

test('We fire nonTCPPeerAvailabilityChangedEvent event when we get ' +
  'fail from _multiConnectResolved',
  function (t) {
    t.skip('NOT IMPLEMENTED');
    t.end();
  }
);

test('make sure bad PSK connections fail',
function () {
  // #1587
  // return platform._isRealMobile;
  return true;
},
function (t) {
  // trivialBadEndtoEndTest(t, true);
  // TODO: Re-enable and fix
  t.ok(true, 'FIX ME, PLEASE!!!');
  t.end();
});

test('peer changes handled from a queue',
  function () {
    return platform.isMobile;
  },
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      var peerAvailabilityHandler;
      var peerCount = 10;
      var getDummyPeers = function (peerAvailable) {
        var dummyPeers = [];
        for (var i = 1; i <= peerCount; i++) {
          dummyPeers.push({
            peerIdentifier: i + '',
            peerAvailable: peerAvailable,
            generation: 0
          });
        }
        return dummyPeers;
      };
      var endTest = function () {
        thaliMobileNativeWrapper.emitter.removeListener(
          'nonTCPPeerAvailabilityChangedEvent',
          peerAvailabilityHandler);
        Mobile.firePeerAvailabilityChanged(getDummyPeers(false));
        t.end();
      };
      var previousPeerNumber = 0;
      peerAvailabilityHandler = function (peer) {
        var peerNumber = parseInt(peer.peerIdentifier);
        if (peerNumber - 1 !== previousPeerNumber) {
          t.fail('peers should be handled in order');
          endTest();
        }
        previousPeerNumber = peerNumber;
        if (peerNumber === peerCount) {
          t.ok(true, 'peers were handled in the right order');
          endTest();
        }
      };
      thaliMobileNativeWrapper.emitter.on('nonTCPPeerAvailabilityChangedEvent',
        peerAvailabilityHandler);
      Mobile.firePeerAvailabilityChanged(getDummyPeers(true));
    });
  });

test('relaying discoveryAdvertisingStateUpdateNonTCP',
  function() {
    return platform._isRealMobile;
  },
  function (t) {
    thaliMobileNativeWrapper.start(express.Router())
      .then(function () {
        thaliMobileNativeWrapper.emitter.once(
          'discoveryAdvertisingStateUpdateNonTCP',
          function (discoveryAdvertisingStateUpdateValue) {
            t.ok(discoveryAdvertisingStateUpdateValue.discoveryActive,
              'discovery is active');
            t.ok(discoveryAdvertisingStateUpdateValue.advertisingActive,
              'advertising is active');
            t.end();
          }
        );
        Mobile.fireDiscoveryAdvertisingStateUpdateNonTCP({
          discoveryActive: true,
          advertisingActive: true
        });
      });
  });

test('thaliMobileNativeWrapper is stopped when ' +
  'incomingConnectionToPortNumberFailed is received',
  function () {
    return platform._isRealMobile;
  },
  function (t) {
    var routerPort = 0;
    thaliMobileNativeWrapper.emitter
      .once('incomingConnectionToPortNumberFailed', function (err) {
        t.equal(err.reason,
          thaliMobileNativeWrapper.routerFailureReason.NATIVE_LISTENER,
          'right error reason');
        t.ok(err.errors.length === 0, 'Stop should be fine');
        t.equal(err.routerPort, routerPort, 'same port');
        t.notOk(thaliMobileNativeWrapper._isStarted(), 'we should be off');
        t.end();
      });
    thaliMobileNativeWrapper.start(express.Router())
      .then(function () {
        routerPort = platform.isAndroid ?
                      thaliMobileNativeWrapper._getServersManagerLocalPort() :
                      thaliMobileNativeWrapper._getRouterServerPort();

        return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
      })
      .then(function () {
        Mobile.fireIncomingConnectionToPortNumberFailed(routerPort);
      });
  });

test('we successfully receive and replay discoveryAdvertisingStateUpdate',
  function (t) {
    var doEqualsChecks = function (value, discoveryActive, advertisingActive) {
      t.equals(
        value.discoveryActive,
        discoveryActive,
        'discoveryActive matches'
      );
      t.equals(
        value.advertisingActive,
        advertisingActive,
        'advertisingActive matches'
      );
    };
    var doChecks = function (discoveryActive, advertisingActive, callback) {
      var previousStateUpdateValue = {};
      var checkingStopping = false;
      var stateUpdateHandler = function (stateUpdateValue) {
        // Ignore duplicates
        if (stateUpdateValue.advertisingActive ===
            previousStateUpdateValue.advertisingActive &&
            stateUpdateValue.discoveryActive ===
            previousStateUpdateValue.discoveryActive) {
          return;
        }
        previousStateUpdateValue = stateUpdateValue;
        if (!checkingStopping) {
          doEqualsChecks(
            stateUpdateValue,
            discoveryActive,
            advertisingActive
          );
          checkingStopping = true;
          thaliMobileNativeWrapper.stop();
        } else {
          doEqualsChecks(
            stateUpdateValue,
            false,
            false
          );
          thaliMobileNativeWrapper.start(express.Router())
          .then(function () {
            thaliMobileNativeWrapper.emitter.removeListener(
              'discoveryAdvertisingStateUpdateNonTCP',
              stateUpdateHandler
            );
            callback();
          });
        }
      };
      thaliMobileNativeWrapper.emitter.on(
        'discoveryAdvertisingStateUpdateNonTCP',
        stateUpdateHandler
      );
    };
    var checkDiscovery = function (callback) {
      doChecks(true, false, callback);
      thaliMobileNativeWrapper.startListeningForAdvertisements();
    };
    var checkAdvertising = function (callback) {
      doChecks(false, true, callback);
      thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
    };
    thaliMobileNativeWrapper.start(express.Router())
    .then(function () {
      checkDiscovery(function () {
        checkAdvertising(function () {
          t.end();
        });
      });
    });
  }
);

if (!tape.coordinated) {
  return;
}

var endToEndWithStateCheck = function (t) {
  trivialEndToEndTest(t, function () {
    t.equals(thaliMobileNativeWrapper._isStarted(), true, 'must be started');
    t.end();
  });
};

test('nonTCPPeerAvailabilityChangedEvent should return null' +
'for a portNumber on iOS',
testUtils.skipOnAndroid,
function (t) {
  thaliMobileNativeWrapper.start(express.Router())
  .then(function () {
    return thaliMobileNativeWrapper.startListeningForAdvertisements();
  })
  .then(function () {
    return thaliMobileNativeWrapper.startUpdateAdvertisingAndListening();
  })
  .then(function () {
    thaliMobileNativeWrapper.emitter.once('nonTCPPeerAvailabilityChangedEvent',
    function(res) {
      t.equals(res.portNumber, null, 'portNumber equal null');
      t.end();
    });
  })
  .catch(function (error) {
    t.fail(error);
    t.end();
  });
});

test('can do HTTP requests between peers', function (t) {
  endToEndWithStateCheck(t);
});

test('can still do HTTP requests between peers with coordinator', function (t) {
  endToEndWithStateCheck(t);
});

test('calls correct starts when network changes',
  testUtils.skipOnIOS, // uses toggleBluetooth
  tape.sinonTest(function (t) {
    var listeningSpy =
      this.spy(thaliMobileNativeWrapper, 'startListeningForAdvertisements');
    var advertisingSpy =
      this.spy(thaliMobileNativeWrapper, 'startUpdateAdvertisingAndListening');

    return thaliMobileNativeWrapper.start(express.Router())
      .then(function () {
        return testUtils.ensureBluetooth(false);
      })
      .then(function () {
        var validateStartResult = function (promise) {
          return promise
            .then(function () {
              t.fail('Should fail');
            })
            .catch(function (error) { // eslint-disable-line
              t.equals(error.message, 'Radio Turned Off',
                'specific error expected');
            });
        };
        var listen = validateStartResult(
          thaliMobileNativeWrapper.startListeningForAdvertisements()
        );
        var advertise = validateStartResult(
          thaliMobileNativeWrapper.startUpdateAdvertisingAndListening()
        );
        return Promise.all([ listen, advertise ]);
      })
      .then(function () {
        listeningSpy.reset();
        advertisingSpy.reset();
        return testUtils.ensureBluetooth(true);
      })
      .then(function () {
        return thaliMobileNativeWrapper._getPromiseQueue().enqueue(
          function (resolve) {
            t.ok(
              listeningSpy.calledOnce,
              'startListeningForAdvertisements should have been called once'
            );
            t.ok(
              advertisingSpy.calledOnce,
              'startUpdateAdvertisingAndListening should have been called once'
            );
            resolve();
          }
        );
      })
      .catch(function (err) {
        t.fail(err.message + '. ' + err.stack);
      })
      .then(function () {
        return thaliMobileNativeWrapper.stop();
      })
      .then(function () {
        t.end();
      });
  })
);

// The connection cut is implemented as a separate test instead
// of doing it in the middle of the actual test so that the
// step gets coordinated between peers.
test('test to coordinate connection cut', function (t) {
    // This cuts connections on Android or iOS
    var result = platform.isAndroid ?
      testUtils.toggleBluetooth(false):
      thaliMobileNativeWrapper.killConnections();

    result.then(function () {
      t.end();
    })
    .catch(function () {
      t.end();
    });
  });

test('can do HTTP requests after connections are cut', function (t) {
  // Turn Bluetooth back on so that Android can operate
  // (iOS does not require separate call to operate since
  // killConnections is more like a single-shot thing).

    if (platform.isAndroid) {
      var networkChangeHandler = function(networkChangedValue) {
        if (networkChangedValue.bluetoothLowEnergy &&
          networkChangedValue.bluetooth) {
          thaliMobileNativeWrapper.emitter.removeListener('networkChangedNonTCP',
         networkChangeHandler);
          endToEndWithStateCheck(t);
        }
      };
      thaliMobileNativeWrapper.emitter.on('networkChangedNonTCP',
      networkChangeHandler);

      t.pass('Turning bluetooth on');
      testUtils.toggleBluetooth(true);
    } else {
      endToEndWithStateCheck(t);
    }
  });

test('will fail bad PSK connection between peers', function (t) {
  // #1587
  // trivialBadEndtoEndTest(t, true);
  // TODO: Re-enable and fix
  t.ok(true, 'FIX ME, PLEASE!!!');
  t.end();
});

test('We provide notification when a listener dies and we recreate it',
  testUtils.skipOnIOS,
  function (t) {
    var recreatedPort = null;
    trivialEndToEndTest(t, function (peerId) {
      function recreatedHandler(record) {
        t.equal(record.peerIdentifier, peerId, 'same ids');
        recreatedPort = record.portNumber;
      }

      thaliMobileNativeWrapper._getServersManager()
        .on('listenerRecreatedAfterFailure', recreatedHandler);

      function exit() {
        thaliMobileNativeWrapper._getServersManager()
          .removeListener('listenerRecreatedAfterFailure', recreatedHandler);
        thaliMobileNativeWrapper.emitter
          .removeListener('nonTCPPeerAvailabilityChangedEvent',
            nonTCPAvailableHandler);
        t.end();
      }

      function nonTCPAvailableHandler(record) {
        // TODO:
        // There is a race condition when this test is ran on Android:
        // This function is called just before recreatedHandler leading
        // to recreatedPort being null.
        // Re-enable the check below once #719 is fixed.
        // Note that due to other changes we also need to add in a test to
        // make sure we are looking at an event for the right peerID
        /* if (!recreatedPort ||
          recreatedPort && record.portNumber !== recreatedPort) {
          logger.debug('No recreated port or port numbers do not match: '
            + record.portNumber + ' !== ' + recreatedPort);
          return;
        }*/
      }

      thaliMobileNativeTestUtils.getSamePeerWithRetry(testPath, pskIdentity, pskKey, peerId)
        .then(function (response) {
          t.equal(response.httpResponseBody, testData,
            'recreate - response body should match testData');
          exit();
        })
        .catch(function (error) {
          t.fail('fail in recreate test - ' + error);
          exit();
        });

      thaliMobileNativeWrapper.emitter.on('nonTCPPeerAvailabilityChangedEvent',
        nonTCPAvailableHandler);

      t.pass('About to destroy connection to peer');

      try {
        thaliMobileNativeWrapper._getServersManager().
          _peerServers[peerId].server._mux.destroy();
      } catch (err) {
        t.fail('destroy failed with - ' + err);
        exit();
      }
    });
  });

test('We fire nonTCPPeerAvailabilityChangedEvent with the same generation ' +
  'and different port when listener is recreated',
  function () {
    // #1597
    // FIXME: it looks like this test expects native layer to repeat
    // peerAvailabilityChanged events but it doesn't work this way anymore
    return true;
    // return platform.isIOS
  },
  tape.sinonTest(function (t) {
    trivialEndToEndTest(t, function (peerId) {
      var beforeRecreatePeer = null;
      var afterRecreatePeer = null;
      var isKilled = false;
      var serversManager = thaliMobileNativeWrapper._getServersManager();
      var smEmitSpy = this.spy(serversManager, 'emit');

      function finishTest() {
        t.ok(isKilled, 'mux must be destroyed');
        t.ok(beforeRecreatePeer, 'peer tracked before recreating');
        t.ok(afterRecreatePeer, 'peer tracked after recreating');
        t.equal(typeof beforeRecreatePeer.generation, 'number');
        t.equal(typeof afterRecreatePeer.generation, 'number');
        t.equal(
          beforeRecreatePeer.generation,
          afterRecreatePeer.generation,
          'the same generation before and after listener recreating'
        );

        var emittedRecreateEventForCurrentPeer =
          smEmitSpy.args.some(function (callArgs) {
            var eventName = callArgs[0];
            var announcement = callArgs[1];
            return (
              eventName === 'listenerRecreatedAfterFailure' &&
              announcement.peerIdentifier === peerId
            );
          });

        t.ok(smEmitSpy.callCount, 'servers manager emitted at least one event');
        t.ok(
          emittedRecreateEventForCurrentPeer,
          'servers manager emitted recreate event for our peer'
        );

        thaliMobileNativeWrapper.emitter.removeListener(
          'nonTCPPeerAvailabilityChangedEvent',
          nonTCPAvailableHandler
        );
        t.end();
      }

      function killMux() {
        if (isKilled) {
          return;
        }
        isKilled = true;
        try {
          serversManager._peerServers[peerId].server._mux.destroy();
        } catch (err) {
          t.fail('destroy failed with - ' + err);
          finishTest();
        }
      }

      function nonTCPAvailableHandler(peer) {
        if (peer.peerIdentifier !== peerId || peer.portNumber === null) {
          return;
        }
        if (!isKilled) {
          beforeRecreatePeer = peer;
          killMux();
        } else {
          afterRecreatePeer = peer;
          finishTest();
        }
      }

      thaliMobileNativeWrapper.emitter
        .on('nonTCPPeerAvailabilityChangedEvent', nonTCPAvailableHandler);
    });
  })
);


text:
import pytest

from xbox.utils import DotNotationDict

def test_dot_notation_dict_raises_attribute_error():
    d = DotNotationDict()
    with pytest.raises(AttributeError):
        d.error


text:
require 'ecloud/spec_helper'

if Fog.mocking?
  describe "Fog::Ecloud::Compute::Network", :type => :mock_tmrk_ecloud_model do
    subject { @vcloud }

    describe :class do
      subject { Fog::Ecloud::Compute::Network }

      it { should have_identity(:href) }
      it { should have_only_these_attributes([:href, :name, :features, :links, :type, :gateway, :broadcast, :address, :rnat, :extension_href, :network_type, :vlan, :friendly_name]) }
    end

    context "with no uri" do

      subject { Fog::Ecloud::Compute::Network.new() }

      it { should have_all_attributes_be_nil }
    end

    context "as a collection member" do
      subject { @vcloud.vdcs[0].networks[0].reload }

      it { should be_an_instance_of(Fog::Ecloud::Compute::Network) }

      its(:href)                  { should == @mock_network.href }
      its(:identity)              { should == @mock_network.href }
      its(:name)                  { should == @mock_network.name }
      its(:type)                  { should == "application/vnd.vmware.vcloud.network+xml" }
      its(:gateway)               { should == @mock_network.gateway }
      its(:broadcast)             { should == @mock_network.broadcast }
      its(:address)               { should == @mock_network.address }
      its(:rnat)                  { should == @mock_network.rnat }
      its(:extension_href)        { should == @mock_network.extensions.href }
      its(:network_type)          { should == @mock_network.extensions.type }
      its(:vlan)                  { should == @mock_network.extensions.vlan }
      its(:friendly_name)         { should == @mock_network.extensions.friendly_name }

      it { should have(1).features }

      describe :features do
        let(:feature) { subject.features.first }
        specify { feature.should be_an_instance_of(Array) }
        specify { feature.last.should == @mock_network.features[0][:value] }
      end

      it { should have(2).links }

      describe :links do
        context "[0]" do
          let(:link) { subject.links[0] }
          specify { link[:rel].should == "down" }
          specify { link[:href].should == @mock_network_ip_collection.href }
          specify { link[:type].should == "application/xml" }
          specify { link[:name].should == @mock_network_ip_collection.name }
        end

        context "[1]" do
          let(:link) { subject.links[1] }
          specify { link[:rel].should == "down" }
          specify { link[:href].should == @mock_network.extensions.href }
          specify { link[:type].should == "application/xml" }
          specify { link[:name].should == @mock_network.name }
        end
      end

    end
  end
else
end