text:
package org.sakaiproject.evaluation.tool.producers;

import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.tool.EvalToolConstants;
import org.sakaiproject.evaluation.tool.renderers.NavBarRenderer;
import org.sakaiproject.evaluation.tool.viewparams.AdminSearchViewParameters;
import org.sakaiproject.evaluation.utils.EvalUtils;

import uk.org.ponder.beanutil.PathUtil;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;

/**
 * Handles administration of the evaluation system
 *
 * @author Aaron Zeckoski (aaronz@vt.edu)
 * @author Kapil Ahuja (kahuja@vt.edu)
 * @author Antranig Basman (antranig@caret.cam.ac.uk)
 */
public class AdministrateProducer extends EvalCommonProducer {

    /**
     * This is used for navigation within the system.
     */
    public static final String VIEW_ID = "administrate";
    public String getViewID() {
        return VIEW_ID;
    }

    // Spring injection
    private EvalCommonLogic commonLogic;
    public void setCommonLogic(EvalCommonLogic commonLogic) {
        this.commonLogic = commonLogic;
    }

    private EvalSettings evalSettings;
    public void setEvalSettings(EvalSettings evalSettings) {
        this.evalSettings = evalSettings;
    }

    private NavBarRenderer navBarRenderer;
    public void setNavBarRenderer(NavBarRenderer navBarRenderer) {
        this.navBarRenderer = navBarRenderer;
    }

    // Used to prepare the path for WritableBeanLocator
    public static final String ADMIN_WBL = "settingsBean";

    public void fill(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
        String currentUserId = commonLogic.getCurrentUserId();
        boolean userAdmin = commonLogic.isUserAdmin(currentUserId);

        if (! userAdmin) {
            // Security check and denial
            throw new SecurityException("Non-admin users may not access this page");
        }

        UIMessage.make(tofill, "administrate-title", "administrate.page.title");

        UIMessage.make(tofill, "app_version_revision", "administrate.version.revision",
                new Object[] {EvalConstants.APP_VERSION, EvalConstants.SVN_REVISION, EvalConstants.SVN_LAST_UPDATE});

        navBarRenderer.makeNavBar(tofill, NavBarRenderer.NAV_ELEMENT, this.getViewID());

        // BREADCRUMBS
        UIInternalLink.make(tofill, "control-email-toplink",
                UIMessage.make("controlemail.page.title"),
                new SimpleViewParameters(AdministrateEmailProducer.VIEW_ID));

        UIInternalLink.make(tofill, "control-administrate-search",
                UIMessage.make("administrate.top.control.search"),
                new AdminSearchViewParameters(AdministrateSearchProducer.VIEW_ID));

        UIInternalLink.make(tofill, "control-reporting-toplink",
                UIMessage.make("administrate.top.control.reporting"),
                new SimpleViewParameters(AdministrateReportingProducer.VIEW_ID));

        UIInternalLink.make(tofill, "control-eval-admin-toplink",
                UIMessage.make("administrate.top.control.evaladmin"),
                new SimpleViewParameters(ControlEvalAdminProducer.VIEW_ID));

        UIInternalLink.make(tofill, "test-evalgroupprovider-toplink",
                UIMessage.make("admintesteg.page.title"),
                new SimpleViewParameters(AdminTestEGProviderProducer.VIEW_ID));

        Boolean enableProviderSync = (Boolean) evalSettings.get(EvalSettings.ENABLE_PROVIDER_SYNC);
        if(enableProviderSync) {
            UIInternalLink.make(tofill, "control-administrate-sync",
                    UIMessage.make("administrate.sync.page.title"),
                    new SimpleViewParameters(AdministrateProviderSyncProducer.VIEW_ID));
        }

        // only show Control Importing if enabled
        Boolean enableImporting = (Boolean) evalSettings.get(EvalSettings.ENABLE_IMPORTING);
        if (enableImporting) {
            UIInternalLink.make(tofill, "control-import-toplink",
                    UIMessage.make("administrate.top.import.data"),
                    new SimpleViewParameters(ControlImportProducer.VIEW_ID));
        }

        // only show Control Hierarchy if enabled
        Boolean useHierarchyFeatures = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_OPTIONS);
        if (useHierarchyFeatures) {
            UIInternalLink.make(tofill, "control-hierarchy-toplink",
                    UIMessage.make("administrate.top.control.hierarchy"),
                    new SimpleViewParameters(ControlHierarchyProducer.VIEW_ID));
        }

        //alert user to current email setting
        Object[] params = new Object[]{"",""};
        String delivery = (String)evalSettings.get(EvalSettings.EMAIL_DELIVERY_OPTION);
        if(EvalConstants.EMAIL_DELIVERY_SEND.equals(delivery)) {
            params[0] = "SEND email";
            params[1] = "PRODUCTION";
        }
        else if (EvalConstants.EMAIL_DELIVERY_LOG.equals(delivery)) {
            params[0] = "LOG email";
            params[1] = "DEVELOPMENT";
        }
        else if(EvalConstants.EMAIL_DELIVERY_NONE.equals(delivery)) {
            params[0] = "NOT send email";
            params[1] = "TEST";
        }
        UIMessage.make(tofill, "email-delivery", "administrate.email.delivery", params);

        //System Settings
        UIForm form = UIForm.make(tofill, "basic-form");
        UIMessage.make(form, "system-settings-header", "administrate.system.settings.header");
        UIMessage.make(form, "system-settings-instructions","administrate.system.settings.instructions");

        //Instructor Settings
        UIMessage.make(form, "instructor-settings-header", "administrate.instructor.settings.header");
        makeBoolean(form, "instructors-eval-create", ADMIN_WBL, EvalSettings.INSTRUCTOR_ALLOWED_CREATE_EVALUATIONS);
        UIMessage.make(form, "instructors-eval-create-note", "administrate.instructors.eval.create.note");

        //Select for whether instructors can view results or not
        String[] administrateConfigurableLabels =
        {
                "administrate.true.label",
                "administrate.false.label",
                "general.configurable"
        };
        String[] administrateConfigurableValues =
        {
                EvalToolConstants.ADMIN_BOOLEAN_YES,
                EvalToolConstants.ADMIN_BOOLEAN_NO,
                EvalToolConstants.ADMIN_BOOLEAN_CONFIGURABLE
        };

        makeSelect(form, "instructors-view-results",
                administrateConfigurableValues,
                administrateConfigurableLabels,
                ADMIN_WBL, EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS, true);
        UIMessage.make(form, "instructors-view-results-note", "administrate.instructors.view.results.note");

        makeBoolean(form, "instructors-email-students", ADMIN_WBL, EvalSettings.INSTRUCTOR_ALLOWED_EMAIL_STUDENTS);
        UIMessage.make(form, "instructors-email-students-note", "administrate.instructors.email.students.note");

        makeBoolean(form,"admin-enable-provider-sync", ADMIN_WBL, EvalSettings.ENABLE_PROVIDER_SYNC);
        UIMessage.make(form, "admin-enable-provider-sync-note", "administrate.admin.enable.provider.sync");

        /*
         * (non-Javadoc)
         * Select for whether instructors must use evaluationSetupService from above.
         *
         * Note: The values should be irrespective of i18n as they are stored in database.
         * Here the 4th values that is "messageLocator.getMessage("general.configurable")"
         * is actually converted to a NULL inside SettingsWBL.java so does not matter to be
         * language specific here.
         */
        String[] hierarchyOptionValues =
        {
                EvalConstants.INSTRUCTOR_OPT_IN,
                EvalConstants.INSTRUCTOR_OPT_OUT,
                EvalConstants.INSTRUCTOR_REQUIRED,
                EvalToolConstants.ADMIN_BOOLEAN_CONFIGURABLE
        };
        String[] hierarchyOptionLabels =
        {
                "evalsettings.instructors.label.opt.in",
                "evalsettings.instructors.label.opt.out",
                "evalsettings.instructors.label.required",
                "general.configurable"
        };
        makeSelect(form, "instructors-hierarchy",
                hierarchyOptionValues,
                hierarchyOptionLabels,
                ADMIN_WBL, EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE, true);
        UIMessage.make(form, "instructors-hierarchy-note", "administrate.instructors.hierarchy.note");

        //Select for number of questions instructors can add
        makeSelect(form, "instructors-num-questions",
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                ADMIN_WBL, EvalSettings.INSTRUCTOR_ADD_ITEMS_NUMBER, false);
        UIMessage.make(form, "instructors-num-questions-note", "administrate.instructors.num.questions.note");

        // Student Settings
        UIMessage.make(form, "student-settings-header", "administrate.student.settings.header");

        //Select for whether students can leave questions unanswered or not
        makeSelect(form, "students-unanswered",	//$NON-NLS-1$
                administrateConfigurableValues,
                administrateConfigurableLabels,
                ADMIN_WBL, EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED, true);
        UIMessage.make(form, "students-unanswered-note", "administrate.students.unanswered.note");

        //Select for whether student can modify responses upto due date
        makeSelect(form, "students-modify-responses",
                administrateConfigurableValues,
                administrateConfigurableLabels,
                ADMIN_WBL, EvalSettings.STUDENT_MODIFY_RESPONSES, true);
        UIMessage.make(form, "students-modify-responses-note", "administrate.students.modify.responses.note");

        //Select for whether students can view results
        makeSelect(form, "students-view-results",
                administrateConfigurableValues,
                administrateConfigurableLabels,
                ADMIN_WBL, EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS, true);
        UIMessage.make(form, "students-view-results-note","administrate.students.view.results.note");

        // Administrator Settings
        UIMessage.make(form, "administrator-settings-header","administrate.admin.settings.header");

        //Select for number of questions admins can add
        makeSelect(form, "admin-hierarchy-num-questions",
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                ADMIN_WBL, EvalSettings.ADMIN_ADD_ITEMS_NUMBER, false);
        UIMessage.make(form, "admin-hierarchy-num-questions-note", "administrate.admin.hierarchy.num.questions.note");

        makeBoolean(form, "admin-view-instructor-added-results", ADMIN_WBL, EvalSettings.ADMIN_VIEW_INSTRUCTOR_ADDED_RESULTS);
        UIMessage.make(form, "admin-view-instructor-added-results-note", "administrate.admin.view.instructor.added.results.note");
        makeBoolean(form, "admin-view-below-results", ADMIN_WBL, EvalSettings.ADMIN_VIEW_BELOW_RESULTS);
        UIMessage.make(form, "admin-view-below-results-note","administrate.admin.view.below.results.note");

        // HIERARCHY settings
        makeBoolean(form, "general-display-hierarchy-options", ADMIN_WBL, EvalSettings.DISPLAY_HIERARCHY_OPTIONS);
        UIMessage.make(form, "general-display-hierarchy-options-note", "administrate.general.show.hierarchy.information");

        makeBoolean(form, "hierarchy-display-node-headers", ADMIN_WBL, EvalSettings.DISPLAY_HIERARCHY_HEADERS);
        UIMessage.make(form, "hierarchy-display-node-headers-note", "administrate.hierarchy-display-node-headers-note");

        // GENERAL settings

        // Select for number of responses before results could be viewed
        makeSelect(form, "general-responses-before-view",
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                ADMIN_WBL, EvalSettings.RESPONSES_REQUIRED_TO_VIEW_RESULTS, false);

        makeBoolean(form, "general-na-allowed", ADMIN_WBL, EvalSettings.ENABLE_NOT_AVAILABLE);

        // Select for maximum number of questions in a block
        makeSelect(form, "general-max-questions-block",	//$NON-NLS-1$
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                EvalToolConstants.PULLDOWN_INTEGER_VALUES,
                ADMIN_WBL, EvalSettings.ITEMS_ALLOWED_IN_QUESTION_BLOCK, false);

        // Select for template sharing and visibility settings
        String[] sharingValues = new String[] {
                EvalConstants.SHARING_OWNER,
                EvalConstants.SHARING_PRIVATE,
                EvalConstants.SHARING_PUBLIC
        };
        String[] sharingLabels = new String[] {
                "administrate.sharing.owner",
                "sharing.private",
                "sharing.public"
        };
        makeSelect(form, "general-template-sharing",
                sharingValues,
                sharingLabels,
                ADMIN_WBL, EvalSettings.TEMPLATE_SHARING_AND_VISIBILITY, true);

        //Select for whether all roles can take the survey
        makeSelect(form, "all-roles-participate",
                administrateConfigurableValues,
                administrateConfigurableLabels,
                ADMIN_WBL, EvalSettings.ALLOW_ALL_SITE_ROLES_TO_RESPOND, true);

        UIMessage.make(form, "all-roles-participate-note","administrate.general.all.roles.participate.note");

        makeBoolean(form, "general-template-copying",  ADMIN_WBL, EvalSettings.ENABLE_TEMPLATE_COPYING);
        makeBoolean(form, "general-use-date-time",  ADMIN_WBL, EvalSettings.EVAL_USE_DATE_TIME);
        makeBoolean(form, "general-use-stop-date", ADMIN_WBL, EvalSettings.EVAL_USE_STOP_DATE);
        makeBoolean(form, "general-use-view-date", ADMIN_WBL, EvalSettings.EVAL_USE_VIEW_DATE);
        makeBoolean(form, "general-same-view-date",  ADMIN_WBL, EvalSettings.EVAL_USE_SAME_VIEW_DATES);

        makeBoolean(form, "general-enable-administrating-box", ADMIN_WBL, EvalSettings.ENABLE_ADMINISTRATING_BOX);
        makeBoolean(form, "general-enable-sites-summary", ADMIN_WBL, EvalSettings.ENABLE_SUMMARY_SITES_BOX);
        makeBoolean(form, "general-enable-evaluatee-box", ADMIN_WBL, EvalSettings.ENABLE_EVALUATEE_BOX);
        makeBoolean(form, "general-show-my-toplinks", ADMIN_WBL, EvalSettings.ENABLE_MY_TOPLINKS);
        makeBoolean(form, "general-use-eval-category", ADMIN_WBL, EvalSettings.ENABLE_EVAL_CATEGORIES);
        makeBoolean(form, "general-use-eval-term-id", ADMIN_WBL, EvalSettings.ENABLE_EVAL_TERM_IDS);
        makeBoolean(form, "general-enable-response-removal", ADMIN_WBL, EvalSettings.ENABLE_EVAL_RESPONSE_REMOVAL);

        makeBoolean(form, "general-default-question-category",  ADMIN_WBL, EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY);

        makeBoolean(form, "general-expert-templates", ADMIN_WBL, EvalSettings.USE_EXPERT_TEMPLATES);
        makeBoolean(form, "general-expert-questions", ADMIN_WBL, EvalSettings.USE_EXPERT_ITEMS);

        makeBoolean(form, "general-view-results-ignore-dates", ADMIN_WBL, EvalSettings.VIEW_SURVEY_RESULTS_IGNORE_DATES);

        makeBoolean(form, "general-enable-adhoc-groups", ADMIN_WBL, EvalSettings.ENABLE_ADHOC_GROUPS);
        makeBoolean(form, "general-enable-adhoc-users", ADMIN_WBL, EvalSettings.ENABLE_ADHOC_USERS);

        makeBoolean(form, "general-enable-eval-close", ADMIN_WBL, EvalSettings.ENABLE_EVAL_EARLY_CLOSE);
        makeBoolean(form, "general-enable-eval-reopen", ADMIN_WBL, EvalSettings.ENABLE_EVAL_REOPEN);

        makeBoolean(form, "general-enable-item-comments", ADMIN_WBL, EvalSettings.ENABLE_ITEM_COMMENTS);

        makeBoolean(form, "general-enable-group-specific-preview", ADMIN_WBL, EvalSettings.ENABLE_GROUP_SPECIFIC_PREVIEW);

        //    makeBoolean(form, "general-require-comments-block",  EvalSettings.REQUIRE_COMMENTS_BLOCK);

        //Number of days old can an eval be and still be recently closed
        Integer recentlyClosedDays = (Integer) evalSettings.get(EvalSettings.EVAL_RECENTLY_CLOSED_DAYS);
        UIInput.make(form, "general-eval-closed-still-recent", PathUtil.composePath(ADMIN_WBL, EvalSettings.EVAL_RECENTLY_CLOSED_DAYS), recentlyClosedDays.toString());
        UIMessage.make(form, "general-eval-closed-still-recent-note","administrate.general.eval.closed.still.recent.note");

        //Min List Length
        Integer minListLength = (Integer) evalSettings.get(EvalSettings.EVAL_MIN_LIST_LENGTH);
        if (minListLength == null) { minListLength = 2; }
        UIInput.make(form, "min-list-length", PathUtil.composePath(ADMIN_WBL, EvalSettings.EVAL_MIN_LIST_LENGTH), minListLength.toString());

        //Max List Length
        Integer maxListLength = (Integer) evalSettings.get(EvalSettings.EVAL_MAX_LIST_LENGTH);
        if (maxListLength == null) { minListLength = 40; }
        UIInput.make(form, "max-list-length", PathUtil.composePath(ADMIN_WBL, EvalSettings.EVAL_MAX_LIST_LENGTH), maxListLength.toString());

        //Minimum time difference (in hours) between the start date and due date
        makeSelect(form, "general-mim-time-diff-between-dates",
                EvalToolConstants.MINIMUM_TIME_DIFFERENCE,
                EvalToolConstants.MINIMUM_TIME_DIFFERENCE,
                ADMIN_WBL, EvalSettings.EVAL_MIN_TIME_DIFF_BETWEEN_START_DUE, false);
        UIMessage.make(form, "general-mim-time-diff-between-dates-note", "administrate.general.eval.mim.time.diff.between.dates");

        // INSTITUTION SPECIFIC SETTINGS
        makeBoolean(form, "general-item-results-sharing",  ADMIN_WBL, EvalSettings.ITEM_USE_RESULTS_SHARING);
        makeBoolean(form, "general-enable-importing",  ADMIN_WBL, EvalSettings.ENABLE_IMPORTING);
        makeBoolean(form, "general-disable-item-bank", ADMIN_WBL, EvalSettings.DISABLE_ITEM_BANK);
        makeBoolean(form, "general-disable-question-blocks", ADMIN_WBL, EvalSettings.DISABLE_QUESTION_BLOCKS);
        makeBoolean(form, "general-enable-ta-category", ADMIN_WBL, EvalSettings.ENABLE_ASSISTANT_CATEGORY);
        makeBoolean(form, "general-enable-selections", ADMIN_WBL, EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION);
        //makeBoolean(form, "general-filter-evalgroups", EvalSettings.ENABLE_FILTER_ASSIGNABLE_GROUPS);  //TODO: refactor this code EVALSYS-942
        UIInput.make(form, "general-local-css-path", PathUtil.composePath(ADMIN_WBL, EvalSettings.LOCAL_CSS_PATH),
                EvalUtils.safeStringSetting(evalSettings, EvalSettings.LOCAL_CSS_PATH));
        UIMessage.make(form, "general-local-css-path-note","administrate.general.local.css.path.note");

        // Save settings button
        // NB no action now required
        UICommand.make(form, "saveSettings", UIMessage.make("administrate.save.settings.button"), null);

        UIForm resetForm = UIForm.make(tofill, "cache-reset-form");
        UICommand.make(resetForm, "cache-reset-submit",
                UIMessage.make("administrate.reset.button"),
                ADMIN_WBL + ".resetConfigCache");
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Bootstrappers.Autofac;
using Nancy.Conventions;
using Serilog;
using Wallr.ImagePersistence;
using Wallr.ImageQueue;
using Wallr.ImageSource;
using Wallr.Platform;
using Wallr.UI.Middleware;

namespace Wallr.UI
{
    public class WallrNancyBootstrapper : AutofacNancyBootstrapper
    {
        private readonly ILifetimeScope _parentScope;

        public WallrNancyBootstrapper(ILifetimeScope parentScope)
        {
            _parentScope = parentScope;
        }

        protected override void ConfigureConventions(NancyConventions nancyConventions)
        {
            nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/static", "content"));
            base.ConfigureConventions(nancyConventions);
        }

        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            container.Update(b => b.RegisterModule<MiddlewareModule>());
        }

        protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
        {
            container.Update(b =>
                b.Register(c =>
                    _parentScope.Resolve<ILogger>()
                        .ForContext("RequestId", Guid.NewGuid())
                        .ForContext("Url", context.Request.Url)
                        .ForContext("Method", context.Request.Method))
                    .As<ILogger>()
            );
            container.Update(b => b.Register(c => _parentScope.Resolve<IImagePersistence>()).As<IImagePersistence>().ExternallyOwned());
            container.Update(b => b.Register(c => _parentScope.Resolve<IImageQueue>()).As<IImageQueue>().ExternallyOwned());
            container.Update(b => b.Register(c => _parentScope.Resolve<IImageSourceConfigurations>()).As<IImageSourceConfigurations>().ExternallyOwned());
            container.Update(b => b.Register(c => _parentScope.Resolve<IImageSourceConfigurationFactory>()).As<IImageSourceConfigurationFactory>().ExternallyOwned());
        }

        protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
        {
            pipelines.BeforeRequest = container.Resolve<IEnumerable<IBeforeRequestMiddleware>>()
                .Aggregate(pipelines.BeforeRequest, (pipeline, middleware) => pipeline + middleware.Invoke);

            pipelines.AfterRequest = container.Resolve<IEnumerable<IAfterRequestMiddleware>>()
                .Aggregate(pipelines.AfterRequest, (pipeline, middleware) => pipeline + middleware.Invoke);

            pipelines.OnError = container.Resolve<IEnumerable<IOnErrorMiddleware>>()
                .Aggregate(pipelines.OnError, (pipeline, middleware) => pipeline + middleware.Invoke);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class SampleAttribute < ActiveRecord::Base
  METHOD_PREFIX = '__sample_data_'

  # attr_accessible :sample_attribute_type_id, :title, :required, :sample_attribute_type, :pos, :sample_type_id,
  #                :_destroy, :sample_type, :unit, :unit_id, :is_title, :template_column_index, :sample_controlled_vocab,
  #                :sample_controlled_vocab_id, :linked_sample_type_id

  belongs_to :sample_attribute_type, inverse_of: :sample_attributes
  belongs_to :sample_type, inverse_of: :sample_attributes
  belongs_to :unit
  belongs_to :sample_controlled_vocab, inverse_of: :sample_attributes
  belongs_to :linked_sample_type, class_name: 'SampleType'

  validates :title, :sample_attribute_type, presence: true
  validates :sample_type, presence: true

  # validates that the attribute type is CV if vocab is set, and vice-versa
  validate :sample_controlled_vocab_and_attribute_type_consistency

  # validates that the attribute type is SeekSample if linked_sample_type is set, and vice-versa
  validate :linked_sample_type_and_attribute_type_consistency

  before_save :generate_accessor_name
  before_save :default_pos, :force_required_when_is_title

  scope :title_attributes, -> { where(is_title: true) }

  delegate :controlled_vocab?, :seek_sample?, :seek_strain?, :seek_resource?, to: :sample_attribute_type, allow_nil: true

  # to store that this attribute should be linked to the sample_type it is being assigned to, but needs to wait until the
  # sample type exists
  attr_reader :deferred_link_to_self

  def title=(title)
    super
    generate_accessor_name
    self.title
  end

  def linked_sample_type_id=(id)
    @deferred_link_to_self = true if id == 'self'
    super(id)
  end

  def validate_value?(value)
    return false if required? && value.blank?
    (value.blank? && !required?) || sample_attribute_type.validate_value?(value, required: required?,
                                                                          controlled_vocab: sample_controlled_vocab,
                                                                          linked_sample_type: linked_sample_type)
  end

  # The method name used to get this attribute via a method call
  def method_name
    METHOD_PREFIX + hash_key
  end

  # The key used to address this attribute in the sample's JSON blob
  def hash_key
    title.parameterize.underscore
  end

  def required?
    super || is_title?
  end

  def pre_process_value(value)
    sample_attribute_type.pre_process_value(value, controlled_vocab: sample_controlled_vocab, linked_sample_type: linked_sample_type)
  end

  def controlled_vocab_labels
    if controlled_vocab?
      sample_controlled_vocab.labels
    else
      []
    end
  end

  # provides the hash that defines the column definition for template generation
  def template_column_definition
    { "#{title}" => controlled_vocab_labels }
  end

  def resolve(value)
    if sample_attribute_type.resolution.present? && sample_attribute_type.regexp.present?
      resolution = value.sub(Regexp.new(sample_attribute_type.regexp), sample_attribute_type.resolution)
    else
      resolution = nil
    end
    resolution
  end

  private

  def generate_accessor_name
    self.accessor_name = hash_key
  end

  # if not set, takes the next value for that sample type
  def default_pos
    self.pos ||= (self.class.where(sample_type_id: sample_type_id).maximum(:pos) || 0) + 1
  end

  def force_required_when_is_title
    # forces required to be true if it is a title
    self.required = required? || is_title?
    true
  end

  def sample_controlled_vocab_and_attribute_type_consistency
    if sample_attribute_type && sample_controlled_vocab && !controlled_vocab?
      errors.add(:sample_attribute_type, 'Attribute type must be CV if controlled vocabulary set')
    end
    if controlled_vocab? && sample_controlled_vocab.nil?
      errors.add(:sample_controlled_vocab, 'Controlled vocabulary must be set if attribute type is CV')
    end
  end

  def linked_sample_type_and_attribute_type_consistency
    if sample_attribute_type && linked_sample_type && !seek_sample?
      errors.add(:sample_attribute_type, 'Attribute type must be SeekSample if linked sample type set')
    end
    if seek_sample? && linked_sample_type.nil?
      errors.add(:sample_controlled_vocab, 'Linked Sample Type must be set if attribute type is SeekSample')
    end
  end

end


text:
<?php
namespace Chamilo\Configuration\Service;

/**
 *
 * @package Chamilo\Configuration\Service
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 */
class LanguageConsulter extends DataConsulter
{

    /**
     *
     * @return string[]
     */
    public function getLanguages()
    {
        return $this->getData();
    }

    /**
     *
     * @param string $isocode
     * @return string
     */
    public function getLanguageNameFromIsocode($isocode)
    {
        $languages = $this->getLanguages();
        return $languages[$isocode];
    }
}


text:
require_relative 'riq_obj'

module RIQ
  # Users are represented by owners and contacts in your SalesforceIQ organization
  class User < RIQObject
    attr_accessor :name
    attr_accessor :email

    # (see RIQObject#node)
    def node
      "users/#{@id}"
    end

    # (see RIQObject#data)
    def data
      {
        id: @id,
        name: @name,
        email: @email
      }
    end

    # Overwriting parent because lists can't be saved through the API
    def save
      raise NotImplementedError, "Users can't be edited through the API"
    end

    private
    def init(obj = nil)
      unless obj.nil?
        @id = obj[:id]
        @name = obj[:name]
        @email = obj[:email]
      else
        @id = nil
        @name = nil
        @email = nil
      end
      self
    end
  end

  class << self
    # Convenience method to create new Users
    # @param id [String, nil] create a blank User object or
    #   fetch an existing one by id.
    # @return [User]
    def user(id = nil)
      RIQ::User.new(id)
    end
  end
end


text:
using RightpointLabs.Pourcast.Application.Orchestrators.Abstract;

namespace RightpointLabs.Pourcast.Application.Orchestrators.Concrete
{
    using RightpointLabs.Pourcast.Domain.Events;
    using RightpointLabs.Pourcast.Application.Transactions;

    public class StatusOrchestrator : IStatusOrchestrator
    {
        [Transactional]
        public void Heartbeat()
        {
            DomainEvents.Raise(new Heartbeat());
        }

        [Transactional]
        public void LogMessage(string message)
        {
            DomainEvents.Raise(new LogMessage(message));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;

namespace Nest.Tests.Integration.Core.Scripts
{
    [TestFixture]
    public class ScriptsTest : IntegrationTests
    {
        [Test]
		[SkipVersion("0 - 1.2.9", "Indexed scripts introduced in ES 1.3")]
        public void AddScriptWithNotSupportedLangParameterShouldBeInvalid()
        {
            var putScriptResponse = this.Client.PutScript(s => s.Lang("lang").Id("id").Script("1*1"));
            putScriptResponse.IsValid.Should().BeFalse();
        }

        [Test]
		[SkipVersion("0 - 1.2.9", "Indexed scripts introduced in ES 1.3")]
        public void AddScript()
        {
            var putScriptResponse = this.Client.PutScript(s => s.Lang(ScriptLang.Groovy).Id("id").Script("1*1"));
            putScriptResponse.IsValid.Should().BeTrue();
        }

        [Test]
		[SkipVersion("0 - 1.2.9", "Indexed scripts introduced in ES 1.3")]
        public void GetScriptShouldReturnScriptContent()
        {
            var script = "1*1";

            this.Client.PutScript(s => s.Lang(ScriptLang.Groovy).Id("id").Script(script));

            var getScriptResponse = this.Client.GetScript(s => s.Lang(ScriptLang.Groovy).Id("id"));
            getScriptResponse.IsValid.Should().BeTrue();
            getScriptResponse.Script.ShouldBeEquivalentTo(script);
        }

        [Test]
		[SkipVersion("0 - 1.2.9", "Indexed scripts introduced in ES 1.3")]
        public void AddAndDeleteScript()
        {
            var putScriptResponse = this.Client.PutScript(s => s.Lang(ScriptLang.Groovy).Id("id").Script("1*1"));
            putScriptResponse.IsValid.Should().BeTrue();

            var getScriptResponse = this.Client.GetScript(s => s.Lang(ScriptLang.Groovy).Id("id"));
            getScriptResponse.IsValid.Should().BeTrue();

            var deleteScriptResponse = this.Client.DeleteScript(s => s.Lang(ScriptLang.Groovy).Id("id"));
            deleteScriptResponse.IsValid.Should().BeTrue();
        }
    }
}


text:
package com.captaciones.persistencia;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.OracleTypes;

public class ConsultasDAO {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@10.110.1.54:1522:orawpor";
	private static final String DB_CONNECTION_APD2 = "jdbc:oracle:thin:@10.110.1.54:1522:orawapd2";
	private static final String DB_CONNECTION_QA = "jdbc:oracle:thin:@10.110.1.128:1521:orawqa";

	private static final String DB_USER = "CAP_ADMIN";
	private static final String DB_PASSWORD = "CAP_ADMIN";
	private static final String DB_USER_APD2 = "CAP_EXP";
	private static final String DB_PASSWORD_APD2 = "CAP_EXP";
	private static final String DB_USER_QA = "POR_EXP";
	private static final String DB_PASSWORD_QA = "POREXP";

	private static Connection getDBConnection(String baseDatos) throws Exception {
		System.err.println("Consultando : " + baseDatos + "\n");

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER); // Create to the heap, Oracle driver on D:\10g\jdbc\lib\classes12.jar

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {
			if("APD2".equals(baseDatos)){

				dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
			}else if("ORAW".equals(baseDatos)){

				dbConnection = DriverManager.getConnection(DB_CONNECTION_APD2, DB_USER_APD2, DB_PASSWORD_APD2);

			}else if("QA".equals(baseDatos)){

				dbConnection = DriverManager.getConnection(DB_CONNECTION_QA, DB_USER_QA, DB_PASSWORD_QA);

			}else{
				throw new Exception("Debe mencionar que base de datos consultar");
			}

			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

	public static void consultaTasas()
			throws Exception {

		Connection dbConnection = null;
		CallableStatement callableStatement = null;
		ResultSet rs = null;

		String getDBUSERCursorSql = "{call CAP_SP_CON_TASAS_DEPOSITO(?,?,?,?,?,?,?)}";
		//CAP_SP_CON_TASAS_DEPOSITO('20160509',0,10,0.0,'MSD,0')
		//CAP_SP_CON_TASAS_DEPOSITO('20160819',13,32,0.0,'MSD,0')
//		CAP_SP_CON_TASAS_DEPOSITO('20161014',13, 7, 0.0, 'EJ1, 0')

		try {

			dbConnection = getDBConnection("APD2");
			callableStatement = dbConnection.prepareCall(getDBUSERCursorSql);

			callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
			callableStatement.setString(2, "20161014");
			callableStatement.setLong(3, 13);
			callableStatement.setInt(4, 7);
			callableStatement.setFloat(5, 0.0f);
			callableStatement.setString(6, "EJ1");
			callableStatement.setInt(7, 0);

			// execute getDBUSERCursor store procedure
			callableStatement.executeQuery();

			// get cursor and cast it to ResultSet
			rs = (ResultSet) callableStatement.getObject(1);

			while (rs.next()) {
				String idTramo = rs.getString("ID_TRAMO");
				String status = rs.getString("STATUS");
				String glosaStatus = rs.getString("GLOSA_STATUS");
				String tasaMinima = rs.getString("tasaMinima");
				String tasaMaxima = rs.getString("tasaMaxima");
				String tasaSugerida = rs.getString("tasaSugerida");
				String tasaPizarra = rs.getString("tasaPizarra");
				String tasaCampana = rs.getString("tasaCampana");
				String tasaMensualMinima = rs.getString("tasaMensualMinima");
				String tasaMensualMaxima = rs.getString("tasaMensualMaxima");
				String tasaMensualSugerida = rs.getString("tasaMensualSugerida");
				String tasaMensualPizarra = rs.getString("tasaMensualPizarra");
				String tasaMensualCampana = rs.getString("tasaMensualCampana");

				System.out.println("ID_TRAMO : " + idTramo);
				System.out.println("STATUS : " + status);
				System.out.println("GLOSA_STATUS : " + glosaStatus);
				System.out.println("tasaMinima : " + tasaMinima );
				System.out.println("tasaMaxima : " + tasaMaxima );
				System.out.println("tasaSugerida : " + tasaSugerida );
				System.out.println("tasaPizarra : " + tasaPizarra );
				System.out.println("tasaCampana : " + tasaCampana );
				System.out.println("tasaMensualMinima : " + tasaMensualMinima );
				System.out.println("tasaMensualMaxima : " + tasaMensualMaxima );
				System.out.println("tasaMensualSugerida : " + tasaMensualSugerida );
				System.out.println("tasaMensualPizarra : " + tasaMensualPizarra );
				System.out.println("tasaMensualCampana : " + tasaMensualCampana );

				System.out.println();
			}

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (rs != null) {
				rs.close();
			}

			if (callableStatement != null) {
				callableStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

}


text:
package abi42_0_0.expo.modules.sensors.modules;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.os.Bundle;

import abi42_0_0.org.unimodules.core.Promise;
import abi42_0_0.org.unimodules.core.interfaces.ExpoMethod;

import abi42_0_0.expo.modules.interfaces.sensors.SensorServiceInterface;
import abi42_0_0.expo.modules.interfaces.sensors.services.AccelerometerServiceInterface;

public class AccelerometerModule extends BaseSensorModule {
  public AccelerometerModule(Context reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "ExponentAccelerometer";
  }

  @Override
  public String getEventName() {
    return "accelerometerDidUpdate";
  }

  @Override
  protected SensorServiceInterface getSensorService() {
    return getModuleRegistry().getModule(AccelerometerServiceInterface.class);
  }

  protected Bundle eventToMap(SensorEvent sensorEvent) {
    Bundle map = new Bundle();
    map.putDouble("x", sensorEvent.values[0] / SensorManager.GRAVITY_EARTH);
    map.putDouble("y", sensorEvent.values[1] / SensorManager.GRAVITY_EARTH);
    map.putDouble("z", sensorEvent.values[2]/  SensorManager.GRAVITY_EARTH);
    return map;
  }

  @ExpoMethod
  public void startObserving(Promise promise) {
    super.startObserving();
    promise.resolve(null);
  }

  @ExpoMethod
  public void stopObserving(Promise promise) {
    super.stopObserving();
    promise.resolve(null);
  }

  @ExpoMethod
  public void setUpdateInterval(int updateInterval, Promise promise) {
    super.setUpdateInterval(updateInterval);
    promise.resolve(null);
  }

  @ExpoMethod
  public void isAvailableAsync(Promise promise) {
    SensorManager mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
    boolean isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null;
    promise.resolve(isAvailable);
  }
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package docking.widgets.tree.tasks;

import java.util.List;

import javax.swing.tree.TreePath;

import docking.widgets.tree.*;
import ghidra.util.task.TaskMonitor;

public class GTreeExpandPathsTask extends GTreeTask {

	private final List<TreePath> paths;

	public GTreeExpandPathsTask(GTree gTree, List<TreePath> paths) {
		super(gTree);
		this.paths = paths;
	}

	@Override
	public void run(TaskMonitor monitor) {
		monitor.setMessage("Expanding Paths");
		monitor.initialize(paths.size());
		for (TreePath path : paths) {
			ensurePathLoaded(path, monitor);
			expandPath(path, monitor);
			monitor.incrementProgress(1);
		}
	}

	private void ensurePathLoaded(TreePath path, TaskMonitor monitor) {
		GTreeNode parent = tree.getViewRoot();
		if (parent == null) {
			return; // disposed?
		}

		Object[] nodeList = path.getPath();
		if (nodeList.length < 2) {
			return;  // only the root is in the path
		}
		List<GTreeNode> allChildren = parent.getChildren();
		for (int i = 1; i < nodeList.length; i++) {
			if (monitor.isCancelled()) {
				return;
			}
			GTreeNode node = findNode(allChildren, (GTreeNode) nodeList[i]);
			if (node == null) {
				return;
			}
			allChildren = node.getChildren();
			parent = node;
		}
	}

	private GTreeNode findNode(List<GTreeNode> children, GTreeNode node) {
		for (GTreeNode childNode : children) {
			if (childNode.equals(node)) {
				return childNode;
			}
		}
		return null;
	}

	private void expandPath(final TreePath treePath, final TaskMonitor monitor) {
		runOnSwingThread(() -> {
			if (monitor.isCancelled()) {
				return; // we can be cancelled while waiting for Swing to run us
			}

			//
			// JTree will do nothing if the last element in a path is a leaf.  We can do
			// better.  We will expand the parent of the given element if it is a leaf.
			//
			TreePath validatedPath = treePath;
			GTreeNode node = (GTreeNode) treePath.getLastPathComponent();
			if (node.isLeaf()) {
				Object[] path = treePath.getPath();
				if (path.length <= 1) {
					return;
				}
				Object[] newPath = new Object[path.length - 1];
				System.arraycopy(path, 0, newPath, 0, path.length - 1);
				validatedPath = new TreePath(newPath);
			}

			jTree.expandPath(validatedPath);
		});
	}

}


text:
define(['select2'], function () {
    return function (el) {
        return $(el).select2();
    }
})


text:
from __future__ import unicode_literals

from django.views import generic
from django.conf import settings
import shutil
import json

import mimetypes
import os
import stat

from django.http import FileResponse, HttpResponseNotModified
from django.utils.http import http_date
from django.contrib.staticfiles.views import static
from django.shortcuts import render
from django.urls import reverse_lazy
from markdown2 import Markdown

class DownloadChallengePack(generic.View):

    @staticmethod
    def get_base_path():
        return os.path.join(settings.BASE_DIR, 'challenge_processor', 'challenge_processor_static',
                            'downloads')

    def get_available_languages(self):
        return [path.replace('challenge_pack_', "") for path in os.listdir(self.get_base_path()) if path != 'packed']

    def create_or_get_archive(self):
        language = self.request.GET.get('lang', settings.CHALLENGE_PACK['default_language'])

        pack_name = 'challenge_pack_{}'.format(language)

        ext = self.request.GET.get('ext', settings.CHALLENGE_PACK['default_extension'])

        relative_path = self.get_base_path()

        directory_path = os.path.join(relative_path, pack_name)

        if not os.path.exists(directory_path):
            base_url = reverse_lazy('challenge_processor:download_pack')
            return {
                       "error_message": "Error no challenge pack for {}".format(language),
                       "links": [
                           {
                               "link": "{}?lang={}".format(base_url, lang),
                               "name": "challenge pack for {}".format(lang)
                           }
                           for lang in self.get_available_languages()],
                   }, False

        with open(os.path.join(directory_path, 'manifest.json'), 'r') as file:
            manifest = json.load(file)

        archive_path = os.path.join(relative_path, 'packed',
                                    "{}_{}_packed".format(pack_name, manifest['manifest_version']))

        if not os.path.exists(archive_path):
            shutil.make_archive(archive_path, ext, directory_path)

        return "{}.{}".format(archive_path, ext), True

    def get(self, request, **kwargs):
        path, found = self.create_or_get_archive()
        if not found:
            return render(request=request, template_name='challenge_processor/download_not_found.html', context=path)
        statobj = os.stat(path)
        if not static.was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                                         statobj.st_mtime, statobj.st_size):
            return HttpResponseNotModified()
        content_type, encoding = mimetypes.guess_type(path)
        content_type = content_type or 'application/octet-stream'
        response = FileResponse(open(path, 'rb'), content_type=content_type)
        response["Last-Modified"] = http_date(statobj.st_mtime)
        if stat.S_ISREG(statobj.st_mode):
            response["Content-Length"] = statobj.st_size
        if encoding:
            response["Content-Encoding"] = encoding
        return response

class ChallengePackDocumentation(generic.View):
    reader = Markdown()
    template = 'challenge_processor/documentation.html'

    def get(self, request, **kwargs):
        language = self.request.GET.get('lang', settings.CHALLENGE_PACK['default_language'])

        pack_name = 'challenge_pack_{}'.format(language)

        relative_path = DownloadChallengePack.get_base_path()

        directory_path = os.path.join(relative_path, pack_name)
        doc_path = os.path.join(directory_path, 'documentation.md')

        if not os.path.exists(directory_path) or not os.path.exists(doc_path):
            documentation = "
Error documentation for {} not found
".format(language)
        else:
            with open(doc_path, 'r') as file:
                documentation = self.reader.convert(file.read())

        return render(request=request, template_name=self.template, context={
            'documentation': documentation,
            'doc_name': language,
        })


text:
export class CombativePlant {
	constructor(public combativePlant1Name: string, public combativePlant2Name: string, public combativePlant1LatinName: string, public combativePlant2LatinName: string){}
}


text:
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/locuser`. To experiment with that code, run `bin/console` for an interactive prompt.

TODO: Delete this and the text above, and describe your gem

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'locuser'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install locuser

An alternative to installing the gem directly is to use the git
repository referenced  in your Gemfile, with a  declaration such as:

```ruby
gem 'locuser',  '~> version', :github => 'sgillesp/locuser', :branch => 'master'
```

To use a local repository do:

```ruby
gem 'locuser', :path => '/path/to/local/gem'
```
or
```ruby
gem 'locuser', :git => '/path/to/local/git/repo'
```

If you are trying to work on the gem integrated into another gem underdevelopment,
(i.e. a .gemspec file), the above will not fly. You can use the option to link to
a remote (GitHub) repository above, and then perform the following command (CLI):

```CLI
bundle config local.locuser /path/to/local/git/repo
```

## Usage

TODO: Write usage instructions here

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/locuser. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
namespace Client.Common
{
    using System.Collections.ObjectModel;
    using System.Collections.Generic;
	using System;

    public static class SystemExtensions
    {
        public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (var item in items)
            {
                collection.Add(item);
            }
        }
    }
}


text:
package spitz // import "stathat.com/c/spitz"

import (
	"bytes"
	"errors"
	"fmt"
	"html/template"
	"io"
	"log"
	"os"
	"path"
	"time"
)

var Verbose bool

type tfile struct {
	filename string
	modTime  time.Time
}

type tfiles []*tfile

func singleFile(filename string) tfiles {
	return tfiles{&tfile{filename: filename}}
}

func multiFile(filenames []string) tfiles {
	tf := make(tfiles, len(filenames))
	for i, v := range filenames {
		tf[i] = &tfile{filename: v}
	}
	return tf
}

func (tf tfiles) name() string {
	if len(tf) == 0 {
		return ""
	}
	return path.Base(tf[0].filename)
}

func (tf tfiles) filenames() []string {
	names := make([]string, len(tf))
	for i, v := range tf {
		names[i] = v.filename
	}
	return names
}

func (tf tfiles) setModTimes() error {
	for _, v := range tf {
		fi, err := os.Stat(v.filename)
		if err != nil {
			return err
		}
		v.modTime = fi.ModTime()
	}
	return nil
}

func (tf tfiles) modifiedSince(t time.Time) bool {
	for _, v := range tf {
		fi, err := os.Stat(v.filename)
		if err == nil && fi.ModTime().After(t) {
			return true
		}
	}
	return false
}

type tmpl struct {
	name       string
	files      tfiles
	plate      *template.Template
	parsedAt   time.Time
	leftDelim  string
	rightDelim string
}

type layout struct {
	header string
	footer string
}

type Pool struct {
	contentDir string
	reload     bool
	tmpls      map[string]*tmpl
	layouts    map[string]*layout
}

func New(contentDir string, reload bool) *Pool {
	pool := &Pool{contentDir: contentDir, reload: reload}
	pool.tmpls = make(map[string]*tmpl)
	pool.layouts = make(map[string]*layout)
	return pool
}

// Register adds the template at ContentDirectory + name + .tmpl.html to the set
// of registered templates.
func (p *Pool) Register(name, leftDelim, rightDelim string) error {
	ename := fmt.Sprintf("%s.tmpl.html", name)
	filename := path.Join(p.contentDir, ename)
	nt := &tmpl{name: name, files: singleFile(filename), leftDelim: leftDelim, rightDelim: rightDelim}
	err := nt.parse()
	if err != nil {
		return err
	}
	p.tmpls[name] = nt
	return nil
}

func (p *Pool) RegisterLayout(name, header, footer string, leftDelim, rightDelim string) error {
	err := p.Register(header, leftDelim, rightDelim)
	if err != nil {
		return err
	}
	err = p.Register(footer, leftDelim, rightDelim)
	if err != nil {
		return err
	}
	p.layouts[name] = &layout{header, footer}
	return nil
}

func (p *Pool) RegisterString(name, content string) error {
	t, err := template.New(name).Funcs(funcMap).Parse(content)
	if err != nil {
		return err
	}
	p.tmpls[name] = &tmpl{plate: t}
	return nil
}

func (p *Pool) RegisterMulti(name, leftDelim, rightDelim string, filenames ...string) error {
	paths := make([]string, len(filenames))
	for i, v := range filenames {
		paths[i] = path.Join(p.contentDir, fmt.Sprintf("%s.tmpl.html", v))
	}
	files := multiFile(paths)

	nt := &tmpl{name: name, files: files, leftDelim: leftDelim, rightDelim: rightDelim}
	err := nt.parse()
	if err != nil {
		return err
	}
	p.tmpls[name] = nt
	return nil
}

func (p *Pool) Render(layout, name string, data interface{}, wr io.Writer) error {
	lout, ok := p.layouts[layout]
	if !ok {
		return errors.New(fmt.Sprintf("layout %q not found", layout))
	}

	err := p.templateRun(lout.header, data, wr)
	if err != nil {
		return err
	}
	err = p.templateRun(name, data, wr)
	if err != nil {
		return err
	}
	err = p.templateRun(lout.footer, data, wr)
	return err
}

func (p *Pool) RenderMulti(layout, name, innerName string, data interface{}, wr io.Writer) error {

	lout, ok := p.layouts[layout]
	if !ok {
		return errors.New(fmt.Sprintf("layout %q not found", layout))
	}

	err := p.templateRun(lout.header, data, wr)
	if err != nil {
		return err
	}

	err = p.templateRunInner(name, innerName, data, wr)
	if err != nil {
		return err
	}

	err = p.templateRun(lout.footer, data, wr)
	return err
}

func (p *Pool) RenderNoLayout(name string, data interface{}, wr io.Writer) error {
	return p.templateRun(name, data, wr)
}

func (p *Pool) RenderToString(layout, template string, data interface{}) (string, error) {
	var b bytes.Buffer
	err := p.Render(layout, template, data, &b)
	if err != nil {
		return "", err
	}
	return string(b.Bytes()), nil
}

func (p *Pool) RenderNoLayoutToString(template string, data interface{}) (string, error) {
	var b bytes.Buffer
	err := p.RenderNoLayout(template, data, &b)
	if err != nil {
		return "", err
	}
	return string(b.Bytes()), nil
}

func (p *Pool) Len() int {
	return len(p.tmpls)
}

func (p *Pool) templateRun(name string, data interface{}, wr io.Writer) error {
	t, ok := p.tmpls[name]
	if !ok {
		return errors.New(fmt.Sprintf("template %q not found", name))
	}
	if p.reload {
		t.checkReload()
	}
	return t.plate.Execute(wr, data)
}

func (p *Pool) templateRunInner(name, innerName string, data interface{}, wr io.Writer) error {
	t, ok := p.tmpls[name]
	if !ok {
		return errors.New(fmt.Sprintf("template %q not found", name))
	}
	if p.reload {
		t.checkReload()
	}
	return t.plate.ExecuteTemplate(wr, innerName, data)
}

func (t *tmpl) parse() error {
	if len(t.files) == 0 {
		return errors.New(fmt.Sprintf("no files for template %q", t.name))
	}
	tm, err := template.New(t.files.name()).Delims(t.leftDelim, t.rightDelim).Funcs(funcMap).ParseFiles(t.files.filenames()...)
	if err != nil {
		return err
	}
	t.plate = tm
	t.parsedAt = time.Now()
	return t.files.setModTimes()
}

func (t *tmpl) checkReload() {
	if len(t.files) == 0 {
		if Verbose {
			log.Printf("no files")
		}
		return
	}
	if t.files.modifiedSince(t.parsedAt) {
		if Verbose {
			log.Printf("template %s changed.  reparsing...", t.name)
		}
		t.parse()
	}
}

func (p *Pool) reloadTemplate(name string) error {
	t, ok := p.tmpls[name]
	if !ok {
		return errors.New(fmt.Sprintf("template %q not registered", name))
	}
	return t.parse()
}


text: <ng-include src="'admin/nav/topnav.html'"></ng-include>


text:
<!DOCTYPE html>

<meta charset='utf-8'>

<link rel="stylesheet" type="text/css" href="../dialog-polyfill.css">

The dialog below is incorrectly positioned within a stacking context.
It should generate a console warning message, and place the _dialog_overlay in a different place in order to try to work around the problem without moving the dialog itself.

<dialog>
  <form method="dialog">
    <input type="submit" />
  </form>

    Help, I'm inside an extra stacking context D:

</dialog>

<button id="show">Show Dialog</button>


text:
package entity;

import simplejdbc.annotation.IncrementValue;
import simplejdbc.annotation.PrimaryKey;
import simplejdbc.annotation.Table;

import java.util.Date;

/**
 * エラー発生用GOODS_MSTテーブルのエンティティクラス
 * @author simpleJdbc (AutoGen)
 */
@Table(name="GOODS_MST")
public class GoodsMstErrorNoColumns {

	@PrimaryKey
	@IncrementValue(sequence="SEQ_GOODS_ID")
	public Integer goodsId;

	public Double price;

	public String goodsName;

	public Date registDate;

	public Date updateDate;

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.hazelcast.spi.WaitNotifyKey (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.hazelcast.spi.WaitNotifyKey

Packages that use WaitNotifyKey

Package
Description

com.hazelcast.concurrent.countdownlatch

This package contains ICountDownLatch functionality for Hazelcast.

 The ICountDownLatch is the distributed version of the CountDownLatch.

com.hazelcast.concurrent.countdownlatch.operations

This package contains the operations on the ICountDownLatch.

com.hazelcast.concurrent.lock

This package contains Lock for Hazelcast.

 The ILock is the distributed version of the Lock.

com.hazelcast.concurrent.lock.operations

This package contains the operations on the ILock.

com.hazelcast.concurrent.semaphore

This package contains ISemaphore functionality for Hazelcast.

 The ISemaphore is the distributed version of the Semaphore.

com.hazelcast.concurrent.semaphore.operations

This package contains the operations on the ISemaphore.

com.hazelcast.map.operation

Package for map operations.

com.hazelcast.map.tx

Contains implementation classes for TransactionalMap

com.hazelcast.multimap.impl.operations

Contains operations for Hazelcast MultiMap module.

com.hazelcast.multimap.impl.txn

This package contains the Transaction behavior for the Multimap.

com.hazelcast.queue.impl

This package contains the IQueue functionality.

 The IQueue is the distributed version of the BlockingQueue.

com.hazelcast.queue.impl.tx

This package contains the Transaction behavior for the IQueue.

com.hazelcast.spi

Provides interfaces/classes for Hazelcast SPI.

Uses of WaitNotifyKey in com.hazelcast.concurrent.countdownlatch

Classes in com.hazelcast.concurrent.countdownlatch that implement WaitNotifyKey

Modifier and Type
Class and Description

class
LatchKey

Uses of WaitNotifyKey in com.hazelcast.concurrent.countdownlatch.operations

Methods in com.hazelcast.concurrent.countdownlatch.operations that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
CountDownOperation.getNotifiedKey()

WaitNotifyKey
AwaitOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.concurrent.lock

Classes in com.hazelcast.concurrent.lock that implement WaitNotifyKey

Modifier and Type
Class and Description

class
ConditionKey

class
LockWaitNotifyKey

Uses of WaitNotifyKey in com.hazelcast.concurrent.lock.operations

Methods in com.hazelcast.concurrent.lock.operations that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
BeforeAwaitOperation.getNotifiedKey()

WaitNotifyKey
UnlockOperation.getNotifiedKey()

WaitNotifyKey
LockOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.concurrent.semaphore

Classes in com.hazelcast.concurrent.semaphore that implement WaitNotifyKey

Modifier and Type
Class and Description

class
SemaphoreWaitNotifyKey

Uses of WaitNotifyKey in com.hazelcast.concurrent.semaphore.operations

Methods in com.hazelcast.concurrent.semaphore.operations that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
SemaphoreDeadMemberOperation.getNotifiedKey()

WaitNotifyKey
ReleaseOperation.getNotifiedKey()

WaitNotifyKey
AcquireOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.map.operation

Methods in com.hazelcast.map.operation that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
LockAwareOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.map.tx

Methods in com.hazelcast.map.tx that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
TxnSetOperation.getNotifiedKey()

WaitNotifyKey
TxnRollbackOperation.getNotifiedKey()

WaitNotifyKey
TxnUnlockOperation.getNotifiedKey()

WaitNotifyKey
TxnDeleteOperation.getNotifiedKey()

Uses of WaitNotifyKey in com.hazelcast.multimap.impl.operations

Methods in com.hazelcast.multimap.impl.operations that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
MultiMapBackupAwareOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.multimap.impl.txn

Methods in com.hazelcast.multimap.impl.txn that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
TxnRollbackOperation.getNotifiedKey()

WaitNotifyKey
TxnCommitOperation.getNotifiedKey()

WaitNotifyKey
TxnLockAndGetOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.queue.impl

Classes in com.hazelcast.queue.impl that implement WaitNotifyKey

Modifier and Type
Class and Description

class
QueueWaitNotifyKey

Wait thread till notify the key.

Methods in com.hazelcast.queue.impl that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
PollOperation.getNotifiedKey()

WaitNotifyKey
OfferOperation.getNotifiedKey()

WaitNotifyKey
RemoveOperation.getNotifiedKey()

WaitNotifyKey
AddAllOperation.getNotifiedKey()

WaitNotifyKey
ClearOperation.getNotifiedKey()

WaitNotifyKey
CompareAndRemoveOperation.getNotifiedKey()

WaitNotifyKey
DrainOperation.getNotifiedKey()

WaitNotifyKey
PollOperation.getWaitKey()

WaitNotifyKey
OfferOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.queue.impl.tx

Methods in com.hazelcast.queue.impl.tx that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
TxnRollbackOperation.getNotifiedKey()

WaitNotifyKey
TxnOfferOperation.getNotifiedKey()

WaitNotifyKey
TxnPollOperation.getNotifiedKey()

WaitNotifyKey
TxnReserveOfferOperation.getWaitKey()

WaitNotifyKey
TxnReservePollOperation.getWaitKey()

Uses of WaitNotifyKey in com.hazelcast.spi

Classes in com.hazelcast.spi that implement WaitNotifyKey

Modifier and Type
Class and Description

class
AbstractWaitNotifyKey

Abstract implementation of the WaitNotifyKey.

Methods in com.hazelcast.spi that return WaitNotifyKey

Modifier and Type
Method and Description

WaitNotifyKey
Notifier.getNotifiedKey()

WaitNotifyKey
WaitSupport.getWaitKey()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
package gov.nih.nci.cabig.caaers.workflow.handler;

import gov.nih.nci.cabig.caaers.AbstractTestCase;
import gov.nih.nci.cabig.caaers.domain.Fixtures;
import gov.nih.nci.cabig.caaers.domain.LocalResearchStaff;
import gov.nih.nci.cabig.caaers.domain.Person;
import gov.nih.nci.cabig.caaers.domain.workflow.TaskConfig;
import gov.nih.nci.cabig.caaers.service.workflow.WorkflowServiceImpl;
import gov.nih.nci.cabig.caaers.workflow.callback.CreateTaskJbpmCallback;
import org.easymock.classextension.EasyMock;
import org.jbpm.graph.def.Node;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;

import java.util.ArrayList;
import java.util.List;
/**
 *
 * @author Biju Joseph
 *
 */
public class NodeSkipActionHandlerTest extends AbstractTestCase {

	private String taskDefName = "MyTask";
	private String emailAddress = "biju.joseph@semanticbits.com";

	private NodeSkipActionHandler handler;
	private WorkflowServiceImpl wfService;

	TaskConfig tConfig;

	protected void setUp() throws Exception {
		super.setUp();
		handler = new NodeSkipActionHandler();
		wfService = registerMockFor(WorkflowServiceImpl.class);

		handler.setWorkflowService(wfService);
	}

	public void testExecute_NotApplicable_Case() throws Exception {
		String wfDefName = "Test";
		String taskDefName = "a1";
		ProcessDefinition pDef = new ProcessDefinition();
		pDef.setName(wfDefName);

		ProcessInstance pInstance = registerMockFor(ProcessInstance.class);
		Node n = registerMockFor(Node.class);
		Token token = registerMockFor(Token.class);
		tConfig = Fixtures.createTaskConfig(taskDefName, false);

		ExecutionContext context = registerMockFor(ExecutionContext.class);
		EasyMock.expect(context.getProcessDefinition()).andReturn(pDef);
		EasyMock.expect(context.getProcessInstance()).andReturn(pInstance);
		EasyMock.expect(pInstance.getRootToken()).andReturn(token);
		EasyMock.expect(token.getNode()).andReturn(n);
		EasyMock.expect(n.getName()).andReturn(taskDefName);

		EasyMock.expect(wfService.findTaskConfig(wfDefName, taskDefName)).andReturn(tConfig);
		n.leave(context);
		replayMocks();
		handler.execute(context);
		verifyMocks();

	}

	public void testExecute_Applicable_Case() throws Exception {
		String wfDefName = "Test";
		String taskDefName = "a1";
		ProcessDefinition pDef = new ProcessDefinition();
		pDef.setName(wfDefName);

		ProcessInstance pInstance = registerMockFor(ProcessInstance.class);
		Node n = registerMockFor(Node.class);
		Token token = registerMockFor(Token.class);
		tConfig = Fixtures.createTaskConfig(taskDefName, true);

		ExecutionContext context = registerMockFor(ExecutionContext.class);
		EasyMock.expect(context.getProcessDefinition()).andReturn(pDef).anyTimes();
		EasyMock.expect(context.getNode()).andReturn(n).anyTimes();
		EasyMock.expect(context.getProcessInstance()).andReturn(pInstance);
		EasyMock.expect(pInstance.getRootToken()).andReturn(token);
		EasyMock.expect(token.getNode()).andReturn(n);
		EasyMock.expect(n.getName()).andReturn(taskDefName);

		EasyMock.expect(wfService.findTaskConfig(wfDefName, taskDefName)).andReturn(tConfig);

		List<Person> users = new ArrayList<Person>();
		Person u1 = new LocalResearchStaff();
		u1.setLoginId("joel@efg.com");
		users.add(u1);

		EasyMock.expect(wfService.findTaskAssignees(pInstance, taskDefName)).andReturn(users);

		wfService.createTaskInstances((CreateTaskJbpmCallback)EasyMock.anyObject());
		replayMocks();

		handler.execute(context);
		verifyMocks();

	}

}


text:
package com.commonsware.android.webserver.simple;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class StopReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    context.stopService(new Intent(context, WebServerService.class));
  }
}


text:
package main

import (
	"github.com/uber/cherami-server/cmd/servicecmd"
)

func main() {
	servicecmd.StartReplicatorService()
}


text: Simple REST API with HTTP Basic Authentication


text:
Edit the update-plugins.groovy script, set the jenkinsVersion variable to be the LTS version of jenkins you are using

# to download a new plugin package

# to add a new plugin

Simply add the entry into the plugin txt file


text:
using Azure.IoT.TimeSeriesInsights.Models;

namespace Azure.IoT.TimeSeriesInsights
{
    /// <summary> Definition of sorting of hierarchy nodes. </summary>
    public partial class HierarchiesSortParameter
    {
        /// <summary> Initializes a new instance of HierarchiesSortParameter. </summary>
        public HierarchiesSortParameter()
        {
        }

        /// <summary> Value to use for hierarchy node sorting. When it is set to 'CumulativeInstanceCount', the returned hierarchies are sorted based on the total instances belonging to the hierarchy node and its child hierarchy nodes. When it is set to 'Name', the returned hierarchies are sorted based on the hierarchy name. Optional, default is 'CumulativeInstanceCount'. </summary>
        public HierarchiesSortBy? By { get; set; }
    }
}


text:
package org.apache.causeway.viewer.wicket.model.models;

import org.apache.wicket.model.IModel;

import org.apache.causeway.core.metamodel.context.MetaModelContext;
import org.apache.causeway.core.metamodel.interactions.managed.ManagedValue;

public interface ScalarModelWithChoice<T>
extends
    IModel<T>,
    HasCommonContext {

    ScalarModel scalarModel();

    default ManagedValue pendingValue() { return scalarModel().proposedValue(); }

    @Override
    default MetaModelContext getMetaModelContext() {
        return scalarModel().getMetaModelContext();
    }

}


text:
<!doctype html>

  <title>Eddie</title>
  <link rel="stylesheet" type="text/css" href="assets/alternate_css1.css">

Home

Blog

About

I am just getting started in building this site, but come back soon to find something interesting.

Thanks!

LinkedIn

Github

Twitter

Facebook

          Thanks for stopping by! |
          Contact Me


text:
import { CommandOutput } from '@salesforce/salesforcedx-utils-vscode';
import { expect } from 'chai';
import * as fs from 'fs';
import * as sinon from 'sinon';
import {
  forceDescribeMetadata,
  ForceDescribeMetadataExecutor
} from '../../../src/commands';

// tslint:disable:no-unused-expression
describe('Force Describe Metadata', () => {
  it('Should build describe metadata command', async () => {
    const forceDescribeMetadataExec = new ForceDescribeMetadataExecutor();
    const forceDescribeMetadataCmd = forceDescribeMetadataExec.build({});
    expect(forceDescribeMetadataCmd.toCommand()).to.equal(
      `sfdx force:mdapi:describemetadata --json --loglevel fatal`
    );
  });

  it('Should write a file with metadata describe output', async () => {
    const execStub = sinon.stub(
      ForceDescribeMetadataExecutor.prototype,
      'execute'
    );
    const writeFileStub = sinon.stub(fs, 'writeFileSync');

    const outputFolder = './test/folder/';
    const resultData = '{status: 0}';
    const cmdOutputStub = sinon
      .stub(CommandOutput.prototype, 'getCmdResult')
      .returns(resultData);

    const result = await forceDescribeMetadata(outputFolder);
    expect(writeFileStub.calledOnce).to.equal(true);
    expect(result).to.equal(resultData);

    writeFileStub.restore();
    cmdOutputStub.restore();
    execStub.restore();
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hack121.Business.Entities
{
    public class University : Entity
    {
        public virtual string Edrpou { get; set; }

        public virtual string Title { get; set; }

        public virtual decimal YearBudget { get; set; }

        public virtual string ShortName { get; set; }
    }
}


text:
package rmdir

import (
	"github.com/ncw/rclone/cmd"
	"github.com/ncw/rclone/fs"
	"github.com/spf13/cobra"
)

func init() {
	cmd.Root.AddCommand(rmdirCmd)
}

var rmdirCmd = &cobra.Command{
	Use:   "rmdir remote:path",
	Short: `Remove the path if empty.`,
	Long: `
Remove the path.  Note that you can't remove a path with
objects in it, use purge for that.`,
	Run: func(command *cobra.Command, args []string) {
		cmd.CheckArgs(1, 1, command, args)
		fdst := cmd.NewFsDst(args)
		cmd.Run(true, command, func() error {
			return fs.Rmdir(fdst)
		})
	},
}


text:
package org.springframework.social.betaseries.api;

import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest;

import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.social.MissingAuthorizationException;

public class ErrorHandlingTest extends AbstractBetaSeriesApiTest {
	@Test(expected=MissingAuthorizationException.class)
	public void unauthorizedAccessTokenTest() {
		unauthorizedMockServer.expect(requestTo("https://api.betaseries.com/members/infos"))
		.andExpect(header(HEADER_API_KEY_PARAMS_NAME, "someApiKey"))
		.andExpect(header(HEADER_ACCESS_TOKEN_PARAMS_NAME, "someAccessToken"))
		.andExpect(header(HEADER_API_VERSION_PARAMS_NAME, API_VERSION))
		.andExpect(method(HttpMethod.GET))
		.andRespond(withBadRequest().body(jsonResource("error-2001-invalid-user-token")));

		unauthorizedBetaSeries.memberOperations().getMemberInfos();
	}
}


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/glue/GlueRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Glue
{
namespace Model
{

  /**
   */
  class AWS_GLUE_API DeleteConnectionRequest : public GlueRequest
  {
  public:
    DeleteConnectionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteConnection"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline const Aws::String& GetCatalogId() const{ return m_catalogId; }

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline bool CatalogIdHasBeenSet() const { return m_catalogIdHasBeenSet; }

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(const Aws::String& value) { m_catalogIdHasBeenSet = true; m_catalogId = value; }

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(Aws::String&& value) { m_catalogIdHasBeenSet = true; m_catalogId = std::move(value); }

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(const char* value) { m_catalogIdHasBeenSet = true; m_catalogId.assign(value); }

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline DeleteConnectionRequest& WithCatalogId(const Aws::String& value) { SetCatalogId(value); return *this;}

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline DeleteConnectionRequest& WithCatalogId(Aws::String&& value) { SetCatalogId(std::move(value)); return *this;}

    /**
     *
The ID of the Data Catalog in which the connection resides. If none is
     * provided, the Amazon Web Services account ID is used by default.

     */
    inline DeleteConnectionRequest& WithCatalogId(const char* value) { SetCatalogId(value); return *this;}

    /**
     *
The name of the connection to delete.

     */
    inline const Aws::String& GetConnectionName() const{ return m_connectionName; }

    /**
     *
The name of the connection to delete.

     */
    inline bool ConnectionNameHasBeenSet() const { return m_connectionNameHasBeenSet; }

    /**
     *
The name of the connection to delete.

     */
    inline void SetConnectionName(const Aws::String& value) { m_connectionNameHasBeenSet = true; m_connectionName = value; }

    /**
     *
The name of the connection to delete.

     */
    inline void SetConnectionName(Aws::String&& value) { m_connectionNameHasBeenSet = true; m_connectionName = std::move(value); }

    /**
     *
The name of the connection to delete.

     */
    inline void SetConnectionName(const char* value) { m_connectionNameHasBeenSet = true; m_connectionName.assign(value); }

    /**
     *
The name of the connection to delete.

     */
    inline DeleteConnectionRequest& WithConnectionName(const Aws::String& value) { SetConnectionName(value); return *this;}

    /**
     *
The name of the connection to delete.

     */
    inline DeleteConnectionRequest& WithConnectionName(Aws::String&& value) { SetConnectionName(std::move(value)); return *this;}

    /**
     *
The name of the connection to delete.

     */
    inline DeleteConnectionRequest& WithConnectionName(const char* value) { SetConnectionName(value); return *this;}

  private:

    Aws::String m_catalogId;
    bool m_catalogIdHasBeenSet = false;

    Aws::String m_connectionName;
    bool m_connectionNameHasBeenSet = false;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
Stuff Still Todo
================

- View settings.
- Support Distributed Builds settings
- Better/more unit tests.


text:
/*
 * error.h for libmenu
 * by lenormf
 */

#pragma once

typedef enum {
	MENU_ERR_NONE,

	MENU_ERR_INVALID_PARAMETER = 100,

	MENU_ERR_ALLOCATION_FAILURE = 200,

	MENU_ERR_INTERNAL_FAILURE = 300
} menu_error_e;

char const *menu_error_to_str(menu_error_e);


text:
Please select a Panchayat

        <button class="btn btn-large dropdown-toggle" data-toggle="dropdown">Panchayat </button>


text:
import {
  IconButton,
  Snackbar,
  SnackbarContent,
  Theme
} from "@material-ui/core";
import amber from "@material-ui/core/colors/amber";
import green from "@material-ui/core/colors/green";
import { WithStyles, createStyles, withStyles } from "@material-ui/core/styles";
import CheckCircleIcon from "@material-ui/icons/CheckCircle";
import CloseIcon from "@material-ui/icons/Close";
import ErrorIcon from "@material-ui/icons/Error";
import InfoIcon from "@material-ui/icons/Info";
import WarningIcon from "@material-ui/icons/Warning";
import * as React from "react";
import { commonString } from "../util/commonstrings";

const variantIcon = {
  success: CheckCircleIcon,
  warning: WarningIcon,
  error: ErrorIcon,
  info: InfoIcon
};

const styles = (theme: Theme) =>
  createStyles({
    success: {
      backgroundColor: green[600]
    },
    error: {
      backgroundColor: theme.palette.error.dark
    },
    info: {
      backgroundColor: theme.palette.primary.dark
    },
    warning: {
      backgroundColor: amber[700]
    },
    icon: {
      fontSize: 20
    },
    iconVariant: {
      opacity: 0.9,
      marginRight: theme.spacing.unit
    },
    message: {
      display: "flex",
      alignItems: "center"
    }
  });

interface MessageInfoProps {
  open: boolean;
  onClose: () => void;
  title: string;
  variant: "success" | "warning" | "error" | "info";
}

export default withStyles(styles)(
  class MessageInfo extends React.Component<
    MessageInfoProps & WithStyles<typeof styles>
  > {
    render() {
      const { open, title, onClose, classes, variant } = this.props;
      const Icon = variantIcon[variant];
      return (
        <Snackbar open={open} onClose={onClose} autoHideDuration={5000}>
          <SnackbarContent
            className={classes[variant]}
            aria-describedby="client-snackbar"
            message={
              <span id="client-snackbar" className={classes.message}>
                <Icon className={`${classes.icon} ${classes.iconVariant}`} />
                {title}
              </span>
            }
            action={
              <IconButton
                key="close"
                aria-label={commonString.action.close}
                color="inherit"
                onClick={onClose}
              >
                <CloseIcon className={classes.icon} />
              </IconButton>
            }
          />
        </Snackbar>
      );
    }
  }
);


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE appref SYSTEM "appref.dtd">

<appref>

    <copyright>
      <year>1996</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>os_mon</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>

  <app>os_mon</app>
  <appsummary>OS Monitoring Application</appsummary>
  <description>

The operating system monitor, OS_Mon, provides the following
      services:

    <list type="bulleted">
      <item><seealso marker="cpu_sup">cpu_sup</seealso>
       CPU load and utilization supervision (Unix)</item>
      <item><seealso marker="disksup">disksup</seealso>
       Disk supervision(Unix, Windows)</item>
      <item><seealso marker="memsup">memsup</seealso>
       Memory supervision (Unix, Windows, VxWorks)</item>
      <item><seealso marker="os_sup">os_sup</seealso>
       Interface to OS system messages (Solaris, Windows)</item>
    </list>

To simplify usage of OS_Mon on distributed Erlang systems, it is
      not considered an error trying to use a service at a node where it
      is not available (either because OS_Mon is not running, or because
      the service is not available for that OS, or because the service
      is not started). Instead, a warning message is issued via
      <c>error_logger</c> and a dummy value is returned, which one is
      specified in the man pages for the respective services.

  </description>

    <title>Configuration</title>

When OS_Mon is started, by default all services available for
      the OS, except <c>os_sup</c>, are automatically started. This
      configuration can be changed using the following application
      configuration parameters:

    <taglist>
      <tag><c>start_cpu_sup = bool()</c></tag>
      <item>

Specifies if <c>cpu_sup</c> should be started. Defaults to
          <c>true</c>.

      </item>
      <tag><c>start_disksup = bool()</c></tag>
      <item>

Specifies if <c>disksup</c> should be started. Defaults to
          <c>true</c>.

      </item>
      <tag><c>start_memsup = bool()</c></tag>
      <item>

Specifies if <c>memsup</c> should be started. Defaults to
          <c>true</c>.

      </item>
      <tag><c>start_os_sup = bool()</c></tag>
      <item>

Specifies if <c>os_sup</c> should be started. Defaults to
          <c>false</c>.

      </item>
    </taglist>

Configuration parameters effecting the different OS_Mon services
      are described in the respective man pages.

See <seealso marker="kernel:config">config(4)</seealso> for
      information about how to change the value of configuration
      parameters.

    <title>SNMP MIBs</title>

The following MIBs are defined in OS_Mon:

    <taglist>
      <tag>OTP-OS-MON-MIB</tag>
      <item>

This MIB contains objects for instrumentation of disk,
          memory and CPU usage of the nodes in the system.

      </item>
    </taglist>

The MIB is stored in the <c>mibs</c> directory.  It is defined
      in SNMPv2 SMI syntax. An SNMPv1 version of the MIB is delivered
      in the <c>mibs/v1</c> directory.

The compiled MIB is located under <c>priv/mibs</c>, and
      the generated <c>.hrl</c> file under the <c>include</c> directory.
      To compile a MIB that IMPORTS the <c>OTP-OS-MON-MIB</c>, give
      the option <c>{il, ["os_mon/priv/mibs"]}</c> to the MIB compiler.

If the MIB should be used in a system, it should be loaded into
      an agent with a call to <c>os_mon_mib:load(Agent)</c>, where
      <c>Agent</c> is the pid or registered name of an SNMP agent. Use
      <c>os_mon_mib:unload(Agent)</c> to unload the MIB.
      The implementation of this MIB uses Mnesia to store a cache with
      data needed, which implicates that Mnesia must be up and running.
      The MIB also use functions defined for the <c>OTP-MIB</c>, thus
      that MIB must be loaded as well.

    <title>See Also</title>

<seealso marker="cpu_sup">cpu_sup(3)</seealso>,
      <seealso marker="disksup">disksup(3)</seealso>,
      <seealso marker="memsup">memsup(3)</seealso>,
      <seealso marker="os_sup">os_sup(3)</seealso>,
      <seealso marker="nteventlog">nteventlog(3)</seealso>,
      <seealso marker="snmp:snmp">snmp(3)</seealso>.

</appref>


text:
package idp.saml;

import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.BasicSAMLMessageContext;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
import org.opensaml.saml2.core.*;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.saml2.metadata.SingleSignOnService;
import org.opensaml.security.SAMLSignatureProfileValidator;
import org.opensaml.ws.message.decoder.MessageDecodingException;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.opensaml.ws.security.SecurityPolicyResolver;
import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.security.SigningUtil;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.credential.CredentialResolver;
import org.opensaml.xml.security.criteria.EntityIDCriteria;
import org.opensaml.xml.signature.*;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.validation.ValidationException;
import org.opensaml.xml.validation.ValidatorSuite;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

import static idp.saml.SAMLBuilder.*;
import static java.util.Arrays.asList;
import static org.opensaml.xml.Configuration.getValidatorSuite;

public class SAMLMessageHandler {

  private final CredentialResolver credentialResolver;
  private final SAMLMessageEncoder encoder;
  private final SAMLMessageDecoder decoder;
  private final SecurityPolicyResolver resolver;
  private final String entityId;
  private final String spEntityId;
  private final String spMetaDataUrl;

  private final List<ValidatorSuite> validatorSuites;

  public SAMLMessageHandler(CredentialResolver credentialResolver,
                            SAMLMessageDecoder samlMessageDecoder,
                            SAMLMessageEncoder samlMessageEncoder,
                            SecurityPolicyResolver securityPolicyResolver,
                            String entityId,
                            String spEntityId,
                            String spMetaDataUrl) {
    this.credentialResolver = credentialResolver;
    this.encoder = samlMessageEncoder;
    this.decoder = samlMessageDecoder;
    this.resolver = securityPolicyResolver;
    this.entityId = entityId;
    this.spEntityId = spEntityId;
    this.spMetaDataUrl = spMetaDataUrl;
    this.validatorSuites = asList(getValidatorSuite("saml2-core-schema-validator"), getValidatorSuite("saml2-core-spec-validator"));
  }

  public SAMLMessageContext extractSAMLMessageContext(HttpServletRequest request)  {
    BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();

    messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));
    messageContext.setSecurityPolicyResolver(resolver);

    try {
      decoder.decode(messageContext);
    } catch (SecurityException | MessageDecodingException e) {
      throw new RuntimeException(e);
    }

    SAMLObject inboundSAMLMessage = messageContext.getInboundSAMLMessage();
    if (!(inboundSAMLMessage instanceof AuthnRequest)) {
      throw new RuntimeException("Expected inboundSAMLMessage to be AuthnRequest, but actual " + inboundSAMLMessage.getClass());
    }

    AuthnRequest authnRequest = (AuthnRequest) inboundSAMLMessage;
    try {
      validate(request, authnRequest);
    } catch (ValidationException | SecurityException e) {
      throw new SAMLAuthenticationException("Exception during validation of AuthnRequest", e, messageContext);
    }
    return messageContext;
  }

  public void sendAuthnResponse(SAMLAuthenticationToken token, HttpServletResponse response) throws MarshallingException, SignatureException, MessageEncodingException {
    doSendAuthnResponse(token, response, buildStatus(StatusCode.SUCCESS_URI));
  }

  public void sendFailedAuthnResponse(SAMLAuthenticationException authenticationException, HttpServletRequest request, HttpServletResponse response ) throws MarshallingException, SignatureException, MessageEncodingException {
    SAMLMessageContext messageContext = authenticationException.getMessageContext();
    AuthnRequest authnRequest = (AuthnRequest) messageContext.getInboundSAMLMessage();
    SAMLAuthenticationToken token = new SAMLAuthenticationToken(authnRequest, messageContext.getRelayState(), request.getRemoteAddr());
    doSendAuthnResponse(token, response, buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, authenticationException.getMessage()));
  }

  private void doSendAuthnResponse(SAMLAuthenticationToken token, HttpServletResponse response, Status status) throws MarshallingException, SignatureException, MessageEncodingException {
    Credential signingCredential = resolveCredential(entityId);

    Response authResponse = buildSAMLObject(Response.class, Response.DEFAULT_ELEMENT_NAME);
    Issuer issuer = buildIssuer(entityId);

    authResponse.setIssuer(issuer);
    authResponse.setID(UUID.randomUUID().toString());
    authResponse.setIssueInstant(new DateTime());
    authResponse.setInResponseTo(token.getId());

    Assertion assertion = buildAssertion(token, status, entityId, spMetaDataUrl);
    signAssertion(assertion, signingCredential);

    authResponse.getAssertions().add(assertion);
    authResponse.setDestination(token.getAssertionConsumerServiceURL());

    authResponse.setStatus(status);

    Endpoint endpoint = buildSAMLObject(Endpoint.class, SingleSignOnService.DEFAULT_ELEMENT_NAME);
    endpoint.setLocation(token.getAssertionConsumerServiceURL());

    HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, false);

    BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();

    messageContext.setOutboundMessageTransport(outTransport);
    messageContext.setPeerEntityEndpoint(endpoint);
    messageContext.setOutboundSAMLMessage(authResponse);
    messageContext.setOutboundSAMLMessageSigningCredential(signingCredential);

    messageContext.setOutboundMessageIssuer(entityId);
    messageContext.setRelayState(token.getRelayState());

    encoder.encode(messageContext);
  }

  private void signAssertion(Assertion assertion, Credential signingCredential) throws MarshallingException, SignatureException {
    Signature signature = buildSAMLObject(Signature.class, Signature.DEFAULT_ELEMENT_NAME);

    signature.setSigningCredential(signingCredential);
    signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    assertion.setSignature(signature);

    Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);
    Signer.signObject(signature);
  }

  private void validate(HttpServletRequest request, AuthnRequest authnRequest) throws ValidationException, SecurityException {
      validateXMLObject(authnRequest);
      validateSignature(authnRequest);
      validateRawSignature(request, authnRequest.getIssuer().getValue());
  }

  private void validateXMLObject(XMLObject xmlObject) throws ValidationException {
    //lambda is poor with Exceptions
    for (ValidatorSuite validatorSuite : validatorSuites) {
      validatorSuite.validate(xmlObject);
    }
  }

  private void validateRawSignature(HttpServletRequest request, String issuer) throws SecurityException {
    String base64signature = request.getParameter("Signature");
    String sigAlg = request.getParameter("SigAlg");
    if (base64signature == null || sigAlg == null) {
      return;
    }
    byte[] input = request.getQueryString().replaceFirst("&Signature[^&]+", "").getBytes();
    byte[] signature = Base64.decode(base64signature);

    Credential credential = resolveCredential(issuer);
    SigningUtil.verifyWithURI(credential, sigAlg, signature, input);
  }

  private void validateSignature(AuthnRequest authnRequest) throws ValidationException {
    Signature signature = authnRequest.getSignature();
    if (signature == null) {
      return;
    }
    new SAMLSignatureProfileValidator().validate(signature);
    String issuer = authnRequest.getIssuer().getValue();
    Credential credential = resolveCredential(issuer);
    new SignatureValidator(credential).validate(signature);
  }

  private Credential resolveCredential(String entityId) {
    try {
      return credentialResolver.resolveSingle(new CriteriaSet(new EntityIDCriteria(entityId)));
    } catch (SecurityException e) {
      throw new RuntimeException(e);
    }
  }

}


text:
package presentation.models;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;

/**
 * Created by Patrick on 17.08.2015.
 */
public class BonusModel
{
    private IntegerProperty points = new SimpleIntegerProperty();

    public int getPoints()
    {
        return points.get();
    }

    public IntegerProperty pointsProperty()
    {
        return points;
    }

    public void setPoints(int points)
    {
        this.points.set(points);
    }
}


text:
package view.controler.dialogInterface;

import view.activity.ActivityListAthlete;
import android.app.Activity;
import android.content.DialogInterface;
import android.widget.NumberPicker;
import android.widget.TextView;
import business.DialogDistance;
import com.chronos.R;

/* _________________________________________________________ */
/**
 * @author Jerome POINAS
 *
 *         La classe ControlerDistanceDialogInterface permettant de gérer les
 *         évenements sur le numberpicker des distances.
 *
 */
public final class ControlerDistanceDialogInterface implements
		DialogInterface.OnClickListener
{
	/** The picker. */
	private final NumberPicker		picker;
	/** The activity. */
	private final Activity			activity;
	/** The dialog distance. */
	private final DialogDistance	dialogDistance;

	/* _________________________________________________________ */
	/**
	 * Instantiates a new controler distance dialog interface.
	 *
	 * @param picker
	 *            the picker
	 * @param activity
	 *            the activity
	 * @param dialogDistance
	 *            the dialog distance
	 */
	public ControlerDistanceDialogInterface(final NumberPicker picker,
			final Activity activity, final DialogDistance dialogDistance)
	{
		this.picker = picker;
		this.activity = activity;
		this.dialogDistance = dialogDistance;
	}

	/* _________________________________________________________ */
	/**
	 * On click.
	 *
	 * @param dialog
	 *            the dialog
	 * @param id
	 *            the id
	 * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface,
	 *      int)
	 */
	@Override
	public void onClick(
			@SuppressWarnings("unused") final DialogInterface dialog,
			@SuppressWarnings("unused") final int id)
	{
		final TextView champsDistance = (TextView) activity
				.findViewById(R.id.textView1);
		final String[] values = picker.getDisplayedValues();
		champsDistance.setText("DialogDistance d'enregistrement : ("
				+ values[picker.getValue()] + "m)");
		ActivityListAthlete.setRecordDistance(Integer.parseInt(values[picker
				.getValue()]));
		dialogDistance.setIndex(picker.getValue());
	}
}


text:
wpContent=${wpContent-wp-content}

# List of WordPress core files
TARGETS=(
	wp-activate.php
	wp-admin/
	wp-blog-header.php
	wp-comments-post.php
	wp-config-sample.php
	${wpContent}/index.php
	${wpContent}/languages
	${wpContent}/plugins/index.php
	${wpContent}/themes/index.php
	${wpContent}/themes/twentyeleven
	${wpContent}/themes/twentytwelve
	${wpContent}/themes/twentythirteen
	${wpContent}/themes/twentyfourteen
	${wpContent}/themes/twentyfifteen
	${wpContent}/themes/twentysixteen
	wp-cron.php
	wp-includes/
	wp-links-opml.php
	wp-load.php
	wp-login.php
	wp-mail.php
	wp-register.php
	wp-settings.php
	wp-signup.php
	wp-trackback.php
	xmlrpc.php
);

removeFiles=(
	license.txt
	liesmich.html
	README
	readme.html
	wp-config-sample.php
);

# Clean-up staged files
git reset HEAD -- . > /dev/null

status=$?

if [ ${status} -ne 0 ]; then
	echo "ERROR: Could not reset the branch to HEAD."
fi

# Add if exists
for T in "${TARGETS[@]}"; do
	if [[ ! -d ${T} && ! -f ${T} ]]; then
		continue;
	fi

	# echo Adding $T
	git add --all $T
done

for singleFile in "${removeFiles[@]}"; do
	if [[ ! -f $singleFile ]]; then
		continue;
	fi

	git rm -rf $singleFile &> /dev/null
done

previousVersion=$(git show HEAD:wp-includes/version.php | grep "wp_version =" | egrep -o "[0-9\.]+")
currentVersion=$(cat wp-includes/version.php | grep "wp_version =" | egrep -o "[0-9\.]+")

git commit -m 'WordPress Core Update ${previousVersion} to ${currentVersion}'

echo "Core Update has been commited."
echo ""
echo "To see what is not yet in the commit type:"
echo "	git diff --name-only"
echo ""
echo "To append such files use"
echo "	git commit --amend FILENAME.1 FILENAME.2 DIRECTORY.42"
echo ""


text:
require Rails.root.join('app/models/plan')

class Service
  attr_reader :id, :name, :description, :bindable, :tags, :metadata, :requires, :plans, :dashboard_client

  def self.build(attrs)
    plan_attrs = attrs['plans'] || []
    plans      = plan_attrs.map { |attr| Plan.build(attr) }
    new(attrs.merge('plans' => plans))
  end

  def initialize(attrs)
    validate_attrs(attrs)

    @id          = attrs.fetch('id')
    @name        = attrs.fetch('name')
    @description = attrs.fetch('description')
    @bindable    = attrs.fetch('bindable', true)
    @tags        = attrs.fetch('tags', []) || []
    @metadata    = attrs.fetch('metadata', nil)
    @requires    = attrs.fetch('requires', []) || []
    @plans       = attrs.fetch('plans')
    @dashboard_client = attrs.fetch('dashboard_client', {}) || {}
  end

  def to_hash
    {
      'id'               => id,
      'name'             => name,
      'description'      => description,
      'bindable'         => bindable,
      'tags'             => tags,
      'metadata'         => metadata,
      'requires'         => requires,
      'plans'            => plans.map(&:to_hash),
      'dashboard_client' => dashboard_client,
    }
  end

  private

  def validate_attrs(attrs)
    required_keys = %w(id name description plans)
    missing_keys = []

    required_keys.each do |key|
      missing_keys << "#{key}" unless attrs.key?(key)
    end

    unless missing_keys.empty?
      raise Exceptions::ArgumentError, "Missing Service parameters: #{missing_keys.join(', ')}"
    end
  end
end