text:
package com.tle.web.cloud.search.filters;

import com.tle.common.NameValue;
import com.tle.core.cloud.service.CloudService;
import com.tle.web.cloud.event.CloudSearchEvent;
import com.tle.web.freemarker.FreemarkerFactory;
import com.tle.web.freemarker.annotations.ViewFactory;
import com.tle.web.search.base.AbstractSearchResultsSection;
import com.tle.web.search.filter.ResetFiltersListener;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.annotations.TreeLookup;
import com.tle.web.sections.equella.search.SearchResultsActionsSection;
import com.tle.web.sections.equella.search.event.SearchEventListener;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.generic.AbstractPrototypeSection;
import com.tle.web.sections.render.HtmlRenderer;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.standard.SingleSelectionList;
import com.tle.web.sections.standard.annotations.Component;
import com.tle.web.sections.standard.model.HtmlListModel;
import javax.inject.Inject;

@SuppressWarnings("nls")
public abstract class AbstractCloudFilter extends AbstractPrototypeSection<Object>
    implements SearchEventListener<CloudSearchEvent>, ResetFiltersListener, HtmlRenderer {
  @ViewFactory protected FreemarkerFactory viewFactory;

  @Inject protected CloudService cloudService;

  @TreeLookup protected AbstractSearchResultsSection<?, ?, ?, ?> searchResults;

  @Component(supported = true)
  protected SingleSelectionList<NameValue> list;

  @Override
  public void registered(String id, SectionTree tree) {
    super.registered(id, tree);
    tree.setLayout(id, SearchResultsActionsSection.AREA_FILTER);
    list.setListModel(buildListModel());
    list.setParameterId(getPublicParam());
  }

  @Override
  public void treeFinished(String id, SectionTree tree) {
    super.treeFinished(id, tree);
    list.addChangeEventHandler(searchResults.getRestartSearchHandler(tree));
  }

  @Override
  public SectionResult renderHtml(RenderEventContext context) throws Exception {
    return viewFactory.createResult("filter/cloudfilter.ftl", context);
  }

  public SingleSelectionList<NameValue> getList() {
    return list;
  }

  @Override
  public void reset(SectionInfo info) {
    list.setSelectedValue(info, null);
  }

  protected abstract Label getTitle();

  protected abstract HtmlListModel<NameValue> buildListModel();

  protected abstract String getPublicParam();
}


text:
var elixir = require('laravel-elixir');
var jsList = [
    '../assets/vendor/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.js',
    '../assets/vendor/smalot-bootstrap-datetimepicker/js/bootstrap-datetimepicker.js',
    '../assets/vendor/Chart.js/Chart.js',
    '_main.js'
];
var cssList = [
    '../assets/vendor/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css',
    '../assets/vendor/smalot-bootstrap-datetimepicker/css/bootstrap-datetimepicker.css',
    'app.css'
];

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Less
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(function (mix) {
    mix.less('app.less', 'resources/css')
        .scripts(jsList, 'public/js/main.js')
        .styles(cssList, 'public/css/app.css');
});

redpajama_set_name: RedPajamaGithub


text:
(function ($) {
    $.fn.serializeFormJSON = function (resourceName, usePlaceholders) {

        function resolveObjectHref(attrVal, attrMetadata) {
            if (attrVal == '') {
                if (usePlaceholders) {
                    attrVal = 'NULL';
                } else {
                    return null;
                }
            }
            var rest_link_template = attrMetadata['rest_link']['href'];
            return decodeURIComponent(rest_link_template).replace('{idPlaceholder}', attrVal);
        }

        function isPartialPropertyField(name) {
            return name.indexOf("_time") > -1;
        }

        var json = {};
        $.each(this.serializeArray(), function () {
            var attrVal = this.value || '';
            var propertyName = this.name.replace("[]", "");
            var property = ConfigurationMetadataService.getProperty(resourceName, propertyName, 'formView');
            if (property == null) {
                if ( isPartialPropertyField(propertyName) && attrVal.length != 0) {
                    var main_property_name = propertyName.substr(0, propertyName.indexOf("_time"));
                    if (json[main_property_name] != null && json[main_property_name].length != 0) {
                        json[main_property_name] = json[main_property_name] + 'T' + attrVal;
                    }
                }
                return;
            }
            var propertyType = property['type'];
            if (propertyType.indexOf('COLLECTION') == 0) {
            	if (!json[propertyName]) {
            		json[propertyName] = [];
                }
            	if(attrVal != ''){
            		json[propertyName].push(attrVal);
            	}
            }else if (propertyType.indexOf('ASSOC') == 0) {
                var href = resolveObjectHref(attrVal, property);
                if (propertyType == 'ASSOC_MULTI') {
                    if (!json[propertyName]) {
                        json[propertyName] = [];
                    }
                    json[propertyName].push(href);
                } else {
                    json[propertyName] = href;
                }
            } else {
                json[propertyName] = attrVal;
            }
        });

        $.each(ConfigurationMetadataService.getDynamicProperties(resourceName, "formView"), function (attrName, attrMetadata) {
            var attrVal = json[attrName];
            if (attrVal != undefined && attrVal != '') {
                return;
            }
            switch (attrMetadata.type) {
                case 'ASSOC_MULTI':
                    json[attrName] = [];
                    break;
                case 'BOOL':
                    json[attrName] = false;
                    break;
                case 'DATE':
                    if (usePlaceholders) {
                        json[attrName] = -377743392000001;
                    }
                    break;
            }
        });
        return json;
    };
})(jQuery);


text:
@interface NSLayoutConstraint (ClassMethodPriority)

+ (id)constraintWithItem:(id)view1
			   attribute:(NSLayoutAttribute)attr1
			   relatedBy:(NSLayoutRelation)relation
				  toItem:(id)view2
			   attribute:(NSLayoutAttribute)attr2
			  multiplier:(CGFloat)multiplier
				constant:(CGFloat)c
				priority:(UILayoutPriority)priority;

@end


text:
set srcdir=..\..\Source\IlmImf
cd %srcdir%
set instdir=..\include
mkdir %instdir%
copy ImfAttribute.h %instdir%
copy ImfBoxAttribute.h %instdir%
copy ImfCRgbaFile.h %instdir%
copy ImfChannelList.h %instdir%
copy ImfChannelListAttribute.h %instdir%
copy ImfCompressionAttribute.h %instdir%
copy ImfDoubleAttribute.h %instdir%
copy ImfFloatAttribute.h %instdir%
copy ImfFrameBuffer.h %instdir%
copy ImfHeader.h %instdir%
copy ImfIO.h %instdir%
copy ImfInputFile.h %instdir%
copy ImfIntAttribute.h %instdir%
copy ImfLineOrderAttribute.h %instdir%
copy ImfMatrixAttribute.h %instdir%
copy ImfOpaqueAttribute.h %instdir%
copy ImfOutputFile.h %instdir%
copy ImfRgbaFile.h %instdir%
copy ImfStringAttribute.h %instdir%
copy ImfVecAttribute.h %instdir%
copy ImfHuf.h %instdir%
copy ImfWav.h %instdir%
copy ImfLut.h %instdir%
copy ImfArray.h %instdir%
copy ImfCompression.h %instdir%
copy ImfLineOrder.h %instdir%
copy ImfName.h %instdir%
copy ImfPixelType.h %instdir%
copy ImfVersion.h %instdir%
copy ImfXdr.h %instdir%
copy ImfConvert.h %instdir%
copy ImfPreviewImage.h %instdir%
copy ImfPreviewImageAttribute.h %instdir%
copy ImfChromaticities.h %instdir%
copy ImfChromaticitiesAttribute.h %instdir%
copy ImfStandardAttributes.h %instdir%
copy ImfStdIO.h  %instdir%
copy ImfEnvmap.h  %instdir%
copy ImfEnvmapAttribute.h  %instdir%
copy ImfInt64.h  %instdir%
copy ImfRgba.h %instdir%
copy ImfTileDescription.h  %instdir%
copy ImfTileDescriptionAttribute.h  %instdir%
copy ImfTiledInputFile.h  %instdir%
copy ImfTiledOutputFile.h  %instdir%
copy ImfTiledRgbaFile.h %instdir%
copy ImfRgbaYca.h %instdir%
copy ImfKeyCode.h %instdir%
copy ImfKeyCodeAttribute.h %instdir%
copy ImfTimeCodeAttribute.h %instdir%
copy ImfTimeCode.h %instdir%
copy ImfTestFile.h %instdir%
copy ImfThreading.h %instdir%


text:
/* 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 org.camunda.bpm.engine.impl;

import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.engine.query.QueryProperty;

/**
 * @author roman.smirnov
 */
public class VariableInstanceQueryProperty implements QueryProperty {

  private static final long serialVersionUID = 1L;
  private static final Map<String, VariableInstanceQueryProperty> properties = new HashMap<String, VariableInstanceQueryProperty>();

  public static final VariableInstanceQueryProperty VARIABLE_NAME = new VariableInstanceQueryProperty("RES.NAME_");
  public static final VariableInstanceQueryProperty VARIABLE_TYPE = new VariableInstanceQueryProperty("RES.TYPE_");
  public static final VariableInstanceQueryProperty ACTIVITY_INSTANCE_ID = new VariableInstanceQueryProperty("RES.ACT_INST_ID_");

  private String name;

  public VariableInstanceQueryProperty(String name) {
    this.name = name;
    properties.put(name, this);
  }

  public String getName() {
    return name;
  }

  public static VariableInstanceQueryProperty findByName(String propertyName) {
    return properties.get(propertyName);
  }

}


text:
package ru.batov.procollection.map;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by Batov Nikolay on 11.04.2017.
 * Project name: junior
 */
public class DirectoryTest {

    /**
     * Test resize massif in Directory class.
     */
    @Test
    public void whenAddInDirectoryThenResizeMassif() {
        Directory<String, Integer> test = new Directory<>(1);

        test.insert("One", 1);
        Directory.Node<String, Integer>[] massif = test.getMassif();

        assertThat(massif.length, is(2));
    }

    /**
     *  Check add in Directory.
     */
    @Test
    public void whenAddThenAdd() {
        Directory<String, Integer> test = new Directory<>(1);

        String testKey = "One";
        test.insert(testKey, 1);
        Directory.Node<String, Integer>[] massif = test.getMassif();
        int position = (massif.length - 1) & (testKey.hashCode() ^ (testKey.hashCode() >>> 16));

        assertThat(massif[position].getKey(), is(testKey));
    }
}


text:
"""
Clean pages which are given in argument list. If there is no argument,
it will clean sample text instead. To configure the cleaning, pleas look
at wp.lcleaner
"""

__version__ = "2.0.1"
__author__ = "Sorawee Porncharoenwase"

import init
import wp
import pywikibot
from wp import lcleaner

def glob():
    pass

def main():
    page = wp.handlearg("page", args)
    if page:
        page = wp.Page(page)
        page.put(lcleaner.clean(page.get()), conf.summary)
    txt = wp.handlearg("txt", args)
    if txt:
        pywikibot.output(lcleaner.clean(txt))

if __name__ == "__main__":
    args, site, conf = wp.pre(u"clean articles")
    try:
        glob()
        main()
    except:
        wp.posterror()
    else:
        wp.post()


text:
<?php

/**
 * sfWidgetFormI18nDate represents a date widget.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormI18nDate.class.php 9046 2008-05-19 08:13:51Z FabianLange $
 */
class sfWidgetFormI18nDate extends sfWidgetFormDate
{
  /**
   * Constructor.
   *
   * Available options:
   *
   *  * culture:      The culture to use for internationalized strings (required)
   *  * month_format: The month format (name - default, short_name, number)
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormDate
   */
  protected function configure($options = array(), $attributes = array())
  {
    parent::configure($options, $attributes);

    $this->addRequiredOption('culture');
    $this->addOption('month_format');

    $culture = isset($options['culture']) ? $options['culture'] : 'en';
    $monthFormat = isset($options['month_format']) ? $options['month_format'] : 'name';

    // format
    $this->setOption('format', $this->getDateFormat($culture));

    // months
    $this->setOption('months', $this->getMonthFormat($culture, $monthFormat));
  }

  protected function getMonthFormat($culture, $monthFormat)
  {
    switch ($monthFormat)
    {
      case 'name':
        return array_combine(range(1, 12), sfDateTimeFormatInfo::getInstance($culture)->getMonthNames());
      case 'short_name':
        return array_combine(range(1, 12), sfDateTimeFormatInfo::getInstance($culture)->getAbbreviatedMonthNames());
      case 'number':
        return $this->getOption('months');
      default:
        throw new InvalidArgumentException(sprintf('The month format "%s" is invalid.', $monthFormat));
    }
  }

  protected function getDateFormat($culture)
  {
    $dateFormat = sfDateTimeFormatInfo::getInstance($culture)->getShortDatePattern();

    if (false === ($dayPos = stripos($dateFormat, 'd')) || false === ($monthPos = stripos($dateFormat, 'm')) || false === ($yearPos = stripos($dateFormat, 'y')))
    {
      return $this->getOption('format');
    }

    return strtr($dateFormat, array(
      substr($dateFormat, $dayPos,   strripos($dateFormat, 'd') - $dayPos + 1)   => '%day%',
      substr($dateFormat, $monthPos, strripos($dateFormat, 'm') - $monthPos + 1) => '%month%',
      substr($dateFormat, $yearPos,  strripos($dateFormat, 'y') - $yearPos + 1)  => '%year%',
    ));
  }
}


text:
Meteor.startup(function() {
  if(Meteor.isClient) {
    SEO.config({
      title: 'Meteor Singapore',
      meta: {
        'description': 'A Bi-Monthly Meteor.js Meetup in Singapore'
      },
      og: {
        'image': Meteor.absoluteUrl('share-image.png')
      },
      ignore: {
        meta: ['fragment', 'viewport', 'msapplication-TileColor', 'msapplication-TileImage', 'msapplication-config'],
        link: ['stylesheet', 'apple-touch-icon', 'rel', 'shortcut icon', 'icon']
      }
    });
  }
});


text:
import os
import base64
from collections import defaultdict
from netaddr import IPAddress, IPNetwork
from django.db.models import F, Q
from xos.config import Config
from synchronizers.base.openstacksyncstep import OpenStackSyncStep
from synchronizers.base.syncstep import *
from core.models.network import *
from core.models.slice import *
from core.models.instance import Instance
from xos.logger import observer_logger as logger
from synchronizers.base.ansible import *
from openstack.driver import OpenStackDriver
from xos.config import Config
import json

import pdb

class SyncControllerNetworks(OpenStackSyncStep):
    requested_interval = 0
    provides=[Network]
    observes=ControllerNetwork
    playbook='sync_controller_networks.yaml'

    def alloc_subnet(self, uuid):
        # 16 bits only
        uuid_masked = uuid & 0xffff
        a = 10
        b = uuid_masked >> 8
        c = uuid_masked & 0xff
        d = 0

        cidr = '%d.%d.%d.%d/24'%(a,b,c,d)
        return cidr

    def alloc_gateway(self, uuid):
        # 16 bits only
        uuid_masked = uuid & 0xffff
        a = 10
        b = uuid_masked >> 8
        c = uuid_masked & 0xff
        d = 1

        gateway = '%d.%d.%d.%d'%(a,b,c,d)
        return gateway

    def save_controller_network(self, controller_network):
        network_name = controller_network.network.name
        subnet_name = '%s-%d'%(network_name,controller_network.pk)
        cidr = self.alloc_subnet(controller_network.pk)
        self.cidr=cidr
        slice = controller_network.network.owner

        network_fields = {'endpoint':controller_network.controller.auth_url,
                    'endpoint_v3': controller_network.controller.auth_url_v3,
                    'admin_user':slice.creator.email,
                    'tenant_name':slice.name,
                    'admin_password':slice.creator.remote_password,
                    'domain': controller_network.controller.domain,
                    'name':network_name,
                    'subnet_name':subnet_name,
                    'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
                    'cidr':cidr,
                    'gateway':self.alloc_gateway(controller_network.pk),
                    'use_vtn':getattr(Config(), "networking_use_vtn", False),
                    'delete':False
                    }
        return network_fields

    def map_sync_outputs(self, controller_network,res):
        network_id = res[0]['id']
        subnet_id = res[1]['id']
        controller_network.net_id = network_id
        controller_network.subnet = self.cidr
        controller_network.subnet_id = subnet_id
	controller_network.backend_status = '1 - OK'
        controller_network.save()

    def map_sync_inputs(self, controller_network):
        # XXX This check should really be made from booleans, rather than using hardcoded network names
        if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
            logger.info("skipping network controller %s because it is not private" % controller_network)
            # We only sync private networks
            return SyncStep.SYNC_WITHOUT_RUNNING

        if not controller_network.controller.admin_user:
            logger.info("controller %r has no admin_user, skipping" % controller_network.controller)
            return

        if controller_network.network.owner and controller_network.network.owner.creator:
	    return self.save_controller_network(controller_network)
        else:
            raise Exception('Could not save network controller %s'%controller_network)

    def map_delete_inputs(self, controller_network):
        # XXX This check should really be made from booleans, rather than using hardcoded network names
	if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
            # We only sync private networks
            return
	try:
        	slice = controller_network.network.owner # XXX: FIXME!!
        except:
                raise Exception('Could not get slice for Network %s'%controller_network.network.name)

	network_name = controller_network.network.name
        subnet_name = '%s-%d'%(network_name,controller_network.pk)
	cidr = controller_network.subnet
	network_fields = {'endpoint':controller_network.controller.auth_url,
                    'admin_user':slice.creator.email, # XXX: FIXME
                    'tenant_name':slice.name, # XXX: FIXME
                    'admin_password':slice.creator.remote_password,
                    'name':network_name,
                    'subnet_name':subnet_name,
                    'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
                    'cidr':cidr,
		    'delete':True
                    }

        return network_fields

	"""
        driver = OpenStackDriver().client_driver(caller=controller_network.network.owner.creator,
                                                 tenant=controller_network.network.owner.name,
                                                 controller=controller_network.controller.name)
        if (controller_network.router_id) and (controller_network.subnet_id):
            driver.delete_router_interface(controller_network.router_id, controller_network.subnet_id)
        if controller_network.subnet_id:
            driver.delete_subnet(controller_network.subnet_id)
        if controller_network.router_id:
            driver.delete_router(controller_network.router_id)
        if controller_network.net_id:
            driver.delete_network(controller_network.net_id)
	"""


text:
{% extends path+"/citizen/app/_layout.html" %}

{% block app_nav %}{{ nav.app_nav('learning',path) }}{% endblock %}

{% block case_content %}

Learning and remembering how to do things

I am not able to {{ 1 | lorum | safe }}

{% endblock %}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/neon-animation/neon-animation-runner-behavior.html">
<link rel="import" href="../../bower_components/neon-animation/animations/fade-in-animation.html">

<dom-module id="encounter-view">
  <template>

    Encountering a [[encounter.name]]

    <template is="dom-repeat" items="[[encounter.reactions]]" index-as="index">
      <paper-button raised="[[isEncounterPhase(game.phase)]]" on-tap="onTapReaction" index$="{{index}}"
      disabled="[[!isEncounterPhase(game.phase)]]">
        [[reaction(encounter.reactions, index)]]
      </paper-button>
    </template>

        [[chosenReaction.name]]

        [[intro]]

      <template is="dom-repeat" items="[[chosenReaction.triggers]]" index-as="index">
        <paper-button raised="[[isStoryPhase(game.phase)]]" disabled="[[!isStoryPhase(game.phase)]]"
        on-tap="onTapTrigger" index$="{{index}}">
          [[triggerName(chosenReaction.triggers,index)]]
        </paper-button>
      </template>

        [[conclusion]]

      <paper-button raised on-tap="onFinish">OK</paper-button>

  </template>

</dom-module>


text:
<Record>
<Term>Lamotrigine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Lamotrigine</Synonym>
<Synonym>Lamictal xr</Synonym>
<Synonym>Lamictal cd</Synonym>
<Synonym>Lamictal odt</Synonym>
<Synonym>Lamictal</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
#import <Foundation/Foundation.h>

#import "FirebaseAuth/Sources/Backend/FIRAuthRPCResponse.h"
#import "FirebaseAuth/Sources/Backend/RPC/Proto/FIRAuthProtoMFAEnrollment.h"

NS_ASSUME_NONNULL_BEGIN

/** @class FIRVerifyAssertionResponse
    @brief Represents the response from the emailLinkSignin endpoint.
 */
@interface FIREmailLinkSignInResponse : NSObject <FIRAuthRPCResponse>

/** @property IDToken
    @brief The ID token in the email link sign-in response.
 */
@property(nonatomic, copy, readonly) NSString *IDToken;

/** @property email
    @brief The email returned by the IdP.
 */
@property(nonatomic, strong, readonly, nullable) NSString *email;

/** @property refreshToken
    @brief The refreshToken returned by the server.
 */
@property(nonatomic, strong, readonly, nullable) NSString *refreshToken;

/** @property localID
    @brief The Firebase Auth user ID.
 */
@property(nonatomic, strong, readonly, nullable) NSString *localID;

/** @property approximateExpirationDate
    @brief The approximate expiration date of the access token.
 */
@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate;

/** @property isNewUser
    @brief Flag indicating that the user signing in is a new user and not a returning user.
 */
@property(nonatomic, assign) BOOL isNewUser;

/** @property MFAPendingCredential
    @brief An opaque string that functions as proof that the user has successfully passed the first
   factor check.
*/
@property(nonatomic, strong, readonly, nullable) NSString *MFAPendingCredential;

/** @property MFAInfo
    @brief Info on which multi-factor authentication providers are enabled.
*/
@property(nonatomic, strong, readonly, nullable) NSArray<FIRAuthProtoMFAEnrollment *> *MFAInfo;

@end

NS_ASSUME_NONNULL_END


text:
package org.dspace.app.xmlui.aspect.general;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;

/**
 * Simple action to return a 304 (Not Modified) status, for when request
 * had the If-modified-since header and resource has not been modified.
 * Used in conjunction with IfModifiedSinceSelector
 *
 * @author Larry Stone
 */

public class NotModifiedAction extends AbstractAction
{
    /**
     * Return a 304 (Not Modified) status in the response.
     */
    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
            String source, Parameters parameters) throws Exception
    {
        final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
        httpResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return new HashMap();
    }
}


text:
module Vines
  # An X509 certificate store that validates certificate trust chains.
  # This uses the config/certs/*.crt files as the list of trusted root
  # CA certificates.
  class Store
    @@sources = nil

    # Create a certificate store to read certificate files from the given
    # directory.
    #
    # dir - The String directory name (absolute or relative).
    def initialize(dir)
      @dir = File.expand_path(dir)
      @store = OpenSSL::X509::Store.new
      certs.each {|cert| append(cert) }
    end

    # Return true if the certificate is signed by a CA certificate in the
    # store. If the certificate can be trusted, it's added to the store so
    # it can be used to trust other certs.
    #
    # pem - The PEM encoded certificate String.
    #
    # Returns true if the certificate is trusted.
    def trusted?(pem)
      if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
        @store.verify(cert).tap do |trusted|
          append(cert) if trusted
        end
      end
    end

    # Return true if the domain name matches one of the names in the
    # certificate. In other words, is the certificate provided to us really
    # for the domain to which we think we're connected?
    #
    # pem    - The PEM encoded certificate String.
    # domain - The domain name String.
    #
    # Returns true if the certificate was issued for the domain.
    def domain?(pem, domain)
      if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
        OpenSSL::SSL.verify_certificate_identity(cert, domain) rescue false
      end
    end

    # Return the trusted root CA certificates installed in config/certs. These
    # certificates are used to start the trust chain needed to validate certs
    # we receive from clients and servers.
    #
    # Returns an Array of OpenSSL::X509::Certificate objects.
    def certs
      @@sources ||= begin
        pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
        pairs = Dir[File.join(@dir, '*.crt')].map do |name|
          File.open(name, "r:UTF-8") do |f|
            pems = f.read.scan(pattern)
            certs = pems.map {|pem| OpenSSL::X509::Certificate.new(pem) }
            certs.reject! {|cert| cert.not_after < Time.now }
            [name, certs]
          end
        end
        Hash[pairs]
      end
      @@sources.values.flatten
    end

    # Returns a pair of file names containing the public key certificate
    # and matching private key for the given domain. This supports using
    # wildcard certificate files to serve several subdomains.
    #
    # Finding the certificate and private key file for a domain follows these steps:
    #
    # - Look for <domain>.crt and <domain>.key files in the config/certs
    #   directory. If found, return those file names, otherwise . . .
    #
    # - Inspect all config/certs/*.crt files for certificates that contain the
    #   domain name either as the subject common name (CN) or as a DNS
    #   subjectAltName. The corresponding private key must be in a file of the
    #   same name as the certificate's, but with a .key extension.
    #
    # So in the simplest configuration, the tea.wonderland.lit encryption files
    # would be named:
    #
    # - config/certs/tea.wonderland.lit.crt
    # - config/certs/tea.wonderland.lit.key
    #
    # However, in the case of a wildcard certificate for *.wonderland.lit,
    # the files would be:
    #
    # - config/certs/wonderland.lit.crt
    # - config/certs/wonderland.lit.key
    #
    # These same two files would be returned for the subdomains of:
    #
    # - tea.wonderland.lit
    # - crumpets.wonderland.lit
    # - etc.
    #
    # domain - The String domain name.
    #
    # Returns a two element String array for the certificate and private key
    #   file names or nil if not found.
    def files_for_domain(domain)
      crt = File.expand_path("#{domain}.crt", @dir)
      key = File.expand_path("#{domain}.key", @dir)
      return [crt, key] if File.exists?(crt) && File.exists?(key)

      # Might be a wildcard cert file.
      @@sources.each do |file, certs|
        certs.each do |cert|
          if OpenSSL::SSL.verify_certificate_identity(cert, domain)
            key = file.chomp(File.extname(file)) + '.key'
            return [file, key] if File.exists?(file) && File.exists?(key)
          end
        end
      end
      nil
    end

    private

    # Add a trusted certificate to the store, suppressing any OpenSSL errors
    # caused by the certificate already being stored.
    #
    # cert - The OpenSSL::X509::Certificate to add.
    #
    # Returns nothing.
    def append(cert)
      @store.add_cert(cert)
    rescue OpenSSL::X509::StoreError
      # Already added to store.
    end
  end
end