text:
'use strict';

const _ = require('lodash');
const P = require('bluebird');
const $ = require('highland');
const flow = require('ent-flow');
const stream = require('stream');
const FieldConfigurator = require('./field-configurator').FieldConfigurator;

/**
 * The result of a query. Houses any metadata returned by the driver and provides an interface to begin streaming
 * the result records.
 */
class QueryResult {
    /**
     * Constructs a new QueryResult instance. Usually only called by the invokeWithReply static function
     * @param {Query} query the query object
     * @param {*=} data the result data, which is wrapped into a highland stream
     */
    constructor (query, data) {
        this.query = query;
        this.fields = _.assign({}, query.fields);
        this.throughHandlers = [].concat(query.throughHandlers);
        this._source = this._initDatastream(data).filter(() => !query.cancelled);
        this._passthrough = new stream.PassThrough({ objectMode: true });

        // cancel was called after execute started but before the result was created
        if (query.cancelled) this.cancel();
    }

    /**
     * Initializes the query result's stream
     * @param data
     * @return {*}
     * @private
     */
    _initDatastream (data) {
        data = data || [];
        return this.query.limit >= 0 ? $(data).take(this.query.limit) : $(data);
    }

    /**
     * Configures a field
     * @param {string} field the field name
     * @param {function=} callback an optional callback function for accessing the field configurator
     * @example
     * // with a callback
     * qr
     *  .field('location', fc => fc.type('geo_point').label('Coordinates'))
     *  .field('firstName', fc => fc.label('First Name'));
     *  .field('lastName', fc => fc.label('Last Name'));
     *
     *  // without a callback
     *  qr.field('location').type('geo_point');
     *  qr.field('firstName').label('First Name');
     *  qr.field('lastName').label('Last Name');
     *
     * @return {FieldConfigurator|QueryResult}
     */
    field (field, callback) {
        const fc = new FieldConfigurator(this.fields, field);

        // hit the call back for chaining
        if (callback) {
            callback(fc);
            return this;
        }

        return fc;
    }

    /**
     * Assigns default configuration to fields
     * @param defaults
     * @return {QueryResult}
     */
    fieldDefaults (defaults) {
        _.defaults(this.fields, defaults);
        return this;
    }

    /**
     * Adds a new stream factory to the end of the through stream
     * @param {function} handlers
     * @example
     * qr.through(s => s.filter(filterFn));
     * @return {QueryResult}
     */
    through (handlers) {
        this.throughHandlers = this.throughHandlers.concat(handlers);
        return this;
    }

    /**
     * Shims the query result for synchronous configuration by the query handler
     * @return {{fields: fields, selected: selected, field: field}}
     */
    shim () {
        var self = this;

        return {
            // configures multiple fields
            fields: function (value) {
                value = _.isArray(value) ? _.object(value.map((v, i) => [v, { position: i }])) : value;
                _.forEach(value, (v, k) => self.fields[k] = _.defaults({}, self.fields[k], v));
                return this;
            },

            // sets the number of selected records (not all records may actually be streamed)
            selected: function (value) {
                self.selected = value;
                return this;
            },

            // subscribes to stream events
            on: function (event, handler) {
                self._passthrough.on(event, handler);
                return this;
            },

            // configures a specific field
            field: function (field, callback) {
                var config = self.field(field);
                if (callback) {
                    callback(config);
                    return this;
                }
                return config;
            }
        };
    }

    /**
     * Creates a data flow by mapping over the source stream through the through stream mappers
     * @return {Object}
     */
    stream () {
        let _sourceErr;
        this._source.on('error', err => _sourceErr = err);

        const streams = []
            .concat(_.constant(this._source.pipe(this._passthrough)))
            .concat(this.throughHandlers);

        // the query result instance will be the context variable passed to all through streams.
        const $flow = flow.create(this, streams).stream();

        // Note:
        // Piping a highlandstream(_source[.take].filter) to a nodestream(passthrough) creates an error
        // propagation disconnect between the piped-from(source.filter) & piped-to(passthrough),
        // and subsequently also further connected (flow/highland) sections of the final composed stream
        // such that errors from the source don't get propagated into the composed stream flow any
        // further than the last highland before the pipe target.
        // Wrap the fully composed flow in a readable+highland to reconnect source-flow error propagation
        const $stream = new stream.Readable({
            objectMode: true,
            read () {
                // shortcircuit
                if (_sourceErr) return this.emit('error', _sourceErr);
                // read, push. coerce any highland-nil to null and push to end stream
                $flow.pull((err, val) => {
                    err = err || _sourceErr;
                    if (err) {
                        this.emit('error', err);
                    } else {
                        val = $.isNil(val) ? null : val;
                        this.push(val);
                    }
                });
            }
        });
        // re-wrap for now to maintain highland utility. Will be removed during rewrite
        return $($stream);
    }

    /**
     * Returns a promise that resolves to an array of all data values
     */
    toArray () {
        return new P((resolve, reject) => {
            const data = [];
            // collect all data, resolve when done
            this.stream()
                .on('error', err => reject(err))
                .on('end', () => resolve(data))
                .on('data', item => data.push(item));
        });
    }

    /**
     * Cancels the result by ending the stream
     */
    cancel () {
        this._source.destroy();
        return this;
    }
}

exports.QueryResult = QueryResult;


text:
/**
 * Contexts wrap the entire Littlest architecture through a single entry point.
 * This solves a few challenges at once:
 *
 * - Debugging is made easier because all internal traffic can be viewed in
 *   one place.
 * - De- and Rehydration of state can be accomplished at once.
 * - Both behaviour and state can be made individual by layering individual
 *   concerns on an existing Context, creating a new Context.
 */
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var dispatcher = require('littlest-dispatcher');
var when = require('when');
var Router = require('./router');

/**
 * Creates a new instance of Context with the provided `options`.
 *
 * @param {Object} options
 */
function Context(options) {
  if (!(this instanceof Context)) {
    return new Context(options);
  }

  EventEmitter.call(this);

  options = options || {};

  this.logger = this.logger || options.logger || null;
  this.router = this.router || options.router || new Router();

  this.dispatcher = dispatcher.createDispatcher({ logger: this.logger });
  this.actions = {};
  this.stores = {};

  this._cloneSteps = options._cloneSteps || [];
}
util.inherits(Context, EventEmitter);
Context.createContext = Context;

/**
 * Creates and returns a new Context inheriting all Actions and Stores from
 * this parent Context. Requests and state updates made within the child
 * Context will be confined to the child, adn lost whenever the child is
 * destroyed.
 *
 * If provided, `options` will override any options this Context would
 * otherwise have provided (or not) to the child.
 */
Context.prototype.getChild = function getChild(options) {
  var opts = {};

  util._extend(opts, this);
  util._extend(opts, options);

  var context = new Context(opts);

  context._cloneFrom(this);

  return context;
};

/**
 * Creates a new, named Action associated with this Context. Modules may
 * perform the Action through this Context, and the Context will be made
 * available as `this` within the function body.
 *
 * Returns the Context for cascading.
 */
Context.prototype.createAction = function createAction(name, fn) {
  function step(parent) {
    this.actions[name] = this.dispatcher.createAction(name, fn);
    return this.actions[name];
  }

  return this._addAndRunStep(step);
};

/**
 * Performs the named Action, passing in `params` as the first and only
 * argument to the originally-defined function.
 */
Context.prototype.performAction = function performAction(name, params) {
  var fn = this.actions[name];

  if (!fn) {
    return when.reject(new Error('Could not find action \'' + name + '\''));
  }

  return fn.call(this, params);
};

/**
 * Creates a new, named Store associated with this Context. Modules may access
 * the Store through this Context, and the Store can subscribe to updates
 * through the Context's shared Dispatcher.
 *
 * Returns the Context for cascading.
 */
Context.prototype.createStore = function createStore(name, props) {
  function step(parent) {
    var ctx = this;

    ctx.stores[name] = ctx.dispatcher.createStore(parent && parent.stores[name].toObject() || props);

    // TODO(schoon) - Find a better way to persist event handlers to child
    // Contexts.
    ctx.stores[name].handle = function handle(eventName, fn) {
      return ctx._addAndRunStep(function () {
        return dispatcher.Store.prototype.handle.call(this.stores[name], eventName, fn);
      });
    };

    return ctx.stores[name];
  }

  return this._addAndRunStep(step);
};

/**
 * Gets the named Store.
 */
Context.prototype.getStore = function getStore(name) {
  return this.stores[name];
};

/**
 * Adds a named route to the Router. See `Router.addRoute` for more details.
 *
 * Returns the Context for cascading.
 */
Context.prototype.createRoute = function createRoute(name, config) {
  this.router.addRoute(name, config);

  return this;
};

/**
 * Adds a status-specific route to the Router. See `Router.addErrorRoute` for
 * more details.
 *
 * Returns the Context for cascading.
 */
Context.prototype.createErrorRoute = function createErrorRoute(status, config) {
  this.router.addErrorRoute(status, config);

  return this;
};

/**
 * Returns a valid URL for the `name` route. Any `params` are used to build
 * the URL, eventually available through `props.route.params`.
 */
Context.prototype.getRouteUrl = function getRouteUrl(name, params) {
  return this.router.getRouteUrl(name, params);
};

/**
 * Navigates to the `name` Route. Any `params` are used internally to build
 * the target URL, eventually available through `props.route.params`.
 */
Context.prototype.navigateToRoute = function navigateToRoute(name, params) {
  // TODO(schoon) - Find a way to do this without seemingly-magical events.
  return this.emit('navigate', {
    location: this.getRouteUrl(name, params)
  });
};

/**
 * Serializes the Context and all associated Stores as JSON.
 */
Context.prototype.toJSON = function toJSON() {
  return {
    stores: this.stores
  };
};

/**
 * Deserializes the passed-in Object into the Context and its associated Stores.
 */
Context.prototype.fromObject = function fromObject(obj) {
  var self = this;

  if (!obj || !obj.stores) {
    return;
  }

  Object.keys(obj.stores)
    .forEach(function (key) {
      var store = self.getStore(key) || self.createStore(key);

      store.fromObject(obj.stores[key]);
    });
};

/**
 * Internal helper to add `step` functions to run when setting up a child
 * Context.
 */
Context.prototype._addAndRunStep = function _addAndRunStep(step) {
  this._cloneSteps.push(step);
  return step.call(this);
};

/**
 * Internal helper to set up a child Context from the steps in the parent.
 */
Context.prototype._cloneFrom = function _cloneFrom(parent) {
  var self = this;

  self._cloneSteps.forEach(function (step) {
    step.call(self, parent);
  });

  return self;
};

/*!
 * Export `Context`.
 */
module.exports = Context;

redpajama_set_name: RedPajamaGithub


text:
package org.qi4j.regression.qi382;

import org.junit.Test;
import org.qi4j.api.association.Association;
import org.qi4j.api.common.Optional;
import org.qi4j.api.entity.EntityBuilder;
import org.qi4j.api.entity.EntityComposite;
import org.qi4j.api.entity.Lifecycle;
import org.qi4j.api.entity.LifecycleException;
import org.qi4j.api.injection.scope.Structure;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.structure.Module;
import org.qi4j.api.unitofwork.UnitOfWork;
import org.qi4j.api.unitofwork.UnitOfWorkCompletionException;
import org.qi4j.api.value.ValueSerialization;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.entitystore.memory.MemoryEntityStoreService;
import org.qi4j.test.AbstractQi4jTest;
import org.qi4j.valueserialization.orgjson.OrgJsonValueSerializationService;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;

public class Qi382Test extends AbstractQi4jTest
{

    @Override
    public void assemble( ModuleAssembly module )
        throws AssemblyException
    {
        module.addServices( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
        module.addServices( MemoryEntityStoreService.class );
        module.entities( Car.class, Person.class );
    }

    @Test
    public void givenCreationOfTwoEntitiesWhenAssigningOneToOtherExpectCompletionToSucceed()
        throws UnitOfWorkCompletionException
    {
        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
        {
            Car car = unitOfWork.newEntity( Car.class, "Ferrari" );
            unitOfWork.complete();
        }
        try( UnitOfWork unitOfWork = module.newUnitOfWork() )
        {
            Car car = unitOfWork.get( Car.class, "Ferrari" );
            assertThat( car, notNullValue() );
            Person p = unitOfWork.get( Person.class, "Niclas" );
            assertThat( p, notNullValue() );
            assertThat( p.car().get(), equalTo( car ) );
        }
    }

    @Mixins( Car.CarMixin.class )
    public interface Car extends EntityComposite, Lifecycle
    {

        static class CarMixin implements Lifecycle
        {
            @This
            private Car me;

            @Structure
            private Module module;

            @Override
            public void create()
                throws LifecycleException
            {
                UnitOfWork unitOfWork = module.currentUnitOfWork();
                EntityBuilder<Person> builder = unitOfWork.newEntityBuilder( Person.class, "Niclas" );
                builder.instance().car().set( me );
                builder.newInstance();
            }

            @Override
            public void remove()
                throws LifecycleException
            {

            }
        }
    }

    public interface Person extends EntityComposite
    {
        Association<Car> car();
    }
}


text:
package com.soontobe.joinpay.model;

import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.Comparator;
import java.util.Date;

/**
 * This class translates the JSONObjects that get returned by the JoinPay
 * APIs into objects. It just helps clean up code by having all the
 * processing done here instead of every file that uses JSONs.
 * <p/>
 * Created by Dale Avery on 10/8/2015.
 */
public class Transaction {

    /* Structure of transaction JSON from JoinPay API
     * [][0]: type
	 *
	 *  type: normal/normal_pn
	 *  	[1] personal note
	 *  	[2] payer
	 *  	[3] payee
	 *  	[4] amount
	 *
	 *  type: summary
	 *  	[1] date (and maybe time)
	 *  	[2] # of ppl
	 *  	[3] total amount
	 *
	 *  type: group_note
	 */

    /**
     * Key for the transaction ID.
     */
    private static final String KEY_ID = "id";

    /**
     * Key for the revision number of the cloudant document storing
     * the transaction.
     */
    private static final String KEY_REV = "_rev";

    /**
     * Key for the user to whom the transaction is sent.
     */
    private static final String KEY_TO_USER = "toUser";

    /**
     * Key for the account number on which the transaction is applied.
     */
    private static final String KEY_TO_ACCOUNT = "toAccount";

    /**
     * Key for the description of the transaction.
     */
    private static final String KEY_DESCRIPTION = "description";

    /**
     * Key for the user who sent the transaction.
     */
    private static final String KEY_FROM_USER = "fromUser";

    /**
     * Key for the amount of the transaction.
     */
    private static final String KEY_AMOUNT = "amount";

    /**
     * Key for the creation date of the transaction.
     */
    private static final String KEY_CREATED = "timestamp";

    /**
     * Key for the status of the transaction.
     */
    private static final String KEY_STATUS = "status";

    /**
     * Key for the type of transaction.
     */
    private static final String KEY_TYPE = "type";

    /**
     * String used to signify denied transactions.
     */
    private static final String DENIED = "DENIED";

    /**
     * String used to signify approved transactions.
     */
    private static final String APPROVED = "APPROVED";

    /**
     * String used to signify pending transactions.
     */
    private static final String PENDING = "PENDING";

    /**
     * The list of statuses that a transaction can have.  Useful
     * for checking transaction statuses in other classes.
     */
    public enum STATUS {
        /**
         * Has been approved and paid.
         */
        APPROVED,

        /**
         * Has been denied and not paid.
         */
        DENIED,

        /**
         * Is awaiting approval and has not been paid.
         */
        PENDING,

        /**
         * Otherwise.
         */
        UNKNOWN
    }

    /**
     * String used to signify outgoing transactions.
     */
    private static final String TYPE_SENDING = "sending";

    /**
     * The list of transaction types.
     */
    public enum TYPE {
        /**
         * The transaction is outgoing.
         */
        SENDING,

        /**
         * Otherwise.
         */
        UNKNOWN
    }

    /**
     * Transaction ID.
     */
    private final String id;

    /**
     * Transaction revision number.
     */
    private final String rev;

    /**
     * The paid user.
     */
    private final String toUser;

    /**
     * The paid account.
     */
    private final String toAccount;

    /**
     * Transaction description.
     */
    private final String description;

    /**
     * The paying user.
     */
    private final String fromUser;

    /**
     * Transaction amount.
     */
    private final String amount;

    /**
     * Transaction UTC.
     */
    private final long created;

    /**
     * Transaction status.
     */
    private final STATUS status;

    /**
     * Transaction type.
     */
    private final TYPE type;

    /**
     * Constructs a new Transaction Object from the given transaction
     * JSONObject.
     *
     * @param obj The transaction to process into an object.
     */
    public Transaction(final JSONObject obj) {

        // Extract transaction details from JSON
        String fallback = "Not found";
        id = obj.optString(KEY_ID, fallback).trim();
        rev = obj.optString(KEY_REV, fallback).trim();
        toUser = obj.optString(KEY_TO_USER, fallback).trim();
        toAccount = obj.optString(KEY_TO_ACCOUNT, fallback).trim();
        description = obj.optString(KEY_DESCRIPTION, fallback).trim();
        fromUser = obj.optString(KEY_FROM_USER, fallback).trim();
        amount = obj.optString(KEY_AMOUNT, fallback).trim();
        created = obj.optLong(KEY_CREATED, 0);

        String stat = obj.optString(KEY_STATUS, fallback).trim();
        if (stat.equalsIgnoreCase(DENIED)) {
            status = STATUS.DENIED;
        } else if (stat.equalsIgnoreCase(APPROVED)) {
            status = STATUS.APPROVED;
        } else if (stat.equalsIgnoreCase(PENDING)) {
            status = STATUS.PENDING;
        } else {
            status = STATUS.UNKNOWN;
        }

        String t = obj.optString(KEY_TYPE, fallback);
        if (t.equalsIgnoreCase(TYPE_SENDING)) {
            type = TYPE.SENDING;
        } else {
            type = TYPE.UNKNOWN;
        }
    }

    /**
     * Constructs a new Transaction object with bogus data.
     * You shouldn't be using this.
     */
    public Transaction() {
        String nothing = "no json";
        id = nothing;
        rev = nothing;
        toUser = nothing;
        toAccount = nothing;
        description = nothing;
        fromUser = nothing;
        amount = nothing;
        created = 0;
        status = STATUS.UNKNOWN;
        type = TYPE.UNKNOWN;
    }

    @Override
    public final String toString() {
        // Just to make Transactions easier to log in other classes.
        String ret = String.format("Transaction: id: %s | rev: %s | "
                        + "toUser: %s | toAcc: %s | desc: %s | "
                        + "fromUser: %s | amount: %s | created: %s | "
                        + "date: %s | status: %s | type: %s",
                id, rev, toUser, toAccount, description, fromUser, amount,
                created, prettyDate(), status, type);
        return ret;
    }

    /**
     * Parses the UTC of the transaction into a Date object.
     *
     * @return A Date representing when the transaction was created.
     */
    public final Date prettyDate() {
        return new Date(created);
    }

    /**
     * Creates a Comparator which can be used to sort Transactions by their
     * date.
     *
     * @param ascending True if the Transactions should be sorted in
     *                  ascending order, false otherwise.
     * @return A Comparator for sorting transactions.
     */
    public static Comparator dateComparator(final boolean ascending) {
        if (ascending) {
            return new Comparator() {
                @Override
                public int compare(final Object lhs, final Object rhs) {
                    if (lhs instanceof Transaction
                            && rhs instanceof Transaction) {
                        Transaction left = (Transaction) lhs;
                        Transaction right = (Transaction) rhs;
                        return left.prettyDate().compareTo(right.prettyDate());
                    } else {
                        throw new IllegalArgumentException("Comparator "
                                + "only works on Transactions");
                    }
                }
            };
        } else {
            return new Comparator() {
                @Override
                public int compare(final Object lhs, final Object rhs) {
                    if (lhs instanceof Transaction
                            || rhs instanceof Transaction) {
                        Transaction left = (Transaction) lhs;
                        Transaction right = (Transaction) rhs;
                        return right.prettyDate().compareTo(left.prettyDate());
                    } else {
                        throw new IllegalArgumentException("Comparator "
                                + "only works on Transactions");
                    }
                }
            };
        }
    }

    /**
     * Creates a Comparator that keeps transactions that require
     * user attention at the top of the list, while other transactions
     * are sorted by their date.
     *
     * @param ascending True is dates should be sorted in ascending
     *                  order, false otherwise
     * @return A Comparator for sorting Transactions.
     */
    public static Comparator finalComparator(final boolean ascending) {
        return new Comparator() {
            @Override
            public int compare(final Object lhs, final Object rhs) {
                // Cast transactions so we can compare them
                if (!(lhs instanceof Transaction)
                        || !(rhs instanceof Transaction)) {
                    throw new IllegalArgumentException(
                            "Comparator only works on Transactions");
                }
                Transaction left = (Transaction) lhs;
                Transaction right = (Transaction) rhs;
                if (isFirst(left) && isFirst(right)) {
                    return dateComparator(ascending).compare(lhs, rhs);
                } else if (isFirst(left)) {
                    return -1;
                } else if (isFirst(right)) {
                    return 1;
                } else {
                    return dateComparator(ascending).compare(lhs, rhs);
                }
            }

            // Sending, pending transactions go first
            private boolean isFirst(final Transaction t) {
                return (t.getType().equals(TYPE.SENDING)
                        && t.getStatus().equals(STATUS.PENDING));
            }
        };
    }

    /**
     * Gets the ID of the transaction.
     *
     * @return The transaction's ID.
     */
    public final String getId() {
        return id;
    }

    /**
     * Gets the paid user.
     *
     * @return The user's name.
     */
    public final String getToUser() {
        return toUser;
    }

    /**
     * Gets the paid user's account.
     *
     * @return The user's account.
     */
    public final String getToAccount() {
        return toAccount;
    }

    /**
     * Gets the transaction description.
     *
     * @return The transaction description.
     */
    public final String getDescription() {
        return description;
    }

    /**
     * Gets the paying user.
     *
     * @return The paying user.
     */
    public final String getFromUser() {
        return fromUser;
    }

    /**
     * Parses the transaction amount into a pretty String that matches
     * the local currency.
     *
     * @return The amount of the transaction.
     */
    public final String getPrettyAmount() {
        String tempString = amount;
        if (amount.startsWith("$ ")) {
            tempString = amount.replace("$ ", "");
        } else if (amount.startsWith("$")) {
            tempString = amount.replace("$", "");
        }

        double amt = Double.parseDouble(tempString);
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        String money = formatter.format(amt);
        return money;
    }

    /**
     * Gets the status of the transaction.
     *
     * @return The transaction status.
     */
    public final STATUS getStatus() {
        return status;
    }

    /**
     * Gets the type of the transaction.
     *
     * @return The transaction type.
     */
    public final TYPE getType() {
        return type;
    }
}


text:
from lxml.builder import ElementMaker

XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'

class OAIDC(object):
    """The standard OAI Dublin Core metadata format.

    Every OAI feed should at least provide this format.

    It is registered under the name 'oai_dc'
    """

    def __init__(self, prefix, config, db):
        self.prefix = prefix
        self.config = config
        self.db = db

        self.ns = {'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/',
                   'dc':'http://purl.org/dc/elements/1.1/'}
        self.schemas = {
            'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd'}

    def get_namespace(self):
        return self.ns[self.prefix]

    def get_schema_location(self):
        return self.schemas[self.prefix]

    def __call__(self, element, metadata):

        data = metadata.record

        OAI_DC =  ElementMaker(namespace=self.ns['oai_dc'],
                               nsmap =self.ns)
        DC = ElementMaker(namespace=self.ns['dc'])

        oai_dc = OAI_DC.dc()
        oai_dc.attrib['{%s}schemaLocation' % XSI_NS] = '%s %s' % (
            self.ns['oai_dc'],
            self.schemas['oai_dc'])

        for field in ['title', 'creator', 'subject', 'description',
                      'publisher', 'contributor', 'type', 'format',
                      'identifier', 'source', 'language', 'date',
                      'relation', 'coverage', 'rights']:
            el = getattr(DC, field)
            for value in data['metadata'].get(field, []):
                if field == 'identifier' and data['metadata'].get('url'):
                    value = data['metadata']['url'][0]
                oai_dc.append(el(value))

        element.append(oai_dc)


text:
macs = split(readall("instances.txt"))

nworkers_per_node = 0

for idx in 1:length(macs)
    macs[idx] = string("ubuntu@", macs[idx])
end

for idx in 1:nworkers_per_node
    addprocs(macs, sshflags=`-i /home/ubuntu/jublr.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no`)
    println("num workers: $(nworkers())")
end

require("ccconsts.jl")
require("ccutils.jl")
require("ccindexer.jl")
require("ccsearcher.jl")

# create_index(2)
# search_index("word")


text:
<title>In-Process Agent - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="JIT-Interface.html#JIT-Interface" title="JIT Interface">
<link rel="next" href="GDB-Bugs.html#GDB-Bugs" title="GDB Bugs">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: GDB Bugs,
Previous: JIT Interface,
Up: Top

30 In-Process Agent

The traditional debugging model is conceptually low-speed, but works fine,
because most bugs can be reproduced in debugging-mode execution.  However,
as multi-core or many-core processors are becoming mainstream, and
multi-threaded programs become more and more popular, there should be more
and more bugs that only manifest themselves at normal-mode execution, for
example, thread races, because debugger's interference with the program's
timing may conceal the bugs.  On the other hand, in some applications,
it is not feasible for the debugger to interrupt the program's execution
long enough for the developer to learn anything helpful about its behavior.
If the program's correctness depends on its real-time behavior, delays
introduced by a debugger might cause the program to fail, even when the
code itself is correct.  It is useful to be able to observe the program's
behavior without interrupting it.

Therefore, traditional debugging model is too intrusive to reproduce
some bugs.  In order to reduce the interference with the program, we can
reduce the number of operations performed by debugger.  The
<dfn>In-Process Agent</dfn>, a shared library, is running within the same
process with inferior, and is able to perform some debugging operations
itself.  As a result, debugger is only involved when necessary, and
performance of debugging can be improved accordingly.  Note that
interference with program can be reduced but can't be removed completely,
because the in-process agent will still stop or slow down the program.

The in-process agent can interpret and execute Agent Expressions
(see Agent Expressions) during performing debugging operations.  The
agent expressions can be used for different purposes, such as collecting
data in tracepoints, and condition evaluation in breakpoints.

You can control whether the in-process agent is used as an aid for
debugging with the following commands:

set agent on
Causes the in-process agent to perform some operations on behalf of the
debugger.  Just which operations requested by the user will be done
by the in-process agent depends on the its capabilities.  For example,
if you request to evaluate breakpoint conditions in the in-process agent,
and the in-process agent has such capability as well, then breakpoint
conditions will be evaluated in the in-process agent.

set agent off
Disables execution of debugging operations by the in-process agent.  All
of the operations will be performed by gdb.

show agent
Display the current setting of execution of debugging operations by
the in-process agent.

In-Process Agent Protocol


text:
using System.Collections ;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.PostEditor.ContentSources;

namespace OpenLiveWriter.PostEditor
{
	internal class PluginsPreferences : OpenLiveWriter.ApplicationFramework.Preferences.Preferences
	{
		public PluginsPreferences() : base("Plugins")
		{
		}

		public void SetPluginEnabledState(ContentSourceInfo contentSourceInfo, bool enabled)
		{
			_enabledStateChanges[contentSourceInfo] = enabled ;
			Modified() ;
		}

		public bool GetPluginEnabledState(ContentSourceInfo contentSourceInfo)
		{
			if ( _enabledStateChanges.Contains(contentSourceInfo) )
				return (bool)_enabledStateChanges[contentSourceInfo] ;
			else
				return contentSourceInfo.Enabled ;
		}

		protected override void LoadPreferences()
		{
			_enabledStateChanges.Clear();
		}

		protected override void SavePreferences()
		{
			foreach ( DictionaryEntry entry in _enabledStateChanges )
			{
				ContentSourceInfo contentSourceInfo = entry.Key as ContentSourceInfo ;
				contentSourceInfo.Enabled = (bool)entry.Value  ;
			}
			_enabledStateChanges.Clear();
		}

		private Hashtable _enabledStateChanges = new Hashtable();

	}
}


text:
This repository contains example Kubernetes applications ("apps") that meet the
requirements for integration with Google Cloud Marketplace. For a complete
description of those requirements, see the technical onboarding guide.
*TODO: add link*

The related [marketplace-k8s-app-tools](https://github.com/GoogleCloudPlatform/marketplace-k8s-app-tools)
repository contains utilities for testing the integration of an app with
Marketplace, including a test harness for simulating UI-based deployment.
The repository is submoduled under `/vendor/marketplace-tools`.

# Getting started

## Updating git submodules

You can run the following commands to make sure submodules
are populated with proper code.

```shell
git submodule sync --recursive
git submodule update --recursive --init --force
```

## Setting up your cluster and environment

See [Getting Started](https://github.com/GoogleCloudPlatform/marketplace-k8s-app-tools/blob/master/README.md#getting-started)

## Installing WordPress

Run the following commands from within `wordpress` folder.

Run app/doctor to determine any necessary setup steps for the cluster:

```shell
make app/doctor
```

Build and install WordPress onto your cluster:

```shell
export REPORTING_SECRET=gs://cloud-marketplace-tools/reporting_secrets/fake_reporting_secret.yaml
make app/install
```

This will build the containers and install the application. Note that the
reporting secret installed for usage reporting is structurally correct, but
the keys are fake. Usage reports will fail.

To delete the installation, run:

```shell
make app/uninstall
```

## Overriding context values (Optional)

By default `make` derives docker registry and k8s namespace
from your local configurations of `gcloud` and `kubectl`.

You can see these values using

```shell
kubectl config view
```

If you want to use values that differ from the local context of `gcloud` and `kubectl`,
you can override them by exporting the appropriate environment variables:

```shell
export REGISTRY=gcr.io/your-registry
export NAMESPACE=your-namespace
export APP_INSTANCE_NAME=your-installation-name
export APP_TAG=your-tag
```

# Marketplace Integration Requirements

Briefly, apps must support two modes of installation:
- **CLI**: via a Kubernetes client tool like kubectl or helm
- **Marketplace UI**: via the deployment container ("deployer") mechanism.

A few additional Marketplace requirements are described below.

## Application resource and controller

Apps must supply an Application resource conforming to the
[Kubernetes community proposal](https://github.com/kubernetes/community/pull/1629).
The proposal describes the Application resource, as well as a corresponding
controller that would be responsible for application-generic functionality such
as assigning owner references to application components.

**Temporary Note**: the public source repository associated with the proposal is
not yet available. In the interim, we have an equivalent CRD and controller in
the marketplace-k8s-app-tools repository. Expect changes once the public repo is
available.

## Deployer

Apps must supply a deployment container image ("deployer") which is used in
UI-based deployment. This image should extend from one of the base images
provided in the marketplace-k8s-app-tools repository.


text:
class EditPartitioning:
	class FixedSubstring:
		def __init__(self, element):
			self.sequence = str(element)

		def append(self, element):
			self.sequence += element

		def extend(self, substring):
			self.sequence += substring.sequence

		def is_change(self):
			return False

		def is_insert(self):
			return False

		def is_delete(self):
			return False

		def __str__(self):
			return self.sequence

	class ChangedSubstring:
		def __init__(self, op_type, element):
			if op_type == "-":
				self.insert = ""
				self.delete = str(element)
			elif op_type == "+":
				self.insert = str(element)
				self.delete = ""

		def append(self, op_type, element):
			if op_type == "-":
				self.delete += element
			elif op_type == "+":
				self.insert += element

		def extend(self, substring):
			self.insert += substring.insert
			self.delete += substring.delete

		def is_change(self):
			return True

		def is_insert(self):
			return len(self.insert) > 0

		def is_delete(self):
			return len(self.delete) > 0

		def __str__(self):
			result = ""
			if len(self.delete) > 0:
				result += "-" + self.delete
			if len(self.insert) > 0:
				result += "+" + self.insert
			return result

	# Creates a 2D matrix of zeros.
	@staticmethod
	def __zero_matrix(width, height):
		return [[0 for column in range(width)] for row in range(height)]

	# Appends an element to the last partition, or creates a new partition.
	def __append(self, op_type, element):
		if len(self.partitions) > 0:
			if op_type == "=":
				if self.partitions[-1].is_change():
					self.partitions.append(EditPartitioning.FixedSubstring(element))
				else:
					self.partitions[-1].append(element)
			else:
				if self.partitions[-1].is_change():
					self.partitions[-1].append(op_type, element)
				else:
					self.partitions.append(EditPartitioning.ChangedSubstring(op_type, element))
		else:
			if op_type == "=":
				self.partitions.append(EditPartitioning.FixedSubstring(element))
			else:
				self.partitions.append(EditPartitioning.ChangedSubstring(op_type, element))

	# Creates the partitioning using dynamic programming. The algorithm starts
	# from the first element of s1 and s2, so in case of several possible
	# solutions, the common subsequence is fixed closer to the beginning of
	# the strings.
	def __init__(self, s1, s2):
		# Compute LCS length table, which contains the length of the longest
		# common subsequence of suffixes of s1 and s2. (Suffix meaning the
		# elements from certain point to the end of the string.)
		lcs = EditPartitioning.__zero_matrix(len(s1) + 1, len(s2) + 1)
		for j in reversed(range(len(s2))):
			for i in reversed(range(len(s1))):
				if s1[i] == s2[j]:
					lcs[j][i] = lcs[j+1][i+1] + 1
				else:
					lcs[j][i] = max(lcs[j][i+1], lcs[j+1][i])

		# Find the path through the LCS table that maximizes common
		# subsequence length.
		self.partitions = []
		i = 0
		j = 0
		while (i < len(s1)) or (j < len(s2)):
			if (i < len(s1)) and (j < len(s2)) and (s1[i] == s2[j]):
				self.__append("=", s1[i])
				i += 1
				j += 1
			elif (j < len(s2)) and ((i == len(s1)) or (lcs[j+1][i] >= lcs[j][i+1])):
				self.__append("+", s2[j])
				j += 1
			else:
				assert (i < len(s1)) and ((j == len(s2)) or (lcs[j][i+1] > lcs[j+1][i]))
				self.__append("-", s1[i])
				i += 1

	# A hack that tries to obtain a smaller set of partitions in case there are
	# consecutive elements. In case there are several possible solutions, the
	# initial algorithm always fixed the common subsequence closer to the
	# beginning of the strings.
	def clean(self):
		for i in range(len(self.partitions) - 1):
			# Find consecutive substrings a and b where n is a deletion or
			# insertion, and a is fixed but the sequence is the same.
			a = self.partitions[i]
			b = self.partitions[i + 1]
			if not ((not a.is_change()) and b.is_change()):
				continue
			if not (((a.sequence == b.delete) and (not b.is_insert())) or \
			        ((a.sequence == b.insert) and (not b.is_delete()))):
				continue
			# If the substring before a is a change or the substring after b
			# is fixed, swap a and b.
			if ((i > 0) and self.partitions[i - 1].is_change) or \
			   ((i < len(self.partitions) - 2) and (not self.partitions[i + 2].is_change())):
				self.partitions[i], self.partitions[i + 1] = self.partitions[i + 1], self.partitions[i]

		# Merge two consecutive changes or two consecutive fixed substrings.
		new_partitions = []
		i = 0
		while i < len(self.partitions) - 1:
			a = self.partitions[i]
			b = self.partitions[i + 1]
			if ((not a.is_change()) and (not b.is_change())) or \
			   (a.is_change() and b.is_change()):
				a.extend(b)
				i += 2
			else:
				i += 1
			new_partitions.append(a)
		if i < len(self.partitions):
			a = self.partitions[i]
			new_partitions.append(a)
		self.partitions = new_partitions

	def __iter__(self):
		if len(self.partitions) < 2:
			return

		for i in range(1, len(self.partitions) - 1):
			left = self.partitions[i - 1]
			center = self.partitions[i]
			right = self.partitions[i + 1]
			if center.is_change():
				yield EditPartitioning.Context(left, center, right, i > 1, i < len(self.partitions) - 2)

		left = self.partitions[-2]
		center = self.partitions[-1]
		if center.is_change():
			yield EditPartitioning.Context(left, center, None, len(self.partitions) > 2, False)

	def __str__(self):
		result = ""
		for partition in self.partitions:
			result += str(partition) + " "
		return result


text:
import argparse
import os

import pyperclip

import oneliners
from declarations import SwapPrivateToProtectedParser
from declarations import ValsParser
from declarations import VarsParser
from formatter import Formatter
from regexparser import RegexParser
from unroller import Unroller

SUPPRESS_ILLEGAL_IDENTIFIER = '@file:Suppress("IllegalIdentifier")\n'

class SpockParser:
    def __init__(self, spock_path, parsers_conf, one_liners_conf):
        with open(spock_path, encoding="utf-8") as open_spock_file:
            self.spock = open_spock_file.read().splitlines()
            self.rules = []
            self.parsers = parsers_conf
            self.one_liners = one_liners_conf

    def parse(self):
        self.spock.insert(0, SUPPRESS_ILLEGAL_IDENTIFIER)

        self.spock = Formatter.format(self.spock)

        for parser in self.parsers:
            self.spock = parser.parse(self.spock[:])

        new_lines = []
        for line in self.spock:
            for one_liner in self.one_liners:
                if one_liner.match(line):
                    line = one_liner.replace(line)
            new_lines.append(line)
        self.spock = new_lines

        self.spock = SwapPrivateToProtectedParser.parse(self.spock)
        self.spock = Formatter.remove_double_empty_lines(self.spock)

        return self.spock

if __name__ == '__main__':

    argparser = argparse.ArgumentParser()
    argparser.add_argument('path', help="a groovy file or path to test/groovy dir that will be scanned recursively")
    argparser.add_argument('-u', '--unrollbig', help="unroll for value sets more than 3", action="store_true")
    args = argparser.parse_args()

    one_liners = [oneliners.MockThrowParser,
                  oneliners.MockParser,
                  oneliners.DifferentMockParser,
                  oneliners.MapParser,
                  oneliners.ListParser,
                  oneliners.LengthParser,
                  oneliners.SizeParser,
                  oneliners.ArgumentsNameTypeSwapper,
                  oneliners.FunctionNameEnhancer,
                  oneliners.QuoteReplacer,
                  oneliners.VerifyReplacer]

    parsers = [RegexParser, Unroller(args.unrollbig), VarsParser, ValsParser]

    if os.path.isdir(args.path):
        for path, subdirs, files in os.walk(args.path):
            for name in files:
                spock_file = os.path.join(path, name)
                kotlin_path = ''.join(spock_file.split('\\')[:-1]) + spock_file.split('\\')[-1].split('.')[0] + "Kt.kt"
                kotlin_path = kotlin_path.replace('/test/groovy', '/test/kotlin')

                spock_parser = SpockParser(spock_file, parsers, one_liners)
                kotlin_lines = spock_parser.parse()

                os.makedirs(os.path.dirname(kotlin_path), exist_ok=True)
                with open(kotlin_path, "w+", encoding="utf-8") as kotlin_file:

                    for line in kotlin_lines:
                        kotlin_file.write(line + '\n')
                    print('Kotlin file {} created'.format(kotlin_path))
    else:
        spock_file = args.path
        kotlin_path = ''.join(args.path.split('\\')[:-1]) + args.path.split('\\')[-1].split('.')[0] + "Kt.kt"
        kotlin_path = kotlin_path.replace('/test/groovy', '/test/java')

        spock_parser = SpockParser(spock_file, parsers, one_liners)
        kotlin_lines = spock_parser.parse()

        if '/' in kotlin_path:
            os.makedirs(os.path.dirname(kotlin_path), exist_ok=True)
        with open(kotlin_path, "w+", encoding="utf-8") as kotlin_file:

            for line in kotlin_lines:
                kotlin_file.write(line + '\n')
            print('Kotlin file in {} created'.format(kotlin_path))

        pyperclip.copy(kotlin_path)
        print("{} has been copied to your clipboard".format(kotlin_path))


text:
package com.zimbra.soap.mail.message;

import javax.xml.bind.annotation.XmlRootElement;

import com.zimbra.common.soap.MailConstants;

/**
 * @zm-api-command-auth-required true
 * @zm-api-command-admin-auth-required false
 * @zm-api-command-description Empty dumpster
 */
@XmlRootElement(name=MailConstants.E_EMPTY_DUMPSTER_REQUEST)
public class EmptyDumpsterRequest {
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>DMA Friends: Class Members - Functions</title>

<link href="bootstrap3/css/bootstrap.min.css" rel="stylesheet">

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

DMA Friends
    2.0

Main Page

Related Pages

Namespaces

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

_

a

b

c

d

e

f

g

h

i

j

l

m

n

o

p

r

s

t

u

v

w

- _ -

__call()
: DMA\Friends\Classes\Mailchimp\BaseMailchimpClient

__construct()
: DMA\Friends\Classes\API\BaseTransformer
, DMA\Friends\Classes\Mailchimp\BaseMailchimpClient
, DMA\Friends\Classes\Mailchimp\MailchimpResponse
, DMA\Friends\Classes\Notifications\Inputs\InputContains
, DMA\Friends\Classes\Notifications\Inputs\InputEquals
, DMA\Friends\Classes\Notifications\Inputs\InputRegex
, DMA\Friends\Classes\PrintManager
, DMA\Friends\Classes\UserExtend
, DMA\Friends\Commands\SyncFriendsDataCommand
, DMA\Friends\Commands\SyncFriendsImagesCommand
, DMA\Friends\Commands\SyncFriendsRelationsCommand

<address class="footer">
Generated on Tue Aug 11 2015 18:30:27 for DMA Friends by

 1.8.9.1
</address>


text:
"""
Python package to interact with UniFi Controller
"""
import shutil
import time
import warnings
import json
import logging

import requests
from urllib3.exceptions import InsecureRequestWarning

"""For testing purposes:
logging.basicConfig(filename='pyunifi.log', level=logging.WARN,
                    format='%(asctime)s %(message)s')
"""  # pylint: disable=W0105
CONS_LOG = logging.getLogger(__name__)

class APIError(Exception):
    """API Error exceptions"""

def retry_login(func, *args, **kwargs):  # pylint: disable=w0613
    """To reattempt login if requests exception(s) occur at time of call"""

    def wrapper(*args, **kwargs):
        try:
            try:
                return func(*args, **kwargs)
            except (requests.exceptions.RequestException, APIError) as err:
                CONS_LOG.warning("Failed to perform %s due to %s", func, err)
                controller = args[0]
                controller._login()  # pylint: disable=w0212
                return func(*args, **kwargs)
        except Exception as err:
            raise APIError(err)

    return wrapper

class Controller:  # pylint: disable=R0902,R0904

    """Interact with a UniFi controller.

    Uses the JSON interface on port 8443 (HTTPS) to communicate with a UniFi
    controller. Operations will raise unifi.controller.APIError on obvious
    problems (such as login failure), but many errors (such as disconnecting a
    nonexistant client) will go unreported.

    >>> from unifi.controller import Controller
    >>> c = Controller('192.168.1.99', 'admin', 'p4ssw0rd')
    >>> for ap in c.get_aps():
    ...     print 'AP named %s with MAC %s' % (ap.get('name'), ap['mac'])
    ...
    AP named Study with MAC dc:9f:db:1a:59:07
    AP named Living Room with MAC dc:9f:db:1a:59:08
    AP named Garage with MAC dc:9f:db:1a:59:0b

    """

    def __init__(  # pylint: disable=r0913
            self,
            host,
            username,
            password,
            port=8443,
            version="v5",
            site_id="default",
            ssl_verify=True,
    ):
        """
        :param host: the address of the controller host; IP or name
        :param username: the username to log in with
        :param password: the password to log in with
        :param port: the port of the controller host
        :param version: the base version of the controller API [v4|v5]
        :param site_id: the site ID to connect to
        :param ssl_verify: Verify the controllers SSL certificate,
            can also be "path/to/custom_cert.pem"
        """

        self.log = logging.getLogger(__name__ + ".Controller")

        self.host = host
        self.headers = None
        self.version = version
        self.port = port
        self.username = username
        self.password = password
        self.site_id = site_id
        self.ssl_verify = ssl_verify

        if version == "unifiOS":
            self.url = "https://" + host + "/proxy/network/"
            self.auth_url = self.url + "api/login"
        elif version == "UDMP-unifiOS":
            self.auth_url = "https://" + host + "/api/auth/login"
            self.url = "https://" + host + "/proxy/network/"
        elif version[:1] == "v":
            if float(version[1:]) < 4:
                raise APIError("%s controllers no longer supported" % version)
            self.url = "https://" + host + ":" + str(port) + "/"
            self.auth_url = self.url + "api/login"
        else:
            raise APIError("%s controllers no longer supported" % version)

        if ssl_verify is False:
            warnings.simplefilter("default", category=InsecureRequestWarning)

        self.log.debug("Controller for %s", self.url)
        self._login()

    @staticmethod
    def _jsondec(data):
        obj = json.loads(data)
        if "meta" in obj:
            if obj["meta"]["rc"] != "ok":
                raise APIError(obj["meta"]["msg"])
        if "data" in obj:
            result = obj["data"]
        else:
            result = obj

        return result

    def _api_url(self):
        return self.url + "api/s/" + self.site_id + "/"

    @retry_login
    def _read(self, url, params=None):
        # Try block to handle the unifi server being offline.
        response = self.session.get(url, params=params, headers=self.headers)

        if response.headers.get("X-CSRF-Token"):
            self.headers = {"X-CSRF-Token": response.headers["X-CSRF-Token"]}

        return self._jsondec(response.text)

    def _api_read(self, url, params=None):
        return self._read(self._api_url() + url, params)

    @retry_login
    def _write(self, url, params=None):
        response = self.session.post(url, json=params, headers=self.headers)

        if response.headers.get("X-CSRF-Token"):
            self.headers = {"X-CSRF-Token": response.headers["X-CSRF-Token"]}

        return self._jsondec(response.text)

    def _api_write(self, url, params=None):
        return self._write(self._api_url() + url, params)

    @retry_login
    def _update(self, url, params=None):
        response = self.session.put(url, json=params, headers=self.headers)

        if response.headers.get("X-CSRF-Token"):
            self.headers = {"X-CSRF-Token": response.headers["X-CSRF-Token"]}

        return self._jsondec(response.text)

    def _api_update(self, url, params=None):
        return self._update(self._api_url() + url, params)

    @retry_login
    def _delete(self, url, params=None):
        response = self.session.delete(url, json=params, headers=self.headers)

        if response.headers.get("X-CSRF-Token"):
            self.headers = {"X-CSRF-Token": response.headers["X-CSRF-Token"]}

        return self._jsondec(response.text)

    def _api_delete(self, url, params=None):
        return self._delete(self._api_url() + url, params)

    def _login(self):
        self.log.debug("login() as %s", self.username)
        self.session = requests.Session()
        self.session.verify = self.ssl_verify

        response = self.session.post(
            self.auth_url,
            json={"username": self.username, "password": self.password},
            headers=self.headers,
        )

        if response.headers.get("X-CSRF-Token"):
            self.headers = {"X-CSRF-Token": response.headers["X-CSRF-Token"]}

        if response.status_code != 200:
            raise APIError(
                "Login failed - status code: %i" % response.status_code
                )

    def _logout(self):
        self.log.debug("logout()")
        self._api_write("logout")
        self.session.close()

    def switch_site(self, name):
        """
        Switch to another site

        :param name: Site Name
        :return: True or APIError
        """

        # TODO: Not currently supported on UDMP as site support doesn't exist.
        if self.version == "UDMP-unifiOS":
            raise APIError(
                "Controller version not supported: %s" % self.version
                )

        for site in self.get_sites():
            if site["desc"] == name:
                self.site_id = site["name"]
                return True
        raise APIError("No site %s found" % name)

    def get_alerts(self):
        """Return a list of all Alerts."""
        return self._api_write("stat/alarm")

    def get_alerts_unarchived(self):
        """Return a list of Alerts unarchived."""
        params = {"archived": False}
        return self._api_write("stat/alarm", params=params)

    def get_statistics_last_24h(self):
        """Returns statistical data of the last 24h"""
        return self.get_statistics_24h(time.time())

    def get_statistics_24h(self, endtime):
        """Return statistical data last 24h from time"""
        params = {
            "attrs": ["bytes", "num_sta", "time"],
            "start": int(endtime - 86400) * 1000,
            "end": int(endtime - 3600) * 1000,
        }
        return self._api_write("stat/report/hourly.site", params)

    def get_events(self):
        """Return a list of all Events."""
        return self._api_read("stat/event")

    def get_aps(self):
        """Return a list of all APs,
        with significant information about each.
        """
        # Set test to 0 instead of NULL
        params = {"_depth": 2, "test": 0}
        return self._api_read("stat/device", params)

    def get_client(self, mac):
        """Get details about a specific client"""

        # stat/user/<mac> works better than stat/sta/<mac>
        # stat/sta seems to be only active clients
        # stat/user includes known but offline clients
        return self._api_read("stat/user/" + mac)[0]

    def get_clients(self):
        """Return a list of all active clients,
        with significant information about each.
        """
        return self._api_read("stat/sta")

    def get_users(self):
        """Return a list of all known clients,
        with significant information about each.
        """
        return self._api_read("list/user")

    def get_user_groups(self):
        """Return a list of user groups with its rate limiting settings."""
        return self._api_read("list/usergroup")

    def get_sysinfo(self):
        """Return basic system informations."""
        return self._api_read("stat/sysinfo")

    def get_healthinfo(self):
        """Return health information."""
        return self._api_read("stat/health")

    def get_sites(self):
        """Return a list of all sites,
        with their UID and description"""
        return self._read(self.url + "api/self/sites")

    def get_wlan_conf(self):
        """Return a list of configured WLANs
        with their configuration parameters.
        """
        return self._api_read("list/wlanconf")

    def _run_command(self, command, params=None, mgr="stamgr"):
        if params is None:
            params = {}
        self.log.debug("_run_command(%s)", command)
        params.update({"cmd": command})
        return self._api_write("cmd/" + mgr, params=params)

    def _mac_cmd(self, target_mac, command, mgr="stamgr", params=None):
        if params is None:
            params = {}
        self.log.debug("_mac_cmd(%s, %s)", target_mac, command)
        params["mac"] = target_mac
        return self._run_command(command, params, mgr)

    def get_device_stat(self, target_mac):
        """Gets the current state & configuration of
        the given device based on its MAC Address.
        :param target_mac: MAC address of the device.
        :type target_mac: str
        :returns: Dictionary containing metadata, state,
            capabilities and configuration of the device
        :rtype: dict()
        """
        self.log.debug("get_device_stat(%s)", target_mac)
        params = {"macs": [target_mac]}
        return self._api_read("stat/device/" + target_mac, params)[0]

    def get_radius_users(self):
        """Return a list of all users, with their
        name, password, 24 digit user id, and 24 digit site id
        """
        return self._api_read('rest/account')

    def add_radius_user(self, name, password):
        """Add a new user with this username and password
        :param name: new user's username
        :param password: new user's password
        :returns: user's name, password, 24 digit user id, and 24 digit site id
        """
        params = {'name': name, 'x_password': password}
        return self._api_write('rest/account/', params)

    def update_radius_user(self, name, password, user_id):
        """Update a user to this new username and password
        :param name: user's new username
        :param password: user's new password
        :param id: the user's 24 digit user id, from get_radius_users()
            or add_radius_user()
        :returns: user's name, password, 24 digit user id, and 24 digit site id
        :returns: [] if no change was made
        """
        params = {'name': name, '_id': user_id, 'x_password': password}
        return self._api_update('rest/account/' + user_id, params)

    def delete_radius_user(self, user_id):
        """Delete user
        :param id: the user's 24 digit user id, from get_radius_users()
            or add_radius_user()
        :returns: [] if successful
        """
        return self._api_delete('rest/account/' + user_id)

    def get_switch_port_overrides(self, target_mac):
        """Gets a list of port overrides, in dictionary
        format, for the given target MAC address. The
        dictionary contains the port_idx, portconf_id,
        poe_mode, & name.

        :param target_mac: MAC address of the device.
        :type target_mac: str
        :returns: [ { 'port_idx': int(), 'portconf': str,
            'poe_mode': str, 'name': str } ]
        :rtype: list( dict() )
        """
        self.log.debug("get_switch_port_overrides(%s)", target_mac)
        return self.get_device_stat(target_mac)["port_overrides"]

    def _switch_port_power(self, target_mac, port_idx, mode):
        """Helper method to set the given PoE mode the port/switch.

        :param target_mac: MAC address of the Switch.
        :type target_mac: str
        :param port_idx: Port ID to target
        :type port_idx: int
        :param mode: PoE mode to set. ie. auto, on, off.
        :type mode: str
        :returns: { 'port_overrides': [ { 'port_idx': int(),
            'portconf': str, 'poe_mode': str, 'name': str } ] }
        :rtype: dict( list( dict() ) )
        """
        # TODO: Switch operations should most likely happen in a
        # different Class, Switch.
        self.log.debug(
            "_switch_port_power(%s, %s, %s)", target_mac, port_idx, mode
            )
        device_stat = self.get_device_stat(target_mac)
        device_id = device_stat.get("_id")
        overrides = device_stat.get("port_overrides")
        found = False
        if overrides:
            for i in overrides:
                if overrides[i]["port_idx"] == port_idx:
                    # Override already exists, update..
                    overrides[i]["poe_mode"] = mode
                    found = True
                    break
        if not found:
            # Retrieve portconf
            portconf_id = None
            for port in device_stat["port_table"]:
                if port["port_idx"] == port_idx:
                    portconf_id = port["portconf_id"]
                    break
            if portconf_id is None:
                raise APIError(
                    "Port ID %s not found in port_table" % str(port_idx)
                    )
            overrides.append(
                {
                    "port_idx": port_idx,
                    "portconf_id": portconf_id,
                    "poe_mode": mode
                    }
            )
        # We return the device_id as it's needed by the parent method
        return {"port_overrides": overrides, "device_id": device_id}

    def switch_port_power_off(self, target_mac, port_idx):
        """Powers Off the given port on the Switch identified
        by the given MAC Address.

        :param target_mac: MAC address of the Switch.
        :type target_mac: str
        :param port_idx: Port ID to power off
        :type port_idx: int
        :returns: API Response which is the resulting complete port overrides
        :rtype: list( dict() )
        """
        self.log.debug("switch_port_power_off(%s, %s)", target_mac, port_idx)
        params = self._switch_port_power(target_mac, port_idx, "off")
        device_id = params["device_id"]
        del params["device_id"]
        return self._api_update("rest/device/" + device_id, params)

    def switch_port_power_on(self, target_mac, port_idx):
        """Powers On the given port on the Switch identified
        by the given MAC Address.

        :param target_mac: MAC address of the Switch.
        :type target_mac: str
        :param port_idx: Port ID to power on
        :type port_idx: int
        :returns: API Response which is the resulting complete port overrides
        :rtype: list( dict() )
        """
        self.log.debug("switch_port_power_on(%s, %s)", target_mac, port_idx)
        params = self._switch_port_power(target_mac, port_idx, "auto")
        device_id = params["device_id"]
        del params["device_id"]
        return self._api_update("rest/device/" + device_id, params)

    def create_site(self, desc="desc"):
        """Create a new site.

        :param desc: Name of the site to be created.
        """

        # TODO: Not currently supported on UDMP as site support doesn't exist.
        if self.version == "UDMP-unifiOS":
            raise APIError(
                "Controller version not supported: %s" % self.version
                )

        return self._run_command(
            "add-site",
            params={"desc": desc},
            mgr="sitemgr"
            )

    def block_client(self, mac):
        """Add a client to the block list.

        :param mac: the MAC address of the client to block.
        """
        return self._mac_cmd(mac, "block-sta")

    def unblock_client(self, mac):
        """Remove a client from the block list.

        :param mac: the MAC address of the client to unblock.
        """
        return self._mac_cmd(mac, "unblock-sta")

    def disconnect_client(self, mac):
        """Disconnect a client.

        Disconnects a client, forcing them to reassociate. Useful when the
        connection is of bad quality to force a rescan.

        :param mac: the MAC address of the client to disconnect.
        """
        return self._mac_cmd(mac, "kick-sta")

    def restart_ap(self, mac):
        """Restart an access point (by MAC).

        :param mac: the MAC address of the AP to restart.
        """
        return self._mac_cmd(mac, "restart", "devmgr")

    def restart_ap_name(self, name):
        """Restart an access point (by name).

        :param name: the name address of the AP to restart.
        """
        if not name:
            raise APIError("%s is not a valid name" % str(name))
        for access_point in self.get_aps():
            if (
                    access_point.get("state", 0) == 1
                    and access_point.get("name", None) == name
            ):
                result = self.restart_ap(access_point["mac"])
        return result

    def archive_all_alerts(self):
        """Archive all Alerts"""
        return self._run_command("archive-all-alarms", mgr="evtmgr")

    # TODO: Not currently supported on UDMP as it now utilizes async-backups.
    def create_backup(self, days="0"):
        """Ask controller to create a backup archive file

        ..warning:
            This process puts significant load on the controller
            and may render it partially unresponsive for other requests.

        :param days: metrics of the last x days will be added to the backup.
            '-1' backup all metrics. '0' backup only the configuration.
        :return: URL path to backup file
        """
        if self.version == "UDMP-unifiOS":
            raise APIError(
                "Controller version not supported: %s" % self.version
                )

        res = self._run_command(
            "backup",
            mgr="system",
            params={"days": days}
            )
        return res[0]["url"]

    # TODO: Not currently supported on UDMP as it now utilizes async-backups.
    def get_backup(self, download_path=None, target_file="unifi-backup.unf"):
        """
        :param download_path: path to backup; if None is given
            one will be created
        :param target_file: Filename or full path to download the
            backup archive to, should have .unf extension for restore.
        """
        if self.version == "UDMP-unifiOS":
            raise APIError(
                "Controller version not supported: %s" % self.version
                )

        if not download_path:
            download_path = self.create_backup()

        response = self.session.get(self.url + download_path, stream=True)

        if response != 200:
            raise APIError("API backup failed: %i" % response.status_code)

        with open(target_file, "wb") as _backfh:
            return shutil.copyfileobj(response.raw, _backfh)

    def authorize_guest(  # pylint: disable=R0913
            self,
            guest_mac,
            minutes,
            up_bandwidth=None,
            down_bandwidth=None,
            byte_quota=None,
            ap_mac=None,
    ):
        """
        Authorize a guest based on his MAC address.

        :param guest_mac: the guest MAC address: 'aa:bb:cc:dd:ee:ff'
        :param minutes: duration of the authorization in minutes
        :param up_bandwidth: up speed allowed in kbps
        :param down_bandwidth: down speed allowed in kbps
        :param byte_quota: quantity of bytes allowed in MB
        :param ap_mac: access point MAC address
        """
        cmd = "authorize-guest"
        params = {"mac": guest_mac, "minutes": minutes}

        if up_bandwidth:
            params["up"] = up_bandwidth
        if down_bandwidth:
            params["down"] = down_bandwidth
        if byte_quota:
            params["bytes"] = byte_quota
        if ap_mac:
            params["ap_mac"] = ap_mac
        return self._run_command(cmd, params=params)

    def unauthorize_guest(self, guest_mac):
        """
        Unauthorize a guest based on his MAC address.

        :param guest_mac: the guest MAC address: 'aa:bb:cc:dd:ee:ff'
        """
        cmd = "unauthorize-guest"
        params = {"mac": guest_mac}
        return self._run_command(
            cmd,
            params=params
            )

    def get_firmware(
            self,
            cached=True,
            available=True,
            known=False,
            site=False
    ):

        """
        Return a list of available/cached firmware versions

        :param cached: Return cached firmwares
        :param available: Return available (and not cached) firmwares
        :param known: Return only firmwares for known devices
        :param site: Return only firmwares for on-site devices
        :return: List of firmware dicts
        """
        res = []
        if cached:
            res.extend(self._run_command("list-cached", mgr="firmware"))
        if available:
            res.extend(self._run_command("list-available", mgr="firmware"))

        if known:
            res = [fw for fw in res if fw["knownDevice"]]
        if site:
            res = [fw for fw in res if fw["siteDevice"]]
        return res

    def cache_firmware(self, version, device):
        """
        Cache the firmware on the UniFi Controller

        .. warning:: Caching one device might very well cache others,
            as they're on shared platforms

        :param version: version to cache
        :param device: device model to cache (e.g. BZ2)
        :return: True/False
        """
        return self._run_command(
            "download",
            mgr="firmware",
            params={
                "device": device,
                "version": version
                }
        )[0]["result"]

    def remove_firmware(self, version, device):
        """
        Remove cached firmware from the UniFi Controller

        .. warning:: Removing one device's firmware might very well remove
            others, as they're on shared platforms

        :param version: version to cache
        :param device: device model to cache (e.g. BZ2)
        :return: True/false
        """
        return self._run_command(
            "remove",
            mgr="firmware",
            params={
                "device": device,
                "version": version
                }
        )[0]["result"]

    def get_tag(self):
        """Get all tags and their member MACs"""
        return self._api_read("rest/tag")

    def upgrade_device(self, mac, version):
        """
        Upgrade a device's firmware to verion
        :param mac: MAC of dev
        :param version: version to upgrade to
        """
        self._mac_cmd(
            mac,
            "upgrade",
            mgr="devmgr",
            params={
                "upgrade_to_firmware": version
                }
        )

    def provision(self, mac):
        """
        Force provisioning of a device
        :param mac: MAC of device
        """
        self._mac_cmd(mac, "force-provision", mgr="devmgr")

    def get_setting(self, section=None, cs_settings=False):
        """
        Return settings for this site or controller

        :param cs_settings: Return only controller-wide settings
        :param section: Only return this/these section(s)
        :return: {section:settings}
        """
        res = {}
        all_settings = self._api_read("get/setting")
        if section and not isinstance(section, (list, tuple)):
            section = [section]

        for setting in all_settings:
            s_sect = setting["key"]
            if (
                    (cs_settings and "site_id" in setting)
                    or (not cs_settings and "site_id" not in setting)
                    or (section and s_sect not in section)
            ):
                continue
            for k in ("_id", "site_id", "key"):
                setting.pop(k, None)
            res[s_sect] = setting
        return res

    def update_setting(self, settings):
        """
        Update settings

        :param settings: {section:{settings}}
        :return: resulting settings
        """
        res = []
        for sect, setting in settings.items():
            res.extend(self._api_write("set/setting/" + sect, setting))
        return res

    def update_user_group(self, group_id, down_kbps=-1, up_kbps=-1):
        """
        Update user group bandwidth settings

        :param group_id: Group ID to modify
        :param down_kbps: New bandwidth in KBPS for download
        :param up_kbps: New bandwidth in KBPS for upload
        """

        res = None
        groups = self.get_user_groups()

        for group in groups:
            if group["_id"] == group_id:
                # Apply setting change
                res = self._api_update(
                    "rest/usergroup/{0}".format(group_id),
                    {
                        "qos_rate_max_down": down_kbps,
                        "qos_rate_max_up": up_kbps,
                        "name": group["name"],
                        "_id": group_id,
                        "site_id": self.site_id,
                    },
                )
                return res

        raise ValueError("Group ID {0} is not valid.".format(group_id))

    def set_client_alias(self, mac, alias):
        """
        Set the client alias. Set to "" to reset to default
        :param mac: The MAC of the client to rename
        :param alias: The alias to set
        """
        client = self.get_client(mac)["_id"]
        return self._api_update("rest/user/" + client, {"name": alias})

    def create_voucher(  # pylint: disable=R0913
            self,
            number,
            quota,
            expire,
            up_bandwidth=None,
            down_bandwidth=None,
            byte_quota=None,
            note=None,
    ):
        """
        Create voucher for guests.

        :param number: number of vouchers
        :param quota: number of using; 0 = unlimited
        :param expire: expiration of voucher in minutes
        :param up_bandwidth: up speed allowed in kbps
        :param down_bandwidth: down speed allowed in kbps
        :param byte_quota: quantity of bytes allowed in MB
        :param note: description
        """
        cmd = "create-voucher"
        params = {
            "n": number,
            "quota": quota,
            "expire": "custom",
            "expire_number": expire,
            "expire_unit": 1,
        }

        if up_bandwidth:
            params["up"] = up_bandwidth
        if down_bandwidth:
            params["down"] = down_bandwidth
        if byte_quota:
            params["bytes"] = byte_quota
        if note:
            params["note"] = note
        res = self._run_command(cmd, mgr="hotspot", params=params)
        return self.list_vouchers(create_time=res[0]["create_time"])

    def list_vouchers(self, **filter_voucher):
        """
        Get list of vouchers

        :param filter_voucher:  Filter vouchers by create_time, code, quota,
                        used, note, status_expires, status, ...

        """
        if "code" in filter_voucher:
            filter_voucher["code"] = filter_voucher["code"].replace("-", "")

        vouchers = []
        for voucher in self._api_read("stat/voucher"):
            voucher_match = True
            for key, val in filter_voucher.items():
                voucher_match &= voucher.get(key) == val
            if voucher_match:
                vouchers.append(voucher)
        return vouchers

    def delete_voucher(self, voucher_id):
        """
        Delete / revoke voucher

        :param id: id of voucher
        """
        cmd = "delete-voucher"
        params = {"_id": voucher_id}
        self._run_command(cmd, mgr="hotspot", params=params)


text:
namespace undocked {
    namespace ui {
        class MessageBox : public UiElement {
        public:
            MessageBox(UiElement *parent, int x, int y, int w, int h, std::string m) : UiElement(parent, x, y, w, h),
                                                                                message(m) {}
            void draw(sf::RenderTarget&, sf::RenderStates states) const;
            void setMessage(std::string message) { this->message = message; };

        private:
            std::string message;
        };
    }
}

#endif //PE_ECON_SIM_MESSAGEBOX_H


text:
import re
from collections import Iterable
from io import StringIO
from itertools import groupby

from typing import List, Tuple, Callable, Any, IO, cast

from smartchangelog import datetools
from smartchangelog.commit import Commit

class Node:
    def __init__(self, name: str = None, criterion: property = None, children: Tuple['Node'] = None,
                 value: Commit = None) -> None:
        self._parent: 'Node' = None
        self.name = name
        self.criterion = criterion
        self._children: Tuple['Node'] = None
        self.children = children
        self.value = value

    @property
    def parent(self) -> 'Node':
        return self._parent

    @property
    def children(self) -> Tuple['Node']:
        return self._children

    @children.setter
    def children(self, children: Tuple['Node']) -> None:
        if children is not None:
            for node in children:
                node._parent = self
        self._children = children

    def depth_level(self) -> int:
        if self.parent is None:
            return 0
        else:
            return self.parent.depth_level() + 1

    def __len__(self):
        if not self.children:
            return 1
        nb_children = 0
        for child in self.children:
            nb_children += len(child)
        return nb_children

    @classmethod
    def print_multilines(cls, name: str, value: str, file: IO):
        if value:
            lines = value.split('\n')
            if len(lines) == 1:
                print("    * {name}: {value}".format(name=name, value=value), file=file)
            else:
                print("    * {name}:".format(name=name), file=file)
                for line in lines:
                    print("        - {line}".format(line=line), file=file)

    @classmethod
    def print_leaf(cls, commit: Commit, file: IO) -> None:
        print("* subject: {subject}".format(subject=commit.subject or ''), file=file)
        cls.print_multilines(name='body', value=commit.body, file=file)
        print("    * date: {date}".format(date=datetools.date2str(commit.date)), file=file)
        print("    * author: {author}".format(author=commit.author), file=file)
        print("    * commit: {id}".format(id=commit.id), file=file)

    def print_header(self, node: 'Node', file: IO):
        print(
            "{header} {criterion_name}: {name}".format(
                header="#" * (self.depth_level() + 1),
                criterion_name=Commit.property_name(node.criterion),
                name=node.name
            ),
            file=file
        )
        print(file=file)

    def report(self) -> str:
        sio = StringIO()
        with sio:
            if self.children is None:
                self.print_leaf(commit=self.value, file=sio)
            else:
                for node in self.children:
                    if node.name:
                        self.print_header(node=node, file=sio)
                    print(node.report().strip('\n'), file=sio)
                    print(file=sio)
            string = sio.getvalue()
            return string

class Changelog(List[Commit]):
    @classmethod
    def parse(cls, log: str) -> 'Changelog':
        raw_commits = re.findall('(commit [a-z0-9]{40}\n(?:.|\n)*?)(?=commit [a-z0-9]{40}|$)', log)
        return Changelog([Commit.parse(rc) for rc in raw_commits])

    def groupby(self, *criteria: property) -> Node:
        if len(criteria) == 0:
            # Sort
            date_prop = cast(property, Commit.date)
            date_getter = cast(Callable[[Commit], Any], date_prop.fget)
            self.sort(key=date_getter)
            return self.node()

        criteria_list = list(criteria)
        criterion = criteria_list.pop(0)
        criterion_getter = cast(Callable[[Commit], Any], criterion.fget)

        # Filter
        # noinspection PyTypeChecker
        categorized_changelog = Changelog([commit for commit in self if criterion_getter(commit) is not None])
        # noinspection PyTypeChecker
        uncategorized_commits = Changelog([commit for commit in self if criterion_getter(commit) is None])

        # Sort
        categorized_changelog.sort(key=criterion_getter)

        # Arrange
        raw_result = self.groupby_to_list(groupby(iterable=categorized_changelog, key=criterion_getter))
        children_list: List[Node] = []
        for key, group in raw_result:
            cl = Changelog(group)
            children_list.append(Node(name=str(key), criterion=criterion, children=cl.groupby(*criteria_list).children))
        if len(uncategorized_commits) > 0:
            children_list.append(uncategorized_commits.node(name="unknown", criterion=criterion))
        children = cast(Tuple[Node], tuple(children_list))

        return Node(children=children)

    def node(self, name: str=None, criterion: property=None) -> Node:
        # noinspection PyTypeChecker
        children = cast(Tuple[Node], tuple(Node(value=commit) for commit in self))
        return Node(name=name, criterion=criterion, children=children)

    @classmethod
    def groupby_to_list(cls, iterable: Iterable):
        return [[key, [i for i in group]] for key, group in iterable]


text:
package app.simone.shared.utils;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;

import java.util.List;

import app.simone.R;
import app.simone.shared.main.FullscreenBaseGameActivity;
import app.simone.shared.styleable.SimoneTextView;
import app.simone.singleplayer.model.SimonColorImpl;
import app.simone.singleplayer.view.GameActivityImpl;

/**
 * AnimationHandler class.
 * Used to animate the fabs and the textviews.
 * @author Michele Sapignoli
 */

public class AnimationHandler {
    private static Animation gameButtonAnimation;

    public static void initAnimations(final GameActivityImpl context, final FloatingActionButton gameFab, final SimoneTextView simoneTextView) {
        final Animation rotate = AnimationUtils.loadAnimation(context, R.anim.rotate);
        final Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoom_in);
        final Animation zoomOut = AnimationUtils.loadAnimation(context, R.anim.zoom_out);
        gameButtonAnimation = AnimationUtils.loadAnimation(context, R.anim.fade_in);
        gameButtonAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                if (context.isPlayerBlinking()) {
                    gameFab.startAnimation(zoomIn);
                    simoneTextView.startAnimation(zoomIn);

                } else {
                    simoneTextView.startAnimation(zoomOut);
                    gameFab.startAnimation(zoomOut);
                }
                simoneTextView.startAnimation(rotate);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    public static Animation getGameButtonAnimation() {
        return gameButtonAnimation;
    }

    public static void performColorSwapAnimation(FullscreenBaseGameActivity context, Integer[] shuffle, List<Button> buttons, FrameLayout[] layouts) {
        for (int i = 0; i < buttons.size(); i++) {
            int index = shuffle[i];
            layouts[i].addView(buttons.get(index));
            ObjectAnimator objectAnimator = ObjectAnimator.ofObject(buttons.get(i), "backgroundColor",
                    new ArgbEvaluator(),
                    ContextCompat.getColor(context, SimonColorImpl.getColorIdFromButtonId(buttons.get(index).getId())),
                    ContextCompat.getColor(context, SimonColorImpl.getColorIdFromButtonId(buttons.get(i).getId())));
            objectAnimator.setRepeatCount(0);
            objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
            objectAnimator.setDuration(300);
            objectAnimator.start();
        }
    }
}


text:
import mongoose from 'mongoose';
import mongooseDelete from 'mongoose-delete';
import crypto from 'crypto';
import uid from 'uid2';
import isEmailValidator from 'validator/lib/isEmail';
import uniqueValidator from 'mongoose-unique-validator';

import Rental from './rental';

import { locationSchema } from './shared';

const Schema = mongoose.Schema;

const userSchema = new Schema({

  email: {
    type: String,
    trim: true,
    lowercase: true,
    unique: true,
    index: true,
    required: 'Email address is required',
    validate: [isEmailValidator, 'Please fill a valid email address'],
  },

  accessToken: {
    type: String,
    required: true,
    unique: true,
    index: true,
  },

  hashedPassword: { type: String, default: '' },
  salt: { type: String, default: '' },
  facebook: {},
  google: {},

  location: { type: locationSchema },

  isSeller: { type: Boolean, default: false, require: true, index: true },

  isAdmin: { type: Boolean, default: false, require: true, index: true },

  rentals: [{
    type: Schema.Types.ObjectId,
    ref: 'Rental',
  }],

}, {
  timestamps: true,
  toJSON: {
    versionKey: false,
    transform(doc, ret) {
      if (!ret.deleted) {
        delete ret.deleted;
      }

      delete ret.hashedPassword;
      delete ret.salt;

      ret.uid = ret.email;
    },
  },
});

/**
 * Plugins
 */
userSchema.plugin(uniqueValidator);
// Apply Soft Delete
// https://github.com/dsanel/mongoose-delete
userSchema.plugin(mongooseDelete, {
  deletedAt: true,
  overrideMethods: true,
  indexFields: true,
});

/**
 * Virtuals
 */
userSchema.virtual('password')
  .set(function (password) {
    this._password = password;
    this.salt = this.constructor.generateSalt();
    this.hashedPassword = this.encryptPassword(password);
  })
  .get(function () {
    return this._password;
  })
;

userSchema.virtual('password_confirmation')
  .set(function (password_confirmation) {
    this._password_confirmation = password_confirmation;
  })
  .get(function () {
    return this._password_confirmation;
  })
;

userSchema.path('hashedPassword')
  .validate(function () {
    if (this._password || this._password_confirmation) {
      if (typeof this._password === 'string' && this._password.length < 6) {
        this.invalidate('password', 'must be at least 6 characters.');
      }
      if (this._password !== this._password_confirmation) {
        this.invalidate('password_confirmation', 'must match password.');
      }
    }

    if (this.isNew && !this._password) {
      this.invalidate('password', 'Password is required');
    }
  })
;

/**
 * Hooks
 */
userSchema.pre('validate', function (next) {
  if (typeof this.accessToken !== 'string' || this.accessToken.length < 10) {
    this.updateAccessToken();
  }

  next();
});

/**
 * Methods
 */
userSchema.methods = {

  addRental(rental) {
    rental.owner = this._id;
    this.rentals.push(rental);
  },

  addRentals(rentals) {
    rentals.forEach(
      rental => this.addRental(rental)
    );
  },

  createRental(data) {
    const newRental = new Rental(data);

    this.addRental(newRental);

    return this.save()
      .then(() => newRental.save())
    ;
  },

  authenticate(password) {
    return this.encryptPassword(password) === this.hashedPassword;
  },

  encryptPassword(password) {
    return this
      .constructor
      .encryptPasswordWithSalt(password, this.salt)
    ;
  },

  updateAccessToken() {
    this.accessToken = uid(256);
  },

  signOut() {
    this.updateAccessToken();

    return this
      .save()
      .then(user => null)
    ;
  },
};

/**
 * Statics
 */
userSchema.statics = {

  signUp(email, password, password_confirmation, confirm_success_url) {
    const User = this;

    const newUser = new User({ email, password, password_confirmation });

    return newUser.save()
      .then(user => {
        return user;
      })
    ;
  },

  signIn(email, password) {
    const User = this;

    return User
      .load({
        criteria: { email },
      })
      .then(user => {
        if (!user) {
          return Promise.reject({ email: {WrongEmail: 'wrong email address'} });
        }
        if (!user.authenticate(password)) {
          return Promise.reject({ password: {WrongPassword: 'incorrect password'} });
        }

        user.updateAccessToken();

        return user.save();
      })
    ;
  },

  authorize(accessToken) {
    const User = this;

    if (typeof accessToken !== 'string' || accessToken.length < 10) {
      return Promise.resolve(null);
    }

    return User.load({
      criteria: { accessToken },
    });
  },

  encryptPasswordWithSalt(password, salt) {
    if (!password) return '';

    try {
      return crypto
        .createHmac('sha1', salt)
        .update(password)
        .digest('hex')
      ;
    } catch (err) {
      return '';
    }
  },

  generateSalt() {
    return `${Math.round((new Date().valueOf() * Math.random()))}`;
  },

  load(options, cb) {
    options = options || {};

    return this
      .findOne(options.criteria)
      .select(options.select)
      .populate('rentals')
      .exec(cb)
    ;
  },
};

export default mongoose.model('User', userSchema);


text:
#pragma once

namespace cusp
{
namespace detail
{

// array view containing random integers
template <typename T>
class random_integers;

// array view containing random real numbers in [0,1)
template <typename T>
class random_reals;

} // end namespace detail
} // end namespace cusp

#include <cusp/detail/random.inl>


text:
<?php

/**
 * @file
 * An Apple News Document Audio.
 */

namespace ChapterThree\AppleNewsAPI\Document\Components;

/**
 * An Apple News Document Audio.
 */
abstract class Audio extends Component {

  protected $URL;

  protected $caption;
  protected $imageURL;
  protected $accessibilityCaption;
  protected $explicitContent;

  /**
   * Implements __construct().
   *
   * @param mixed $role
   *   Role.
   * @param mixed $url
   *   Text.
   * @param mixed $identifier
   *   Identifier.
   */
  public function __construct($role, $url, $identifier = NULL) {
    parent::__construct($role, $identifier);
    $this->setUrl($url);
  }

  /**
   * {@inheritdoc}
   */
  protected function optional() {
    return array_merge(parent::optional(), array(
      'caption',
      'imageURL',
      'accessibilityCaption',
      'explicitContent',
    ));
  }

  /**
   * Getter for url.
   */
  public function getUrl() {
    return $this->URL;
  }

  /**
   * Setter for url.
   *
   * @param mixed $url
   *   Url.
   *
   * @return $this
   */
  public function setUrl($url) {
    $this->URL = $url;
    return $this;
  }

  /**
   * Getter for caption.
   */
  public function getCaption() {
    return $this->caption;
  }

  /**
   * Setter for caption.
   *
   * @param string $value
   *   Caption.
   *
   * @return $this
   */
  public function setCaption($value) {
    $this->caption = (string) $value;
    return $this;
  }

  /**
   * Getter for imageURL.
   */
  public function getImageURL() {
    return $this->imageURL;
  }

  /**
   * Setter for imageURL.
   *
   * @param string $value
   *   ImageURL.
   *
   * @return $this
   */
  public function setImageURL($value) {
    $this->imageURL = (string) $value;
    return $this;
  }

  /**
   * Getter for accessibilityCaption.
   */
  public function getAccessibilityCaption() {
    return $this->accessibilityCaption;
  }

  /**
   * Setter for accessibilityCaption.
   *
   * @param string $value
   *   AccessibilityCaption.
   *
   * @return $this
   */
  public function setAccessibilityCaption($value) {
    $this->accessibilityCaption = (string) $value;
    return $this;
  }

  /**
   * Getter for explicitContent.
   */
  public function getExplicitContent() {
    return $this->explicitContent;
  }

  /**
   * Setter for explicitContent.
   *
   * @param bool $value
   *   ExplicitContent.
   *
   * @return $this
   */
  public function setExplicitContent($value = false) {
    $this->explicitContent = $value;
    return $this;
  }

}


text:
package io.cattle.platform.servicediscovery.process;

import static io.cattle.platform.core.model.tables.InstanceTable.*;

import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.NetworkDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.process.common.handler.AbstractObjectProcessHandler;
import io.cattle.platform.servicediscovery.service.ServiceDiscoveryService;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class NetworkFromInstanceStop extends AbstractObjectProcessHandler {

    @Inject
    ServiceDiscoveryService sdService;
    @Inject
    JsonMapper jsonMapper;

    @Inject
    NetworkDao ntwkDao;

    @Override
    public String[] getProcessNames() {
        return new String[] { InstanceConstants.PROCESS_STOP, InstanceConstants.PROCESS_RESTART };
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        Instance instance = (Instance) state.getResource();
        if (instance.getDeploymentUnitUuid() == null) {
            return null;
        }

        List<Instance> dependants = objectManager.find(Instance.class, INSTANCE.REMOVED, null,
                INSTANCE.DEPLOYMENT_UNIT_UUID, instance.getDeploymentUnitUuid(), INSTANCE.NETWORK_CONTAINER_ID,
                instance.getId());
        if (dependants.isEmpty()) {
            return null;
        }

        List<String> invalidStates = Arrays.asList(CommonStatesConstants.REMOVING, InstanceConstants.STATE_ERROR,
                InstanceConstants.STATE_ERRORING, InstanceConstants.STATE_STOPPING, InstanceConstants.STATE_STOPPED);
        for (Instance dependant : dependants) {
            if (!invalidStates.contains(dependant.getState())) {
                objectProcessManager.scheduleProcessInstance(InstanceConstants.PROCESS_STOP, dependant, null);

            }
        }

        return null;
    }
}