text:
import TestContainer from 'mocha-test-container-support';

import {
  assign
} from 'min-dash';

import {
  domify
} from 'min-dom';

import modelingModule from 'lib/features/modeling';
import keyboardModule from 'lib/features/keyboard';

import {
  bootstrapDiagram,
  inject
} from 'test/TestHelper';

import { createKeyEvent } from 'test/util/KeyEvents';

describe('features/keyboard', function() {

  var TEST_KEY = 'Numpad3';

  var defaultDiagramConfig = {
    modules: [
      modelingModule,
      keyboardModule
    ],
    canvas: {
      deferUpdate: false
    }
  };

  beforeEach(bootstrapDiagram(defaultDiagramConfig));

  it('should bootstrap diagram with keyboard', inject(function(keyboard) {
    expect(keyboard).to.exist;
  }));

  describe('keyboard binding', function() {

    var keyboardConfig = {
      keyboard: {
        bindTo: document
      }
    };

    beforeEach(bootstrapDiagram(assign(defaultDiagramConfig, keyboardConfig)));

    it('should integrate with <attach> + <detach> events', inject(
      function(keyboard, eventBus) {

        // assume
        expect(keyboard._node).not.to.exist;

        // when
        eventBus.fire('attach');

        expect(keyboard._node).to.eql(document);

        // but when
        eventBus.fire('detach');

        expect(keyboard._node).not.to.exist;
      }
    ));

  });

  describe('keydown event listener handling', function() {

    var testDiv;

    beforeEach(function() {

      var testContainer = TestContainer.get(this);

      testDiv = document.createElement('div');
      testDiv.setAttribute('class', 'testClass');
      testContainer.appendChild(testDiv);
    });

    it('should bind keyboard events to node', inject(function(keyboard) {

      // given
      var keyHandlerSpy = sinon.spy(keyboard, '_keyHandler');

      // when
      keyboard.bind(testDiv);

      // then
      dispatchKeyboardEvent(testDiv, 'keydown');

      expect(keyHandlerSpy).to.have.been.called;
    }));

    it('should unbind keyboard events to node', inject(function(keyboard) {

      // given
      var keyHandlerSpy = sinon.spy(keyboard, '_keyHandler');

      keyboard.bind(testDiv);

      // when
      keyboard.unbind();

      // then
      dispatchKeyboardEvent(testDiv, 'keydown');

      expect(keyHandlerSpy).not.to.have.been.called;
    }));

    it('should unbind regardless of not being bound', inject(function(keyboard) {

      // when
      keyboard.unbind();
    }));

    it('should return node', inject(function(keyboard) {

      // given
      keyboard.bind(testDiv);

      // when
      var binding = keyboard.getBinding();

      // then
      expect(binding).to.equal(testDiv);
    }));

    describe('should ignore input field targets', function() {

      it('non-modifier event', inject(
        function(keyboard, eventBus) {

          // given
          var eventBusSpy = sinon.spy(eventBus, 'fire');

          var inputField = document.createElement('input');
          testDiv.appendChild(inputField);

          // when
          keyboard._keyHandler({ key: TEST_KEY, target: inputField });
          keyboard._keyHandler({ key: TEST_KEY, shiftKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.not.be.called;
        })
      );

      it('modifier event', inject(
        function(keyboard, eventBus) {

          // given
          var eventBusSpy = sinon.spy(eventBus, 'fire');

          var inputField = document.createElement('input');
          testDiv.appendChild(inputField);

          // when
          keyboard._keyHandler({ key: TEST_KEY, metaKey: true, target: inputField });
          keyboard._keyHandler({ key: TEST_KEY, ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.not.be.called;
        })
      );

    });

    it('should ignore propagation stopped events', inject(
      function(keyboard, eventBus) {

        // given
        var keyListener = sinon.spy();

        keyboard.bind(testDiv);

        eventBus.on('keyboard.keydown', keyListener);
        eventBus.on('keyboard.keyup', keyListener);

        var testEl = domify('

');

        testEl.addEventListener('keydown', function(event) {
          event.stopPropagation();
        });

        testEl.addEventListener('keyup', function(event) {
          event.stopPropagation();
        });

        testDiv.appendChild(testEl);

        // when
        dispatchKeyboardEvent(testEl, 'keydown');
        dispatchKeyboardEvent(testEl, 'keyup');

        // then
        expect(keyListener).not.to.be.called;
      })
    );

    it('should ignore default prevented events', inject(
      function(keyboard, eventBus) {

        // given
        var keyListener = sinon.spy();

        keyboard.bind(testDiv);

        eventBus.on('keyboard.keydown', keyListener);
        eventBus.on('keyboard.keyup', keyListener);

        var testEl = domify('

');

        testEl.addEventListener('keydown', function(event) {
          event.preventDefault();
        });

        testEl.addEventListener('keyup', function(event) {
          event.preventDefault();
        });

        testDiv.appendChild(testEl);

        // when
        dispatchKeyboardEvent(testEl, 'keydown');
        dispatchKeyboardEvent(testEl, 'keyup');

        // then
        expect(keyListener).not.to.be.called;
      })
    );

    describe('input-handle-modified-keys property', function() {

      it('should fire modifier event if requesting it', inject(
        function(keyboard, eventBus) {

          // given
          var eventBusSpy = sinon.spy(eventBus, 'fire');

          var inputField = domify('<input></input>');
          testDiv.appendChild(inputField);
          testDiv.setAttribute('input-handle-modified-keys', 'a');

          // when
          keyboard._keyHandler({ key: 'a', metaKey: true, target: inputField });
          keyboard._keyHandler({ key: 'a', ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.have.been.calledTwice;
        })
      );

      it('should not fire modifier event if not requested', inject(
        function(keyboard, eventBus) {

          // given
          var eventBusSpy = sinon.spy(eventBus, 'fire');

          var inputField = domify('<input></input>');
          testDiv.appendChild(inputField);
          testDiv.setAttribute('input-handle-modified-keys', 'a');

          // when
          keyboard._keyHandler({ key: 'b', metaKey: true, target: inputField });
          keyboard._keyHandler({ key: 'b', ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.not.be.called;
        })
      );

      it('should override handled keys', inject(
        function(keyboard, eventBus) {

          // given
          var eventBusSpy = sinon.spy(eventBus, 'fire');

          var inputField = domify('<input input-handle-modified-keys="b"></input>');
          testDiv.appendChild(inputField);
          testDiv.setAttribute('input-handle-modified-keys', 'a');

          // when
          keyboard._keyHandler({ key: 'a', metaKey: true, target: inputField });
          keyboard._keyHandler({ key: 'a', ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.not.be.called;

          // when
          keyboard._keyHandler({ key: 'b', metaKey: true, target: inputField });
          keyboard._keyHandler({ key: 'b', ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.have.been.calledTwice;
        })
      );

      it('should not fire modifier event if the requesting element is outside of binding', inject(
        function(keyboard, eventBus) {

          // given
          var inputContainer = domify('
<input />
'),
              inputField = inputContainer.querySelector('input');

          testDiv.appendChild(inputContainer);
          testDiv.setAttribute('input-handle-modified-keys', 'a');

          keyboard.bind(inputContainer);

          var eventBusSpy = sinon.spy(eventBus, 'fire');

          // when
          keyboard._keyHandler({ key: 'a', metaKey: true, target: inputField });
          keyboard._keyHandler({ key: 'a', ctrlKey: true, target: inputField });

          // then
          expect(eventBusSpy).to.not.be.called;
        })
      );

    });

  });

  describe('add listener', function() {

    it('should add keydown listener by default', inject(function(keyboard) {

      // given
      var keydownSpy = sinon.spy();

      // when
      keyboard.addListener(keydownSpy);

      var event = createKeyEvent(TEST_KEY);

      keyboard._keydownHandler(event);

      // then
      expect(keydownSpy).to.have.been.called;
    }));

    it('should add keyup listener', inject(function(keyboard) {

      // given
      var keyupSpy = sinon.spy();

      // when
      keyboard.addListener(keyupSpy, 'keyboard.keyup');

      var event = createKeyEvent(TEST_KEY, { type: 'keyup' });

      keyboard._keyupHandler(event);

      // then
      expect(keyupSpy).to.have.been.called;
    }));

    it('should handle listeners by priority', inject(function(keyboard) {

      // given
      var lowerPrioritySpy = sinon.spy();
      var higherPrioritySpy = sinon.stub().returns(true);

      keyboard.addListener(500, lowerPrioritySpy);
      keyboard.addListener(1000, higherPrioritySpy);

      var event = createKeyEvent(TEST_KEY);

      // when
      keyboard._keyHandler(event);

      // then
      expect(higherPrioritySpy).to.be.called;
      expect(lowerPrioritySpy).to.not.be.called;
    }));

    it('should invoke listener of lower priority if key was not handled', inject(
      function(keyboard) {

        // given
        var lowerPrioritySpy = sinon.spy();
        var higherPrioritySpy = sinon.spy();

        keyboard.addListener(500, lowerPrioritySpy);
        keyboard.addListener(1000, higherPrioritySpy);

        var event = createKeyEvent(TEST_KEY);

        // when
        keyboard._keyHandler(event);

        // then
        expect(higherPrioritySpy).to.be.called;
        expect(lowerPrioritySpy).to.be.called;
      }
    ));

    it('should allow to add event listener by passing bare function', inject(
      function(keyboard) {

        // given
        var keyboardEventSpy = sinon.spy();

        keyboard.addListener(keyboardEventSpy);

        var event = createKeyEvent(TEST_KEY);

        // when
        keyboard._keyHandler(event);

        // then
        expect(keyboardEventSpy).to.be.called;
      }
    ));

    it('should prevent default if listener returned true', inject(
      function(keyboard) {

        // given
        var keyboardEventStub = sinon.stub().returns(true);

        keyboard.addListener(keyboardEventStub);

        var event = createKeyEvent(TEST_KEY);

        // when
        keyboard._keyHandler(event);

        // then
        expect(keyboardEventStub).to.be.called;

        expect(event.defaultPrevented).to.be.true;
      }
    ));

  });

  describe('remove listener', function() {

    it('should remove keydown listener by default', inject(function(keyboard) {

      // given
      var keydownSpy = sinon.spy();

      keyboard.addListener(keydownSpy);

      // when
      keyboard.removeListener(keydownSpy);

      // then
      var event = createKeyEvent(TEST_KEY);

      keyboard._keydownHandler(event);

      // then
      expect(keydownSpy).not.to.have.been.called;
    }));

    it('should remove keyup listener', inject(function(keyboard) {

      // given
      var keyupSpy = sinon.spy();

      keyboard.addListener(keyupSpy, 'keyboard.keyup');

      // when
      keyboard.removeListener(keyupSpy, 'keyboard.keyup');

      var event = createKeyEvent(TEST_KEY, { type: 'keyup' });

      keyboard._keyupHandler(event);

      // then
      expect(keyupSpy).not.to.have.been.called;
    }));

  });

});

// helpers //////////

function dispatchKeyboardEvent(target, type) {
  var event = createKeyEvent('KeyA', { type });

  target.dispatchEvent(event);
}


text:
require 'simple_json_api/member/data'
require 'simple_json_api/member/included'
require 'simple_json_api/member/links'
require 'simple_json_api/member/meta'

module SimpleJsonApi
  # JSONAPI Wrapper
  class JsonApiWrapper
    def initialize(root_node, page)
      @root_node = root_node
      @page = page
      @result = {}
    end

    def as_json(_options = nil)
      add_members
      @result.delete_if { |key, content| content.blank? && key != :data }
      @result
    end

    private

    def add_members
      links
      meta
      data
      included
    end

    def links
      page = @root_node.collection? ? @page : {}
      @result[:links] ||= Member::Links.new(@root_node, page).content
    end

    def meta
      @result[:meta] ||= Member::Meta.new.content
    end

    def data
      @result[:data] ||= Member::Data.new(@root_node).content
    end

    def included
      @result[:included] ||=
        Member::Included.new(@root_node, @result[:data]).content
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
"""
Extended Api Namespace implementation with an application-specific helpers
--------------------------------------------------------------------------
"""
from contextlib import contextmanager
from functools import wraps

import flask_marshmallow
import sqlalchemy
from werkzeug.exceptions import HTTPException

from flask_restplus_patched import Namespace as BaseNamespace

from . import http_exceptions
from .webargs_parser import CustomWebargsParser

class Namespace(BaseNamespace):
    """
    Having app-specific handlers here.
    """

    WEBARGS_PARSER = CustomWebargsParser()

    def resolve_object_by_model(self, model, object_arg_name, identity_arg_name=None):
        """
        A helper decorator to resolve DB record instance by id.

        Arguments:
            model (type) - a Flask-SQLAlchemy model class with
                ``query.get_or_404`` method
            object_arg_name (str) - argument name for a resolved object
            identity_arg_name (str) - argument name holding an object identity,
                by default it will be auto-generated as
                ``%(object_arg_name)s_id``.

        Example:
        >>> @namespace.resolve_object_by_model(User, 'user')
        ... def get_user_by_id(user):
        ...     return user
        >>> get_user_by_id(user_id=3)
        <User(id=3, ...)>
        """
        if identity_arg_name is None:
            identity_arg_name = '%s_id' % object_arg_name
        return self.resolve_object(
            object_arg_name,
            resolver=lambda kwargs: model.query.get_or_404(kwargs.pop(identity_arg_name))
        )

    def model(self, name=None, model=None, **kwargs):
        """
        A decorator which registers a model (aka schema / definition).

        This extended implementation auto-generates a name for
        ``Flask-Marshmallow.Schema``-based instances by using a class name
        with stripped off `Schema` prefix.
        """
        if isinstance(model, flask_marshmallow.Schema) and not name:
            name = model.__class__.__name__
            if name.endswith('Schema'):
                name = name[:-len('Schema')]
        return super(Namespace, self).model(name=name, model=model, **kwargs)

    def login_required(self, oauth_scopes):
        """
        A decorator which restricts access for authorized users only.

        This decorator automatically applies the following features:

        * ``OAuth2.require_oauth`` decorator requires authentication;
        * ``permissions.ActiveUserRolePermission`` decorator ensures
          minimal authorization level;
        * All of the above requirements are put into OpenAPI Specification with
          relevant options and in a text description.

        Arguments:
            oauth_scopes (list) - a list of required OAuth2 Scopes (strings)

        Example:
        >>> class Users(Resource):
        ...     @namespace.login_required(oauth_scopes=['users:read'])
        ...     def get(self):
        ...         return []
        ...
        >>> @namespace.login_required(oauth_scopes=['users:read'])
        ... class Users(Resource):
        ...     def get(self):
        ...         return []
        ...
        ...     @namespace.login_required(oauth_scopes=['users:write'])
        ...     def post(self):
        ...         return User()
        ...
        >>> @namespace.login_required(oauth_scopes=[])
        ... class Users(Resource):
        ...     @namespace.login_required(oauth_scopes=['users:read'])
        ...     def get(self):
        ...         return []
        ...
        ...     @namespace.login_required(oauth_scopes=['users:write'])
        ...     def post(self):
        ...         return User()
        """
        def decorator(func_or_class):
            """
            A helper wrapper.
            """
            if isinstance(func_or_class, type):
                # Handle Resource classes decoration
                # pylint: disable=protected-access
                func_or_class._apply_decorator_to_methods(decorator)
                return func_or_class
            else:
                func = func_or_class

            # Avoid circilar dependency
            from app.extensions import oauth2
            from app.modules.users import permissions

            # Automatically apply `permissions.ActiveUserRolePermisson`
            # guard if none is yet applied.
            if getattr(func, '_role_permission_applied', False):
                protected_func = func
            else:
                protected_func = self.permission_required(
                    permissions.ActiveUserRolePermission()
                )(func)

            # Ignore the current OAuth2 scopes if another @login_required
            # decorator was applied and just copy the already applied scopes.
            if hasattr(protected_func, '__apidoc__') \
                    and 'security' in protected_func.__apidoc__ \
                    and '__oauth__' in protected_func.__apidoc__['security']:
                _oauth_scopes = protected_func.__apidoc__['security']['__oauth__']['scopes']
            else:
                _oauth_scopes = oauth_scopes

            oauth_protection_decorator = oauth2.require_oauth(*_oauth_scopes)
            self._register_access_restriction_decorator(protected_func, oauth_protection_decorator)
            oauth_protected_func = oauth_protection_decorator(protected_func)

            return self.doc(
                security={
                    # This is a temporary configuration which is overriden in
                    # `Api.add_namespace`.
                    '__oauth__': {
                        'type': 'oauth',
                        'scopes': _oauth_scopes,
                    }
                }
            )(
                self.response(
                    code=http_exceptions.Unauthorized.code,
                    description=(
                        "Authentication is required"
                        if not oauth_scopes else
                        "Authentication with %s OAuth scope(s) is required" % (
                            ', '.join(oauth_scopes)
                        )
                    ),
                )(oauth_protected_func)
            )

        return decorator

    def permission_required(self, permission, kwargs_on_request=None):
        """
        A decorator which restricts access for users with a specific
        permissions only.

        This decorator puts together permissions restriction code with OpenAPI
        Specification documentation.

        Arguments:
            permission (Permission) - it can be a class or an instance of
                :class:``Permission``, which will be applied to a decorated
                function, and docstrings of which will be used in OpenAPI
                Specification.
            kwargs_on_request (func) - a function which should accept only one
                ``dict`` argument (all kwargs passed to the function), and
                must return a ``dict`` of arguments which will be passed to
                the ``permission`` object.

        Example:
        >>> @namespace.permission_required(
        ...     OwnerRolePermission,
        ...     kwargs_on_request=lambda kwargs: {'obj': kwargs['team']}
        ... )
        ... def get_team(team):
        ...     # This line will be reached only if OwnerRolePermission check
        ...     # is passed!
        ...     return team
        """
        def decorator(func):
            """
            A helper wrapper.
            """
            # Avoid circilar dependency
            from app.modules.users import permissions

            if getattr(permission, '_partial', False):
                # We don't apply partial permissions, we only use them for
                # documentation purposes.
                protected_func = func
            else:
                if not kwargs_on_request:
                    _permission_decorator = permission
                else:
                    def _permission_decorator(func):
                        @wraps(func)
                        def wrapper(*args, **kwargs):
                            with permission(**kwargs_on_request(kwargs)):
                                return func(*args, **kwargs)
                        return wrapper

                protected_func = _permission_decorator(func)
                self._register_access_restriction_decorator(protected_func, _permission_decorator)

            # Apply `_role_permission_applied` marker for Role Permissions,
            # so don't apply unnecessary permissions in `login_required`
            # decorator.
            #
            # TODO: Change this behaviour when implement advanced OPTIONS
            # method support
            if (
                    isinstance(permission, permissions.RolePermission)
                    or
                    (
                        isinstance(permission, type)
                        and
                        issubclass(permission, permissions.RolePermission)
                    )
            ):
                protected_func._role_permission_applied = True  # pylint: disable=protected-access

            permission_description = permission.__doc__.strip()
            return self.doc(
                description="**PERMISSIONS: %s**\n\n" % permission_description
            )(
                self.response(
                    code=http_exceptions.Forbidden.code,
                    description=permission_description,
                )(protected_func)
            )

        return decorator

    def _register_access_restriction_decorator(self, func, decorator_to_register):
        # pylint: disable=invalid-name
        """
        Helper function to register decorator to function to perform checks
        in options method
        """
        if not hasattr(func, '_access_restriction_decorators'):
            func._access_restriction_decorators = []  # pylint: disable=protected-access
        func._access_restriction_decorators.append(decorator_to_register)  # pylint: disable=protected-access

    @contextmanager
    def commit_or_abort(self, session, default_error_message="The operation failed to complete"):
        """
        Context manager to simplify a workflow in resources

        Args:
            session: db.session instance
            default_error_message: Custom error message

        Exampple:
        >>> with api.commit_or_abort(db.session):
        ...     team = Team(**args)
        ...     db.session.add(team)
        ...     return team
        """
        try:
            try:
                yield session
                session.commit()
            except ValueError as exception:
                http_exceptions.abort(code=http_exceptions.Conflict.code, message=str(exception))
            except sqlalchemy.exc.IntegrityError:
                http_exceptions.abort(
                    code=http_exceptions.Conflict.code,
                    message=default_error_message
                )
        except HTTPException:
            session.rollback()
            raise


text:
package function.external.discovehr;

import global.Data;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.commons.csv.CSVRecord;
import utils.ErrorManager;
import utils.FormatManager;

/**
 *
 * @author nick
 */
public class DiscovEHR {

    private String chr;
    private int pos;
    private String ref;
    private String alt;
    private float af;

    public DiscovEHR(String chr, int pos, String ref, String alt) {
        this.chr = chr;
        this.pos = pos;
        this.ref = ref;
        this.alt = alt;

        initAF();
    }

    public DiscovEHR(ResultSet rs) {
        try {
            chr = rs.getString("chr");
            pos = rs.getInt("pos");
            ref = rs.getString("ref_allele");
            alt = rs.getString("alt_allele");

            initAF();
        } catch (Exception e) {
            ErrorManager.send(e);
        }
    }

    public DiscovEHR(CSVRecord record) {
        af = FormatManager.getFloat(record, "DiscovEHR AF");
    }

    private void initAF() {
        try {
            PreparedStatement preparedStatement = DiscovEHRManager.getPreparedStatement4Variant();
            preparedStatement.setString(1, chr);
            preparedStatement.setInt(2, pos);
            preparedStatement.setString(3, ref);
            preparedStatement.setString(4, alt);
            ResultSet rs = preparedStatement.executeQuery();
            if (rs.next()) {
                af = rs.getFloat("af");
            } else {
                af = Data.FLOAT_NA;
            }

            rs.close();
        } catch (Exception e) {
            ErrorManager.send(e);
        }
    }

    public String getVariantId() {
        return chr + "-" + pos + "-" + ref + "-" + alt;
    }

    public boolean isValid() {
        return DiscovEHRCommand.isDiscovEHRAFValid(af);
    }

    @Override
    public String toString() {
        return FormatManager.getFloat(af);
    }
}


text:
require 'test_helper'

class AzActivityFieldTest < ActiveSupport::TestCase
  # Replace this with your real tests.
#  test "the truth" do
#    assert true
#  end
end


text:
#ifndef SZ_LOGGER_
#define SZ_LOGGER_

#include <sstream>
#include <iostream>
#include <fstream>

#include "LogTag.hpp"
#include "Config.hpp"

namespace SZ
{
    template <typename TStream>
    class zstream
    {
        TStream &s;
        LogTag tag;
        std::string clr;

        bool CanLog() const { return Config::Me()->LogLevel() >= tag; }
        bool IsColored() const { return Config::Me()->ColoredLogs(); }
    public:
        zstream(TStream &str, LogTag tag_, std::string clr_)
          : s(str),
            tag(tag_),
            clr(clr_)
        {
        }

        template <typename T>
        zstream<TStream>& operator<<(const T &x)
        {
            if (CanLog())
            {
                bool colored = IsColored();
                if (colored)
                {
                    s << clr;
                }
                s << x;
                if (colored)
                {
                    s << "\033[m";
                }
            }
            return *this;
        }
    };

    template <typename streamType, LogTag tag, LogTarget target>
    class ZLog
    {
        static zstream<streamType> str;

        static std::string TagToString()
        {
            switch (tag)
            {
            case LogTag::Debug: return "debug";
            case LogTag::Info: return "info ";
            case LogTag::Warn: return "warn ";
            case LogTag::Error: return "error";
            default: return "unknown";
            }
        }

    public:
        static zstream<streamType>& S()
        {
            str << "\n[" << TagToString() << "] ";
            return str;
        }

        static zstream<streamType>& S_(const char *file, int line)
        {
            str << "\n[" << TagToString() << " " << file << "@" << line << "] ";
            return str;
        }
    };

    std::string LogColor(const LogTag &tag);
    std::ostream &LogStream(LogTarget target);

    template <typename streamType, LogTag tag, LogTarget target>
    zstream<streamType> ZLog<streamType, tag, target>::str(LogStream(target), tag, LogColor(tag));

}

#define ZLOGTARGET SZ::LogTarget::Console

#define ZLOGX(tag) (SZ::ZLog<std::ostream, tag, ZLOGTARGET>::S_(__FILE__, __LINE__))
#define ZLOGD() ZLOGX(SZ::LogTag::Debug)
#define ZLOGI() ZLOGX(SZ::LogTag::Info)
#define ZLOGW() ZLOGX(SZ::LogTag::Warn)
#define ZLOGE() ZLOGX(SZ::LogTag::Error)

#endif // SZ_LOGGER_


text:
package models.Stat;

public class Mana extends Secondary {
    // currently based off Intellect and Level
    public Mana(Stat stat_one, Stat stat_two) {
        setName("Mana");
        setStatOne(stat_one);
        setStatTwo(stat_two);
        calculate();
    }

    //TODO Fix this, causes a crash when initiating a pet
    public void calculate() {
//        setValue(((0.5 * stat_two.value()) + 50 + stat_one.value()) * stat_two.value());
        setValue(400);
    }

    @Override
    public void print() {System.out.println(name() + ": " + (int)value());}
}


text:
package director

// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a
// drop in replacement for FooBarAbstract but the reverse causes a compile time
// error.
type FooBarGo interface {
	FooBarAbstract
	deleteFooBarAbstract()
	IsFooBarGo()
}

// Via embedding fooBarGo "inherits" all methods of FooBarAbstract.
type fooBarGo struct {
	FooBarAbstract
}

func (fbgs *fooBarGo) deleteFooBarAbstract() {
	DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
}

// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract.
// This is also how the class hierarchy gets represented by the SWIG generated
// wrapper code.  For an instance FooBarCpp has the IsFooBarAbstract and
// IsFooBarCpp methods.
func (fbgs *fooBarGo) IsFooBarGo() {}

// Go type that defines the DirectorInterface. It contains the Foo and Bar
// methods that overwrite the respective virtual C++ methods on FooBarAbstract.
type overwrittenMethodsOnFooBarAbstract struct {
	// Backlink to FooBarAbstract so that the rest of the class can be used by
	// the overridden methods.
	fb FooBarAbstract

	// If additional constructor arguments have been given they are typically
	// stored here so that the overriden methods can use them.
}

func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
	// DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo.
	return "Go " + DirectorFooBarAbstractFoo(om.fb)
}

func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
	return "Go Bar"
}

func NewFooBarGo() FooBarGo {
	// Instantiate FooBarAbstract with selected methods overridden.  The methods
	// that will be overwritten are defined on
	// overwrittenMethodsOnFooBarAbstract and have a compatible signature to the
	// respective virtual C++ methods. Furthermore additional constructor
	// arguments will be typically stored in the
	// overwrittenMethodsOnFooBarAbstract struct.
	om := &overwrittenMethodsOnFooBarAbstract{}
	fb := NewDirectorFooBarAbstract(om)
	om.fb = fb // Backlink causes cycle as fb.v = om!

	fbgs := &fooBarGo{FooBarAbstract: fb}
	// The memory of the FooBarAbstract director object instance can be
	// automatically freed once the FooBarGo instance is garbage collected by
	// uncommenting the following line.  Please make sure to understand the
	// runtime.SetFinalizer specific gotchas before doing this.  Furthemore
	// DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo
	// struct needs additional data to prevent double deletion.
	// runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
	return fbgs
}

// Recommended to be removed if runtime.SetFinalizer is in use.
func DeleteFooBarGo(fbg FooBarGo) {
	fbg.deleteFooBarAbstract()
}


text:
package com.ckt.io.wifidirect.utils;

/**
 * Created by admin on 2016/3/9.
 */
public class Movie {
    private String fileName;
    private String title;
    private int duration;
    private String size;
    private String fileUrl;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public Movie() {
        super();
    }

    public Movie(String fileName, String title, int duration, String singer, String album, String size,
                 String fileUrl) {
        super();
        this.fileName = fileName;
        this.title = title;
        this.duration = duration;
        this.size = size;
        this.fileUrl = fileUrl;
    }

    @Override
    public String toString() {
        return fileName;
    }
}


text:
@implementation KWCaptureSpy
@dynamic argument;

- (id)initWithArgumentIndex:(NSUInteger)index {
    if ((self = [super init])) {
        _argumentIndex = index;
    }
    return self;
}

- (id)argument {
    if (!_argument) {
        @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Argument requested has yet to be captured." userInfo:nil];
    }
    return [[_argument retain] autorelease];
}

- (void)object:(id)anObject didReceiveInvocation:(NSInvocation *)anInvocation {
    if (!_argument) {
        NSMethodSignature *signature = [anInvocation methodSignature];
        const char *objCType = [signature messageArgumentTypeAtIndex:_argumentIndex];
        if (KWObjCTypeIsObject(objCType)) {
            id argument = nil;
            [anInvocation getMessageArgument:&argument atIndex:_argumentIndex];
            if (KWObjCTypeIsBlock(objCType)) {
                _argument = [argument copy];
            } else {
                _argument = [argument retain];
            }
        } else {
            NSData *data = [anInvocation messageArgumentDataAtIndex:_argumentIndex];
            _argument = [[KWValue valueWithBytes:[data bytes] objCType:objCType] retain];
        }
    }
}

- (void)dealloc {
    [_argument release];
    [super dealloc];
}
@end


text:
#include <linux/kernel.h>
#include <linux/initrd.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/seq_file.h>
#define PCI_DEBUG
#include <linux/pci.h>
#undef PCI_DEBUG
#include <linux/proc_fs.h>

#include <asm/processor.h>
#include <asm/pdc.h>
#include <asm/led.h>
#include <asm/machdep.h>	/* for pa7300lc_init() proto */
#include <asm/pdc_chassis.h>
#include <asm/io.h>
#include <asm/setup.h>
#include <asm/unwind.h>

static char __initdata command_line[COMMAND_LINE_SIZE];

/* Intended for ccio/sba/cpu statistics under /proc/bus/{runway|gsc} */
struct proc_dir_entry * proc_runway_root __read_mostly = NULL;
struct proc_dir_entry * proc_gsc_root __read_mostly = NULL;
struct proc_dir_entry * proc_mckinley_root __read_mostly = NULL;

#if !defined(CONFIG_PA20) && (defined(CONFIG_IOMMU_CCIO) || defined(CONFIG_IOMMU_SBA))
int parisc_bus_is_phys __read_mostly = 1;	/* Assume no IOMMU is present */
EXPORT_SYMBOL(parisc_bus_is_phys);
#endif

void __init setup_cmdline(char **cmdline_p)
{
	extern unsigned int boot_args[];

	/* Collect stuff passed in from the boot loader */

	/* boot_args[0] is free-mem start, boot_args[1] is ptr to command line */
	if (boot_args[0] < 64) {
		/* called from hpux boot loader */
		boot_command_line[0] = '\0';
	} else {
		strcpy(boot_command_line, (char *)__va(boot_args[1]));

#ifdef CONFIG_BLK_DEV_INITRD
		if (boot_args[2] != 0) /* did palo pass us a ramdisk? */
		{
		    initrd_start = (unsigned long)__va(boot_args[2]);
		    initrd_end = (unsigned long)__va(boot_args[3]);
		}
#endif
	}

	strcpy(command_line, boot_command_line);
	*cmdline_p = command_line;
}

#ifdef CONFIG_PA11
void __init dma_ops_init(void)
{
	switch (boot_cpu_data.cpu_type) {
	case pcx:
		/*
		 * We've got way too many dependencies on 1.1 semantics
		 * to support 1.0 boxes at this point.
		 */
		panic(	"PA-RISC Linux currently only supports machines that conform to\n"
			"the PA-RISC 1.1 or 2.0 architecture specification.\n");

	case pcxs:
	case pcxt:
		hppa_dma_ops = &pcx_dma_ops;
		break;
	case pcxl2:
		pa7300lc_init();
	case pcxl: /* falls through */
		hppa_dma_ops = &pcxl_dma_ops;
		break;
	default:
		break;
	}
}
#endif

extern int init_per_cpu(int cpuid);
extern void collect_boot_cpu_data(void);

void __init setup_arch(char **cmdline_p)
{
#ifdef CONFIG_64BIT
	extern int parisc_narrow_firmware;
#endif
	unwind_init();

	init_per_cpu(smp_processor_id());	/* Set Modes & Enable FP */

#ifdef CONFIG_64BIT
	printk(KERN_INFO "The 64-bit Kernel has started...\n");
#else
	printk(KERN_INFO "The 32-bit Kernel has started...\n");
#endif

	pdc_console_init();

#ifdef CONFIG_64BIT
	if(parisc_narrow_firmware) {
		printk(KERN_INFO "Kernel is using PDC in 32-bit mode.\n");
	}
#endif
	setup_pdc();
	setup_cmdline(cmdline_p);
	collect_boot_cpu_data();
	do_memory_inventory();  /* probe for physical memory */
	parisc_cache_init();
	paging_init();

#ifdef CONFIG_CHASSIS_LCD_LED
	/* initialize the LCD/LED after boot_cpu_data is available ! */
	led_init();		/* LCD/LED initialization */
#endif

#ifdef CONFIG_PA11
	dma_ops_init();
#endif

#if defined(CONFIG_VT) && defined(CONFIG_DUMMY_CONSOLE)
	conswitchp = &dummy_con;	/* we use take_over_console() later ! */
#endif

}

/*
 * Display CPU info for all CPUs.
 * for parisc this is in processor.c
 */
extern int show_cpuinfo (struct seq_file *m, void *v);

static void *
c_start (struct seq_file *m, loff_t *pos)
{
    	/* Looks like the caller will call repeatedly until we return
	 * 0, signaling EOF perhaps.  This could be used to sequence
	 * through CPUs for example.  Since we print all cpu info in our
	 * show_cpuinfo() disregarding 'pos' (which I assume is 'v' above)
	 * we only allow for one "position".  */
	return ((long)*pos < 1) ? (void *)1 : NULL;
}

static void *
c_next (struct seq_file *m, void *v, loff_t *pos)
{
	++*pos;
	return c_start(m, pos);
}

static void
c_stop (struct seq_file *m, void *v)
{
}

const struct seq_operations cpuinfo_op = {
	.start	= c_start,
	.next	= c_next,
	.stop	= c_stop,
	.show	= show_cpuinfo
};

static void __init parisc_proc_mkdir(void)
{
	/*
	** Can't call proc_mkdir() until after proc_root_init() has been
	** called by start_kernel(). In other words, this code can't
	** live in arch/.../setup.c because start_parisc() calls
	** start_kernel().
	*/
	switch (boot_cpu_data.cpu_type) {
	case pcxl:
	case pcxl2:
		if (NULL == proc_gsc_root)
		{
			proc_gsc_root = proc_mkdir("bus/gsc", NULL);
		}
		break;
        case pcxt_:
        case pcxu:
        case pcxu_:
        case pcxw:
        case pcxw_:
        case pcxw2:
                if (NULL == proc_runway_root)
                {
                        proc_runway_root = proc_mkdir("bus/runway", NULL);
                }
                break;
	case mako:
	case mako2:
                if (NULL == proc_mckinley_root)
                {
                        proc_mckinley_root = proc_mkdir("bus/mckinley", NULL);
                }
                break;
	default:
		/* FIXME: this was added to prevent the compiler
		 * complaining about missing pcx, pcxs and pcxt
		 * I'm assuming they have neither gsc nor runway */
		break;
	}
}

static struct resource central_bus = {
	.name	= "Central Bus",
	.start	= F_EXTEND(0xfff80000),
	.end    = F_EXTEND(0xfffaffff),
	.flags	= IORESOURCE_MEM,
};

static struct resource local_broadcast = {
	.name	= "Local Broadcast",
	.start	= F_EXTEND(0xfffb0000),
	.end	= F_EXTEND(0xfffdffff),
	.flags	= IORESOURCE_MEM,
};

static struct resource global_broadcast = {
	.name	= "Global Broadcast",
	.start	= F_EXTEND(0xfffe0000),
	.end	= F_EXTEND(0xffffffff),
	.flags	= IORESOURCE_MEM,
};

static int __init parisc_init_resources(void)
{
	int result;

	result = request_resource(&iomem_resource, &central_bus);
	if (result < 0) {
		printk(KERN_ERR
		       "%s: failed to claim %s address space!\n",
		       __FILE__, central_bus.name);
		return result;
	}

	result = request_resource(&iomem_resource, &local_broadcast);
	if (result < 0) {
		printk(KERN_ERR
		       "%s: failed to claim %saddress space!\n",
		       __FILE__, local_broadcast.name);
		return result;
	}

	result = request_resource(&iomem_resource, &global_broadcast);
	if (result < 0) {
		printk(KERN_ERR
		       "%s: failed to claim %s address space!\n",
		       __FILE__, global_broadcast.name);
		return result;
	}

	return 0;
}

extern void gsc_init(void);
extern void processor_init(void);
extern void ccio_init(void);
extern void hppb_init(void);
extern void dino_init(void);
extern void iosapic_init(void);
extern void lba_init(void);
extern void sba_init(void);
extern void eisa_init(void);

static int __init parisc_init(void)
{
	u32 osid = (OS_ID_LINUX << 16);

	parisc_proc_mkdir();
	parisc_init_resources();
	do_device_inventory();                  /* probe for hardware */

	parisc_pdc_chassis_init();

	/* set up a new led state on systems shipped LED State panel */
	pdc_chassis_send_status(PDC_CHASSIS_DIRECT_BSTART);

	/* tell PDC we're Linux. Nevermind failure. */
	pdc_stable_write(0x40, &osid, sizeof(osid));

	processor_init();
	printk(KERN_INFO "CPU(s): %d x %s at %d.%06d MHz\n",
			num_present_cpus(),
			boot_cpu_data.cpu_name,
			boot_cpu_data.cpu_hz / 1000000,
			boot_cpu_data.cpu_hz % 1000000	);

	parisc_setup_cache_timing();

	/* These are in a non-obvious order, will fix when we have an iotree */
#if defined(CONFIG_IOSAPIC)
	iosapic_init();
#endif
#if defined(CONFIG_IOMMU_SBA)
	sba_init();
#endif
#if defined(CONFIG_PCI_LBA)
	lba_init();
#endif

	/* CCIO before any potential subdevices */
#if defined(CONFIG_IOMMU_CCIO)
	ccio_init();
#endif

	/*
	 * Need to register Asp & Wax before the EISA adapters for the IRQ
	 * regions.  EISA must come before PCI to be sure it gets IRQ region
	 * 0.
	 */
#if defined(CONFIG_GSC_LASI) || defined(CONFIG_GSC_WAX)
	gsc_init();
#endif
#ifdef CONFIG_EISA
	eisa_init();
#endif

#if defined(CONFIG_HPPB)
	hppb_init();
#endif

#if defined(CONFIG_GSC_DINO)
	dino_init();
#endif

#ifdef CONFIG_CHASSIS_LCD_LED
	register_led_regions();	/* register LED port info in procfs */
#endif

	return 0;
}
arch_initcall(parisc_init);

void start_parisc(void)
{
	extern void start_kernel(void);

	int ret, cpunum;
	struct pdc_coproc_cfg coproc_cfg;

	cpunum = smp_processor_id();

	set_firmware_width_unlocked();

	ret = pdc_coproc_cfg_unlocked(&coproc_cfg);
	if (ret >= 0 && coproc_cfg.ccr_functional) {
		mtctl(coproc_cfg.ccr_functional, 10);

		per_cpu(cpu_data, cpunum).fp_rev = coproc_cfg.revision;
		per_cpu(cpu_data, cpunum).fp_model = coproc_cfg.model;

		asm volatile ("fstd	%fr0,8(%sp)");
	} else {
		panic("must have an fpu to boot linux");
	}

	start_kernel();
	// not reached
}


text:
using System;
using Cassandra.Mapping;
using Cassandra.Mapping.Attributes;

namespace  Cassandra.Tests.Mapping.Pocos
{
    /// <summary>
    /// A user decorated with attributes indicating how it should be mapped, specifically the ExplicitColumnsAttribute.
    /// </summary>
    [Table("users", ExplicitColumns = true)]
    public class ExplicitColumnsUser
    {
        [Column]
        public Guid UserId { get; set; }

        // Should not be mapped since no Column attribute and ExplicitColumns was used
        public string Name { get; set; }

        [Column("age")]
        public int UserAge { get; set; }
    }
}


text:
import contextlib
import datetime

import marathon
import mock

from paasta_tools import bounce_lib
from paasta_tools import utils

class TestBounceLib:

    def fake_system_paasta_config(self):
        return utils.SystemPaastaConfig({"synapse_port": 123456}, "/fake/configs")

    def test_bounce_lock(self):
        import fcntl
        lock_name = 'the_internet'
        lock_file = '/var/lock/%s.lock' % lock_name
        fake_fd = mock.MagicMock(spec=file)
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.open', create=True, return_value=fake_fd),
            mock.patch('fcntl.lockf'),
            mock.patch('os.remove')
        ) as (
            open_patch,
            lockf_patch,
            remove_patch
        ):
            with bounce_lib.bounce_lock(lock_name):
                pass
            open_patch.assert_called_once_with(lock_file, 'w')
            lockf_patch.assert_called_once_with(fake_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            fake_fd.close.assert_called_once_with()
            remove_patch.assert_called_once_with(lock_file)

    def test_bounce_lock_zookeeper(self):
        lock_name = 'watermelon'
        fake_lock = mock.Mock()
        fake_zk = mock.MagicMock(Lock=mock.Mock(return_value=fake_lock))
        fake_zk_hosts = 'awjti42ior'
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.KazooClient', return_value=fake_zk, autospec=True),
            mock.patch(
                'paasta_tools.bounce_lib.load_system_paasta_config',
                return_value=mock.Mock(
                    get_zk_hosts=lambda: fake_zk_hosts
                ),
                autospec=True,
            ),
        ) as (
            client_patch,
            hosts_patch,
        ):
            with bounce_lib.bounce_lock_zookeeper(lock_name):
                pass
            hosts_patch.assert_called_once_with()
            client_patch.assert_called_once_with(hosts=fake_zk_hosts,
                                                 timeout=bounce_lib.ZK_LOCK_CONNECT_TIMEOUT_S)
            fake_zk.start.assert_called_once_with()
            fake_zk.Lock.assert_called_once_with('%s/%s' % (bounce_lib.ZK_LOCK_PATH, lock_name))
            fake_lock.acquire.assert_called_once_with(timeout=1)
            fake_lock.release.assert_called_once_with()
            fake_zk.stop.assert_called_once_with()

    def test_create_marathon_app(self):
        marathon_client_mock = mock.create_autospec(marathon.MarathonClient)
        fake_client = marathon_client_mock
        fake_config = {'id': 'fake_creation'}
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.create_app_lock', spec=contextlib.contextmanager),
            mock.patch('paasta_tools.bounce_lib.wait_for_create'),
        ) as (
            lock_patch,
            wait_patch,
        ):
            bounce_lib.create_marathon_app('fake_creation', fake_config, fake_client)
            assert lock_patch.called
            assert fake_client.create_app.call_count == 1
            actual_call_args = fake_client.create_app.call_args
            actual_config = actual_call_args[0][1]
            assert actual_config.id == 'fake_creation'
            wait_patch.assert_called_once_with(fake_config['id'], fake_client)

    def test_delete_marathon_app(self):
        fake_client = mock.Mock(delete_app=mock.Mock())
        fake_id = 'fake_deletion'
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.create_app_lock', spec=contextlib.contextmanager),
            mock.patch('paasta_tools.bounce_lib.wait_for_delete'),
            mock.patch('time.sleep')
        ) as (
            lock_patch,
            wait_patch,
            sleep_patch
        ):
            bounce_lib.delete_marathon_app(fake_id, fake_client)
            fake_client.scale_app.assert_called_once_with(fake_id, instances=0, force=True)
            fake_client.delete_app.assert_called_once_with(fake_id, force=True)
            sleep_patch.assert_called_once_with(1)
            wait_patch.assert_called_once_with(fake_id, fake_client)
            assert lock_patch.called

    def test_kill_old_ids(self):
        old_ids = ['mmm.whatcha.say', 'that.you', 'only.meant.well']
        fake_client = mock.MagicMock()
        with mock.patch('paasta_tools.bounce_lib.delete_marathon_app') as delete_patch:
            bounce_lib.kill_old_ids(old_ids, fake_client)
            for old_id in old_ids:
                delete_patch.assert_any_call(old_id, fake_client)
            assert delete_patch.call_count == len(old_ids)

    def test_wait_for_create_slow(self):
        fake_id = 'my_created'
        fake_client = mock.Mock(spec='paasta_tools.setup_marathon_job.MarathonClient')
        fake_is_app_running_values = [False, False, True]
        with contextlib.nested(
            mock.patch('paasta_tools.marathon_tools.is_app_id_running'),
            mock.patch('time.sleep'),
        ) as (
            is_app_id_running_patch,
            sleep_patch,
        ):
            is_app_id_running_patch.side_effect = fake_is_app_running_values
            bounce_lib.wait_for_create(fake_id, fake_client)
        assert sleep_patch.call_count == 2
        assert is_app_id_running_patch.call_count == 3

    def test_wait_for_create_fast(self):
        fake_id = 'my_created'
        fake_client = mock.Mock(spec='paasta_tools.setup_marathon_job.MarathonClient')
        fake_is_app_running_values = [True]
        with contextlib.nested(
            mock.patch('paasta_tools.marathon_tools.is_app_id_running'),
            mock.patch('time.sleep'),
        ) as (
            is_app_id_running_patch,
            sleep_patch,
        ):
            is_app_id_running_patch.side_effect = fake_is_app_running_values
            bounce_lib.wait_for_create(fake_id, fake_client)
        assert sleep_patch.call_count == 0
        assert is_app_id_running_patch.call_count == 1

    def test_wait_for_delete_slow(self):
        fake_id = 'my_deleted'
        fake_client = mock.Mock(spec='paasta_tools.setup_marathon_job.MarathonClient')
        fake_is_app_running_values = [True, True, False]
        with contextlib.nested(
            mock.patch('paasta_tools.marathon_tools.is_app_id_running'),
            mock.patch('time.sleep'),
        ) as (
            is_app_id_running_patch,
            sleep_patch,
        ):
            is_app_id_running_patch.side_effect = fake_is_app_running_values
            bounce_lib.wait_for_delete(fake_id, fake_client)
        assert sleep_patch.call_count == 2
        assert is_app_id_running_patch.call_count == 3

    def test_wait_for_delete_fast(self):
        fake_id = 'my_deleted'
        fake_client = mock.Mock(spec='paasta_tools.setup_marathon_job.MarathonClient')
        fake_is_app_running_values = [False]
        with contextlib.nested(
            mock.patch('paasta_tools.marathon_tools.is_app_id_running'),
            mock.patch('time.sleep'),
        ) as (
            is_app_id_running_patch,
            sleep_patch,
        ):
            is_app_id_running_patch.side_effect = fake_is_app_running_values
            bounce_lib.wait_for_delete(fake_id, fake_client)
        assert sleep_patch.call_count == 0
        assert is_app_id_running_patch.call_count == 1

    def test_get_bounce_method_func(self):
        actual = bounce_lib.get_bounce_method_func('brutal')
        expected = bounce_lib.brutal_bounce
        assert actual == expected

    def test_get_happy_tasks_when_running_without_healthchecks_defined(self):
        """All running tasks with no health checks results are healthy if the app does not define healthchecks"""
        tasks = [mock.Mock(health_check_results=[]) for _ in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        assert bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config()) == tasks

    def test_get_happy_tasks_when_running_with_healthchecks_defined(self):
        """All running tasks with no health check results are unhealthy if the app defines healthchecks"""
        tasks = [mock.Mock(health_check_results=[]) for _ in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=["fake_healthcheck_definition"])
        assert bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config()) == []

    def test_get_happy_tasks_when_all_healthy(self):
        """All tasks with only passing healthchecks should be happy"""
        tasks = [mock.Mock(health_check_results=[mock.Mock(alive=True)]) for _ in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        assert bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config()) == tasks

    def test_get_happy_tasks_when_some_unhealthy(self):
        """Only tasks with a passing healthcheck should be happy"""
        fake_failing_healthcheck_results = [mock.Mock(alive=False)]
        fake_successful_healthcheck_results = [mock.Mock(alive=True)]
        tasks = [mock.Mock(health_check_results=fake_failing_healthcheck_results),
                 mock.Mock(health_check_results=fake_failing_healthcheck_results),
                 mock.Mock(health_check_results=fake_successful_healthcheck_results)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config())
        expected = tasks[-1:]
        assert actual == expected

    def test_get_happy_tasks_with_multiple_healthchecks_success(self):
        """All tasks with at least one passing healthcheck should be happy"""
        fake_successful_healthcheck_results = [mock.Mock(alive=True), mock.Mock(alive=False)]
        tasks = [mock.Mock(health_check_results=fake_successful_healthcheck_results)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        assert bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config()) == tasks

    def test_get_happy_tasks_with_multiple_healthchecks_fail(self):
        """Only tasks with at least one passing healthcheck should be happy"""
        fake_successful_healthcheck_results = [mock.Mock(alive=False), mock.Mock(alive=False)]
        tasks = [mock.Mock(health_check_results=fake_successful_healthcheck_results)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        assert bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config()) == []

    def test_get_happy_tasks_min_task_uptime(self):
        """If we specify a minimum task age, tasks newer than that should not be considered happy."""
        now = datetime.datetime(2000, 1, 1, 0, 0, 0)
        tasks = [mock.Mock(health_check_results=[], started_at=(now - datetime.timedelta(minutes=i)))
                 for i in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])

        # I would have just mocked datetime.datetime.utcnow, but that's apparently difficult; I have to mock
        # datetime.datetime instead, and give it a utcnow attribute.
        with mock.patch('paasta_tools.bounce_lib.datetime.datetime', utcnow=lambda: now, autospec=True):
            actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config(),
                                                min_task_uptime=121)
            expected = tasks[3:]
            assert actual == expected

    def test_get_happy_tasks_min_task_uptime_when_unhealthy(self):
        """If we specify a minimum task age, tasks newer than that should not be considered happy."""
        now = datetime.datetime(2000, 1, 1, 0, 0, 0)
        tasks = [mock.Mock(health_check_results=[mock.Mock(alive=False)],
                           started_at=(now - datetime.timedelta(minutes=i)))
                 for i in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])

        with mock.patch('paasta_tools.bounce_lib.datetime.datetime', utcnow=lambda: now, autospec=True):
            actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config(),
                                                min_task_uptime=121)
            expected = []
            assert actual == expected

    def test_get_happy_tasks_check_haproxy(self):
        """If we specify that a task should be in haproxy, don't call it happy unless it's in haproxy."""

        tasks = [mock.Mock(health_check_results=[mock.Mock(alive=True)]) for i in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.get_registered_marathon_tasks', return_value=tasks[2:], autospec=True),
            mock.patch('paasta_tools.mesos_tools.get_mesos_slaves_grouped_by_attribute',
                       return_value={'fake_region': ['fake_host']}, autospec=True),
        ) as (
            _,
            get_mesos_slaves_grouped_by_attribute_patch,
        ):
            actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config(),
                                                check_haproxy=True)
            expected = tasks[2:]
            assert actual == expected

    def test_get_happy_tasks_check_haproxy_when_unhealthy(self):
        """If we specify that a task should be in haproxy, don't call it happy unless it's in haproxy."""

        tasks = [mock.Mock(health_check_results=[mock.Mock(alive=False)]) for i in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        with contextlib.nested(
            mock.patch('paasta_tools.bounce_lib.get_registered_marathon_tasks', return_value=tasks[2:], autospec=True),
            mock.patch('paasta_tools.mesos_tools.get_mesos_slaves_grouped_by_attribute',
                       return_value={'fake_region': ['fake_host']}, autospec=True),
        ) as (
            _,
            get_mesos_slaves_grouped_by_attribute_patch,
        ):
            actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config(),
                                                check_haproxy=True)
            expected = []
            assert actual == expected

    def test_get_happy_tasks_check_haproxy_multiple_locations(self):
        """If we specify that a task should be in haproxy, don't call it happy unless it's in haproxy."""

        tasks = [mock.Mock(health_check_results=[mock.Mock(alive=True)]) for i in xrange(5)]
        fake_app = mock.Mock(tasks=tasks, health_checks=[])
        with contextlib.nested(
            mock.patch(
                'paasta_tools.bounce_lib.get_registered_marathon_tasks',
                side_effect=[tasks[2:3], tasks[3:]], autospec=True,
            ),
            mock.patch('paasta_tools.mesos_tools.get_mesos_slaves_grouped_by_attribute', autospec=True),
        ) as (
            get_registered_marathon_tasks_patch,
            get_mesos_slaves_grouped_by_attribute_patch,
        ):
            get_mesos_slaves_grouped_by_attribute_patch.return_value = {
                'fake_region': ['fake_host1'],
                'fake_other_region': ['fake_host2'],
            }
            actual = bounce_lib.get_happy_tasks(fake_app, 'service', 'namespace', self.fake_system_paasta_config(),
                                                check_haproxy=True)
            expected = tasks[2:]
            assert actual == expected

            get_registered_marathon_tasks_patch.assert_any_call(
                'fake_host1',
                123456,
                utils.DEFAULT_SYNAPSE_HAPROXY_URL_FORMAT,
                'service.namespace',
                tasks,
            )
            get_registered_marathon_tasks_patch.assert_any_call(
                'fake_host2',
                123456,
                utils.DEFAULT_SYNAPSE_HAPROXY_URL_FORMAT,
                'service.namespace',
                tasks,
            )

    def test_flatten_tasks(self):
        """Simple check of flatten_tasks."""
        all_tasks = [mock.Mock(task_id='id_%d' % i) for i in range(10)]

        expected = set(all_tasks)
        actual = bounce_lib.flatten_tasks({
            'app_id_1': set(all_tasks[:5]),
            'app_id_2': set(all_tasks[5:])
        })

        assert actual == expected

class TestBrutalBounce:

    def test_brutal_bounce_no_existing_apps(self):
        """When marathon is unaware of a service, brutal bounce should try to
        create a marathon app."""
        new_config = {'id': 'foo.bar.12345'}
        happy_tasks = []

        assert bounce_lib.brutal_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks={},
            old_app_live_unhappy_tasks={},
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_brutal_bounce_done(self):
        """When marathon has the desired app, and there are no other copies of
        the service running, brutal bounce should neither start nor stop
        anything."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]

        assert bounce_lib.brutal_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks={},
            old_app_live_unhappy_tasks={},
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

    def test_brutal_bounce_mid_bounce(self):
        """When marathon has the desired app, but there are other copies of
        the service running, brutal bounce should stop the old ones."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.brutal_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set.union(
                old_app_live_happy_tasks['app1'],
                old_app_live_happy_tasks['app2'],
                old_app_live_unhappy_tasks['app1'],
                old_app_live_unhappy_tasks['app2'],
            ),
        }

    def test_brutal_bounce_old_but_no_new(self):
        """When marathon does not have the desired app, but there are other copies of
        the service running, brutal bounce should stop the old ones and start
        the new one."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.brutal_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=[],
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": True,
            "tasks_to_drain": set.union(
                old_app_live_happy_tasks['app1'],
                old_app_live_happy_tasks['app2'],
                old_app_live_unhappy_tasks['app1'],
                old_app_live_unhappy_tasks['app2'],
            ),
        }

class TestUpthendownBounce:

    def test_upthendown_bounce_no_existing_apps(self):
        """When marathon is unaware of a service, upthendown bounce should try to
        create a marathon app."""
        new_config = {'id': 'foo.bar.12345'}
        happy_tasks = []

        assert bounce_lib.upthendown_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks={},
            old_app_live_unhappy_tasks={},
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_upthendown_bounce_old_but_no_new(self):
        """When marathon has the desired app, but there are other copies of
        the service running, upthendown bounce should start the new one. but
        not stop the old one yet."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.upthendown_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=[],
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_upthendown_bounce_mid_bounce(self):
        """When marathon has the desired app, and there are other copies of
        the service running, but the new app is not fully up, upthendown bounce
        should not stop the old ones."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(3)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.upthendown_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

    def test_upthendown_bounce_cleanup(self):
        """When marathon has the desired app, and there are other copies of
        the service running, and the new app is fully up, upthendown bounce
        should stop the old ones."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.upthendown_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set.union(
                old_app_live_happy_tasks['app1'],
                old_app_live_happy_tasks['app2'],
                old_app_live_unhappy_tasks['app1'],
                old_app_live_unhappy_tasks['app2'],
            ),
        }

    def test_upthendown_bounce_done(self):
        """When marathon has the desired app, and there are no other copies of
        the service running, upthendown bounce should neither start nor stop
        anything."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {}

        assert bounce_lib.upthendown_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

class TestCrossoverBounce:

    def test_crossover_bounce_no_existing_apps(self):
        """When marathon is unaware of a service, crossover bounce should try to
        create a marathon app."""
        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {}

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_crossover_bounce_old_but_no_new(self):
        """When marathon only has old apps for this service, crossover bounce should start the new one, but not kill any
        old tasks yet."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(),
        }

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_crossover_bounce_old_app_is_happy_but_no_new_app_happy_tasks(self):
        """When marathon only has old apps for this service and margin_factor != 1,
        crossover bounce should start the new app and kill some old tasks."""

        new_config = {'id': 'foo.bar.12345', 'instances': 100}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(60)),
            'app2': set(mock.Mock() for _ in xrange(40)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
            margin_factor=0.95,
        )
        assert actual["create_app"] is True
        assert len(actual["tasks_to_drain"]) == 5

    def test_crossover_bounce_some_unhappy_old_some_happy_old_no_new(self):
        """When marathon only has old apps for this service, and some of them are unhappy (maybe they've been recently
        started), the crossover bounce should start a new app and prefer killing the unhappy tasks over the happy ones.
        """

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(old_app_live_unhappy_tasks['app1'] | old_app_live_unhappy_tasks['app2']),
        }

    def test_crossover_bounce_some_unhappy_old_no_happy_old_no_new_tasks_no_excess(self):
        """When marathon only has old apps for this service, and all of their tasks are unhappy, and there are no excess
        tasks, the crossover bounce should start a new app and not kill any old tasks.
        """

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

    def test_crossover_bounce_lots_of_unhappy_old_no_happy_old_no_new(self):
        """When marathon has a new app and multiple old apps, no new tasks are up, all old tasks are unhappy, and there
        are too many tasks running, the crossover bounce should kill some (but not all) of the old
        tasks.

        This represents a situation where
        """

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(5)),
            'app2': set(mock.Mock() for _ in xrange(5)),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )
        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 5

    def test_crossover_bounce_lots_of_unhappy_old_some_happy_old_new_app_exists_no_new_tasks(self):
        """When marathon has a new app and multiple old apps, no new tasks are up, one of the old apps is healthy and
        the other is not, only unhealthy tasks should get killed.
        """

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(5)),
        }
        old_app_live_unhappy_tasks = {
            'app2': set(mock.Mock() for _ in xrange(5)),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )
        assert actual['create_app'] is False
        assert actual['tasks_to_drain'] == old_app_live_unhappy_tasks['app2']
        # Since there are plenty of unhappy old tasks, we should not kill any new ones.
        assert len(actual['tasks_to_drain'] & old_app_live_happy_tasks['app1']) == 0

    def test_crossover_bounce_mid_bounce(self):
        """When marathon has the desired app, and there are other copies of the service running, but the new app is not
        fully up, crossover bounce should only stop a few of the old instances."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(3)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {}

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )

        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 3

    def test_crossover_bounce_mid_bounce_some_happy_old_some_unhappy_old(self):
        """When marathon has the desired app, and there are other copies of the service running, and some of those
        older tasks are unhappy, we should prefer killing the unhappy tasks."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(3)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(1)),
            'app2': set(),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )

        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 4
        # There are fewer unhappy old tasks than excess tasks, so we should kill all unhappy old ones, plus a few
        # happy ones.
        assert old_app_live_unhappy_tasks['app1'].issubset(actual['tasks_to_drain'])

    def test_crossover_bounce_mid_bounce_some_happy_old_lots_of_unhappy_old(self):
        """When marathon has the desired app, and there are other copies of the service running, and there are more
        unhappy old tasks than excess tasks, we should only kill unhappy tasks.
        """

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(3)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(2)),
            'app2': set(),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(mock.Mock() for _ in xrange(5)),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )

        assert actual['create_app'] is False
        # There are as many unhappy old tasks as excess tasks, so all tasks that we kill should be old unhappy ones.
        assert len(actual['tasks_to_drain']) == 5
        assert actual['tasks_to_drain'] == old_app_live_unhappy_tasks['app2']

    def test_crossover_bounce_mid_bounce_no_happy_old_lots_of_unhappy_old(self):
        """When marathon has the desired app, and there are other copies of the service running, but none of the old
        tasks are happy, and there are excess tasks, we should kill some (but not all) unhappy old tasks."""
        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(3)]
        old_app_live_happy_tasks = {
            'app1': set(),
            'app2': set(),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(3)),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        )
        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 4

    def test_crossover_bounce_using_margin_factor_big_numbers(self):
        new_config = {'id': 'foo.bar.12345', 'instances': 500}
        happy_tasks = [mock.Mock() for _ in xrange(100)]
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(300)),
            'app2': set(),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(mock.Mock() for _ in xrange(100)),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
            margin_factor=0.95,
        )
        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 25

    def test_crossover_bounce_using_margin_factor_small_numbers(self):
        new_config = {'id': 'foo.bar.12345', 'instances': 3}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(),
        }

        actual = bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
            margin_factor=0.66,
        )
        assert actual['create_app'] is False
        assert len(actual['tasks_to_drain']) == 1

    def test_crossover_bounce_cleanup(self):
        """When marathon has the desired app, and there are other copies of
        the service running, which have no remaining tasks, those apps should
        be killed."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]
        old_app_live_happy_tasks = {
            'app1': set(),
            'app2': set(),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(),
        }

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

    def test_crossover_bounce_done(self):
        """When marathon has the desired app, and there are no other copies of
        the service running, crossover bounce should neither start nor stop
        anything."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {}

        assert bounce_lib.crossover_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

class TestDownThenUpBounce(object):

    def test_downthenup_bounce_no_existing_apps(self):
        """When marathon is unaware of a service, downthenup bounce should try to
        create a marathon app."""
        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {}
        old_app_live_unhappy_tasks = {}

        assert bounce_lib.downthenup_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": True,
            "tasks_to_drain": set(),
        }

    def test_downthenup_bounce_old_but_no_new(self):
        """When marathon has only old copies of the service, downthenup_bounce should kill them and not start a new one
        yet."""
        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = []
        old_app_live_happy_tasks = {
            'app1': set(mock.Mock() for _ in xrange(3)),
            'app2': set(mock.Mock() for _ in xrange(2)),
        }
        old_app_live_unhappy_tasks = {
            'app1': set(),
            'app2': set(mock.Mock() for _ in xrange(1)),
        }

        assert bounce_lib.downthenup_bounce(
            new_config=new_config,
            new_app_running=False,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks=old_app_live_happy_tasks,
            old_app_live_unhappy_tasks=old_app_live_unhappy_tasks,
        ) == {
            "create_app": False,
            "tasks_to_drain": set.union(
                old_app_live_happy_tasks['app1'],
                old_app_live_happy_tasks['app2'],
                old_app_live_unhappy_tasks['app2'],
            ),
        }

    def test_downthenup_bounce_done(self):
        """When marathon has the desired app, and there are no other copies of the service running, downthenup bounce
        should neither start nor stop anything."""

        new_config = {'id': 'foo.bar.12345', 'instances': 5}
        happy_tasks = [mock.Mock() for _ in xrange(5)]

        assert bounce_lib.downthenup_bounce(
            new_config=new_config,
            new_app_running=True,
            happy_new_tasks=happy_tasks,
            old_app_live_happy_tasks={},
            old_app_live_unhappy_tasks={},
        ) == {
            "create_app": False,
            "tasks_to_drain": set(),
        }

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


text:
set -e
. ~/userpassword
pushd ~/dump/
timestamp=knowls`date -u +%Y%m%d-%H%M`
mkdir $timestamp
mongodump --host m0 -u "${MONGO_USERNAME}" -p "${MONGO_PASSWORD}" --authenticationDatabase admin -o "$timestamp" --db knowledge
rm -rf $timestamp/knowledge/system.profile*
rm -rf $timestamp/knowledge/system.users*
time mongorestore  -u "${MONGO_USERNAME}" -p "${MONGO_PASSWORD}" --authenticationDatabase admin  --db knowledge --drop "$timestamp/knowledge"
rm -rf $timestamp
popd
set +e


text:
<!DOCTYPE html>
<title>math::constants - Tcl Math Library</title>

 [
   Tcllib Home
| Main Table Of Contents
| Table Of Contents
| Keyword Index
| Categories
| Modules
| Applications
 ]

math::constants(n) 1.0.2 tcllib "Tcl Math Library"

Name

math::constants - Mathematical and numerical constants

Table Of Contents

Table Of Contents

Synopsis

Description

PROCEDURES

Constants

Bugs, Ideas, Feedback

Keywords

Category

Copyright

Synopsis

package require Tcl ?8.3?

package require math::constants ?1.0.2?

::math::constants::constants args

::math::constants::print-constants args

Description

This package defines some common mathematical and numerical constants.
By using the package you get consistent values for numbers like pi and
ln(10).

It defines two commands:

One for importing the constants

One for reporting which constants are defined and what values they
actually have.

The motivation for this package is that quite often, with
(mathematical) computations, you need a good approximation to, say,
the ratio of degrees to radians. You can, of course, define this
like:

    variable radtodeg [expr {180.0/(4.0*atan(1.0))}]

and use the variable radtodeg whenever you need the conversion.

This has two drawbacks:

You need to remember the proper formula or value and that is
error-prone.

Especially with the use of mathematical functions like atan
you assume that they have been accurately implemented. This is seldom or
never the case and for each platform you can get subtle differences.

Here is the way you can do it with the math::constants package:

    package require math::constants
    ::math::constants::constants radtodeg degtorad

which creates two variables, radtodeg and (its reciprocal) degtorad
in the calling namespace.

Constants that have been defined (their values are mostly taken
from mathematical tables with more precision than usually can be
handled) include:

basic constants like pi, e, gamma (Euler's constant)

derived values like ln(10) and sqrt(2)

purely numerical values such as 1/3 that are included for convenience
and for the fact that certain seemingly trivial computations like:

    set value [expr {3.0*$onethird}]

give exactly the value you expect (if IEEE arithmetic is
available).

The full set of named constants is listed in section Constants.

PROCEDURES

The package defines the following public procedures:

::math::constants::constants args

Import the constants whose names are given as arguments

::math::constants::print-constants args

Print the constants whose names are given as arguments on the screen
(name, value and description) or, if no arguments are given, print all
defined constants. This is mainly a convenience procedure.

Constants

pi

Ratio of circle circumference to diameter

e

Base for natural logarithm

ln10

Natural logarithm of 10

phi

Golden ratio

gamma

Euler's constant

sqrt2

Square root of 2

thirdrt2

One-third power of 2

sqrt3

Square root of 3

radtodeg

Conversion from radians to degrees

degtorad

Conversion from degrees to radians

onethird

One third (0.3333....)

twothirds

Two thirds (0.6666....)

onesixth

One sixth (0.1666....)

huge

(Approximately) largest number

tiny

(Approximately) smallest number not equal zero

eps

Smallest number such that 1+eps != 1

Bugs, Ideas, Feedback

This document, and the package it describes, will undoubtedly contain
bugs and other problems.
Please report such in the category math :: constants of the
Tcllib Trackers.
Please also report any ideas for enhancements you may have for either
package and/or documentation.

When proposing code changes, please provide unified diffs,
i.e the output of diff -u.

Note further that attachments are strongly preferred over
inlined patches. Attachments can be made by going to the Edit
form of the ticket immediately after its creation, and then using the
left-most button in the secondary navigation bar.

Keywords

constants, degrees, e, math, pi, radians

Category

Mathematics

Copyright

Copyright © 2004 Arjen Markus <arjenmarkus@users.sourceforge.net>


text:
//
//  BannerLoopView.m
//  bannerLoop
//
//  Created by hisa on 15/5/7.
//  Copyright (c) 2015年 hisa. All rights reserved.
//

#import "BannerLoopView.h"

#define JumpTime     2
@interface BannerLoopView()<UIScrollViewDelegate>
{
    UIScrollView *_scrollView;
    UIPageControl *_pageControl;
    int _totalPages;
    int _curPage;

    NSMutableArray *loopArray;

    NSArray  *itemArray;

    NSTimer  *loopTimer;

}

@end

@implementation BannerLoopView

- (id)initWithFrame:(CGRect)frame items:(NSArray*)items
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, self.bounds.size.height);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
        _scrollView.pagingEnabled = YES;
        [self addSubview:_scrollView];

        _scrollView.backgroundColor = [UIColor purpleColor];

        CGRect rect = self.bounds;
        rect.origin.y = rect.size.height - 30;
        rect.size.height = 30;
        _pageControl = [[UIPageControl alloc] initWithFrame:rect];
        _pageControl.userInteractionEnabled = NO;

        [self addSubview:_pageControl];

        _curPage = 0;

        itemArray = items;

        [self reloadData];

    }
    return self;
}
- (void)reloadData
{
    _totalPages = (int)[itemArray count];
    if (_totalPages == 0) {
        return;
    }
    _pageControl.numberOfPages = _totalPages;
    [self loadData];

    [self autoStart];
}
- (void)loadData
{

    _pageControl.currentPage = _curPage;

    NSArray *subViews = [_scrollView subviews];
    if([subViews count] != 0) {
        [subViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }

    [self getDisplayImagesWithCurpage:_curPage];

    for (int i = 0; i < 3; i++) {

        UIImage *img =  [loopArray objectAtIndex:i];

        UIImageView *v = [[UIImageView alloc]init];

        v.image  = img;

        v.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);

        v.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(handleTap:)];
        [v addGestureRecognizer:singleTap];

        v.frame = CGRectOffset(v.frame, v.frame.size.width * i, 0);
        [_scrollView addSubview:v];

    }

    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];

    if(_totalPages<2)
    {
        _scrollView.scrollEnabled = NO;
        [_pageControl removeFromSuperview];
    }
}
- (void)getDisplayImagesWithCurpage:(int)page {

    int pre = [self validPageValue:_curPage-1];
    int last = [self validPageValue:_curPage+1];

    if (!loopArray) {
        loopArray = [[NSMutableArray alloc] init];
    }

    [loopArray removeAllObjects];

    [loopArray addObject:[itemArray objectAtIndex:pre]];
    [loopArray addObject:[itemArray objectAtIndex:page]];
    [loopArray addObject:[itemArray objectAtIndex:last]];
}

- (int)validPageValue:(int)value {

    if(value == -1) value = _totalPages - 1;
    if(value == _totalPages) value = 0;

    return value;

}
- (void)handleTap:(UITapGestureRecognizer *)tap {

    if ([_delegate respondsToSelector:@selector(didClickPageAtIndex:)]) {
        [_delegate didClickPageAtIndex:_curPage];
    }

}
-(void)autoStart
{

    [self performSelector:@selector(setUpFirstView) withObject:nil afterDelay:JumpTime];

}

-(void)setUpFirstView
{
    if(_totalPages>=2)
    {
        [_scrollView setContentOffset:CGPointMake(2*self.frame.size.width, 0) animated:YES];

        loopTimer = [NSTimer scheduledTimerWithTimeInterval:JumpTime target:self selector:@selector(switchFocusImageItems) userInfo:nil repeats:YES];

    }

}

- (void)switchFocusImageItems
{

    float x =_scrollView.contentOffset.x;

    if(x >= (2*self.frame.size.width)) {
        _curPage = [self validPageValue:_curPage+1];
        [self loadData];
    }

    if(x <= 0) {
        _curPage = [self validPageValue:_curPage-1];
        [self loadData];
    }

    [_scrollView setContentOffset:CGPointMake(self.frame.size.width+_scrollView.contentOffset.x, 0) animated:YES];

}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {

    int x = aScrollView.contentOffset.x;

    if(x >= (2*self.frame.size.width)) {
        _curPage = [self validPageValue:_curPage+1];
        [self loadData];
    }

    if(x <= 0) {
        _curPage = [self validPageValue:_curPage-1];
        [self loadData];
    }

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView {

    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0) animated:YES];

}

-(void)dealloc
{
    [_scrollView setDelegate:nil];

    [loopTimer  invalidate];

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
package com.github.kaitoy.sneo.giane.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.github.kaitoy.sneo.giane.action.message.DialogMessage;
import com.github.kaitoy.sneo.giane.action.message.FormMessage;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("giane-default")
@InterceptorRef("gianeDefaultStack")
public class ConfirmationDialogAction extends ActionSupport
implements DialogMessage, FormMessage {

  /**
   *
   */
  private static final long serialVersionUID = 8986143503120527708L;

  private String deletingIdList;
  private int numDeletingItems;

  public void setDeletingIdList(String deletingIdList) {
    this.deletingIdList = deletingIdList;
  }

  public int getNumDeletingItems() {
    return numDeletingItems;
  }

  @Override
  @Action(
    results = {
      @Result(name = "success", location = "confirmation-dialog.jsp")
    }
  )
  @SkipValidation
  public String execute() throws Exception {
    numDeletingItems = deletingIdList.split(",").length;
    return "success";
  }

}


text:
java -jar bin/swagger-codegen-cli.jar generate -i https://raw.githubusercontent.com/cloudiator/rest-swagger/master/swagger.yaml -l spring --output server --artifact-id rest-server --group-id io.github.cloudiator --artifact-version 0.3.0-SNAPSHOT --api-package io.github.cloudiator.rest.api --model-package io.github.cloudiator.rest.model -DhideGenerationTimestamp=true

# move the model
mv server/src/main/java/io/github/cloudiator/rest/model/* model/src/main/java/io/github/cloudiator/rest/model/

# Delete the model
rm -rf server/src/main/java/io/github/cloudiator/rest/model