text:
package com.evolveum.midpoint.repo.sql.data.common;

import com.evolveum.midpoint.repo.sql.data.RepositoryContext;
import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString;
import com.evolveum.midpoint.repo.sql.query.definition.JaxbName;
import com.evolveum.midpoint.repo.sql.util.DtoTranslationException;
import com.evolveum.midpoint.repo.sql.util.IdGeneratorResult;
import com.evolveum.midpoint.repo.sql.util.MidPointJoinedPersister;
import com.evolveum.midpoint.repo.sql.util.RUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Persister;

import javax.persistence.*;
import java.util.Set;

/**
 * @author lazyman
 */
@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "uc_user_name", columnNames = {"name_norm"}),
        indexes = {
                @Index(name = "iFullName", columnList = "fullName_orig"),
                @Index(name = "iFamilyName", columnList = "familyName_orig"),
                @Index(name = "iGivenName", columnList = "givenName_orig"),
                @Index(name = "iEmployeeNumber", columnList = "employeeNumber"),
                @Index(name = "iUserNameOrig", columnList = "name_orig")})
@ForeignKey(name = "fk_user")
@Persister(impl = MidPointJoinedPersister.class)
public class RUser extends RFocus<UserType> {

    private RPolyString nameCopy;
    private RPolyString fullName;
    private RPolyString givenName;
    private RPolyString familyName;
    private RPolyString additionalName;
    private RPolyString honorificPrefix;
    private RPolyString honorificSuffix;
    private String employeeNumber;
    @Deprecated //todo remove collection in 3.9
    private Set<String> employeeType;
    private Set<RPolyString> organizationalUnit;
    private RPolyString title;
    private RPolyString nickName;
    private Set<RPolyString> organization;

    @ElementCollection
    @ForeignKey(name = "fk_user_organization")
    @CollectionTable(name = "m_user_organization", joinColumns = {
            @JoinColumn(name = "user_oid", referencedColumnName = "oid")
    })
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    public Set<RPolyString> getOrganization() {
        return organization;
    }

    @Embedded
    public RPolyString getAdditionalName() {
        return additionalName;
    }

    @ElementCollection
    @ForeignKey(name = "fk_user_org_unit")
    @CollectionTable(name = "m_user_organizational_unit", joinColumns = {
            @JoinColumn(name = "user_oid", referencedColumnName = "oid")
    })
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    public Set<RPolyString> getOrganizationalUnit() {
        return organizationalUnit;
    }

    @ElementCollection
    @ForeignKey(name = "fk_user_employee_type")
    @CollectionTable(name = "m_user_employee_type", joinColumns = {
            @JoinColumn(name = "user_oid", referencedColumnName = "oid")
    })
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    public Set<String> getEmployeeType() {
        return employeeType;
    }

    @Embedded
    public RPolyString getFamilyName() {
        return familyName;
    }

    @Embedded
    public RPolyString getFullName() {
        return fullName;
    }

    @Embedded
    public RPolyString getGivenName() {
        return givenName;
    }

    public String getEmployeeNumber() {
        return employeeNumber;
    }

    @Embedded
    public RPolyString getHonorificPrefix() {
        return honorificPrefix;
    }

    @Embedded
    public RPolyString getHonorificSuffix() {
        return honorificSuffix;
    }

    @JaxbName(localPart = "name")
    @AttributeOverrides({
            @AttributeOverride(name = "orig", column = @Column(name = "name_orig")),
            @AttributeOverride(name = "norm", column = @Column(name = "name_norm"))
    })
    @Embedded
    public RPolyString getNameCopy() {
        return nameCopy;
    }

    public void setNameCopy(RPolyString nameCopy) {
        this.nameCopy = nameCopy;
    }

    @Embedded
    public RPolyString getNickName() {
        return nickName;
    }

    @Embedded
    public RPolyString getTitle() {
        return title;
    }

    public void setOrganization(Set<RPolyString> organization) {
        this.organization = organization;
    }

    public void setNickName(RPolyString nickName) {
        this.nickName = nickName;
    }

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

    public void setAdditionalName(RPolyString additionalName) {
        this.additionalName = additionalName;
    }

    public void setEmployeeNumber(String employeeNumber) {
        this.employeeNumber = employeeNumber;
    }

    public void setEmployeeType(Set<String> employeeType) {
        this.employeeType = employeeType;
    }

    public void setFamilyName(RPolyString familyName) {
        this.familyName = familyName;
    }

    public void setGivenName(RPolyString givenName) {
        this.givenName = givenName;
    }

    public void setHonorificPrefix(RPolyString honorificPrefix) {
        this.honorificPrefix = honorificPrefix;
    }

    public void setHonorificSuffix(RPolyString honorificSuffix) {
        this.honorificSuffix = honorificSuffix;
    }

    public void setOrganizationalUnit(Set<RPolyString> organizationalUnit) {
        this.organizationalUnit = organizationalUnit;
    }

    public void setFullName(RPolyString fullName) {
        this.fullName = fullName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        RUser rUser = (RUser) o;

        if (nameCopy != null ? !nameCopy.equals(rUser.nameCopy) : rUser.nameCopy != null) return false;
        if (additionalName != null ? !additionalName.equals(rUser.additionalName) : rUser.additionalName != null)
            return false;
        if (employeeNumber != null ? !employeeNumber.equals(rUser.employeeNumber) : rUser.employeeNumber != null)
            return false;
        if (employeeType != null ? !employeeType.equals(rUser.employeeType) : rUser.employeeType != null) return false;
        if (familyName != null ? !familyName.equals(rUser.familyName) : rUser.familyName != null) return false;
        if (fullName != null ? !fullName.equals(rUser.fullName) : rUser.fullName != null) return false;
        if (givenName != null ? !givenName.equals(rUser.givenName) : rUser.givenName != null) return false;
        if (honorificPrefix != null ? !honorificPrefix.equals(rUser.honorificPrefix) : rUser.honorificPrefix != null)
            return false;
        if (honorificSuffix != null ? !honorificSuffix.equals(rUser.honorificSuffix) : rUser.honorificSuffix != null)
            return false;
        if (organizationalUnit != null ? !organizationalUnit.equals(rUser.organizationalUnit) : rUser.organizationalUnit != null)
            return false;
        if (title != null ? !title.equals(rUser.title) : rUser.title != null) return false;
        if (nickName != null ? !nickName.equals(rUser.nickName) : rUser.nickName != null) return false;
        if (organization != null ? !organization.equals(rUser.organization) : rUser.organization != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (nameCopy != null ? nameCopy.hashCode() : 0);
        result = 31 * result + (fullName != null ? fullName.hashCode() : 0);
        result = 31 * result + (givenName != null ? givenName.hashCode() : 0);
        result = 31 * result + (familyName != null ? familyName.hashCode() : 0);
        result = 31 * result + (honorificPrefix != null ? honorificPrefix.hashCode() : 0);
        result = 31 * result + (honorificSuffix != null ? honorificSuffix.hashCode() : 0);
        result = 31 * result + (employeeNumber != null ? employeeNumber.hashCode() : 0);
        result = 31 * result + (title != null ? title.hashCode() : 0);
        result = 31 * result + (nickName != null ? nickName.hashCode() : 0);

        return result;
    }

    // dynamically called
    public static void copyFromJAXB(UserType jaxb, RUser repo, RepositoryContext repositoryContext,
            IdGeneratorResult generatorResult) throws DtoTranslationException {
        copyFocusInformationFromJAXB(jaxb, repo, repositoryContext, generatorResult);

        repo.setNameCopy(RPolyString.copyFromJAXB(jaxb.getName()));
        repo.setFullName(RPolyString.copyFromJAXB(jaxb.getFullName()));
        repo.setGivenName(RPolyString.copyFromJAXB(jaxb.getGivenName()));
        repo.setFamilyName(RPolyString.copyFromJAXB(jaxb.getFamilyName()));
        repo.setHonorificPrefix(RPolyString.copyFromJAXB(jaxb.getHonorificPrefix()));
        repo.setHonorificSuffix(RPolyString.copyFromJAXB(jaxb.getHonorificSuffix()));
        repo.setEmployeeNumber(jaxb.getEmployeeNumber());
        repo.setAdditionalName(RPolyString.copyFromJAXB(jaxb.getAdditionalName()));
        repo.setEmailAddress(jaxb.getEmailAddress());
        repo.setTelephoneNumber(jaxb.getTelephoneNumber());

        repo.setLocale(jaxb.getLocale());
        repo.setTimezone(jaxb.getTimezone());
        repo.setPreferredLanguage(jaxb.getPreferredLanguage());
        repo.setTitle(RPolyString.copyFromJAXB(jaxb.getTitle()));
        repo.setNickName(RPolyString.copyFromJAXB(jaxb.getNickName()));

        //sets
        repo.setEmployeeType(RUtil.listToSet(jaxb.getEmployeeType()));
        repo.setOrganizationalUnit(RUtil.listPolyToSet(jaxb.getOrganizationalUnit()));
        repo.setOrganization(RUtil.listPolyToSet(jaxb.getOrganization()));
    }
}


text:
require 'testup/ui/preferences'
require 'testup/ui/window'
require 'testup/api'
require 'testup/config'
require 'testup/debug'
require 'testup/debugger'
require 'testup/defer'
require 'testup/editor'
require 'testup/log'
require 'testup/runs'
require 'testup/taskbar_progress'

module TestUp
  class TestRunnerWindow < Window

    include Debug::Timing

    def initialize
      super
      # on(:close) {
      #   @preferences_window.close unless @preferences_window.nil?
      # }
    end

    def toggle
      time('TestRunnerWindow#toggle') { super }
    end

    # Clears and reloads the test suites.
    def reload
      return false unless visible?
      call('app.reset')
      true
    end

    private

    # @return [Hash]
    def window_options
      {
        :title           => PLUGIN_NAME,
        :preferences_key => PLUGIN_ID,
        :width           => 600,
        :height          => 400,
        :min_width       => 300,
        :min_height      => 300,
        :resizable       => true,
        # This cause errors in JS:
        #   Uncaught TypeError: Cannot read property 'style' of null
        #   document.body.style.overflow="hidden";
        # :scrollable      => false,
      }
    end

    # @return [String]
    def window_source
      filename = File.join(PATH_UI, 'html', 'runner.html')
    end

    def register_callbacks(dialog)
      super
      dialog.register_callback('runTests') { |dialog, test_suite_json|
        Log.trace :callback, "runTests(...)"
        event_run_tests(test_suite_json)
      }
      dialog.register_callback('reRunTests') { |dialog|
        Log.trace :callback, "reRunTests(...)"
        event_rerun_tests
      }
      dialog.register_callback('discoverTests') { |dialog, test_suites_json|
        Log.trace :callback, "discoverTests(...)"
        # Workaround for a sporadic crash where it appear SU crash, without
        # BugSplat when passing a JS object back to Ruby. For some reason it
        # had only been seen in this callback. Not sure if it's the content of
        # the object or the amount of data. The crash would manifest itself at
        # various places, which indicate some kind of memory issue.
        # The workaround is to have JS convert to JSON string and decode in
        # Ruby. Doesn't appear to have any significant impact on performance.
        test_suites_json = JSON.parse(test_suites_json)
        event_discover(test_suites_json)
      }
      dialog.register_callback('changeActiveTestSuite') { |dialog, title|
        Log.trace :callback, "event_change_testsuite(#{title})"
        event_change_testsuite(title)
      }
      dialog.register_callback('openSourceFile') { |dialog, location|
        Log.trace :callback, "openSourceFile(#{location})"
        event_open_source_file(location)
      }
      dialog.register_callback('openPreferences') { |dialog|
        Log.trace :callback, "openPreferences(.)"
        event_open_preferences
      }

      dialog
    end

    def event_window_ready
      time('event_window_ready') {
        discover_tests
        config = {
          :active_tab => TestUp.settings[:last_active_testsuite],
        }
        time('app.configure') { call('app.configure', config) }
      }
    end

    # @param [Hash] test_suite_json JSON data from JavaScript side.
    def event_run_tests(test_suite_json)
      Log.trace :callback, 'event_run_tests(...)'
      options = {}
      test_suite = Report::TestSuite.from_hash(test_suite_json)
      TestUp::API.run_test_suite(test_suite, options: options) { |results|
        test_suite.merge_results(results)
        time('app.update_results') { call('app.update_results', test_suite) }
      }
    end

    def event_rerun_tests
      Log.trace :callback, 'event_rerun_tests(...)'
      # TODO: Refactor Runs into API.
      run_file = TestUp::Runs.select_config
      return unless run_file
      run_config = TestUp::Runs.read_config(run_file)
      options = {
        seed: run_config[:seed]
      }
      tests = run_config[:tests]
      title = run_config[:test_suite]
      path = run_config[:path]
      raise 'path missing from run-config' if path.nil?

      # Bah... all this re-run code is really fragile... :(
      test_suite = TestUp::API.discover_tests([path]).first

      TestUp::API.run_tests(tests, title: title, path: path,  options: options) { |results|
        test_suite.merge_results(results)
        time('app.update_results') { call('app.update_results', test_suite) }
      }
    end

    # @param [Array<Hash>] test_suites_json JSON data from JavaScript side.
    def event_discover(test_suites_json)
      time('event_discover') {
        Log.trace :callback, 'event_discover(...)'
        test_suites = test_suites_json.map { |test_suite_json|
          Log.trace :discover, '> Report::TestSuite.from_hash(...)'
          Report::TestSuite.from_hash(test_suite_json)
        }
        Log.trace :discover, '> time("rediscover")'
        time('rediscover') { rediscover_tests(test_suites) }
      }
    end

    # @param [String] test_suite_title
    def event_change_testsuite(test_suite_title)
      TestUp.settings[:last_active_testsuite] = test_suite_title
    end

    def event_console_output(value)
      Debugger.output(value)
    end

    # @param [String] location
    def event_open_source_file(location)
      Log.trace :callback, "event_open_source_file(#{location})"
      result = location.match(/^(.+):(\d+)?$/)
      if result
        filename = result[1]
        line_number = result[2]
      else
        filename = location
        line_number = 0
      end
      unless File.exist?(filename)
        warn "Unable to find: #{filename}"
        warn 'Trying to account for encoding bug...'
        warn filename
        filename = filename.encode('ISO-8859-1')
        warn filename
        filename.force_encoding('UTF-8')
        warn filename
        warn "Exists: #{File.exist?(filename)}"
      end
      if File.exist?(filename)
        Editor.open_file(filename, line_number)
      else
        UI.beep
        warn "Unable to open: #{filename}"
        p filename.bytes
      end
    end

    def event_open_preferences
      # Work around a crash in SketchUp 2018 (maybe others) by deferring
      # the Preferences dialog. Maybe it's related to Chromiums event thread.
      Execution.defer {
        @preferences_window = PreferencesWindow.new
        @preferences_window.show
      }
    end

    # @return [nil]
    def discover_tests
      Log.trace :discover, "discover_tests()"
      paths = TestUp.settings[:paths_to_testsuites]
      discoveries = time('discover') { TestUp::API.discover_tests(paths) }
      Debugger.time("JS:update(...)") {
        progress = TaskbarProgress.new
        begin
          progress.set_state(TaskbarProgress::INDETERMINATE)
          time('app.discover') { call('app.discover', discoveries) }
        ensure
          progress.set_state(TaskbarProgress::NOPROGRESS)
        end
      }
      nil
    end

    # @param [Report::TestSuite] test_suite
    # @return [nil]
    def rediscover_tests(test_suites)
      Log.trace :discover, "rediscover_tests(...)"
      paths = TestUp.settings[:paths_to_testsuites]
      Log.trace :discover, "> TestUp::API.discover_tests(...):"
      discoveries = time('discover') { TestUp::API.discover_tests(paths) }
      Log.trace :discover, "> discoveries.map:"
      discoveries.map! { |discovery|
        test_suite = test_suites.find { |suite| suite.title == discovery.title }
        test_suite ? test_suite.rediscover(discovery) : discovery
      }
      Log.trace :discover, "> JS:rediscover:"
      Debugger.time("JS:rediscover(...)") {
        progress = TaskbarProgress.new
        begin
          progress.set_state(TaskbarProgress::INDETERMINATE)
          time('app.rediscover') { call('app.rediscover', discoveries) }
        ensure
          progress.set_state(TaskbarProgress::NOPROGRESS)
        end
      }
      nil
    end

  end # class
end # module

redpajama_set_name: RedPajamaGithub


text:
@import Foundation;

@interface NSURL (STKExtensions)

- (BOOL)stk_isMailLink;
- (NSString *)stk_emailAddress;

@end


text:
include_recipe 'apache2::mod_dav'

package 'libapache2-svn' do
  case node['platform_family']
  when 'rhel', 'fedora', 'suse'
    package_name 'mod_dav_svn'
  else
    package_name 'libapache2-svn'
  end
end

case node['platform_family']
when 'rhel', 'fedora', 'suse'
  file "#{node['apache']['dir']}/conf-available/subversion.conf" do
    action :delete
    backup false
  end
end

apache_module 'dav_svn'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Mapping;
using AcceptFramework.Domain.PostEditAudit;

namespace AcceptFramework.Mapping.PostEditAudit
{
    public class ThinkPhaseMap : ClassMap<ThinkPhase>
    {

        public ThinkPhaseMap()
        {
            Table("ThinkPhases");

            Id(e => e.Id);
            Map(e => e.PhaseName).Length(250);
            Map(e => e.ProcessName);
            Map(e => e.Date);
            Map(e => e.Tool);
            Map(e => e.ToolId).Length(250);
            Map(e => e.JobId);
            Map(e => e.ContactEmail);

            HasManyToMany(e => e.Notes).Cascade.All().
            Not.LazyLoad().
            AsSet().
            Table("ThinkPhaseNotes").
            ParentKeyColumn("ThinkPhaseID").
            ChildKeyColumn("NoteID");

            References(e => e.PhaseCountGroup).Not.LazyLoad().Column("PhaseCountGroupId").Cascade.All();

        }
    }
}


text:
import datetime

from novaclient import exceptions as nova_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import strutils

from blazar.db import api as db_api
from blazar.db import exceptions as db_ex
from blazar.db import utils as db_utils
from blazar.manager import exceptions as manager_ex
from blazar.plugins import base
from blazar.plugins import oshosts as plugin
from blazar import status
from blazar.utils.openstack import nova
from blazar.utils.openstack import placement
from blazar.utils import plugins as plugins_utils
from blazar.utils import trusts

plugin_opts = [
    cfg.StrOpt('blazar_az_prefix',
               default='blazar_',
               help='Prefix for Availability Zones created by Blazar'),
    cfg.StrOpt('before_end',
               default='',
               help='Actions which we will be taken before the end of '
                    'the lease'),
    cfg.BoolOpt('enable_notification_monitor',
                default=False,
                help='Enable notification-based resource monitoring. '
                     'If it is enabled, the blazar-manager monitors states of '
                     'compute hosts by subscribing to notifications of Nova.'),
    cfg.ListOpt('notification_topics',
                default=['notifications', 'versioned_notifications'],
                help='Notification topics to subscribe to.'),
    cfg.BoolOpt('enable_polling_monitor',
                default=False,
                help='Enable polling-based resource monitoring. '
                     'If it is enabled, the blazar-manager monitors states '
                     'of compute hosts by polling the Nova API.'),
    cfg.IntOpt('polling_interval',
               default=60,
               min=1,
               help='Interval (seconds) of polling for health checking.'),
    cfg.IntOpt('healing_interval',
               default=60,
               min=0,
               help='Interval (minutes) of reservation healing. '
                    'If 0 is specified, the interval is infinite and all the '
                    'reservations in the future is healed at one time.'),
]

CONF = cfg.CONF
CONF.register_opts(plugin_opts, group=plugin.RESOURCE_TYPE)
LOG = logging.getLogger(__name__)

before_end_options = ['', 'snapshot', 'default']

QUERY_TYPE_ALLOCATION = 'allocation'

class PhysicalHostPlugin(base.BasePlugin, nova.NovaClientWrapper):
    """Plugin for physical host resource."""
    resource_type = plugin.RESOURCE_TYPE
    title = 'Physical Host Plugin'
    description = 'This plugin starts and shutdowns the hosts.'
    freepool_name = CONF.nova.aggregate_freepool_name
    pool = None
    query_options = {
        QUERY_TYPE_ALLOCATION: ['lease_id', 'reservation_id']
    }

    def __init__(self):
        super(PhysicalHostPlugin, self).__init__(
            username=CONF.os_admin_username,
            password=CONF.os_admin_password,
            user_domain_name=CONF.os_admin_user_domain_name,
            project_name=CONF.os_admin_project_name,
            project_domain_name=CONF.os_admin_project_domain_name)
        self.monitor = PhysicalHostMonitorPlugin()
        self.monitor.register_healing_handler(self.heal_reservations)
        self.placement_client = placement.BlazarPlacementClient()

    def reserve_resource(self, reservation_id, values):
        """Create reservation."""
        host_ids = self.allocation_candidates(values)

        if not host_ids:
            raise manager_ex.NotEnoughHostsAvailable()

        pool = nova.ReservationPool()
        pool_name = reservation_id
        az_name = "%s%s" % (CONF[self.resource_type].blazar_az_prefix,
                            pool_name)
        pool_instance = pool.create(name=pool_name, az=az_name)
        host_rsrv_values = {
            'reservation_id': reservation_id,
            'aggregate_id': pool_instance.id,
            'resource_properties': values['resource_properties'],
            'hypervisor_properties': values['hypervisor_properties'],
            'count_range': values['count_range'],
            'status': 'pending',
            'before_end': values['before_end']
        }
        host_reservation = db_api.host_reservation_create(host_rsrv_values)
        for host_id in host_ids:
            db_api.host_allocation_create({'compute_host_id': host_id,
                                          'reservation_id': reservation_id})
        return host_reservation['id']

    def update_reservation(self, reservation_id, values):
        """Update reservation."""
        reservation = db_api.reservation_get(reservation_id)
        lease = db_api.lease_get(reservation['lease_id'])

        if (not [x for x in values.keys() if x in ['min', 'max',
                                                   'hypervisor_properties',
                                                   'resource_properties']]
                and values['start_date'] >= lease['start_date']
                and values['end_date'] <= lease['end_date']):
            # Nothing to update
            return

        dates_before = {'start_date': lease['start_date'],
                        'end_date': lease['end_date']}
        dates_after = {'start_date': values['start_date'],
                       'end_date': values['end_date']}
        host_reservation = db_api.host_reservation_get(
            reservation['resource_id'])
        self._update_allocations(dates_before, dates_after, reservation_id,
                                 reservation['status'], host_reservation,
                                 values)

        updates = {}
        if 'min' in values or 'max' in values:
            count_range = str(values.get(
                'min', host_reservation['count_range'].split('-')[0])
            ) + '-' + str(values.get(
                'max', host_reservation['count_range'].split('-')[1])
            )
            updates['count_range'] = count_range
        if 'hypervisor_properties' in values:
            updates['hypervisor_properties'] = values.get(
                'hypervisor_properties')
        if 'resource_properties' in values:
            updates['resource_properties'] = values.get(
                'resource_properties')
        if updates:
            db_api.host_reservation_update(host_reservation['id'], updates)

    def on_start(self, resource_id):
        """Add the hosts in the pool."""
        host_reservation = db_api.host_reservation_get(resource_id)
        pool = nova.ReservationPool()
        hosts = []
        for allocation in db_api.host_allocation_get_all_by_values(
                reservation_id=host_reservation['reservation_id']):
            host = db_api.host_get(allocation['compute_host_id'])
            hosts.append(host['service_name'])
        pool.add_computehost(host_reservation['aggregate_id'], hosts)

    def before_end(self, resource_id):
        """Take an action before the end of a lease."""
        host_reservation = db_api.host_reservation_get(resource_id)
        action = host_reservation['before_end']
        if action == 'default':
            action = CONF[plugin.RESOURCE_TYPE].before_end
        if action == 'snapshot':
            pool = nova.ReservationPool()
            client = nova.BlazarNovaClient()
            for host in pool.get_computehosts(
                    host_reservation['aggregate_id']):
                for server in client.servers.list(
                        search_opts={"host": host, "all_tenants": 1}):
                    client.servers.create_image(server=server)

    def on_end(self, resource_id):
        """Remove the hosts from the pool."""
        host_reservation = db_api.host_reservation_get(resource_id)
        db_api.host_reservation_update(host_reservation['id'],
                                       {'status': 'completed'})
        allocations = db_api.host_allocation_get_all_by_values(
            reservation_id=host_reservation['reservation_id'])
        for allocation in allocations:
            db_api.host_allocation_destroy(allocation['id'])
        pool = nova.ReservationPool()
        for host in pool.get_computehosts(host_reservation['aggregate_id']):
            for server in self.nova.servers.list(
                    search_opts={"host": host, "all_tenants": 1}):
                try:
                    self.nova.servers.delete(server=server)
                except nova_exceptions.NotFound:
                    LOG.info('Could not find server %s, may have been deleted '
                             'concurrently.', server)
                except Exception as e:
                    LOG.exception('Failed to delete %s: %s.', server, str(e))
        try:
            pool.delete(host_reservation['aggregate_id'])
        except manager_ex.AggregateNotFound:
            pass

    def heal_reservations(self, failed_resources, interval_begin,
                          interval_end):
        """Heal reservations which suffer from resource failures.

        :param failed_resources: a list of failed hosts.
        :param interval_begin: start date of the period to heal.
        :param interval_end: end date of the period to heal.
        :return: a dictionary of {reservation id: flags to update}
                 e.g. {'de27786d-bd96-46bb-8363-19c13b2c6657':
                       {'missing_resources': True}}
        """
        reservation_flags = {}

        host_ids = [h['id'] for h in failed_resources]
        reservations = db_utils.get_reservations_by_host_ids(host_ids,
                                                             interval_begin,
                                                             interval_end)

        for reservation in reservations:
            if reservation['resource_type'] != plugin.RESOURCE_TYPE:
                continue

            for allocation in [alloc for alloc
                               in reservation['computehost_allocations']
                               if alloc['compute_host_id'] in host_ids]:
                if self._reallocate(allocation):
                    if reservation['status'] == status.reservation.ACTIVE:
                        if reservation['id'] not in reservation_flags:
                            reservation_flags[reservation['id']] = {}
                        reservation_flags[reservation['id']].update(
                            {'resources_changed': True})
                else:
                    if reservation['id'] not in reservation_flags:
                        reservation_flags[reservation['id']] = {}
                    reservation_flags[reservation['id']].update(
                        {'missing_resources': True})

        return reservation_flags

    def _reallocate(self, allocation):
        """Allocate an alternative host.

        :param allocation: allocation to change.
        :return: True if an alternative host was successfully allocated.
        """
        reservation = db_api.reservation_get(allocation['reservation_id'])
        h_reservation = db_api.host_reservation_get(
            reservation['resource_id'])
        lease = db_api.lease_get(reservation['lease_id'])
        pool = nova.ReservationPool()

        # Remove the old host from the aggregate.
        if reservation['status'] == status.reservation.ACTIVE:
            host = db_api.host_get(allocation['compute_host_id'])
            pool.remove_computehost(h_reservation['aggregate_id'],
                                    host['service_name'])

        # Allocate an alternative host.
        start_date = max(datetime.datetime.utcnow(), lease['start_date'])
        new_hostids = self._matching_hosts(
            reservation['hypervisor_properties'],
            reservation['resource_properties'],
            '1-1', start_date, lease['end_date']
        )
        if not new_hostids:
            db_api.host_allocation_destroy(allocation['id'])
            LOG.warning('Could not find alternative host for reservation %s '
                        '(lease: %s).', reservation['id'], lease['name'])
            return False
        else:
            new_hostid = new_hostids.pop()
            db_api.host_allocation_update(allocation['id'],
                                          {'compute_host_id': new_hostid})
            LOG.warning('Resource changed for reservation %s (lease: %s).',
                        reservation['id'], lease['name'])
            if reservation['status'] == status.reservation.ACTIVE:
                # Add the alternative host into the aggregate.
                new_host = db_api.host_get(new_hostid)
                pool.add_computehost(h_reservation['aggregate_id'],
                                     new_host['service_name'])

            return True

    def _get_extra_capabilities(self, host_id):
        extra_capabilities = {}
        raw_extra_capabilities = (
            db_api.host_extra_capability_get_all_per_host(host_id))
        for capability, property_name in raw_extra_capabilities:
            key = property_name
            extra_capabilities[key] = capability.capability_value
        return extra_capabilities

    def get(self, host_id):
        return self.get_computehost(host_id)

    def get_computehost(self, host_id):
        host = db_api.host_get(host_id)
        extra_capabilities = self._get_extra_capabilities(host_id)
        if host is not None and extra_capabilities:
            res = host.copy()
            res.update(extra_capabilities)
            return res
        else:
            return host

    def list_computehosts(self, query=None):
        raw_host_list = db_api.host_list()
        host_list = []
        for host in raw_host_list:
            host_list.append(self.get_computehost(host['id']))
        return host_list

    def create_computehost(self, host_values):
        # TODO(sbauza):
        #  - Exception handling for HostNotFound
        host_id = host_values.pop('id', None)
        host_name = host_values.pop('name', None)
        try:
            trust_id = host_values.pop('trust_id')
        except KeyError:
            raise manager_ex.MissingTrustId()

        host_ref = host_id or host_name
        if host_ref is None:
            raise manager_ex.InvalidHost(host=host_values)

        with trusts.create_ctx_from_trust(trust_id):
            inventory = nova.NovaInventory()
            servers = inventory.get_servers_per_host(host_ref)
            if servers:
                raise manager_ex.HostHavingServers(host=host_ref,
                                                   servers=servers)
            host_details = inventory.get_host_details(host_ref)
            # NOTE(sbauza): Only last duplicate name for same extra capability
            # will be stored
            to_store = set(host_values.keys()) - set(host_details.keys())
            extra_capabilities_keys = to_store
            extra_capabilities = dict(
                (key, host_values[key]) for key in extra_capabilities_keys
            )

            if any([len(key) > 64 for key in extra_capabilities_keys]):
                raise manager_ex.ExtraCapabilityTooLong()

            self.placement_client.create_reservation_provider(
                host_details['hypervisor_hostname'])

            pool = nova.ReservationPool()
            pool.add_computehost(self.freepool_name,
                                 host_details['service_name'])

            host = None
            cantaddextracapability = []
            try:
                if trust_id:
                    host_details.update({'trust_id': trust_id})
                host = db_api.host_create(host_details)
            except db_ex.BlazarDBException as e:
                # We need to rollback
                # TODO(sbauza): Investigate use of Taskflow for atomic
                # transactions
                pool.remove_computehost(self.freepool_name,
                                        host_details['service_name'])
                self.placement_client.delete_reservation_provider(
                    host_details['hypervisor_hostname'])
                raise e
            for key in extra_capabilities:
                values = {'computehost_id': host['id'],
                          'property_name': key,
                          'capability_value': extra_capabilities[key],
                          }
                try:
                    db_api.host_extra_capability_create(values)
                except db_ex.BlazarDBException:
                    cantaddextracapability.append(key)
            if cantaddextracapability:
                raise manager_ex.CantAddExtraCapability(
                    keys=cantaddextracapability,
                    host=host['id'])
            return self.get_computehost(host['id'])

    def is_updatable_extra_capability(self, capability, property_name):
        reservations = db_utils.get_reservations_by_host_id(
            capability['computehost_id'], datetime.datetime.utcnow(),
            datetime.date.max)

        for r in reservations:
            plugin_reservation = db_utils.get_plugin_reservation(
                r['resource_type'], r['resource_id'])

            requirements_queries = plugins_utils.convert_requirements(
                plugin_reservation['resource_properties'])

            # TODO(masahito): If all the reservations using the
            # extra_capability can be re-allocated it's okay to update
            # the extra_capability.
            for requirement in requirements_queries:
                # A requirement is of the form "key op value" as string
                if requirement.split(" ")[0] == property_name:
                    return False
        return True

    def update_computehost(self, host_id, values):
        # nothing to update
        if not values:
            return self.get_computehost(host_id)

        cant_update_extra_capability = []
        previous_capabilities = self._get_extra_capabilities(host_id)
        updated_keys = set(values.keys()) & set(previous_capabilities.keys())
        new_keys = set(values.keys()) - set(previous_capabilities.keys())

        for key in updated_keys:
            raw_capability, property_name = next(iter(
                db_api.host_extra_capability_get_all_per_name(host_id, key)))
            capability = {'capability_value': values[key]}

            if self.is_updatable_extra_capability(
                    raw_capability, property_name):
                try:
                    db_api.host_extra_capability_update(
                        raw_capability['id'], capability)
                except (db_ex.BlazarDBException, RuntimeError):
                    cant_update_extra_capability.append(property_name)
            else:
                LOG.info("Capability %s can't be updated because "
                         "existing reservations require it.",
                         property_name)
                cant_update_extra_capability.append(property_name)

        for key in new_keys:
            new_capability = {
                'computehost_id': host_id,
                'property_name': key,
                'capability_value': values[key],
            }
            try:
                db_api.host_extra_capability_create(new_capability)
            except (db_ex.BlazarDBException, RuntimeError):
                cant_update_extra_capability.append(key)

        if cant_update_extra_capability:
            raise manager_ex.CantAddExtraCapability(
                host=host_id, keys=cant_update_extra_capability)

        LOG.info('Extra capabilities on compute host %s updated with %s',
                 host_id, values)
        return self.get_computehost(host_id)

    def delete_computehost(self, host_id):
        host = db_api.host_get(host_id)
        if not host:
            raise manager_ex.HostNotFound(host=host_id)

        with trusts.create_ctx_from_trust(host['trust_id']):
            if db_api.host_allocation_get_all_by_values(
                    compute_host_id=host_id):
                raise manager_ex.CantDeleteHost(
                    host=host_id,
                    msg='The host is reserved.'
                )

            inventory = nova.NovaInventory()
            servers = inventory.get_servers_per_host(
                host['hypervisor_hostname'])
            if servers:
                raise manager_ex.HostHavingServers(
                    host=host['hypervisor_hostname'], servers=servers)

            try:
                pool = nova.ReservationPool()
                pool.remove_computehost(self.freepool_name,
                                        host['service_name'])
                self.placement_client.delete_reservation_provider(
                    host['hypervisor_hostname'])
                # NOTE(sbauza): Extracapabilities will be destroyed thanks to
                #  the DB FK.
                db_api.host_destroy(host_id)
            except db_ex.BlazarDBException as e:
                # Nothing so bad, but we need to alert admins
                # they have to rerun
                raise manager_ex.CantDeleteHost(host=host_id, msg=str(e))

    def list_allocations(self, query):
        hosts_id_list = [h['id'] for h in db_api.host_list()]
        options = self.get_query_options(query, QUERY_TYPE_ALLOCATION)

        hosts_allocations = self.query_allocations(hosts_id_list, **options)
        return [{"resource_id": host, "reservations": allocs}
                for host, allocs in hosts_allocations.items()]

    def get_allocations(self, host_id, query):
        options = self.get_query_options(query, QUERY_TYPE_ALLOCATION)
        host_allocations = self.query_allocations([host_id], **options)
        if host_id not in host_allocations:
            host_allocations = {host_id: []}
        allocs = host_allocations[host_id]
        return {"resource_id": host_id, "reservations": allocs}

    def query_allocations(self, hosts, lease_id=None, reservation_id=None):
        """Return dict of host and its allocations.

        The list element forms
        {
          'host-id': [
                       {
                         'lease_id': lease_id,
                         'id': reservation_id,
                         'start_date': lease_start_date,
                         'end_date': lease_end_date,
                       },
                     ]
        }.
        """
        start = datetime.datetime.utcnow()
        end = datetime.date.max

        # To reduce overhead, this method only executes one query
        # to get the allocation information
        reservations = db_utils.get_reservation_allocations_by_host_ids(
            hosts, start, end, lease_id, reservation_id)
        host_allocs = {h: [] for h in hosts}
        attributes_to_copy = ["id", "lease_id", "start_date", "end_date"]
        for reservation in reservations:
            for host_id in reservation['host_ids']:
                if host_id in host_allocs.keys():
                    host_allocs[host_id].append({
                        k: v for k, v in reservation.items()
                        if k in attributes_to_copy})
        return host_allocs

    def allocation_candidates(self, values):
        self._check_params(values)

        return self._matching_hosts(
            values['hypervisor_properties'],
            values['resource_properties'],
            values['count_range'],
            values['start_date'],
            values['end_date'])

    def _matching_hosts(self, hypervisor_properties, resource_properties,
                        count_range, start_date, end_date):
        """Return the matching hosts (preferably not allocated)

        """
        count_range = count_range.split('-')
        min_host = count_range[0]
        max_host = count_range[1]
        allocated_host_ids = []
        not_allocated_host_ids = []
        filter_array = []
        start_date_with_margin = start_date - datetime.timedelta(
            minutes=CONF.cleaning_time)
        end_date_with_margin = end_date + datetime.timedelta(
            minutes=CONF.cleaning_time)

        # TODO(frossigneux) support "or" operator
        if hypervisor_properties:
            filter_array = plugins_utils.convert_requirements(
                hypervisor_properties)
        if resource_properties:
            filter_array += plugins_utils.convert_requirements(
                resource_properties)
        for host in db_api.reservable_host_get_all_by_queries(filter_array):
            if not db_api.host_allocation_get_all_by_values(
                    compute_host_id=host['id']):
                not_allocated_host_ids.append(host['id'])
            elif db_utils.get_free_periods(
                host['id'],
                start_date_with_margin,
                end_date_with_margin,
                end_date_with_margin - start_date_with_margin
            ) == [
                (start_date_with_margin, end_date_with_margin),
            ]:
                allocated_host_ids.append(host['id'])
        if len(not_allocated_host_ids) >= int(min_host):
            return not_allocated_host_ids[:int(max_host)]
        all_host_ids = allocated_host_ids + not_allocated_host_ids
        if len(all_host_ids) >= int(min_host):
            return all_host_ids[:int(max_host)]
        else:
            return []

    def _convert_int_param(self, param, name):
        """Checks that the parameter is present and can be converted to int."""
        if param is None:
            raise manager_ex.MissingParameter(param=name)
        if strutils.is_int_like(param):
            param = int(param)
        else:
            raise manager_ex.MalformedParameter(param=name)
        return param

    def _check_params(self, values):
        self._validate_min_max_range(values, values.get('min'),
                                     values.get('max'))

        if 'hypervisor_properties' not in values:
            raise manager_ex.MissingParameter(param='hypervisor_properties')
        if 'resource_properties' not in values:
            raise manager_ex.MissingParameter(param='resource_properties')

        if 'before_end' not in values:
            values['before_end'] = 'default'
        if values['before_end'] not in before_end_options:
            raise manager_ex.MalformedParameter(param='before_end')

    def _validate_min_max_range(self, values, min_hosts, max_hosts):
        self._convert_int_param(min_hosts, 'min')
        self._convert_int_param(max_hosts, 'max')
        if min_hosts <= 0 or max_hosts <= 0:
            raise manager_ex.MalformedParameter(
                param='min and max (must be greater than or equal to 1)')
        if max_hosts < min_hosts:
            raise manager_ex.InvalidRange()
        values['count_range'] = str(min_hosts) + '-' + str(max_hosts)

    def _update_allocations(self, dates_before, dates_after, reservation_id,
                            reservation_status, host_reservation, values):
        min_hosts = values.get('min', int(
            host_reservation['count_range'].split('-')[0]))
        max_hosts = values.get(
            'max', int(host_reservation['count_range'].split('-')[1]))
        self._validate_min_max_range(values, min_hosts, max_hosts)
        hypervisor_properties = values.get(
            'hypervisor_properties',
            host_reservation['hypervisor_properties'])
        resource_properties = values.get(
            'resource_properties',
            host_reservation['resource_properties'])
        allocs = db_api.host_allocation_get_all_by_values(
            reservation_id=reservation_id)

        allocs_to_remove = self._allocations_to_remove(
            dates_before, dates_after, max_hosts, hypervisor_properties,
            resource_properties, allocs)

        if (allocs_to_remove and
                reservation_status == status.reservation.ACTIVE):
            raise manager_ex.NotEnoughHostsAvailable()

        kept_hosts = len(allocs) - len(allocs_to_remove)
        if kept_hosts < max_hosts:
            min_hosts = min_hosts - kept_hosts \
                if (min_hosts - kept_hosts) > 0 else 0
            max_hosts = max_hosts - kept_hosts
            host_ids = self._matching_hosts(
                hypervisor_properties, resource_properties,
                str(min_hosts) + '-' + str(max_hosts),
                dates_after['start_date'], dates_after['end_date'])
            if len(host_ids) >= min_hosts:
                new_hosts = []
                pool = nova.ReservationPool()
                for host_id in host_ids:
                    db_api.host_allocation_create(
                        {'compute_host_id': host_id,
                         'reservation_id': reservation_id})
                    new_host = db_api.host_get(host_id)
                    new_hosts.append(new_host['service_name'])
                if reservation_status == status.reservation.ACTIVE:
                    # Add new hosts into the aggregate.
                    pool.add_computehost(host_reservation['aggregate_id'],
                                         new_hosts)
            else:
                raise manager_ex.NotEnoughHostsAvailable()

        for allocation in allocs_to_remove:
            db_api.host_allocation_destroy(allocation['id'])

    def _allocations_to_remove(self, dates_before, dates_after, max_hosts,
                               hypervisor_properties, resource_properties,
                               allocs):
        allocs_to_remove = []
        requested_host_ids = [host['id'] for host in
                              self._filter_hosts_by_properties(
                                  hypervisor_properties, resource_properties)]

        for alloc in allocs:
            if alloc['compute_host_id'] not in requested_host_ids:
                allocs_to_remove.append(alloc)
                continue
            if (dates_before['start_date'] > dates_after['start_date'] or
                    dates_before['end_date'] < dates_after['end_date']):
                reserved_periods = db_utils.get_reserved_periods(
                    alloc['compute_host_id'],
                    dates_after['start_date'],
                    dates_after['end_date'],
                    datetime.timedelta(seconds=1))

                max_start = max(dates_before['start_date'],
                                dates_after['start_date'])
                min_end = min(dates_before['end_date'],
                              dates_after['end_date'])

                if not (len(reserved_periods) == 0 or
                        (len(reserved_periods) == 1 and
                         reserved_periods[0][0] == max_start and
                         reserved_periods[0][1] == min_end)):
                    allocs_to_remove.append(alloc)
                    continue

        kept_hosts = len(allocs) - len(allocs_to_remove)
        if kept_hosts > max_hosts:
            allocs_to_remove.extend(
                [allocation for allocation in allocs
                 if allocation not in allocs_to_remove
                 ][:(kept_hosts - max_hosts)]
            )

        return allocs_to_remove

    def _filter_hosts_by_properties(self, hypervisor_properties,
                                    resource_properties):
        filter = []
        if hypervisor_properties:
            filter += plugins_utils.convert_requirements(hypervisor_properties)
        if resource_properties:
            filter += plugins_utils.convert_requirements(resource_properties)
        if filter:
            return db_api.host_get_all_by_queries(filter)
        else:
            return db_api.host_list()

class PhysicalHostMonitorPlugin(base.BaseMonitorPlugin,
                                nova.NovaClientWrapper):
    """Monitor plugin for physical host resource."""

    # Singleton design pattern
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super(PhysicalHostMonitorPlugin, cls).__new__(cls)
            cls._instance.healing_handlers = []
            super(PhysicalHostMonitorPlugin, cls._instance).__init__(
                username=CONF.os_admin_username,
                password=CONF.os_admin_password,
                user_domain_name=CONF.os_admin_user_domain_name,
                project_name=CONF.os_admin_project_name,
                project_domain_name=CONF.os_admin_project_domain_name)
        return cls._instance

    def __init__(self):
        """Do nothing.

        This class uses the Singleton design pattern and an instance of this
        class is generated and initialized in __new__().
        """
        pass

    def register_healing_handler(self, handler):
        self.healing_handlers.append(handler)

    def is_notification_enabled(self):
        """Check if the notification monitor is enabled."""
        return CONF[plugin.RESOURCE_TYPE].enable_notification_monitor

    def get_notification_event_types(self):
        """Get event types of notification messages to handle."""
        return ['service.update']

    def get_notification_topics(self):
        """Get topics of notification to subscribe to."""
        return CONF[plugin.RESOURCE_TYPE].notification_topics

    def notification_callback(self, event_type, payload):
        """Handle a notification message.

        It is used as a callback of a notification-based resource monitor.

        :param event_type: an event type of a notification.
        :param payload: a payload of a notification.
        :return: a dictionary of {reservation id: flags to update}
                 e.g. {'de27786d-bd96-46bb-8363-19c13b2c6657':
                       {'missing_resources': True}}
        """
        LOG.trace('Handling a notification...')
        reservation_flags = {}

        data = payload.get('nova_object.data', None)
        if data:
            if data['disabled'] or data['forced_down']:
                failed_hosts = db_api.reservable_host_get_all_by_queries(
                    ['hypervisor_hostname == ' + data['host']])
                if failed_hosts:
                    LOG.warning('%s failed.',
                                failed_hosts[0]['hypervisor_hostname'])
                    reservation_flags = self._handle_failures(failed_hosts)
            else:
                recovered_hosts = db_api.host_get_all_by_queries(
                    ['reservable == 0',
                     'hypervisor_hostname == ' + data['host']])
                if recovered_hosts:
                    db_api.host_update(recovered_hosts[0]['id'],
                                       {'reservable': True})
                    LOG.warning('%s recovered.',
                                recovered_hosts[0]['hypervisor_hostname'])

        return reservation_flags

    def is_polling_enabled(self):
        """Check if the polling monitor is enabled."""
        return CONF[plugin.RESOURCE_TYPE].enable_polling_monitor

    def get_polling_interval(self):
        """Get interval of polling."""
        return CONF[plugin.RESOURCE_TYPE].polling_interval

    def poll(self):
        """Detect and handle resource failures.

        :return: a dictionary of {reservation id: flags to update}
                 e.g. {'de27786d-bd96-46bb-8363-19c13b2c6657':
                 {'missing_resources': True}}
        """
        LOG.trace('Poll...')
        reservation_flags = {}

        failed_hosts, recovered_hosts = self._poll_resource_failures()
        if failed_hosts:
            for host in failed_hosts:
                LOG.warning('%s failed.', host['hypervisor_hostname'])
            reservation_flags = self._handle_failures(failed_hosts)
        if recovered_hosts:
            for host in recovered_hosts:
                db_api.host_update(host['id'], {'reservable': True})
                LOG.warning('%s recovered.', host['hypervisor_hostname'])

        return reservation_flags

    def _poll_resource_failures(self):
        """Check health of hosts by calling Nova Hypervisors API.

        :return: a list of failed hosts, a list of recovered hosts.
        """
        hosts = db_api.host_get_all_by_filters({})
        reservable_hosts = [h for h in hosts if h['reservable'] is True]
        unreservable_hosts = [h for h in hosts if h['reservable'] is False]

        try:
            hvs = self.nova.hypervisors.list()

            failed_hv_ids = [str(hv.id) for hv in hvs
                             if hv.state == 'down' or hv.status == 'disabled']
            failed_hosts = [host for host in reservable_hosts
                            if host['id'] in failed_hv_ids]

            active_hv_ids = [str(hv.id) for hv in hvs
                             if hv.state == 'up' and hv.status == 'enabled']
            recovered_hosts = [host for host in unreservable_hosts
                               if host['id'] in active_hv_ids]
        except Exception as e:
            LOG.exception('Skipping health check. %s', str(e))

        return failed_hosts, recovered_hosts

    def _handle_failures(self, failed_hosts):
        """Handle resource failures.

        :param failed_hosts: a list of failed hosts.
        :return: a dictionary of {reservation id: flags to update}
                 e.g. {'de27786d-bd96-46bb-8363-19c13b2c6657':
                 {'missing_resources': True}}
        """

        # Update the computehosts table
        for host in failed_hosts:
            try:
                db_api.host_update(host['id'], {'reservable': False})
            except Exception as e:
                LOG.exception('Failed to update %s. %s',
                              host['hypervisor_hostname'], str(e))

        # Heal related reservations
        return self.heal()

    def get_healing_interval(self):
        """Get interval of reservation healing in minutes."""
        return CONF[plugin.RESOURCE_TYPE].healing_interval

    def heal(self):
        """Heal suffering reservations in the next healing interval.

        :return: a dictionary of {reservation id: flags to update}
        """
        reservation_flags = {}
        hosts = db_api.unreservable_host_get_all_by_queries([])

        interval_begin = datetime.datetime.utcnow()
        interval = self.get_healing_interval()
        if interval == 0:
            interval_end = datetime.date.max
        else:
            interval_end = interval_begin + datetime.timedelta(
                minutes=interval)

        for handler in self.healing_handlers:
            reservation_flags.update(handler(hosts,
                                             interval_begin,
                                             interval_end))

        return reservation_flags


text:
class MeetingIDs
	include Scraper

	attr_reader :ids

	# TO DO: Pass scrape decision body IDs and pass them into this class to get
	# 			 meeting IDs for different committees.
	def initialize(date)
		@now           = date
		@decision_body = "961"
		@ids           = meeting_ids
	end

	private

	def meeting_ids
		page        = meeting_page
		headers     = page.css("h3").to_ary
		headers.map do |header|
		  header.attr("id").remove("header") if past_meeting? header
		end.flatten.reject(&:nil?)
	end

	def meeting_page
  	url  = "decisionBodyProfile.do?function=doPrepare&decisionBodyId=#{@decision_body}"
		page = get url
		Nokogiri::HTML(page)
	end

	def past_meeting?(header)
		meeting_date = DateTime.parse(header.text.split("-")[0].strip)
		@now - meeting_date > 0 ? true : false
	end

end


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ecopueblo.app" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>EcoPueblo</name>
    <description>
        App para los vendedores de loteos en EcoPueblo
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Alpha Social Marketing
    </author>
    <content src="index.html" />
    <icon src="img/logo-isotipo.png"/>
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <preference name="android-minSdkVersion" value="14" />
        <!--<preference name="Orientation" value="landscape" />-->
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <preference name="BackupWebStorage" value="none" />
    </platform>
    <preference name="DisallowOverscroll" value="true" />
    <plugin name="cordova-plugin-whitelist" spec="~1.2.0" />
    <plugin name="cordova-plugin-console" spec="~1.0.1" />
    <plugin name="cordova-plugin-statusbar" spec="~1.0.1" />
</widget>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/header_image"
        android:layout_width="match_parent"
        android:layout_height="240dp"
        android:src="@mipmap/header_image"
        android:scaleType="centerCrop" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Material Design"
        android:textColor="@color/white"
        android:textSize="23sp"
        android:layout_alignBottom="@id/header_image"
        android:layout_margin="16dp"
        />
</RelativeLayout>


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

	var isArray = require('util').isArray;
	var analyzers = require('./lib/analyzers');

	var analyzersMapping = {
		all: 					analyzers.AllCharsAnalyzer,
		bylength:				analyzers.PasswordLengthAnalyzer,
		loweralpha:				analyzers.LowerAlphaAnalyzer,
		loweralphanum:			analyzers.LowerAlphaNumAnalyzer,
		loweralphaspecial: 		analyzers.LowerAlphaSpecialAnalyzer,
		loweralphaspecialnum: 	analyzers.LowerAlphaSpecialNumAnalyzer,
		mixedalpha:				analyzers.MixedAlphaAnalyzer,
		mixedalphanum:			analyzers.MixedAlphaNumAnalyzer,
		mixedalphaspecial: 		analyzers.MixedAlphaSpecialAnalyzer,
		months:					analyzers.MonthsAnalyzer,
		numeric:				analyzers.NumericAnalyzer,
		special:				analyzers.SpecialAnalyzer,
		specialnum:				analyzers.SpecialNumAnalyzer,
		upperalpha:				analyzers.UpperAlphaAnalyzer,
		upperalphanum:			analyzers.UpperAlphaNumAnalyzer,
		upperalphaspecial: 		analyzers.UpperAlphaSpecialAnalyzer,
		upperalphaspecialnum: 	analyzers.UpperAlphaSpecialNumAnalyzer
	};

	function PasswordAnalyzer () {
		this._groups = [];
		this._total = 0;
	}

	PasswordAnalyzer.prototype.addGroup = function (name, analyzersOrFn) {
		if (!analyzersOrFn) {
			throw new Error('Analyzers are required');
		}
		var group;

		for (var i = this._groups.length - 1; i >= 0; i--) {
			if(this._groups[i].name === name) {
				group = this._groups[i];
				break;
			}
		}

		if(!group) {
			group = new Group(name);
			this._groups.push(group);
		}

		if(isArray(analyzersOrFn)) {
			analyzersOrFn.forEach(group.addAnalyzer.bind(group));
		}
		else {
			group.addAnalyzer(analyzersOrFn);
		}
	};

	PasswordAnalyzer.prototype.analyze = function (password) {
		this._total++;
		this._groups.forEach(function (group) {
			group.analyze(password);
		});
	};

	PasswordAnalyzer.prototype.getResults = function() {
		var results = { total: this._total, groups: [] };

		return this._groups.reduce(function (results, group) {
			results.groups.push(group.getResults());
			return results;
		}, results);
	};

	function Group (name, analyzers) {
		this.name = name || '[group]';
		this._results = {};
		this._analyzers = [];

		if(isArray(analyzers)) {
			this._analyzers = this._analyzers.concat(analyzers);
		} else if(analyzers) {
			this.analyzers.push(analyzers);
		}
	}

	Group.prototype.addAnalyzer = function (analyzer) {
		if(isFunction(analyzer)) {
			/*jshint -W055 */
			this._analyzers.push(new analyzer());
		}
		else if(typeof analyzer === 'string') {
			this._analyzers.push(new analyzersMapping[analyzer]());
		}
		else {
			this._analyzers.push(analyzer);
		}
	};

	Group.prototype.analyze = function (password) {
		this._results.total++;
		this._analyzers.forEach(function (analyzer) {
			analyzer.analyze(password, this._results);
		}, this);
	};

	Group.prototype.getResults = function() {
		var results = { name: this.name, analyzers:[] };

		this._analyzers.reduce(function (results, analyzer) {
			Array.prototype.push.apply(results, analyzer.getResults());
			return results;
		}, results.analyzers);

		return results;
	};

	module.exports = {
		PasswordAnalyzer: PasswordAnalyzer,
		analyzers: analyzers
	};

	function isFunction(object) {
		return !!(object && object.constructor && object.call && object.apply);
	}
}());


text:
package main

import (
	"context"
	"net/http"
	"os"
	"runtime"
	"time"

	"github.com/coreos/vault-operator/pkg/operator"
	"github.com/coreos/vault-operator/pkg/util/k8sutil"
	"github.com/coreos/vault-operator/pkg/util/probe"
	"github.com/coreos/vault-operator/version"

	"github.com/sirupsen/logrus"
	"k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	v1core "k8s.io/client-go/kubernetes/typed/core/v1"
	"k8s.io/client-go/tools/leaderelection"
	"k8s.io/client-go/tools/leaderelection/resourcelock"
	"k8s.io/client-go/tools/record"
)

func main() {
	namespace := os.Getenv("MY_POD_NAMESPACE")
	if len(namespace) == 0 {
		logrus.Fatalf("must set env MY_POD_NAMESPACE")
	}
	name := os.Getenv("MY_POD_NAME")
	if len(name) == 0 {
		logrus.Fatalf("must set env MY_POD_NAME")
	}

	logrus.Infof("Go Version: %s", runtime.Version())
	logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
	logrus.Infof("vault-operator Version: %v", version.Version)
	logrus.Infof("Git SHA: %s", version.GitSHA)

	kubecfg, err := k8sutil.InClusterConfig()
	if err != nil {
		panic(err)
	}
	kubecli := kubernetes.NewForConfigOrDie(kubecfg)

	http.HandleFunc(probe.HTTPReadyzEndpoint, probe.ReadyzHandler)
	go http.ListenAndServe("0.0.0.0:8080", nil)

	id, err := os.Hostname()
	if err != nil {
		logrus.Fatalf("failed to get hostname: %v", err)
	}
	rl, err := resourcelock.New(resourcelock.EndpointsResourceLock,
		namespace,
		"vault-operator",
		kubecli.CoreV1(),
		resourcelock.ResourceLockConfig{
			Identity:      id,
			EventRecorder: createRecorder(kubecli, name, namespace),
		})
	if err != nil {
		logrus.Fatalf("error creating lock: %v", err)
	}

	leaderelection.RunOrDie(leaderelection.LeaderElectionConfig{
		Lock:          rl,
		LeaseDuration: 15 * time.Second,
		RenewDeadline: 10 * time.Second,
		RetryPeriod:   2 * time.Second,
		Callbacks: leaderelection.LeaderCallbacks{
			OnStartedLeading: run,
			OnStoppedLeading: func() {
				logrus.Fatalf("leader election lost")
			},
		},
	})
	// unreachable
}

func run(stop <-chan struct{}) {
	v := operator.New()
	err := v.Start(context.TODO())
	if err != nil {
		// If we don't exit the program,
		// there is another go routine that keeps renewing the LE lock.
		logrus.Fatalf("operator stopped with %v", err)
	}
}

func createRecorder(kubecli kubernetes.Interface, name, namespace string) record.EventRecorder {
	eventBroadcaster := record.NewBroadcaster()
	eventBroadcaster.StartLogging(logrus.Infof)
	eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(kubecli.Core().RESTClient()).Events(namespace)})
	return eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: name})
}


text:
/*
 *  sdp_rfcomm_query.h
 */

#pragma once

#include <btstack/utils.h>
#include "sdp_parser.h"
#include "sdp_query_util.h"

#define SDP_SERVICE_NAME_LEN 20

#if defined __cplusplus
extern "C" {
#endif

/* SDP Queries */

/* SDP Query for RFCOMM */

// SDP Query RFCOMM event to deliver channel number and service name
// byte by byte.
typedef struct sdp_query_rfcomm_service_event {
    uint8_t type;
    uint8_t channel_nr;
    uint8_t * service_name;
} sdp_query_rfcomm_service_event_t;

void sdp_query_rfcomm_init(void);

// Searches SDP records on a remote device for RFCOMM services with
// a given UUID.
void sdp_query_rfcomm_channel_and_name_for_uuid(bd_addr_t remote, uint16_t uuid);

// Searches SDP records on a remote device for RFCOMM services with
// a given service search pattern.
void sdp_query_rfcomm_channel_and_name_for_search_pattern(bd_addr_t remote, uint8_t * des_serviceSearchPattern);

// Registers a callback to receive RFCOMM service and query complete event.
void sdp_query_rfcomm_register_callback(void(*sdp_app_callback)(sdp_query_event_t * event, void * context), void * context);

#if defined __cplusplus
}
#endif


text:
from itertools import zip_longest
from pyfasta import Fasta
from fast2phy.command_line import make_parser

LINE_LENGTH = 60
CHUNK_LENGTH = 10
PAD_STRING = ''.ljust(CHUNK_LENGTH)

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def main():
    args = make_parser()
    if args.inplace:
        f = Fasta(args.fasta_file, flatten_inplace=True)
    else:
        f = Fasta(args.fasta_file)

    if args.output_file is not None:
        output = open(args.output_file, 'w')
    else:
        output_file_name = args.fasta_file.split('.')[0]
        output_file = '{0}.phylip'.format(output_file_name)
        output = open(output_file, 'w')

    sequence_count = len(f.keys())
    sequence_length = len(f[next(iter(f.keys()))])
    # print('', sequence_count, sequence_length, sep=' ')
    output.write(' {0} {1}\n'.format(sequence_count, sequence_length))

    for key in f.keys():
        subseq = []
        for chunk in grouper(f[key][:LINE_LENGTH], CHUNK_LENGTH):
            subseq.append(''.join(item[0] for item in chunk))
        subseq = ' '.join(subseq)
        if len(key) < CHUNK_LENGTH:
            key = key.ljust(CHUNK_LENGTH)
        else:
            key = key[:CHUNK_LENGTH]
        # print(key, ' ', subseq)
        output.write('{0} {1}\n'.format(key, subseq))

    sequence_length -= LINE_LENGTH
    start = LINE_LENGTH
    stop = LINE_LENGTH * 2
    # print()
    output.write('\n')

    while sequence_length > 0:
        for key in f.keys():
            subseq = []
            for chunk in grouper(f[key][start:stop], CHUNK_LENGTH, ' '):
                subseq.append(''.join(item[0] for item in chunk))
            subseq = ' '.join(subseq)
            # print(PAD_STRING, ' ', subseq)
            output.write('{0} {1}\n'.format(PAD_STRING, subseq))
        sequence_length -= LINE_LENGTH
        start += LINE_LENGTH
        stop += LINE_LENGTH
        # print()
        output.write('\n')

    output.close()

if __name__ == '__main__':
    main()


text:
@media only print{
a,a:visited{text-decoration:underline}
a[href]:after{content:" (" attr(href) ")"}
abbr[title]:after{content:" (" attr(title) ")"}
}


text:
package org.thingsboard.rule.engine.action;

import lombok.Data;
import org.thingsboard.rule.engine.api.NodeConfiguration;
import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.script.ScriptLanguage;

import java.util.Collections;
import java.util.List;

@Data
public class TbCreateAlarmNodeConfiguration extends TbAbstractAlarmNodeConfiguration implements NodeConfiguration<TbCreateAlarmNodeConfiguration> {

    private String severity;
    private boolean propagate;
    private boolean propagateToOwner;
    private boolean propagateToTenant;
    private boolean useMessageAlarmData;
    private boolean overwriteAlarmDetails = true;
    private boolean dynamicSeverity;

    private List<String> relationTypes;

    @Override
    public TbCreateAlarmNodeConfiguration defaultConfiguration() {
        TbCreateAlarmNodeConfiguration configuration = new TbCreateAlarmNodeConfiguration();
        configuration.setScriptLang(ScriptLanguage.MVEL);
        configuration.setAlarmDetailsBuildJs(ALARM_DETAILS_BUILD_JS_TEMPLATE);
        configuration.setAlarmDetailsBuildMvel(ALARM_DETAILS_BUILD_MVEL_TEMPLATE);
        configuration.setAlarmType("General Alarm");
        configuration.setSeverity(AlarmSeverity.CRITICAL.name());
        configuration.setPropagate(false);
        configuration.setPropagateToOwner(false);
        configuration.setPropagateToTenant(false);
        configuration.setUseMessageAlarmData(false);
        configuration.setOverwriteAlarmDetails(false);
        configuration.setRelationTypes(Collections.emptyList());
        configuration.setDynamicSeverity(false);
        return configuration;
    }

}


text:
package org.jboss.shrinkwrap.impl.gradle.archive.importer.embedded;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URI;

import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.model.DomainObjectSet;
import org.gradle.tooling.model.GradleProject;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Assignable;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.gradle.archive.importer.embedded.ConfigurationStage;
import org.jboss.shrinkwrap.api.gradle.archive.importer.embedded.DistributionConfigurationStage;
import org.jboss.shrinkwrap.api.gradle.archive.importer.embedded.EmbeddedGradleImporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.impl.base.Validate;

/**
 * @author Michal Matloka
 */
public class EmbeddedGradleImporterImpl implements EmbeddedGradleImporter, DistributionConfigurationStage {

    private static final String SAX_PARSER_FACTORY_KEY = "javax.xml.parsers.SAXParserFactory";

    private final Archive<?> archive;

    private final GradleConnector connector = GradleConnector.newConnector();

    private String[] tasks = new String[] { "build" };
    private String[] arguments = new String[] { "--exclude-task", "test" };

    private BuildLauncher buildLauncher;

    private ProjectConnection projectConnection;

    private String projectName;

    private File buildResult;

    private BuildLauncher getBuildLauncher() {
        if (buildLauncher == null) {
            projectConnection = connector.connect();
            buildLauncher = projectConnection.newBuild();
        }
        return buildLauncher;
    }

    public EmbeddedGradleImporterImpl(Archive<?> archive) {
        this.archive = archive;
    }

    @Override
    public DistributionConfigurationStage forProjectDirectory(final File projectDir) {
        Validate.notNull(projectDir, "Project directory file can not be null!");

        final File absoluteFile = projectDir.getAbsoluteFile();
        if (!absoluteFile.exists()) {
            throw new IllegalArgumentException("Given project dir do not exist: " + absoluteFile);
        } else if (!absoluteFile.isDirectory()) {
            throw new IllegalArgumentException("Given project dir is not a directory" + absoluteFile);
        }

        projectName = absoluteFile.getName();
        connector.forProjectDirectory(absoluteFile);
        return this;
    }

    @Override
    public DistributionConfigurationStage forProjectDirectory(final String projectDir) {
        Validate.notNull(projectDir, "Project directory path can not be null or empty");

        return this.forProjectDirectory(new File(projectDir));
    }

    @Override
    public DistributionConfigurationStage forThisProjectDirectory() {
        return forProjectDirectory("");
    }

    @Override
    public <TYPE extends Assignable> TYPE as(final Class<TYPE> clazz) {
        final File result;
        if (buildResult == null) {
            result = importFromDefaultLibsDirectory();
        } else {
            result = importFromConfiguredPath();
        }
        return ShrinkWrap.create(ZipImporter.class, archive.getName()).importFrom(result).as(clazz);
    }

    private File importFromDefaultLibsDirectory() {
        final GradleProject currentGradleProject = findCurrentGradleProject();
        final File buildDir = currentGradleProject.getBuildDirectory();
        final File libsDir = new File(buildDir, "libs");
        final File[] results = libsDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(final File dir, final String name) {
                return name.startsWith(currentGradleProject.getName());
            }
        });

        if (results == null || results.length == 0) {
            throw new IllegalArgumentException(
                "Wrong project directory is used. Tests have to be run from working directory which is a current sub-module directory.");
        }

        return results[0];
    }

    private File importFromConfiguredPath() {
        return buildResult;
    }

    private GradleProject findCurrentGradleProject() {
        final GradleProject rootGradleProject = projectConnection.getModel(GradleProject.class);
        if (!rootGradleProject.getName().equals(projectName)) {
            final GradleProject child = findChildProject(rootGradleProject, projectName);
            if (child != null) {
                return child;

            }
        }
        return rootGradleProject;
    }

    private GradleProject findChildProject(GradleProject gradleProject, String childProjectName) {
        final DomainObjectSet<? extends GradleProject> children = gradleProject.getChildren();
        for (GradleProject child : children) {
            if (child.getName().equals(childProjectName)) {
                return child;
            }
        }

        for (GradleProject child : children) {
            final GradleProject foundChild = findChildProject(child, childProjectName);
            if (foundChild != null) {
                return foundChild;
            }
        }

        return null;
    }

    @Override
    public ConfigurationStage useGradleVersion(final String version) {
        connector.useGradleVersion(version);
        return this;
    }

    @Override
    public ConfigurationStage useDistribution(final URI gradleDistribution) {
        connector.useDistribution(gradleDistribution);
        return this;
    }

    @Override
    public ConfigurationStage useInstallation(final File gradleHome) {
        connector.useInstallation(gradleHome);
        return this;
    }

    @Override
    public ConfigurationStage useDefaultDistribution() {
        return this;
    }

    @Override
    public ConfigurationStage useGradleUserHomeDir(final File gradleUserHomeDir) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
        return this;
    }

    @Override
    public ConfigurationStage forTasks(final String... tasks) {
        this.tasks = tasks;
        return this;
    }

    @Override
    public ConfigurationStage withArguments(final String... arguments) {
        this.arguments = arguments;
        return this;
    }

    @Override
    public ConfigurationStage setJavaHome(final File javaHome) {
        getBuildLauncher().setJavaHome(javaHome);
        return this;
    }

    @Override
    public ConfigurationStage setJvmArguments(final String... jvmArguments) {
        getBuildLauncher().setJvmArguments(jvmArguments);
        return this;
    }

    @Override
    public Assignable importBuildOutput() {
        final String oldValue = removeSAXParserFactoryProperty();
        getBuildLauncher().forTasks(tasks).withArguments(arguments).run();
        setSAXParserFactoryProperty(oldValue);
        return this;
    }

    @Override
    public Assignable importBuildOutput(File buildResult) {
        this.buildResult = buildResult.getAbsoluteFile();
        return importBuildOutput();
    }

    @Override
    public Assignable importBuildOutput(String buildResult) {
        return importBuildOutput(new File(buildResult));
    }

    private String removeSAXParserFactoryProperty() {
        // solution for https://issues.jboss.org/browse/SHRINKRES-212
        final Object value = System.getProperties().remove(SAX_PARSER_FACTORY_KEY);
        return value != null ? (String) value : null;
    }

    private void setSAXParserFactoryProperty(String oldValue) {
        if (oldValue != null) {
            System.setProperty(SAX_PARSER_FACTORY_KEY, oldValue);
        }
    }
}


text:
#ifndef __CONFIG_DEVKIT3250_H__
#define __CONFIG_DEVKIT3250_H__

/* SoC and board defines */
#include <linux/sizes.h>
#include <asm/arch/cpu.h>

/*
 * Define DevKit3250 machine type by hand until it lands in mach-types
 */
#define MACH_TYPE_DEVKIT3250		3697
#define CONFIG_MACH_TYPE		MACH_TYPE_DEVKIT3250

#define CONFIG_SYS_ICACHE_OFF
#define CONFIG_SYS_DCACHE_OFF
#if !defined(CONFIG_SPL_BUILD)
#define CONFIG_SKIP_LOWLEVEL_INIT
#endif
#define CONFIG_BOARD_EARLY_INIT_F

/*
 * Memory configurations
 */
#define CONFIG_NR_DRAM_BANKS		1
#define CONFIG_SYS_MALLOC_LEN		SZ_1M
#define CONFIG_SYS_SDRAM_BASE		EMC_DYCS0_BASE
#define CONFIG_SYS_SDRAM_SIZE		SZ_64M
#define CONFIG_SYS_TEXT_BASE		0x83F00000
#define CONFIG_SYS_MEMTEST_START	(CONFIG_SYS_SDRAM_BASE + SZ_32K)
#define CONFIG_SYS_MEMTEST_END		(CONFIG_SYS_TEXT_BASE - SZ_1M)

#define CONFIG_SYS_LOAD_ADDR		(CONFIG_SYS_SDRAM_BASE + SZ_32K)

#define CONFIG_SYS_INIT_SP_ADDR		(CONFIG_SYS_SDRAM_BASE + SZ_4K \
					 - GENERATED_GBL_DATA_SIZE)

/*
 * Serial Driver
 */
#define CONFIG_SYS_LPC32XX_UART		5   /* UART5 */
#define CONFIG_BAUDRATE			115200

/*
 * DMA
 */
#if !defined(CONFIG_SPL_BUILD)
#define CONFIG_DMA_LPC32XX
#endif

/*
 * I2C
 */
#define CONFIG_SYS_I2C
#define CONFIG_SYS_I2C_LPC32XX
#define CONFIG_SYS_I2C_SPEED		100000

/*
 * GPIO
 */
#define CONFIG_LPC32XX_GPIO

/*
 * SSP/SPI
 */
#define CONFIG_LPC32XX_SSP
#define CONFIG_LPC32XX_SSP_TIMEOUT	100000

/*
 * Ethernet
 */
#define CONFIG_RMII
#define CONFIG_PHY_SMSC
#define CONFIG_LPC32XX_ETH
#define CONFIG_PHYLIB
#define CONFIG_PHY_ADDR			0x1F
#define CONFIG_SYS_FAULT_ECHO_LINK_DOWN

/*
 * NOR Flash
 */
#define CONFIG_SYS_MAX_FLASH_BANKS	1
#define CONFIG_SYS_MAX_FLASH_SECT	71
#define CONFIG_SYS_FLASH_BASE		EMC_CS0_BASE
#define CONFIG_SYS_FLASH_SIZE		SZ_4M
#define CONFIG_SYS_FLASH_CFI

/*
 * NAND controller
 */
#define CONFIG_NAND_LPC32XX_SLC
#define CONFIG_SYS_NAND_BASE		SLC_NAND_BASE
#define CONFIG_SYS_MAX_NAND_DEVICE	1
#define CONFIG_SYS_NAND_BASE_LIST	{ CONFIG_SYS_NAND_BASE }

/*
 * NAND chip timings
 */
#define CONFIG_LPC32XX_NAND_SLC_WDR_CLKS	14
#define CONFIG_LPC32XX_NAND_SLC_WWIDTH		66666666
#define CONFIG_LPC32XX_NAND_SLC_WHOLD		200000000
#define CONFIG_LPC32XX_NAND_SLC_WSETUP		50000000
#define CONFIG_LPC32XX_NAND_SLC_RDR_CLKS	14
#define CONFIG_LPC32XX_NAND_SLC_RWIDTH		66666666
#define CONFIG_LPC32XX_NAND_SLC_RHOLD		200000000
#define CONFIG_LPC32XX_NAND_SLC_RSETUP		50000000

#define CONFIG_SYS_NAND_BLOCK_SIZE		0x20000
#define CONFIG_SYS_NAND_PAGE_SIZE		NAND_LARGE_BLOCK_PAGE_SIZE
#define CONFIG_SYS_NAND_USE_FLASH_BBT

#define CONFIG_CMD_JFFS2
#define CONFIG_CMD_NAND

/*
 * USB
 */
#define CONFIG_USB_OHCI_LPC32XX
#define CONFIG_USB_ISP1301_I2C_ADDR		0x2d

/*
 * U-Boot General Configurations
 */
#define CONFIG_SYS_LONGHELP
#define CONFIG_SYS_CBSIZE		1024
#define CONFIG_SYS_PBSIZE		\
	(CONFIG_SYS_CBSIZE + sizeof(CONFIG_SYS_PROMPT) + 16)
#define CONFIG_SYS_MAXARGS		16
#define CONFIG_SYS_BARGSIZE		CONFIG_SYS_CBSIZE

#define CONFIG_AUTO_COMPLETE
#define CONFIG_CMDLINE_EDITING
#define CONFIG_DISPLAY_CPUINFO
#define CONFIG_DOS_PARTITION

/*
 * Pass open firmware flat tree
 */

/*
 * Environment
 */
#define CONFIG_ENV_IS_IN_NAND		1
#define CONFIG_ENV_SIZE			SZ_128K
#define CONFIG_ENV_OFFSET		0x000A0000

#define CONFIG_BOOTCOMMAND			\
	"dhcp; "				\
	"tftp ${loadaddr} ${serverip}:${tftpdir}/${bootfile}; "		\
	"tftp ${dtbaddr} ${serverip}:${tftpdir}/devkit3250.dtb; "	\
	"setenv nfsargs ip=dhcp root=/dev/nfs nfsroot=${serverip}:${nfsroot},tcp; "	\
	"setenv bootargs ${bootargs} ${nfsargs} ${userargs}; "			\
	"bootm ${loadaddr} - ${dtbaddr}"

#define CONFIG_EXTRA_ENV_SETTINGS		\
	"autoload=no\0"				\
	"ethaddr=00:01:90:00:C0:81\0"		\
	"dtbaddr=0x81000000\0"			\
	"nfsroot=/opt/projects/images/vladimir/oe/devkit3250/rootfs\0"	\
	"tftpdir=vladimir/oe/devkit3250\0"	\
	"userargs=oops=panic\0"

/*
 * U-Boot Commands
 */

/*
 * Boot Linux
 */
#define CONFIG_CMDLINE_TAG
#define CONFIG_SETUP_MEMORY_TAGS

#define CONFIG_BOOTFILE			"uImage"
#define CONFIG_BOOTARGS			"console=ttyS0,115200n8"
#define CONFIG_LOADADDR			0x80008000

/*
 * SPL specific defines
 */
/* SPL will be executed at offset 0 */
#define CONFIG_SPL_TEXT_BASE		0x00000000

/* SPL will use SRAM as stack */
#define CONFIG_SPL_STACK		0x0000FFF8
#define CONFIG_SPL_BOARD_INIT

/* Use the framework and generic lib */
#define CONFIG_SPL_FRAMEWORK
#define CONFIG_SPL_LIBGENERIC_SUPPORT
#define CONFIG_SPL_LIBCOMMON_SUPPORT

/* SPL will use serial */
#define CONFIG_SPL_SERIAL_SUPPORT

/* SPL loads an image from NAND */
#define CONFIG_SPL_NAND_SIMPLE
#define CONFIG_SPL_NAND_RAW_ONLY
#define CONFIG_SPL_NAND_SUPPORT
#define CONFIG_SPL_NAND_DRIVERS

#define CONFIG_SPL_NAND_ECC
#define CONFIG_SPL_NAND_SOFTECC

#define CONFIG_SPL_MAX_SIZE		0x20000
#define CONFIG_SPL_PAD_TO		CONFIG_SPL_MAX_SIZE

/* U-Boot will be 0x60000 bytes, loaded and run at CONFIG_SYS_TEXT_BASE */
#define CONFIG_SYS_NAND_U_BOOT_OFFS	0x40000
#define CONFIG_SYS_NAND_U_BOOT_SIZE	0x60000

#define CONFIG_SYS_NAND_U_BOOT_START	CONFIG_SYS_TEXT_BASE
#define CONFIG_SYS_NAND_U_BOOT_DST	CONFIG_SYS_TEXT_BASE

/* See common/spl/spl.c  spl_set_header_raw_uboot() */
#define CONFIG_SYS_MONITOR_LEN		CONFIG_SYS_NAND_U_BOOT_SIZE

/*
 * Include SoC specific configuration
 */
#include <asm/arch/config.h>

#endif  /* __CONFIG_DEVKIT3250_H__*/


text:
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Common styles for adapting cr-button with cros colors.
 */

// Force tsc to consider this file a module.
export {};

const template = document.createElement('dom-module');
template.innerHTML = `{__html_template__}`;
template.register('cros-button-style');


text:
/**
 * Functionality for drawing waved lines.
 */
import { __extends } from "tslib";
/**
 * ============================================================================
 * IMPORTS
 * ============================================================================
 * @hidden
 */
import { Line } from "./Line";
import { color } from "../utils/Color";
import { wavedLine } from "../rendering/Smoothing";
import * as $path from "../rendering/Path";
/**
 * ============================================================================
 * MAIN CLASS
 * ============================================================================
 * @hidden
 */
/**
 * Draws a waved line.
 *
 * @see {@link IWavedLineEvents} for a list of available events
 * @see {@link IWavedLineAdapters} for a list of available Adapters
 */
var WavedLine = /** @class */ (function (_super) {
    __extends(WavedLine, _super);
    /**
     * Constructor
     */
    function WavedLine() {
        var _this = _super.call(this) || this;
        _this.className = "WavedLine";
        _this.element = _this.paper.add("path");
        _this.waveLength = 16;
        _this.waveHeight = 4;
        _this.tension = 0.8;
        _this.pixelPerfect = false;
        _this.fill = color();
        _this.applyTheme();
        return _this;
    }
    /**
     * Draws the waved line.
     *
     * @ignore Exclude from docs
     */
    WavedLine.prototype.draw = function () {
        //super.draw();
        var p1 = { x: this.x1, y: this.y1 };
        var p2 = { x: this.x2, y: this.y2 };
        this.path = $path.moveTo(p1) + wavedLine(p1, p2, this.waveLength, this.waveHeight, this.tension, true);
    };
    Object.defineProperty(WavedLine.prototype, "waveLength", {
        /**
         * @return Wave length (px)
         */
        get: function () {
            return this.getPropertyValue("waveLength");
        },
        /**
         * Wave length in pixels.
         *
         * @default 16
         * @param value  Wave length (px)
         */
        set: function (value) {
            this.setPropertyValue("waveLength", value);
            this.invalidate();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(WavedLine.prototype, "waveHeight", {
        /**
         * @return Wave height (px)
         */
        get: function () {
            return this.getPropertyValue("waveHeight");
        },
        /**
         * Wave height in pixels.
         *
         * @default 4
         * @param value  Wave height (px)
         */
        set: function (value) {
            this.setPropertyValue("waveHeight", value);
            this.invalidate();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(WavedLine.prototype, "tension", {
        /**
         * @return Tension
         */
        get: function () {
            return this.getPropertyValue("tension");
        },
        /**
         * Tension of the wave.
         *
         * @default 0.8
         * @param value  Tension
         */
        set: function (value) {
            this.setPropertyValue("tension", value);
            this.invalidate();
        },
        enumerable: true,
        configurable: true
    });
    return WavedLine;
}(Line));
export { WavedLine };
//# sourceMappingURL=WavedLine.js.map


text:
{% load i18n %}

{% trans "Remove donation wallpost" %}

    {% trans "Remove the donation wallpost for " %}
    "{{effects.0.instance}}"
    {% if effects|length > 1 %}
        {% blocktrans with extra=effects|length|add:"-1" %}
        and {{ extra }} other donations
        {% endblocktrans %}
    {% endif %}


text:
<?php

namespace Tests\Linting;

use PHPUnit\Framework\TestCase;
use Tighten\TLint\Utils\ParsesGitOutput;

class EmptyDiffDoesNotTriggerWarningTest extends TestCase
{
    /** @test */
    public function gracefully_handles_empty_diff()
    {
        $files = ParsesGitOutput::parseFilesFromGitDiffOutput('');

        $this->assertCount(0, $files);
    }
}


text:
"""The tests for the Recorder component."""
# pylint: disable=protected-access
import json
from datetime import datetime, timedelta
import unittest

import pytest
from homeassistant.core import callback
from homeassistant.const import MATCH_ALL
from homeassistant.components import recorder
from homeassistant.bootstrap import setup_component
from tests.common import get_test_home_assistant

class TestRecorder(unittest.TestCase):
    """Test the recorder module."""

    def setUp(self):  # pylint: disable=invalid-name
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        db_uri = 'sqlite://'  # In memory DB
        setup_component(self.hass, recorder.DOMAIN, {
            recorder.DOMAIN: {recorder.CONF_DB_URL: db_uri}})
        self.hass.start()
        recorder._verify_instance()
        self.session = recorder.Session()
        recorder._INSTANCE.block_till_done()

    def tearDown(self):  # pylint: disable=invalid-name
        """Stop everything that was started."""
        recorder._INSTANCE.shutdown(None)
        self.hass.stop()
        assert recorder._INSTANCE is None

    def _add_test_states(self):
        """Add multiple states to the db for testing."""
        now = datetime.now()
        five_days_ago = now - timedelta(days=5)
        attributes = {'test_attr': 5, 'test_attr_10': 'nice'}

        self.hass.block_till_done()
        recorder._INSTANCE.block_till_done()

        for event_id in range(5):
            if event_id < 3:
                timestamp = five_days_ago
                state = 'purgeme'
            else:
                timestamp = now
                state = 'dontpurgeme'

            self.session.add(recorder.get_model('States')(
                entity_id='test.recorder2',
                domain='sensor',
                state=state,
                attributes=json.dumps(attributes),
                last_changed=timestamp,
                last_updated=timestamp,
                created=timestamp,
                event_id=event_id + 1000
            ))

        self.session.commit()

    def _add_test_events(self):
        """Add a few events for testing."""
        now = datetime.now()
        five_days_ago = now - timedelta(days=5)
        event_data = {'test_attr': 5, 'test_attr_10': 'nice'}

        self.hass.block_till_done()
        recorder._INSTANCE.block_till_done()
        for event_id in range(5):
            if event_id < 2:
                timestamp = five_days_ago
                event_type = 'EVENT_TEST_PURGE'
            else:
                timestamp = now
                event_type = 'EVENT_TEST'

            self.session.add(recorder.get_model('Events')(
                event_type=event_type,
                event_data=json.dumps(event_data),
                origin='LOCAL',
                created=timestamp,
                time_fired=timestamp,
            ))

    def test_saving_state(self):
        """Test saving and restoring a state."""
        entity_id = 'test.recorder'
        state = 'restoring_from_db'
        attributes = {'test_attr': 5, 'test_attr_10': 'nice'}

        self.hass.states.set(entity_id, state, attributes)

        self.hass.block_till_done()
        recorder._INSTANCE.block_till_done()

        db_states = recorder.query('States')
        states = recorder.execute(db_states)

        assert db_states[0].event_id is not None

        self.assertEqual(1, len(states))
        self.assertEqual(self.hass.states.get(entity_id), states[0])

    def test_saving_event(self):
        """Test saving and restoring an event."""
        event_type = 'EVENT_TEST'
        event_data = {'test_attr': 5, 'test_attr_10': 'nice'}

        events = []

        @callback
        def event_listener(event):
            """Record events from eventbus."""
            if event.event_type == event_type:
                events.append(event)

        self.hass.bus.listen(MATCH_ALL, event_listener)

        self.hass.bus.fire(event_type, event_data)

        self.hass.block_till_done()
        recorder._INSTANCE.block_till_done()

        db_events = recorder.execute(
            recorder.query('Events').filter_by(
                event_type=event_type))

        assert len(events) == 1
        assert len(db_events) == 1

        event = events[0]
        db_event = db_events[0]

        assert event.event_type == db_event.event_type
        assert event.data == db_event.data
        assert event.origin == db_event.origin

        # Recorder uses SQLite and stores datetimes as integer unix timestamps
        assert event.time_fired.replace(microsecond=0) == \
            db_event.time_fired.replace(microsecond=0)

    def test_purge_old_states(self):
        """Test deleting old states."""
        self._add_test_states()
        # make sure we start with 5 states
        states = recorder.query('States')
        self.assertEqual(states.count(), 5)

        # run purge_old_data()
        recorder._INSTANCE.purge_days = 4
        recorder._INSTANCE._purge_old_data()

        # we should only have 2 states left after purging
        self.assertEqual(states.count(), 2)

    def test_purge_old_events(self):
        """Test deleting old events."""
        self._add_test_events()
        events = recorder.query('Events').filter(
            recorder.get_model('Events').event_type.like("EVENT_TEST%"))
        self.assertEqual(events.count(), 5)

        # run purge_old_data()
        recorder._INSTANCE.purge_days = 4
        recorder._INSTANCE._purge_old_data()

        # now we should only have 3 events left
        self.assertEqual(events.count(), 3)

    def test_purge_disabled(self):
        """Test leaving purge_days disabled."""
        self._add_test_states()
        self._add_test_events()
        # make sure we start with 5 states and events
        states = recorder.query('States')
        events = recorder.query('Events').filter(
            recorder.get_model('Events').event_type.like("EVENT_TEST%"))
        self.assertEqual(states.count(), 5)
        self.assertEqual(events.count(), 5)

        # run purge_old_data()
        recorder._INSTANCE.purge_days = None
        recorder._INSTANCE._purge_old_data()

        # we should have all of our states still
        self.assertEqual(states.count(), 5)
        self.assertEqual(events.count(), 5)

@pytest.fixture
def hass_recorder():
    """HASS fixture with in-memory recorder."""
    hass = get_test_home_assistant()

    def setup_recorder(config):
        """Setup with params."""
        db_uri = 'sqlite://'  # In memory DB
        conf = {recorder.CONF_DB_URL: db_uri}
        conf.update(config)
        assert setup_component(hass, recorder.DOMAIN, {recorder.DOMAIN: conf})
        hass.start()
        hass.block_till_done()
        recorder._verify_instance()
        recorder._INSTANCE.block_till_done()
        return hass

    yield setup_recorder
    hass.stop()

def _add_entities(hass, entity_ids):
    """Add entities."""
    attributes = {'test_attr': 5, 'test_attr_10': 'nice'}
    for idx, entity_id in enumerate(entity_ids):
        hass.states.set(entity_id, 'state{}'.format(idx), attributes)
        hass.block_till_done()
    recorder._INSTANCE.block_till_done()
    db_states = recorder.query('States')
    states = recorder.execute(db_states)
    assert db_states[0].event_id is not None
    return states

# pylint: disable=redefined-outer-name,invalid-name
def test_saving_state_include_domains(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({'include': {'domains': 'test2'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
    assert len(states) == 1
    assert hass.states.get('test2.recorder') == states[0]

def test_saving_state_incl_entities(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({'include': {'entities': 'test2.recorder'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
    assert len(states) == 1
    assert hass.states.get('test2.recorder') == states[0]

def test_saving_state_exclude_domains(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({'exclude': {'domains': 'test'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
    assert len(states) == 1
    assert hass.states.get('test2.recorder') == states[0]

def test_saving_state_exclude_entities(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({'exclude': {'entities': 'test.recorder'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
    assert len(states) == 1
    assert hass.states.get('test2.recorder') == states[0]

def test_saving_state_exclude_domain_include_entity(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({
        'include': {'entities': 'test.recorder'},
        'exclude': {'domains': 'test'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder'])
    assert len(states) == 2

def test_saving_state_include_domain_exclude_entity(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder({
        'exclude': {'entities': 'test.recorder'},
        'include': {'domains': 'test'}})
    states = _add_entities(hass, ['test.recorder', 'test2.recorder',
                                  'test.ok'])
    assert len(states) == 1
    assert hass.states.get('test.ok') == states[0]
    assert hass.states.get('test.ok').state == 'state2'