text:
<?php //-->

namespace Eden\Twitter;

/**
 * Twitter list
 *
 * @vendor Eden
 * @package Twitter
 * @author Federico A. Maglayon rmaglayon@gmail.com
 */
class Lists extends Base
{
    const URL_ALL_LIST = 'https://api.twitter.com/1.1/lists/list.json';
    const URL_GET_STATUS = 'https://api.twitter.com/1.1/lists/statuses.json';
    const URL_REMOVE_MEMBER = 'https://api.twitter.com/1.1/lists/members/destroy.json';
    const URL_MEMBERSHIP = 'https://api.twitter.com/1.1/lists/memberships.json';
    const URL_SUBSCRIBER = 'https://api.twitter.com/1.1/lists/subscribers.json';
    const URL_CREATE_SUBCRIBER = 'https://api.twitter.com/1.1/lists/subscribers/create.json';
    const URL_SHOW_SUBSCRIBER = 'https://api.twitter.com/1.1/lists/subscribers/show.json';
    const URL_REMOVE_SUBCRIBER = 'https://api.twitter.com/1.1/lists/subscribers/destroy.json';
    const URL_CREATE_ALL = 'https://api.twitter.com/1.1/lists/members/create_all.json';
    const URL_GET_MEMBER = 'https://api.twitter.com/1.1/lists/members/show.json';
    const URL_GET_DETAIL = 'https://api.twitter.com/1.1/lists/members.json';
    const URL_CREATE_MEMBER = 'https://api.twitter.com/1.1/lists/members/create.json';
    const URL_REMOVE = 'https://api.twitter.com/1.1/lists/destroy.json';
    const URL_UPDATE = 'https://api.twitter.com/1.1/lists/update.json';
    const URL_CREATE_USER = 'https://api.twitter.com/1.1/lists/create.json';
    const URL_SHOW = 'https://api.twitter.com/1.1/lists/show.json';
    const URL_GET_SUBSCRITION = 'https://api.twitter.com/1.1/lists/subscriptions.json';

    /**
     * Add a member to a list. The authenticated user
     * must own the list to be able to add members
     * to it. Note that lists can't have more than 500 members.
     *
     * @param int|string
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function addMember($userId, $listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer or string
            ->test(2, 'int', 'string')
            //Argument 3 must be an integer, null or string
            ->test(3, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        //if it is integer
        if(is_int($userId)) {
            //lets put it in our query
            $this->query['user_id'] = $userId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['screen_name'] = $userId;
        }

        return $this->post(self::URL_CREATE_MEMBER, $this->query);
    }

    /**
     * Adds multiple members to a list, by specifying a
     * comma-separated list of member ids or screen names.
     *
     * @param int|string list ID or slug
     * @param array list of user IDs
     * @param int|string ownder ID or screen name
     * @return array
     */
    public function addMembers($listId, $userIds, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an array
            ->test(2, 'array')
            //Argument 3 must be an integer or string
            ->test(3, 'int', 'string');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        //if it is integer
        if(is_int($ownerId)) {
            //lets put it in our query
            $this->query['owner_id'] = $ownerId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['owner_screen_name'] = $ownerId;
        }

        //if id is integer
        if(is_int($userIds[0])) {
            //lets put it in query
            $this->query['user_id'] = implode(',',$userIds);
        //if it is streing
        } else {
            //lets put it in query
            $this->query['screen_name'] = implode(',',$userIds);
        }

        return $this->post(self::URL_CREATE_ALL, $this->query);
    }

    /**
     * Creates a new list for the authenticated user.
     * Note that you can't create more than 20 lists per account.
     *
     * @param string
     * @return array
     */
    public function createList($name)
    {
        //argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['name'] = $name;

        return $this->post(self::URL_CREATE_USER, $this->query);
    }

    /**
     * Returns the members of the specified list.
     * Private list members will only be shown if
     * the authenticated user owns the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function getMembers($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->getResponse(self::URL_GET_DETAIL, $this->query);
    }

    /**
     * Returns all lists the authenticating or specified user
     * subscribes to, including their own.
     *
     * @param string|null
     * @return array
     */
    public function getAllLists($id = NULL)
    {
        //Argument 2 must be an integer, null or string
        Argument::i()->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($id)) {
            //lets put it in our query
            $this->query['user_id'] = $id;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['screen_name'] = $id;
        }

        return $this->getResponse(self::URL_ALL_LIST, $this->query);
    }

    /**
     * Returns the specified list. Private lists will only
     * be shown if the authenticated user owns the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function getList($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->getResponse(self::URL_SHOW, $this->query);
    }

    /**
     * Returns the lists the specified user has been
     * added to. If user_id or screen_name are not
     * provided the memberships for the authenticating
     * user are returned.
     *
     * @param int|string|null
     * @return array
     */
    public function getMemberships($id = NULL)
    {
        //Argument 1 must be an integer, null or string
        Argument::i()->test(1, 'int', 'string', 'null');

        if(!is_null($id)) {
            //if it is integer
            if(is_int($id)) {
                //lets put it in our query
                $this->query['user_id'] = $id;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['screen_name'] = $id;
            }
        }

        return $this->getResponse(self::URL_MEMBERSHIP, $this->query);
    }

    /**
     * Returns tweet timeline for members
     * of the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function getTweets($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->getResponse(self::URL_GET_STATUS, $this->query);
    }

    /**
     * Returns the subscribers of the specified list. Private list
     * subscribers will only be shown if the authenticated user owns
     * the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function getSubscribers($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->getResponse(self::URL_SUBSCRIBER, $this->query);
    }

    /**
     * Obtain a collection of the lists the specified user is subscribed to,
     * 20 lists per page by default. Does not include the user's own lists.
     *
     * @param int|string
     * @return array
     */
    public function getSubscriptions($id)
    {
        //Argument 1 must be an integer or string
        Argument::i()->test(1, 'int', 'string');

        //if it is integer
        if(is_int($id)) {
            //lets put it in our query
            $this->query['user_id'] = $id;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['screen_name'] = $id;
        }

        return $this->getResponse(self::URL_GET_SUBSCRITION, $this->query);
    }

    /**
     * Will return just lists the authenticating user owns, and the user
     * represented by user_id or screen_name is a member of.
     *
     * @return this
     */
    public function filterToOwn()
    {
        $this->query['filter_to_owned_lists'] = true;
        return $this;
    }

    /**
     * Each tweet will include a node called "entities". This node offers a variety
     * of metadata about the tweet in a discreet structure, including: user_mentions,
     * urls, and hashtags.
     *
     * @return this
     */
    public function includeEntities()
    {
        $this->query['include_entities'] = true;
        return $this;
    }

    /**
     * The list timeline will contain native retweets (if they exist) in addition to the
     * standard stream of tweets. The output format of retweeted tweets is identical to
     * the representation you see in home_timeline.
     *
     * @return this
     */
    public function includeRts()
    {
        $this->query['include_rts'] = true;
        return $this;
    }

    /**
     * Check if the specified user is a member of the specified list.
     *
     * @param int|string
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function isMember($userId, $listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer or string
            ->test(2, 'int', 'string')
            //Argument 3 must be an integer, null or string
            ->test(3, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else if(!is_int($listId)) {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        //if it is integer
        if(is_int($user_id)) {
            //lets put it in our query
            $this->query['user_id'] = $userId;
        //else it is string
        } else if(!is_int($user_id)) {
            //lets put it in our query
            $this->query['screen_name'] = $userId;
        }

        return $this->getResponse(self::URL_GET_MEMBER, $this->query);
    }

    /**
     * Check if the specified user is a subscriber of the specified list.
     * Returns the user if they are subscriber.
     *
     * @param int|string
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function isSubscriber($userId, $listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer or string
            ->test(2, 'int', 'string')
            //Argument 3 must be an integer, null or string
            ->test(3, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        //if it is integer
        if(is_int($userId)) {
            //lets put it in our query
            $query['user_id'] = $userId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['screen_name'] = $userId;
        }

        return $this->getResponse(self::URL_SHOW_SUBSCRIBER, $this->query);
    }

    /**
     * Deletes the specified list. The authenticated
     * user must own the list to be able to destroy it
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function remove($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $qthis->uery['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->post(self::URL_REMOVE, $this->query);
    }

    /**
     * Removes the specified member from the list.
     * The authenticated user must be the list's
     * owner to remove members from the list.
     *
     * @param int|string
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function removeMember($userId, $listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer or string
            ->test(2, 'int', 'string')
            //Argument 3 must be an integer, null or string
            ->test(3, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        //if it is integer
        if(is_int($userId)) {
            //lets put it in our query
            $this->query['user_id'] = $userId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['screen_name'] = $userId;
        }

        return $this->post(self::URL_REMOVE_MEMBER, $this->query);
    }

    /**
     * Sets count
     *
     * @param integer
     * @return this
     */
    public function setCount($count)
    {
        //Argument 1 must be an integer
        Argument::i()->test(1, 'int');
        $this->query['count'] = $count;

        return $this;
    }

    /**
     * Causes the list of connections to be broken into pages of no more than 5000
     * IDs at a time. The number of IDs returned is not guaranteed to be 5000 as
     * suspended users are filtered out after connections are queried.
     *
     * @param string
     * @return this
     */
    public function setCursor($cursor)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');
        $this->query['cursor'] = $cursor;

        return $this;
    }

    /**
     * Set max id
     *
     * @param integer
     * @return this
     */
    public function setMax($max)
    {
        //Argument 1 must be an integer
        Argument::i()->test(1, 'int');
        $this->query['max_id'] = $max;

        return $this;
    }

    /**
     * Sets page
     *
     * @param integer
     * @return this
     */
    public function setPage($perPage)
    {
        //Argument 1 must be an integer
        Argument::i()->test(1, 'int');
        $this->query['per_page'] = $perPage;

        return $this;
    }

    /**
     * Set since id
     *
     * @param integer the tweet ID
     * @return this
     */
    public function setSinceId($sinceId)
    {
        //Argument 1 must be an integer
        Argument::i()->test(1, 'int');
        $this->query['since_id'] = $sinceId;

        return $this;
    }

    /**
     * The description to give the list.
     *
     * @param string
     * @return this
     */
    public function setDescription($description)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');
        $this->query['description'] = $description;

        return $this;
    }

    /**
     * Whether your list is public or private. Values can be public
     * or private. If no mode is specified the list will be public.
     *
     * @return this
     */
    public function setModeToPrivate()
    {
        $this->query['mode'] = 'private';

        return $this;
    }
    /**
     * Statuses will not be included in the returned user objects.
     *
     * @return this
     */
    public function skipStatus()
    {
        $this->query['skip_status'] = true;
        return $this;
    }

    /**
     * Subscribes the authenticated
     * user to the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function subscribe($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->post(self::URL_CREATE_SUBCRIBER, $this->query);
    }

    /**
     * Unsubscribes the authenticated
     * user from the specified list.
     *
     * @param int|string
     * @param int|string|null
     * @return array
     */
    public function unsubscribe($listId, $ownerId = NULL)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an integer, null or string
            ->test(2, 'int', 'string', 'null');

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->post(self::URL_REMOVE_SUBCRIBER, $this->query);
    }

    /**
     * Updates the specified list. The authenticated user must own
     * the list to be able to update it.
     *
     * @param int|string
     * @param string
     * @param string
     * @param int|string|null
     * @param bool
     * @return array
     */
    public function update($listId, $name, $description, $ownerId = NULL, $public = true)
    {
        Argument::i()
            //Argument 1 must be an integer or string
            ->test(1, 'int', 'string')
            //Argument 2 must be an string
            ->test(2, 'string')
            //Argument 3 must be an string
            ->test(3, 'string')
            //Argument 4 must be an integer, string or null
            ->test(4, 'int', 'string', 'null')
            //Argument 3 must be an boolean
            ->test(5, 'bool');

        $this->query['name']            = $name;
        $this->query['description'] = $description;

        //if it is integer
        if(is_int($listId)) {
            //lets put it in our query
            $this->query['list_id'] = $listId;
        //else it is string
        } else {
            //lets put it in our query
            $this->query['slug'] = $listId;
        }

        if(!is_null($ownerId)) {
            //if it is integer
            if(is_int($ownerId)) {
                //lets put it in our query
                $this->query['owner_id'] = $ownerId;
            //else it is string
            } else {
                //lets put it in our query
                $this->query['owner_screen_name'] = $ownerId;
            }
        }

        return $this->post(self::URL_UPDATE, $this->query);
    }
}


text:
'use strict';

/******************************************************************************
 * Module dependencies.
 *****************************************************************************/

var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var bunyan = require('bunyan');
var morgan = require('morgan');

var config = require('./config');

// set up database for express session
var MongoStore = require('connect-mongo')(expressSession);
var mongoose = require('mongoose');

// Start QuickStart here

var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;

var log = bunyan.createLogger({
    name: 'Microsoft OIDC Example Web Application'
});

/******************************************************************************
 * Set up passport in the app
 ******************************************************************************/

//-----------------------------------------------------------------------------
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session.  Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
//-----------------------------------------------------------------------------
passport.serializeUser(function(user, done) {
  done(null, user.oid);
});

passport.deserializeUser(function(oid, done) {
  findByOid(oid, function (err, user) {
    done(err, user);
  });
});

// array to hold logged in users
var users = [];

var findByOid = function(oid, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
   log.info('we are using user: ', user);
    if (user.oid === oid) {
      return fn(null, user);
    }
  }
  return fn(null, null);
};

//-----------------------------------------------------------------------------
// Use the OIDCStrategy within Passport.
//
// Strategies in passport require a `verify` function, which accepts credentials
// (in this case, the `oid` claim in id_token), and invoke a callback to find
// the corresponding user object.
//
// The following are the accepted prototypes for the `verify` function
// (1) function(iss, sub, done)
// (2) function(iss, sub, profile, done)
// (3) function(iss, sub, profile, access_token, refresh_token, done)
// (4) function(iss, sub, profile, access_token, refresh_token, params, done)
// (5) function(iss, sub, profile, jwtClaims, access_token, refresh_token, params, done)
// (6) prototype (1)-(5) with an additional `req` parameter as the first parameter
//
// To do prototype (6), passReqToCallback must be set to true in the config.
//-----------------------------------------------------------------------------
passport.use(new OIDCStrategy({
    identityMetadata: config.creds.identityMetadata,
    clientID: config.creds.clientID,
    responseType: config.creds.responseType,
    responseMode: config.creds.responseMode,
    redirectUrl: config.creds.redirectUrl,
    allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl,
    clientSecret: config.creds.clientSecret,
    validateIssuer: config.creds.validateIssuer,
    isB2C: config.creds.isB2C,
    issuer: config.creds.issuer,
    passReqToCallback: config.creds.passReqToCallback,
    scope: config.creds.scope,
    loggingLevel: config.creds.loggingLevel,
    nonceLifetime: config.creds.nonceLifetime,
    nonceMaxAmount: config.creds.nonceMaxAmount,
    useCookieInsteadOfSession: config.creds.useCookieInsteadOfSession,
    cookieEncryptionKeys: config.creds.cookieEncryptionKeys,
    clockSkew: config.creds.clockSkew,
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    if (!profile.oid) {
      return done(new Error("No oid found"), null);
    }
    // asynchronous verification, for effect...
    process.nextTick(function () {
      findByOid(profile.oid, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          users.push(profile);
          return done(null, profile);
        }
        return done(null, user);
      });
    });
  }
));

//-----------------------------------------------------------------------------
// Config the app, include middlewares
//-----------------------------------------------------------------------------
var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser());

// set up session middleware
if (config.useMongoDBSessionStore) {
  mongoose.connect(config.databaseUri);
  app.use(expressSession({
    secret: 'secret',
    cookie: {maxAge: config.mongoDBSessionMaxAge * 1000},
    store: new MongoStore({
      mongooseConnection: mongoose.connection,
      clear_interval: config.mongoDBSessionMaxAge
    })
  }));
} else {
  app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
}

app.use(express.urlencoded({ extended : true }));

// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/../../public'));

//-----------------------------------------------------------------------------
// Set up the route controller
//
// 1. For 'login' route and 'returnURL' route, use `passport.authenticate`.
// This way the passport middleware can redirect the user to login page, receive
// id_token etc from returnURL.
//
// 2. For the routes you want to check if user is already logged in, use
// `ensureAuthenticated`. It checks if there is an user stored in session, if not
// it will call `passport.authenticate` to ask for user to log in.
//-----------------------------------------------------------------------------
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
};

app.get('/', function(req, res) {
  res.render('index', { user: req.user });
});

// '/account' is only available to logged in user
app.get('/account', ensureAuthenticated, function(req, res) {
  console.log(req.user);
  res.render('account', { user: req.user });
});

app.get('/login',
  function(req, res, next) {
    passport.authenticate('azuread-openidconnect',
      {
        response: res,                      // required
        resourceURL: config.resourceURL,    // optional. Provide a value if you want to specify the resource.
        customState: 'my_state',            // optional. Provide a value if you want to provide custom state value.
        failureRedirect: '/'
      }
    )(req, res, next);
  },
  function(req, res) {
    log.info('Login was called in the Sample');
    res.redirect('/');
});

// 'GET returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// query (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.get('/auth/openid/return',
  function(req, res, next) {
    passport.authenticate('azuread-openidconnect',
      {
        response: res,    // required
        failureRedirect: '/'
      }
    )(req, res, next);
  },
  function(req, res) {
    log.info('We received a return from AzureAD.');
    res.redirect('/');
  });

// 'POST returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// body (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.post('/auth/openid/return',
  function(req, res, next) {
    passport.authenticate('azuread-openidconnect',
      {
        response: res,    // required
        failureRedirect: '/'
      }
    )(req, res, next);
  },
  function(req, res) {
    log.info('We received a return from AzureAD.');
    res.redirect('/');
  });

// 'logout' route, logout from passport, and destroy the session with AAD.
app.get('/logout', function(req, res){
  req.session.destroy(function(err) {
    req.logOut();
    res.redirect(config.destroySessionUrl);
  });
});

app.listen(3000);

redpajama_set_name: RedPajamaGithub


text:
This template deploys SharePoint 2013 or 2016 with following configuration:

* 1 web application with 2 zones: Default zone uses Windows and Intranet zone uses ADFS. A couple of site collections are created
* User Profiles and Addins service applications are provisioned
* 2 extra DNS zones are created to support SharePoint apps, and app domains are set in all zones of the web application.
* Latest version of claims provider [LDAPCP](https://ldapcp.com/) is installed and configured
* A certificate authority (ADCS) is provisioned on the DC and is used for all certificates issued (ADFS and the HTTPS site in Intranet zone)
* ADFS is configured on the DC with a relying party for SharePoint web application
* A font-end can be optionnally added to the farm
* Super user / super reader are set

Each VM has its own public IP address and is in a subnet protected with a Network Security Group.

With the default sizes of virtual machines, provisioning of the template takes about 1h15 to complete.


text:
require 'rspec'
require 'personal_wordlist_cli'

include PersonalWordlistCLI


text:
/// <reference path="_References.ts" />
/// <reference path="../System/ConfigBase.ts" />

/**
    App
    @namespace App
*/
module App
{
    export class Config extends System.ConfigBase
    {
        //if user does not have gps pos, start here by default (oslo sentrum)
        public mapStartPos: System.Models.Position = new System.Models.Position(59.9122, 10.7517);

        public mapCenterMarker: string = "./../Content/images/AppIcons/mapMarker.png";
        public mapSearchLocationMarker: string = "./../Content/images/AppIcons/mapMarker_active.png";

        public poiVideoPlayerIconAndroid: string = "./../Content/images/AppIcons/video_Play.png";

        public norvegianaAutoRetryDelaySeconds: number = 10;
        public norvegianaAutoRetryCount: number = 3;
        public norvegianaSearchTimeoutSeconds: number = 30;
        public searchTimeoutSeconds: number = 30;
        public searchLimitWikiLocation: number = 500;
        public searchCountMultiplier: number = 1;
        public norvegianaURL: string = 'http://kulturnett2.delving.org/api/search';
        public ssrURL: string = 'https://ws.geonorge.no/SKWS3Index/ssr/sok';

        public templatePOIDetailsView: string = "Views/POIDetails.html";
        public templateAboutView: string = "Views/About.html";
        public templatePOIPreview: string = "POIPreview.html";
        public templatePOIAR: string = "POIAR.html";

        // For "prod"
        public routeAdminIndexUrl: string = "http://knappen.kodeogdemo.no:8081/knappenservice/api/RouteIndex";
        public routeAdminDownloadUrl: string = "http://knappen.kodeogdemo.no:8081/knappenservice/api/Route";
        public poiTypeDataUrl: string = "http://knappen.kodeogdemo.no:8081/knappenservice/FileService.aspx?file=TypeInfo.json";
        public feedbackUrl: string = "http://knappen.kodeogdemo.no:8081/knappenservice/api/Feedback";
        public adminRouteUrl: string = "http://knappen.kodeogdemo.no:8081/knappenservice/api/Route";
        public webProxy: string = "http://knappen.kodeogdemo.no:8081/knappenservice/WebProxy.aspx?url=";

        public numSearchProviders: number = 3;
        public digitalArkivetPropertyCategory: string = "Folketelling";
        public wikiPropertyCategory: string = "Wikipedia";

        // For local debugging
        //public routeAdminIndexUrl: string = "http://localhost:44000/api/RouteIndex";
        //public routeAdminDownloadUrl: string = "http://localhost:44000/api/Route";
        //public poiTypeDataUrl: string = "http://localhost:44000/FileService.aspx?file=TypeInfo.json";
        //public feedbackUrl: string = "http://localhost:44000/api/Feedback";
        //public adminRouteUrl: string = "http://localhost:44000/api/Route";
        //public webProxy: string = "http://localhost:44000/WebProxy.aspx?url=";
    }
}
var config = new App.Config();


text:
<?php

namespace Jamii\MessageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Jamii\MessageBundle\Entity\Message
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Jamii\MessageBundle\Repository\MessageRepository")
 */
class Message
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var text $message
     *
     * @ORM\Column(name="message", type="text")
     */
    private $message;

    /**
     * @var datetime $createdAt
     *
     * @ORM\Column(name="createdAt", type="datetime")
     */
    private $createdAt;

    /**
     * @var datetime $readAt
     *
     * @ORM\Column(name="readAt", type="datetime", nullable = true)
     */
    private $readAt;

    /**
     * @ORM\ManyToOne(targetEntity="Jamii\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="sender_id", referencedColumnName="id", onDelete="SET NULL")
     */
    private $sender;

    /**
     * @ORM\ManyToOne(targetEntity="Jamii\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="recipient_id", referencedColumnName="id", onDelete="SET NULL")
     */
    private $recipient;

     public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * Set recipient
     *
     * @param Jamii\UserBundle\Entity\User $recipient
     */
    public function setRecipient(\Jamii\UserBundle\Entity\User $recipient)
    {
        $this->recipient = $recipient;
    }

    /**
     * Get recipient
     *
     * @return Jamii\UserBundle\Entity\User
     */
    public function getRecipient()
    {
        return $this->recipient;
    }

    /**
     * Set addressee
     *
     * @param Jamii\UserBundle\Entity\User $author
     */
    public function setSender(\Jamii\UserBundle\Entity\User $author)
    {
        $this->sender = $author;
    }

    /**
     * Get addressee
     *
     * @return Jamii\UserBundle\Entity\User
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set message
     *
     * @param text $message
     */
    public function setMessage($message)
    {
        $this->message = $message;
    }

    /**
     * Get message
     *
     * @return text
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set createdAt
     *
     * @param datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * Get createdAt
     *
     * @return datetime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set readAt
     *
     * @param datetime $readAt
     */
    public function setReadAt($readAt)
    {
        $this->readAt = $readAt;
    }

    /**
     * Get readAt
     *
     * @return datetime
     */
    public function getReadAt()
    {
        return $this->readAt;
    }
}


text:
module DiamondLang
  module Helpers
    class Coordinates
      def initialize(*args)
        @coordinates, args = if args.first.is_a? Coordinate
          args.slice_before{|a| a.is_a? Coordinate }
        else
          axes_args = args.take Constants::Axes.length
          [
            axes_args.zip(Constants::Axes).flat_map do |value, axis|
              Coordinate.new axis, value
            end,
            args.drop(axes_args.length+1)
          ]
        end
      end
      def [](axis)
        @coordinates.select{|coord| coord.axis == axis}[0]
      end
      def x
        self['x'.freeze]
      end
      def y
        self['y'.freeze]
      end
      def z
        self['z'.freeze]
      end
      def to_s
        self.to_fs "{x} {y} {z}".freeze
      end
      def to_fs(format)
        format.gsub(/{(\w)}/) {|match| self[match[1]].value}
      end
      def to_arg
        @coordinates.map {|coord| coord.to_arg}.join ','
      end
    end
  end
end


text:
package cn.edu.zzu.nlp.editor;

import com.mxgraph.swing.handler.mxKeyboardHandler;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.swing.util.mxGraphActions;

import javax.swing.*;

/**
 * @author Administrator
 */
public class EditorKeyboardHandler extends mxKeyboardHandler {

    /**
     * @param graphComponent
     */
    public EditorKeyboardHandler(mxGraphComponent graphComponent) {
        super(graphComponent);
    }

    /**
     * Return JTree's input map.
     */
    protected InputMap getInputMap(int condition) {
        InputMap map = super.getInputMap(condition);

        if (condition == JComponent.WHEN_FOCUSED && map != null) {
            map.put(KeyStroke.getKeyStroke("control S"), "save");
            map.put(KeyStroke.getKeyStroke("control shift S"), "saveAs");
//			map.put(KeyStroke.getKeyStroke("control N"), "new");
            map.put(KeyStroke.getKeyStroke("control O"), "open");

            map.put(KeyStroke.getKeyStroke("control Z"), "undo");
            map.put(KeyStroke.getKeyStroke("control Y"), "redo");
//			map.put(KeyStroke.getKeyStroke("control shift V"), "selectVertices");
//			map.put(KeyStroke.getKeyStroke("control shift E"), "selectEdges");

            map.put(KeyStroke.getKeyStroke("delect"), "delect");

        }

        return map;
    }

    /**
     * Return the mapping between JTree's input map and JGraph's actions.
     */
    protected ActionMap createActionMap() {
        ActionMap map = super.createActionMap();

        map.put("save", new EditorActions.SaveAction(false));
        map.put("saveAs", new EditorActions.SaveAction(true));
//		map.put("new", new EditorActions.NewAction());
        map.put("open", new EditorActions.OpenAction());
        map.put("undo", new EditorActions.HistoryAction(true));
        map.put("redo", new EditorActions.HistoryAction(false));

//		map.put("selectVertices", mxGraphActions.getSelectVerticesAction());
//		map.put("selectEdges", mxGraphActions.getSelectEdgesAction());

        map.put("delect", mxGraphActions.getDeleteAction());

        return map;
    }

}


text:
package root.gast.audio.interp;

import root.gast.audio.record.AudioClipListener;
import android.util.Log;

/**
 * @author Greg Milette <<a
 *         href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
 *
 */
public class LoudNoiseDetector implements AudioClipListener
{
    private static final String TAG = "LoudNoiseDetector";

    private double volumeThreshold;

    public static final int DEFAULT_LOUDNESS_THRESHOLD = 2000;

    private static final boolean DEBUG = true;

    public LoudNoiseDetector()
    {
        volumeThreshold = DEFAULT_LOUDNESS_THRESHOLD;
    }

    public LoudNoiseDetector(double volumeThreshold)
    {
        this.volumeThreshold = volumeThreshold;
    }

    @Override
    public boolean heard(short[] data, int sampleRate)
    {
        boolean heard = false;
        // use rms to take the entire audio signal into account
        // and discount any one single high amplitude
        double currentVolume = rootMeanSquared(data);
        if (DEBUG)
        {
            Log.d(TAG, "current: " + currentVolume + " threshold: "
                    + volumeThreshold);
        }

        if (currentVolume > volumeThreshold)
        {
            Log.d(TAG, "heard");
            heard = true;
        }

        return heard;
    }

    private double rootMeanSquared(short[] nums)
    {
        double ms = 0;
        for (int i = 0; i < nums.length; i++)
        {
            ms += nums[i] * nums[i];
        }
        ms /= nums.length;
        return Math.sqrt(ms);
    }
}


text:
<?php

namespace EOI\BlackboardBundle\Services;

use BeSimple\SoapClient\SoapClient;
use BeSimple\SoapClient\WsSecurityFilter as BeSimpleWsSecurityFilter;

class Server
{
    private $client;
    private $proxyTool;
    private $session_id;

    public function __construct(
        SoapClient $client,
        array $proxyTool
    ) {
        $this->client = $client;
        $this->proxyTool = $proxyTool;
        $this->initialize();
        $this->login();
    }

    public function initialize() {
        $this->buildHeader();
        $this->session_id = $this->client->initialize();
    }

    public function login()
    {
        $this->buildHeader();
        $this->client->loginTool($this->proxyTool);
    }

    public function getSessionId()
    {
        return $this->session_id;
    }

    public function setSessionId($session)
    {
        $this->session_id = $session;
    }

    private function buildHeader()
    {
        if (empty($this->session_id)) {
            $password = 'nosession';
        } else {
            $password = $this->session_id->return;
        }

        $this->setHeader($password);
    }

    private function setHeader($password)
    {
        $wssFilter = new BeSimpleWsSecurityFilter(true, 600);
        $wssFilter->addUserData('session', $password, BeSimpleWsSecurityFilter::PASSWORD_TYPE_TEXT);
        $soapKernel = $this->client->getSoapKernel();
        $soapKernel->registerFilter($wssFilter);
    }
}


text: MathJax.Localization.addTranslation("bcc","FontWarnings",{version:"2.7.2-beta.0",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/bcc/FontWarnings.js");


text:
layout: post
title:  Capacity Planning
categories: SBP
parent: production.html
weight: 100
---

{% tip %}
**Summary:** {% excerpt %}Capacity Planning - voodoo or simple math?{% endexcerpt %}

**Author**: Shay Hassidim, Deputy CTO, GigaSpaces

**Contents:**

{% toc minLevel=1|maxLevel=1|type=flat|separator=pipe %}

{% endtip %}

# Capacity Planning - Voodoo or Simple Math?
Planning the number of machines your application requires, is one of the most important tasks you need to do before moving into production and making your application available to your customers/users. Typically, this is a task you need to do in the early stages of the project in order to budget for hardware and relevant software products your system will use. At a minimum, this involves estimating the number of CPUs and cores plus the memory each machine must have.

Another important deployment decision is to calculate the maximum number of In-Memory-Data-Grid (IMDG) partitions the application requires. This deployment parameter determines how scalable your application IMDG is. Once the application is deployed, the number of IMDG partitions remains constant, but their physical location, their activation mode (primary or backup), and hosting containers are dynamic.

The IMDG instances could fail and relocate themselves to another machine automatically. They can relocate as a result of an SLA (Service-Level-Agreement) event (for example - CPU and memory utilization breach), or they can relocate, based on manual intervention by an administrator. This IMDG "mobility" is a critical capability that, beyond providing the application with the ability to scale dynamically and self-heal itself, can avoid over provisioning and unnecessary over budgeting of your hardware. You can start small, and grow as needed with your hardware utilization. The capacity planning should take this fact into consideration.

This article deals with the following capacity planning issues:

1. How to calculate the footprint of your objects when stored within the IMDG?
2. What is the balance between the amount of active clients, machine cores, and the IMDG process heap size?
3. How should the number of IMDG Partitions be calculated? We demonstrate how this should be done using 2 examples.

Please note that there is no need to specify the maximum number of partitions for services that are not collocated with IMDG instances. These can be scaled dynamically without the need to specify maximum instances.

# The Object Footprint within the IMDG
The object footprint within the IMDG is determined, based on:

- The original object size - the number of object fields and their content size.
- The JVM type (32 or 64 bit) - a 64 bit JVM might consume more memory due to the pointer address size.
- The number of indexed fields - every indexed value means another copy of the value within the index list.
- The number of different indexed values - more different values means a different index list.
- The object UID size - the UID is a string-based field, and consumes about 35 characters. You might have the object UID based on your own unique ID.

The best way to determine the exact footprint is via a simple test that allows you to perform some extrapolation when running the application in production. Here is how you should calculate the footprint:

1. Start a single IMDG instance.
2. Take a measurement of the free memory.
3. Write a sample number of objects into the IMDG (have a decent number of objects written - 100,000 is a good number).
4. Measure the free memory again.

This test gives you a very good understanding of the object footprint within the IMDG. Don't forget that if you have a backup running, the amount of memory you need to accommodate your objects, is double.

See below an example of an object footprint using a 32 and 64 Bit JVM using different amount of indexes. The numbers below may vary based on the actual Object data and indexes values.

{: .table .table-bordered}
|Indexes	|Footprint 32 Bit JVM - Windows|Footprint 64 Bit JVM - Linux|Footprint 64 Bit JVM - UseCompressedOops - Linux|
|:--|:----|:-----------------------------|:----------------------------------------------------------------------------|
|0	|331	|306	|308|
|1 - String	|456	|705	|493|
|2 - String+Integer	|493	|989	|671|
|3 - String+Integer+Long	|533	|1002	|680|
|4 - String+Integer+Long+Double	|571	|1026	|691|

{% indent %}
![footprint_bench7.1.2.jpg](/attachment_files/sbp/footprint_bench7.1.2.jpg)
{% endindent %}

- Test conducted using GigaSpaces XAP 7.1.2.
- All objects values are different.
- The Object has one String field, one Integer field, one Long field and one Double field.
- Footprint measured in Bytes.
- Basic Index type is used. An Extended Index type will have an additional footprint (20%) compared to a Basic Index type.

{% tip %}
You may decrease the raw object footprint (not the indexes footprint) using the [GigaSpaces Serialization API](./lowering-the-space-object-footprint.html)
{% endtip %}

{% tip %}
You can reduce the JVM memory footprint using the `-XX:+UseCompressedOops` JVM option. It is part of the JDK6u14 and JDK7. See more details here: [http://wikis.sun.com/display/HotSpotInternals/CompressedOops](http://wikis.sun.com/display/HotSpotInternals/CompressedOops). It is highly recommended to use the latest JDK release when using this option.
{% endtip %}

# Active Clients vs. Cores vs. Heap Size
Since the IMDG kernel is a highly multi-threaded process, it has a relatively large number of active threads handling incoming requests. These requests could come from remote clients or collocated clients. Here are a few examples:

- any remote call involves a thread at the IMDG side that handles the request.
- a notification delivery might involve multiple threads sending events to registered clients.
- any destructive operation (write, update, take) also triggers a replication event that is handled via a dedicated replication channel, which is using a dedicated thread to handle the replication request to the backup IMDG instance.
- there is some periodic background activity, used to monitor the relevant components that are using its own dedicated threads within the IMDG kernel.

A collocated client does not go through the network layer, and interacts with the IMDG kernel very fast. This means that the machine CPU core that has been assigned to deal with this thread activity is very busy, and it does not wait for the operating system to handle IO operations. Taking this fact into consideration means we can have less concurrent clients served by the same core when compared to remote clients activity.

The number of active threads and machine cores is important also for the maximum heap size allocated for the JVM running the GSC. You should have some "headroom" for the JVM garbage collection activity to deal with cleaning allocated resources and reclaiming unused memory. A large heap size means a potentially large number of temporary objects that might generate work for the garbage collection activity. So you should have some reasonable balance between the number of cores the machine is running, the number of GSCs/IMDG running, and the number of active clients/threads accessing the IMDG.

A machine running 4 quad-core cores with fast CPUs (3GHz clock) is able to handle 20-30 concurrent collocated clients without any special delay, and 100-150 concurrent remote clients without any special delay. Such a JVM should have at least a 2-3GB heap size to handle the IMDG data and additional resources utilizing memory. With the above we assume the application business logic is very simple and does not have any IO operations, and the IMDG persistency mode is asynchronous.

# How should I Calculate the Number of IMDG Partitions?
The question is how to calculate the number of IMDG partitions required by an application.
The calculation is essentially based on the maximum number of machines available. Theoretically, in an ideal world where you have an unlimited budget and unlimited resources, you might want to have a dedicated machine per IMDG instance hosted within a dedicated Grid Container (GSC). In the real world, in order to avoid a large budget for hardware, you can initially have multiple IMDG instances running on the same machine within a single GSC. This deployment topology can be modified later to move closer to the ideal of a dedicated GSC hosting a single IMDG instance (one IMDG instance per GSC).

The number of GSCs per machine you need initially, is calculated based on the machine's physical RAM and the amount of heap memory you would like to have for the JVM running the GSC. In many cases the heap size is determined based on the operating system: for a 32 bit OS, you would go for a 2G maximum heap size, and for a 64 bit OS, you would go for 6-10G maximum heap size (the JVM -Xmx argument). For performance optimization you should have the initial heap size the same as the maximum size. The next sections demonstrate capacity planning using a simple real life example.

Here are a few basic formulas you can use:

{% highlight java %}
Amount of GSCs per Machine = Amount of Total Machine Cores/2
{% endhighlight %}

{% highlight java %}
Total Amount of GSC = Amount of GSCs per Machine X Initial amount of Machines
{% endhighlight %}

{% highlight java %}
GSC max heap Size = min (6, (Machine RAM Size * 0.8) / Amount of GSCs per Machine))
{% endhighlight %}

{% highlight java %}
Amount of Data-Grid Partitions = Total Amount of GSC X Scaling Growth Rate / 2
{% endhighlight %}

Where:

- Number of Total Machine Cores - the total number of cores the machine is running. For a quad-core with 2 CPUs (Duo) machine this value is 8.
- Number of Data-Grid Partitions - this is the number of IMDG Partitions you need to set when deploying.
- GSC max heap Size - JVM Xmx value
- Number of GSCs per machine - the number of GSCs you run per machine. This is a GSA parameter.
- Total amount of data in-memory - this is a number you should estimate, based on the object footprint you are storing within the space.
- Scaling Growth Rate - this is the expansion ratio. Usually it might be between 2 to 10. This value determines how much you would like to expand the Data-Grid capacity without downtime.
- Initial number of machines - the initial available machines you have when deploying the Data-Grid.
- Machine RAM Size - amount of physical RAM a machine has.
- Total number of GSCs - total number of GSCs that are initially running when deploying the Data-Grid.

## Example 1 - Basic Capacity Planning
With our example, we initially have 2 machines used to run our IMDG application. 10 machines might be allocated for the project within the next 12 months. Each machine has 32GB of RAM with 4 quad-core CPUs. This gives us a total of 64GB of RAM. Later, when all 10 machines are available we will have potentially 320GB of total memory. The memory is used both by the primary IMDG and the backup IMDG instances (exact replica of the primary machines).

The machines run Linux 64 bit OS. Allocating 6GB per JVM as the max heap size for the GSC, results in 5 GSCs per machine - i.e. 10 GSCs initially across 2 machines. Once we use all the machines our full budget allows us, we will have 50 GSCs.

{% indent %}
![capacity_planning1.jpg](/attachment_files/sbp/capacity_planning1.jpg)
{% endindent %}

Figure 1: 2 Machines Topology - five IMDG Instances per GSC, total 64GB RAM

Having a maximum of 40 GSCs hosting the IMDG, means you might want to have half of them (20 GSCs) running primary IMDG instances and the other half running backup instances. This number is used as the number of partitions the IMDG is deployed with - this means that with the 2 machines we have initially, 10 GSCs host 40 IMDG instances. Later, as needed, these IMDG instances will be relocated to new GSCs that are started on new machines. Each machine will start 4 GSCs that will join the GigaSpaces grid and will allow the administrator to manually or automatically expand the capacity of the IMDG while the application is running.

{% indent %}
![capacity_planning2.jpg](/attachment_files/sbp/capacity_planning2.jpg)
{% endindent %}

Figure 2: 10 Machines Topology - one IMDG Instance per GSC, total 320GB RAM

This rebalancing of the IMDG instances can be done via the UI, or via a simple program using the new Admin API released with XAP 7.0. Future versions of XAP will have built-in re-balancing models you may use.

Note that being able to determine the number of IMDG partitions prior to the application deployment allows you to have exact knowledge of how your routing field values should be distributed, and how your data will be partitioned across the different JVMs that will be hosting your data in-memory.

## Example 2 - Capacity Planning when Running on the Cloud
In a cloud environment, you have access to essentially unlimited resources. You can spin up new virtual machines and have practically unlimited amounts of memory and CPU power. With such an environment, the calculation of the maximum number of IMDG partitions cannot be based on the maximum number of machines you might have allocated for your project. Theoretically you could have an unlimited number of machines started on the cloud to host your IMDG.

Still, you must have some value for the maximum number of IMDG partitions when deploying your application. In such cases, you should calculate the number of IMDG partitions, based on the amount of memory your application might generate and store within the IMDG.

Here is a simple example you might use:
An application using 3 types of classes to store its data within the IMDG.

- Class A - object average size is 1KB
- Class B - object average size is 10KB
- Class C - object average size is 100KB

The application needs to generate 1 million objects for each type of class during its life cycle:

- Class A - total memory needed = 1KB X 1M = 1GB
- Class B - total memory needed = 10KB X 1M = 10GB
- Class C - total memory needed = 100KB X 1M = 100GB

Total memory required to store application data in memory = 111GB

When using a machine with 32GB of RAM, we need 4 machines to run primary IMDG instances to store 111GB of data in memory and another 4 machines to run backup IMDG instances. For a 64 bit OS we have 5 GSCs, each having a 6GB maximum heap size - for a total of 40 GSCs (5 X 4 X 2). With 20 GSCs used to run primary instances, we could pick 80 as the number of partitions we could have (each GSC will initially host 4 IMDG instances).

This means that we have 160 IMDG instances (half primary and half backups) hosted within 40 GSCs. Theoretically, this allows us to expand the IMDG to run across 160 machines (one GSC per machine). This means 160 X 10GB as the heap size = 1.6TB of IMDG memory capacity to host the IMDG objects!  This is a huge capacity for the IMDG, which is in fact, ten times larger than the estimated size - we have lots of room in case our initial memory utilization was wrong.

# Conclusion
Capacity planning is not voodoo. You can estimate the number of machines your application IMDG might need via a simple capacity planning process. To avoid over provisioning, you should start small, and expand your IMDG capacity when needed. The maximum number of IMDG partitions can be calculated, based on a simple estimation of the number of machines you have available, or based on the size and quantity of objects your application generates. This allows your application to scale while remaining resilient and robust.


text:
/*
 *
 *
 *
 */
package connexion.events;

import client.Client;
import client.Personnage;
import client.StatutClient;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import connexion.NetConnexion;
import connexion.events.NetConnexionEventConnexion.RecConnexion;
import connexion.modele.ModeleConnexion;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import netserv.EventListener;
import netserv.NetworkServeur;
import netserv.Receptable;
import netserv.Sendable;

/**
 * NetConnexionEventConnexion.java
 *
 */
public class NetConnexionEventConnexion extends EventListener<NetConnexion, ModeleConnexion, RecConnexion> {

	private static final String EVENT = "connexion";

	public NetConnexionEventConnexion(NetConnexion nspCtn) {
		super(EVENT, nspCtn, RecConnexion.class);
	}

	@Override
	public void onEvent(SocketIOClient client, RecConnexion data, AckRequest ackSender) {

		if (client.get(NetworkServeur.CLIENT_VERSION) == null
				|| !client.<Boolean>get(NetworkServeur.CLIENT_VERSION)) {
			Logger.getGlobal().log(Level.WARNING, "Connexion : version client non conforme");
			SendConnexion retour = new SendConnexion();
			retour.setSuccess(false);
			client.sendEvent(getEvent(), retour);
			return;
		}

		String pseudo = data.getPseudo();
		String mdp = data.getMdp();

		Optional<Map<String, Object>> result = this.modele.checkConnexion(pseudo, mdp);

		boolean success = result.isPresent();

		SendConnexion retour = new SendConnexion();
		retour.setSuccess(success);

		if (success) {
			Map<String, Object> map = result.get();
			retour.setIdJoueur((long) map.get("id_joueur"));
			retour.setPseudo((String) map.get("pseudo"));
			retour.setMail((String) map.get("mail"));
		}

		client.sendEvent(getEvent(), retour);

		if (success && !this.nspCtn.getClients().containsKey(client.getSessionId())) {
			Client c = new Client(retour.getIdJoueur(), client,
					retour.getPseudo(), retour.getMail());
			c.addStatut(StatutClient.LOGGUE, StatutClient.CONNECTE, StatutClient.CLIENT_OK);
			this.nspCtn.getClients().put(client.getSessionId(), c);

			client.set(NetworkServeur.CLIENT_CLIENT, c);

			Set<Personnage> persos = this.modele.getAllPersonnagesClient(c);
			c.setPersonnages(persos);
			Map<String, Integer> statsCombat = this.modele.getStatsCombat(c.getId());
			c.getDonnees().setNbrCombatJoues(statsCombat.get("total"));
			c.getDonnees().setNbrVictoires(statsCombat.get("gagne"));
			c.getDonnees().setNbrDefaites(statsCombat.get("perdu"));
		}
	}

	public static class RecConnexion extends Receptable {

		private String pseudo;
		private String mdp;

		public String getPseudo() {
			return pseudo;
		}

		public void setPseudo(String pseudo) {
			this.pseudo = pseudo;
		}

		public String getMdp() {
			return mdp;
		}

		public void setMdp(String mdp) {
			this.mdp = mdp;
		}

		@Override
		public String toString() {
			return "RecConnexion{" + super.toString() + ", pseudo=" + pseudo + ", mdp=" + mdp + '}';
		}
	}

	public static class SendConnexion extends Sendable {

		private Long idJoueur;
		private String pseudo;
		private String mail;

		public Long getIdJoueur() {
			return idJoueur;
		}

		public void setIdJoueur(Long idJoueur) {
			this.idJoueur = idJoueur;
		}

		public String getPseudo() {
			return pseudo;
		}

		public void setPseudo(String pseudo) {
			this.pseudo = pseudo;
		}

		public String getMail() {
			return mail;
		}

		public void setMail(String mail) {
			this.mail = mail;
		}

	}
}


text: <button id="hide" class="autocompare">Hide first series</button>


text:
REG_FIDDLE(Surface_peekPixels, 256, 64, false, 0) {
void draw(SkCanvas* canvas) {
    sk_sp<SkSurface> surf(SkSurface::MakeRasterN32Premul(64, 64));
    auto surfCanvas = surf->getCanvas();
    surfCanvas->clear(SK_ColorRED);
    SkPaint paint;
    paint.setTextSize(40);
    surfCanvas->drawString("&", 16, 48, paint);
    SkPixmap pixmap;
    if (surf->peekPixels(&pixmap)) {
        SkBitmap surfBits;
        surfBits.installPixels(pixmap);
        canvas->drawBitmap(surfBits, 0, 0);
    }
}
}  // END FIDDLE
#endif  // Disabled until updated to use current API.


text:
<jqxListBox #jqxListBox
            style="float: left"
            (onCheckChange)="checkChange($event)"
            [source]="listSource"
            [width]="120"
            [height]="200"
            checkboxes="true">
</jqxListBox>

<jqxTreeGrid style="margin-left: 20px; float: left;"
            [source]="dataAdapter"
            [altRows]="true"
            [columns]="columns"
            [ready]="ready"
            #TreeGrid>
</jqxTreeGrid>


text:
import pytest
from unittest.mock import patch

from jupyterlab_git.git import execute, execution_lock

@pytest.mark.asyncio
async def test_execute_waits_on_index_lock(tmp_path):
    lock_file = tmp_path / ".git/index.lock"
    lock_file.parent.mkdir(parents=True, exist_ok=True)
    lock_file.write_text("")

    async def remove_lock_file(*args):
        assert "unlocked" not in repr(execution_lock)  # Check that the lock is working
        lock_file.unlink()  # Raise an error for missing file

    with patch("tornado.gen.sleep") as sleep:
        sleep.side_effect = remove_lock_file  # Remove the lock file instead of sleeping

        assert "unlock" in repr(execution_lock)
        cmd = ["git", "dummy"]
        kwargs = {"cwd": "{!s}".format(tmp_path)}
        await execute(cmd, **kwargs)
        assert "unlock" in repr(execution_lock)

        assert not lock_file.exists()
        assert sleep.call_count == 1


text:
<?xml version="1.0" encoding="UTF-8"?>
<holidays xmlns="https://kayaposoft.com/enrico/xsd/1.0" country="bel">
	<metadata>
		<reference>https://en.wikipedia.org/wiki/Public_holidays_in_Belgium</reference>
	</metadata>

	<!-- current dates -->
	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="1" month="1" />
		</date>
		<name lang="nl">Niewjaar</name>
		<name lang="fr">Nouvel An</name>
		<name lang="de">Neujahr</name>
		<name lang="en">New Year's Day</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<specialDate>EASTER_SUNDAY</specialDate>
		</date>
		<name lang="nl">Pasen</name>
		<name lang="fr">Pâques</name>
		<name lang="de">Ostern</name>
		<name lang="en">Easter Sunday</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<dateTransformation>
				<baseDate>
					<specialDate>EASTER_SUNDAY</specialDate>
				</baseDate>
				<addDays>1</addDays>
			</dateTransformation>
		</date>
		<name lang="nl">Paasmaandag</name>
		<name lang="fr">Lundi de Pâques</name>
		<name lang="de">Ostermontag</name>
		<name lang="en">Easter Monday</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<dateTransformation>
				<baseDate>
					<specialDate>EASTER_SUNDAY</specialDate>
				</baseDate>
				<addDays>39</addDays>
			</dateTransformation>
		</date>
		<name lang="nl">Onze Lieve Heer hemelvaart</name>
		<name lang="fr">Ascension</name>
		<name lang="de">Christi Himmelfahrt</name>
		<name lang="en">Ascension Day</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<dateTransformation>
				<baseDate>
					<specialDate>EASTER_SUNDAY</specialDate>
				</baseDate>
				<addDays>49</addDays>
			</dateTransformation>
		</date>
		<name lang="nl">Pinksteren</name>
		<name lang="fr">Pentecôte</name>
		<name lang="de">Pfingsten</name>
		<name lang="en">Whit Sunday</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<dateTransformation>
				<baseDate>
					<specialDate>EASTER_SUNDAY</specialDate>
				</baseDate>
				<addDays>50</addDays>
			</dateTransformation>
		</date>
		<name lang="nl">Pinkstermaandag</name>
		<name lang="fr">Lundi de Pentecôte</name>
		<name lang="de">Pfingstmontag</name>
		<name lang="en">Whit Monday</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="1" month="5" />
		</date>
		<name lang="nl">Dag van de arbeid</name>
		<name lang="fr">Fête du Travail</name>
		<name lang="de">Tag der Arbeit</name>
		<name lang="en">Labour Day</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="21" month="7" />
		</date>
		<name lang="nl">Nationale feestdag</name>
		<name lang="fr">Fête nationale</name>
		<name lang="de">Nationalfeiertag</name>
		<name lang="en">National holiday</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="15" month="8" />
		</date>
		<name lang="nl">Onze Lieve Vrouw hemelvaart</name>
		<name lang="fr">Assomption</name>
		<name lang="de">Mariä Himmelfahrt</name>
		<name lang="en">Assumption of Mary</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="1" month="11" />
		</date>
		<name lang="nl">Allerheiligen</name>
		<name lang="fr">Toussaint</name>
		<name lang="de">Allerheiligen</name>
		<name lang="en">All Saints' Day</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="11" month="11" />
		</date>
		<name lang="nl">Wapenstilstand (Belgische feestdag)</name>
		<name lang="fr">Jour de l'armistice</name>
		<name lang="de">Waffenstillstand</name>
		<name lang="en">Armistice Day</name>
	</holiday>

	<holiday validFrom="2011-01-01">
		<date>
			<fixedDate day="25" month="12" />
		</date>
		<name lang="nl">Kerstmis</name>
		<name lang="fr">Noël</name>
		<name lang="de">Weihnachten</name>
		<name lang="en">Christmas Day</name>
	</holiday>

</holidays>


text:
cd ~
#for data anaylis
sudo pip3 install numpy
sudo pip3 install numpy --upgrade
sudo pip3 install scipy
sudo pip3 install scipy --upgrade
sudo pip3 install matplotlib
sudo pip3 install matplotlib --upgrade
sudo pip3 install ipython
sudo pip3 install ipython --upgrade

#for finiance
sudo pip3 install pandas
sudo pip3 install pandas --upgrade


text:
var ar = new Array(200);
ar[0] = "Software Manager";
ar[1] = "Software Manager non ha rilevato aggiornamenti per l'applicazione.";
ar[2] = "Preparazione in corso dell'Installaazione guidata, che guiderà l'utente nel processo di installazione. Attendere.";
ar[3] = "Installaazione guidata";
ar[4] = "Ricerca in corso degli aggiornamenti disponibili per l'applicazione tramite Software Manager.";
ar[5] = "Un'altra sessione di Software Manager è in esecuzione nel computer.";
ar[6] = "Software Manager è disattivato.";
ar[7] = "Non si è connessi a Internet oppure i server di Update Manager non sono al momento disponibili.\n \nFare clic su Riprova se si ritiene di essere connessi a Internet.\nFare clic su Annulla per ignorare la ricerca degli aggiornamenti.";
ar[8] = "La lingua fornita a Software Manager non è corretta o non è supportata.";
ar[9] = "Il prodotto non è riconosciuto in Software Manager.";
ar[10] = "Download tramite Software Manager dei file richiesti da";
ar[11] = "Attendere. Preparazione dell'installazione tramite l'Installaazione guidata in corso.";
ar[12] = "Il download dell'aggiornamento tramite Software Manager è stato completato. Fare clic su Fine per uscire dall'installazione guidata.";
ar[13] = "Attendere. Download dell'applicazione tramite Software Manager in corso.";
ar[14] = "Download completato - Software Manager";
ar[15] = "Impossibile continuare a causa di un errore nel download tramite Software Manager.";
ar[16] = "L'installazione degli aggiornamenti tramite l'Installaazione guidata è stata completata. Fare clic su Fine per uscire dall'installazione guidata.";
ar[17] = "Software Manager esegue la ricerca di versioni aggiornate dei programmi installati nel computer.";
ar[18] = "Ricerca degli aggiornamenti tramite Software Manager in corso... L'operazione può richiedere alcuni istanti.";
ar[19] = "Download dell'aggiornamento selezionato tramite Software Manager in corso.";
ar[20] = "Download e installazione dell'aggiornamento selezionato tramite Software Manager in corso.";
ar[21] = "Il download dell'aggiornamento selezionato tramite Software Manager è stato completato.";
ar[22] = "L'aggiornamento selezionato è stato scaricato e installato correttamente tramite Software Manager.";
ar[23] = "Quando si esegue il controllo degli aggiornamenti con Update Manager, viene fornito un elenco degli aggiornamenti disponibili per i programmi presenti nel computer. Sono disponibili tre tipi di aggiornamenti: \n\nAggiornamenti: Il fornitore del software consiglia l'installazione di questo aggiornamento. È possibile selezionare il download e l'installazione automatici dell'aggiornamento dal desktop, senza visitare il sito Web del fornitore. \n\nMessaggi di aggiornamento: Questo messaggio informa che è disponibile un aggiornamento per il programma nel sito Web del fornitore del software. Viene fornito il collegamento al sito Web. \n\nMessaggi: Il fornitore del software desidera fornire all'utente informazioni sul programma che non riguardano l'aggiornamento del software. È possibile che sia presente un collegamento al sito Web del fornitore del software per ulteriori informazioni.\n";
ar[24] = "Software Manager deve cercare gli aggiornamenti del programma.";
ar[25] = "Macrovision è da sempre impegnata a proteggere la privacy dell'utente e sviluppare tecnologie in grado di assicurare la protezione dei dati personali in linea.\n\nPer fornire aggiornamenti specifici per il software utilizzato, in Update Manager vengono raccolte alcune informazioni dal computer dell'utente, tra cui il nome e il numero di versione del software. Tuttavia, non vengono raccolti il nome, l'indirizzo di posta elettronica o altre informazioni personali che consentono di identificare l'utente. Per migliorare il servizio, viene inoltre tenuta traccia dell'esito positivo o negativo del download e dell'installazione degli aggiornamenti, insieme al numero dei computer che recuperano gli aggiornamenti.";
ar[26] = "Software Manager";
ar[27] = "Informazioni su Software Manager";
ar[28] = "Copyright (c) 1997-2011 Flexera Software LLC.  All Rights Reserved.";
ar[29] = "Nessun aggiornamento disponibile per questo computer rilevato da Software Manager.";
ar[30] = "Attendere. Download dell'aggiornamento tramite Software Manager in corso.";
ar[31] = "Attendere. Installazione dell'aggiornamento tramite Software Manager in corso.";
ar[32] = "Client Software Manager non installato correttamente. Per l'installazione corretta, sono necessari i diritti di amministratore nel computer e le impostazioni di protezione predefinite del browser. Premere OK per riprovare a visualizzare gli aggiornamenti con il client Software Manager. Premere Annulla per continuare senza installare il client Software Manager. Se si sceglie di proseguire senza installare il client, non sarà possibile visualizzare alcuni aggiornamenti.";
ar[33] = "Attendere. Autenticazione dei dati dell'utente tramite Software Manager in corso.";
ar[34] = "Personalizzazione in corso del catalogo degli aggiornamenti per il computer dell'utente tramite Software Manager.";
ar[35] = "Software Manager sta effettuando la ricerca degli aggiornamenti disponibili per l'applicazione.";
ar[36] = "Per ulteriori informazioni visitare http://consumer.flexerasoftware.com.com.";
ar[37] = "Aggiornamenti";
ar[38] = "Impostazioni";
ar[39] = "Informazioni su";
ar[40] = "Fare clic su Cerca aggiornamenti per visualizzare gli aggiornamenti e i messaggi disponibili per il programma.  ";
ar[41] = "Programmi";
ar[42] = "Tutto";
ar[43] = "Cerca automaticamente gli aggiornamenti la prossima volta";
ar[44] = "Cerca aggiornamenti";
ar[45] = "Attendere. Rilevamento in corso degli aggiornamenti disponibili per il sistema dell'utente tramite Software Manager.";
ar[46] = "Software Manager consente di tenere aggiornati i programmi con le patch di protezione, i miglioramenti e le correzioni dei problemi più recenti. \nQuando un aggiornamento è disponibile, è possibile:";
ar[47] = "Visualizza gli aggiornamenti per il sistema";
ar[48] = "Visualizza descrizioni aggiornamento";
ar[49] = "Scarica e installa aggiornamenti";
ar[50] = "Annullare il download? ";
ar[51] = "Questo aggiornamento è già stato parzialmente scaricato. Riprendere il download? ";
ar[52] = "Visualizza Cronologia aggiornamenti";
ar[53] = "Immettere Nome utente e Password per continuare.";
ar[54] = "Nota: l'aggiornamento è disponibile con accesso limitato. È necessario immettere nome utente e password per poter scaricare e installare l'aggiornamento. Se non si dispone di nome utente e password, contattare il supporto tecnico o l'organizzazione vendite del programma software per ottenere l'accesso. ";
ar[55] = "Software Manager ha terminato l'aggiornamento del programma. È ora possibile chiudere la finestra o utilizzare Software Manager per visualizzare altri aggiornamenti.";
ar[56] = "Impossibile scaricare e installare l'aggiornamento specificato tramite Software Manager.";
ar[57] = "Scegliere un prodotto e fare clic su Manuale per disattivare le notifiche automatiche di aggiornamento per il prodotto. ";
ar[58] = "Nota: la selezione di una pianificazione per le notifiche di aggiornamento di solito non sostituisce la pianificazione impostata dall'autore del programma. ";
ar[59] = "Come funziona?";
ar[60] = "Gli avvisi di aggiornamento includono la dimensione e una descrizione dell'aggiornamento. Scegliere dall'elenco gli aggiornamenti che si desidera installare. Facendo clic su una voce è possibile ottenere ulteriori informazioni sull'aggiornamento o rimuovere l'avviso. ";
ar[61] = "Seleziona per prodotto";
ar[62] = "Seleziona per tipo";
ar[63] = "Critico";
ar[64] = "Importante";
ar[65] = "Secondario";
ar[66] = "Aggiornamenti critici";
ar[67] = "Aggiornamenti importanti";
ar[68] = "Aggiornamenti secondari";
ar[69] = "Messaggi critici";
ar[70] = "Messaggi importanti";
ar[71] = "Messaggi secondari";
ar[72] = "Elementi selezionati:";
ar[73] = "Dimensione download (totale):";
ar[74] = "KB";
ar[75] = "MB";
ar[76] = "GB";
ar[77] = "Installa";
ar[78] = "or";
ar[79] = "Solo download";
ar[80] = "Nuovi aggiornamenti e messaggi";
ar[81] = "Ripristina aggiornamenti nascosti";
ar[82] = "Visualizza cronologia";
ar[83] = "Nome:";
ar[84] = "Autore:";
ar[85] = "Versione:";
ar[86] = "Percorso file:";
ar[87] = "Data";
ar[88] = "Altri dettagli...";
ar[89] = "Non visualizzare più";
ar[90] = "Rimuovi il messaggio";
ar[91] = "Ripristina";
ar[92] = "Prodotto";
ar[93] = "Stato";
ar[94] = "Completato";
ar[95] = "Annullato";
ar[96] = "Non riuscito";
ar[97] = "rapporto da stampare";
ar[98] = "sconosciuto";
ar[99] = "Dimensione";
ar[100] = "Manuale";
ar[101] = "Quotidiano";
ar[102] = "Settimanale";
ar[103] = "Mensile";
ar[104] = "primo";
ar[105] = "secondo";
ar[106] = "terzo";
ar[107] = "quarto";
ar[108] = "Lunedì";
ar[109] = "Martedì";
ar[110] = "Mercoledì";
ar[111] = "Giovedì";
ar[112] = "Venerdì";
ar[113] = "Sabato";
ar[114] = "Domenica";
ar[115] = "A.M.";
ar[116] = "P.M.";
ar[117] = "Applica";
ar[118] = "Applica a tutti i prodotti";
ar[119] = "Annulla";
ar[120] = "Nessun aggiornamento disponibile.";
ar[121] = "ogni ";
ar[122] = "alle";
ar[123] = "Condizioni per l'utilizzo";
ar[124] = "Informativa sulla privacy";
ar[125] = "Guida";
ar[126] = "Nota: le informazioni raccolte verranno utilizzate per verificare l'abilitazione alla ricezione degli aggiornamenti. ";
ar[127] = "Salva valori";
ar[128] = "Nome utente:";
ar[129] = "Password:";
ar[130] = "Immettere Nome utente e Password per continuare.";
ar[131] = "Protezione utente";
ar[132] = "Invia";
ar[133] = "Download in corso";
ar[134] = "Completato";
ar[135] = "Operazione non riuscita";
ar[136] = "Come cercare gli aggiornamenti. ";
ar[137] = "1. Dall'elenco Programmi scegliere il programma per il quale si desidera ricercare gli aggiornamenti. ";
ar[138] = "2. Fare clic su Cerca aggiornamenti. ";
ar[139] = "3. Verranno visualizzati gli aggiornamenti disponibili per il programma. ";
ar[140] = "Come installare un aggiornamento";
ar[141] = "1. Fare clic su Cerca aggiornamenti. Verranno visualizzati gli aggiornamenti disponibili. ";
ar[142] = "1. Selezionare l'aggiornamento da installare. ";
ar[143] = "2. Fare clic su Installa. Gli aggiornamenti verranno scaricati e installati nel sistema tramite Software Manager. ";
ar[144] = "Come interrompere la visualizzazione degli avvisi di aggiornamento in futuro. ";
ar[145] = "Interrompi gli avvisi per un livello di aggiornamento del prodotto";
ar[146] = "1. Fare clic su Impostazioni. Viene visualizzata la schermata Impostazioni personali aggiornamenti. ";
ar[147] = "2. Selezionare il livello di aggiornamento del prodotto raggiunto il quale si desidera interrompere la ricezione degli avvisi di aggiornamento. ";
ar[148] = "3. Fare clic su Manuale nelle opzioni di pianificazione. ";
ar[149] = "4. Fare clic su Applica per disattivare tutti gli avvisi per il livello di aggiornamento specificato. ";
ar[150] = "Interrompi gli avvisi per tutti i prodotti";
ar[151] = "1. Fare clic sulla casella di controllo Interrompi controllo automatico aggiornamenti per tutti i prodotti.";
ar[152] = "Come recuperare un aggiornamento nascosto dall'utente. ";
ar[153] = "1. Nella visualizzazione Aggiornamenti, fare clic su Ripristina aggiornamenti nascosti. ";
ar[154] = "2. Se in precedenza è stato selezionato un aggiornamento e scelto Non visualizzare più questo aggiornamento, l'aggiornamento verrà visualizzato.";
ar[155] = "3. Selezionare l'aggiornamento da ripristinare. ";
ar[156] = "4. Fare clic su Ripristina.  ";
ar[157] = "Come visualizzare gli aggiornamenti già installati. ";
ar[158] = "1. Nella visualizzazione Aggiornamenti, fare clic su Visualizza cronologia. ";
ar[159] = "2. Viene visualizzato un elenco dei prodotti gestiti da Software Manager.";
ar[160] = "3. Selezionare un prodotto ed espanderlo per visualizzare gli aggiornamenti installati, non installati correttamente o annullati. ";
ar[161] = "Interrompi controllo automatico aggiornamenti per tutti i prodotti.";
ar[162] = "---------------";
ar[163] = "Aggiornamento critico disponibile";
ar[164] = "Aggiornamento importante disponibile";
ar[165] = "Aggiornamento secondario disponibile";
ar[166] = "Messaggio critico disponibile";
ar[167] = "Messaggio importante disponibile";
ar[168] = "Messaggio secondario disponibile";
ar[169] = "Visualizza il promemoria tra ";
ar[170] = "1 ora";
ar[171] = "3 ore";
ar[172] = "1 giorno";
ar[173] = "3 giorni";
ar[174] = "1 settimana";
ar[175] = "Non visualizzare più questo messaggio";
ar[176] = "Mostra tutti gli aggiornamenti e i messaggi";
ar[177] = "*update* per *product*";
ar[178] = "Nuovo";
ar[179] = "Messaggi";
ar[180] = "Ulteriori informazioni";
ar[181] = "Istruzioni per l'installazione...";
ar[182] = "Aggiornamento annullato dall'utente.";
ar[183] = "Deve essere installato separatamente rispetto agli altri aggiornamenti.";
ar[184] = "Ulteriori informazioni";
ar[185] = "È necessario installare {0} separatamente dagli altri aggiornamenti. Se si aggiunge {0} all'elenco degli aggiornamenti, il client Software Manager rimuoverà automaticamente gli altri aggiornamenti presenti nell'elenco. Per rimuovere gli altri aggiornamenti e aggiungere solo {0}, fare clic su OK. Per tornare alla finestra di ricerca senza aggiungere l'aggiornamento, fare clic su Annulla.";
ar[186] = "L'elenco degli aggiornamenti totali selezionati contiene attualmente {0}, che è un oggetto esclusivo e deve essere installato separatamente rispetto agli altri aggiornamenti. Per rimuovere {0} dall'elenco e aggiungervi {1}, selezionare OK. Per mantenere {0} senza aggiungere {1}, selezionare Annulla.";
ar[187] = "Sono disponibili aggiornamenti dei programmi.";
ar[188] = "Chiudi";


text:
// -----------------------------------------------------------------------
// <copyright file="IBaseEnvelope.cs" company="YamNet">
//   Copyright (c) 2013 YamNet contributors
// </copyright>
// -----------------------------------------------------------------------

namespace YamNet.Client
{
    using System;

    /// <summary>
    /// The BaseEnvelope interface.
    /// </summary>
    /// <typeparam name="T">The class type.</typeparam>
    public interface IBaseEnvelope<T>
    {
        /// <summary>
        /// Gets or sets the content.
        /// </summary>
        T Content { get; set; }

        /// <summary>
        /// Gets or sets the exception.
        /// </summary>
        Exception Exception { get; set; }

        /// <summary>
        /// Gets a value indicating whether the response is faulted.
        /// </summary>
        bool IsFaulted { get; }

        /// <summary>
        /// The result.
        /// </summary>
        /// <returns>The <see cref="T"/>.</returns>
        T Result();
    }
}


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

    <TextView
        android:id="@+id/map_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="25sp"
        android:layout_gravity="center"
        android:textStyle="bold" >
    </TextView>

    <ImageView
        android:id="@+id/map_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp" >
    </ImageView>

</LinearLayout>


text:
/*
Placeholder manifest file.
the installer will append this file to the app vendored assets here: 'vendor/assets/stylesheets/spree/frontend/all.css'
*/

.ups-address-validation-suggestion {
  float: left;
  padding: 10px;
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace DotConsole.Tests.Mocks
{
    public class MockCommandArgs : CommandArguments
    {
        [Argument("version", "v", "Version to migrate up or down to",
            Position = 2)]
        [Range(typeof(Int64), "1", "5",
            ErrorMessage = "Target version must be between 1 and 5")]
        public long TargetVersion { get; set; }

        //  this property has a position of 1 and should be
        //  at the end of the class (after a property with a higher position)
        //  for accurate testing of certain methods
        [Argument("connection", "c", "Name of the connection to use",
            ValueName = "connection_value",
            Position = 1)]
        [Required(ErrorMessage = "Connection is required")]
        public string Connection { get; set; }

        //  property that doesn't have the [ArgumentAttribute]
        public string NotAnArgument { get; set; }
    }
}


text:
using content::BrowserThread;
using content::WebContents;

namespace printing {

BackgroundPrintingManager::BackgroundPrintingManager() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

BackgroundPrintingManager::~BackgroundPrintingManager() {
  DCHECK(CalledOnValidThread());
  // The might be some TabContentsWrappers still in |printing_tabs_| at
  // this point. E.g. when the last remaining tab is a print preview tab and
  // tries to print. In which case it will fail to print.
  // TODO(thestig) handle this case better.
}

void BackgroundPrintingManager::OwnPrintPreviewTab(
    TabContentsWrapper* preview_tab) {
  DCHECK(CalledOnValidThread());
  DCHECK(PrintPreviewTabController::IsPrintPreviewTab(preview_tab));
  CHECK(!HasPrintPreviewTab(preview_tab));

  printing_tabs_.insert(preview_tab);

  registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_RELEASED,
                 content::Source<TabContentsWrapper>(preview_tab));

  // OwnInitiatorTabContents() may have already added this notification.
  WebContents* preview_contents = preview_tab->web_contents();
  if (!registrar_.IsRegistered(
          this,
          content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
          content::Source<WebContents>(preview_contents))) {
    registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
                   content::Source<WebContents>(preview_contents));
  }

  // If a tab that is printing crashes, the user cannot destroy it since it is
  // not in any tab strip. Thus listen for crashes here and delete the tab.
  //
  // Multiple sites may share the same RenderProcessHost, so check if this
  // notification has already been added.
  content::RenderProcessHost* rph =
      preview_tab->web_contents()->GetRenderProcessHost();
  if (!registrar_.IsRegistered(this,
                               content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
                               content::Source<content::RenderProcessHost>(
                                  rph))) {
    registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
                   content::Source<content::RenderProcessHost>(rph));
  }

  // Activate the initiator tab.
  PrintPreviewTabController* tab_controller =
      PrintPreviewTabController::GetInstance();
  if (!tab_controller)
    return;
  TabContentsWrapper* initiator_tab =
      tab_controller->GetInitiatorTab(preview_tab);
  if (!initiator_tab)
    return;
  initiator_tab->web_contents()->GetRenderViewHost()->GetDelegate()->Activate();
}

void BackgroundPrintingManager::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
    case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
      OnRendererProcessClosed(
          content::Source<content::RenderProcessHost>(source).ptr());
      break;
    }
    case chrome::NOTIFICATION_PRINT_JOB_RELEASED: {
      OnPrintJobReleased(content::Source<TabContentsWrapper>(source).ptr());
      break;
    }
    case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: {
      OnTabContentsDestroyed(
          TabContentsWrapper::GetCurrentWrapperForContents(
              content::Source<WebContents>(source).ptr()));
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

void BackgroundPrintingManager::OnRendererProcessClosed(
    content::RenderProcessHost* rph) {
  TabContentsWrapperSet preview_tabs_pending_deletion;
  TabContentsWrapperSet::const_iterator it;
  for (it = begin(); it != end(); ++it) {
    TabContentsWrapper* preview_tab = *it;
    if (preview_tab->web_contents()->GetRenderProcessHost() == rph) {
      preview_tabs_pending_deletion.insert(preview_tab);
    }
  }
  for (it = preview_tabs_pending_deletion.begin();
       it != preview_tabs_pending_deletion.end();
       ++it) {
    DeletePreviewTab(*it);
  }
}

void BackgroundPrintingManager::OnPrintJobReleased(
    TabContentsWrapper* preview_tab) {
  DeletePreviewTab(preview_tab);
}

void BackgroundPrintingManager::OnTabContentsDestroyed(
    TabContentsWrapper* preview_tab) {
  // Always need to remove this notification since the tab is gone.
  registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
                    content::Source<WebContents>(preview_tab->web_contents()));

  if (!HasPrintPreviewTab(preview_tab)) {
    NOTREACHED();
    return;
  }

  // Remove NOTIFICATION_RENDERER_PROCESS_CLOSED if |preview_tab| is the last
  // TabContents associated with |rph|.
  bool shared_rph = HasSharedRenderProcessHost(printing_tabs_, preview_tab) ||
      HasSharedRenderProcessHost(printing_tabs_pending_deletion_, preview_tab);
  if (!shared_rph) {
    content::RenderProcessHost* rph =
        preview_tab->web_contents()->GetRenderProcessHost();
    registrar_.Remove(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
                      content::Source<content::RenderProcessHost>(rph));
  }

  // Remove other notifications and remove the tab from its
  // TabContentsWrapperSet.
  if (printing_tabs_.find(preview_tab) != printing_tabs_.end()) {
    registrar_.Remove(this, chrome::NOTIFICATION_PRINT_JOB_RELEASED,
                      content::Source<TabContentsWrapper>(preview_tab));
    printing_tabs_.erase(preview_tab);
  } else {
    // DeletePreviewTab already deleted the notification.
    printing_tabs_pending_deletion_.erase(preview_tab);
  }
}

void BackgroundPrintingManager::DeletePreviewTab(TabContentsWrapper* tab) {
  registrar_.Remove(this, chrome::NOTIFICATION_PRINT_JOB_RELEASED,
                    content::Source<TabContentsWrapper>(tab));
  printing_tabs_.erase(tab);
  printing_tabs_pending_deletion_.insert(tab);
  MessageLoop::current()->DeleteSoon(FROM_HERE, tab);
}

bool BackgroundPrintingManager::HasSharedRenderProcessHost(
    const TabContentsWrapperSet& set,
    TabContentsWrapper* tab) {
  content::RenderProcessHost* rph = tab->web_contents()->GetRenderProcessHost();
  for (TabContentsWrapperSet::const_iterator it = set.begin();
       it != set.end();
       ++it) {
    TabContentsWrapper* iter_tab = *it;
    if ((iter_tab != tab) &&
        (iter_tab->web_contents()->GetRenderProcessHost() == rph)) {
      return true;
    }
  }
  return false;
}

BackgroundPrintingManager::TabContentsWrapperSet::const_iterator
    BackgroundPrintingManager::begin() {
  return printing_tabs_.begin();
}

BackgroundPrintingManager::TabContentsWrapperSet::const_iterator
    BackgroundPrintingManager::end() {
  return printing_tabs_.end();
}

bool BackgroundPrintingManager::HasPrintPreviewTab(
    TabContentsWrapper* preview_tab) {
  if (printing_tabs_.find(preview_tab) != printing_tabs_.end())
    return true;
  return printing_tabs_pending_deletion_.find(preview_tab) !=
      printing_tabs_pending_deletion_.end();
}

}  // namespace printing


text:
PACKAGE_VERSION=$(node -p "require('semver').inc(require('./package.json').version, '$1')")
github_changelog_generator --future-release $PACKAGE_VERSION