text:
package org.elasticsearch.index.mapper;

import org.apache.lucene.document.StoredField;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.IndexAnalyzers;
import org.elasticsearch.index.mapper.MapperService.MergeReason;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

public class DocumentMapper implements ToXContentFragment {

    public static final class Builder {
        private final Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappers;
        private final RootObjectMapper rootObjectMapper;
        private final ContentPath contentPath;
        private final IndexSettings indexSettings;
        private final IndexAnalyzers indexAnalyzers;
        private final DocumentParser documentParser;

        private Map<String, Object> meta;

        public Builder(RootObjectMapper.Builder builder, MapperService mapperService) {
            this(builder, mapperService.getIndexSettings(), mapperService.getIndexAnalyzers(), mapperService.documentParser(),
                mapperService.getMetadataMappers());
        }

        Builder(RootObjectMapper.Builder builder,
                IndexSettings indexSettings,
                IndexAnalyzers indexAnalyzers,
                DocumentParser documentParser,
                Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappers) {
            this.indexSettings = indexSettings;
            this.indexAnalyzers = indexAnalyzers;
            this.documentParser = documentParser;
            this.contentPath = new ContentPath(1);
            this.rootObjectMapper = builder.build(contentPath);
            this.metadataMappers = metadataMappers;
        }

        public Builder meta(Map<String, Object> meta) {
            this.meta = meta;
            return this;
        }

        public Builder put(MetadataFieldMapper.Builder mapper) {
            MetadataFieldMapper metadataMapper = mapper.build(contentPath);
            metadataMappers.put(metadataMapper.getClass(), metadataMapper);
            return this;
        }

        public DocumentMapper build() {
            Objects.requireNonNull(rootObjectMapper, "Mapper builder must have the root object mapper set");
            Mapping mapping = new Mapping(
                    rootObjectMapper,
                    metadataMappers.values().toArray(new MetadataFieldMapper[0]),
                    meta);
            return new DocumentMapper(indexSettings, indexAnalyzers, documentParser, mapping);
        }
    }

    private final String type;
    private final CompressedXContent mappingSource;
    private final DocumentParser documentParser;
    private final MappingLookup mappingLookup;
    private final MetadataFieldMapper[] deleteTombstoneMetadataFieldMappers;
    private final MetadataFieldMapper[] noopTombstoneMetadataFieldMappers;

    private DocumentMapper(IndexSettings indexSettings,
                           IndexAnalyzers indexAnalyzers,
                           DocumentParser documentParser,
                           Mapping mapping) {
        this.type = mapping.root().name();
        this.documentParser = documentParser;
        this.mappingLookup = MappingLookup.fromMapping(mapping, documentParser, indexSettings, indexAnalyzers);

        try {
            mappingSource = new CompressedXContent(this, XContentType.JSON, ToXContent.EMPTY_PARAMS);
        } catch (Exception e) {
            throw new ElasticsearchGenerationException("failed to serialize source for type [" + type + "]", e);
        }

        final Collection<String> deleteTombstoneMetadataFields = Arrays.asList(VersionFieldMapper.NAME, IdFieldMapper.NAME,
            SeqNoFieldMapper.NAME, SeqNoFieldMapper.PRIMARY_TERM_NAME, SeqNoFieldMapper.TOMBSTONE_NAME);
        this.deleteTombstoneMetadataFieldMappers = Stream.of(mapping.metadataMappers)
            .filter(field -> deleteTombstoneMetadataFields.contains(field.name())).toArray(MetadataFieldMapper[]::new);
        final Collection<String> noopTombstoneMetadataFields = Arrays.asList(
            VersionFieldMapper.NAME, SeqNoFieldMapper.NAME, SeqNoFieldMapper.PRIMARY_TERM_NAME, SeqNoFieldMapper.TOMBSTONE_NAME);
        this.noopTombstoneMetadataFieldMappers = Stream.of(mapping.metadataMappers)
            .filter(field -> noopTombstoneMetadataFields.contains(field.name())).toArray(MetadataFieldMapper[]::new);
    }

    public Mapping mapping() {
        return mappingLookup.getMapping();
    }

    public String type() {
        return this.type;
    }

    public Map<String, Object> meta() {
        return mapping().meta;
    }

    public CompressedXContent mappingSource() {
        return this.mappingSource;
    }

    public RootObjectMapper root() {
        return mapping().root;
    }

    public <T extends MetadataFieldMapper> T metadataMapper(Class<T> type) {
        return mapping().metadataMapper(type);
    }

    public SourceFieldMapper sourceMapper() {
        return metadataMapper(SourceFieldMapper.class);
    }

    public IdFieldMapper idFieldMapper() {
        return metadataMapper(IdFieldMapper.class);
    }

    public RoutingFieldMapper routingFieldMapper() {
        return metadataMapper(RoutingFieldMapper.class);
    }

    public IndexFieldMapper IndexFieldMapper() {
        return metadataMapper(IndexFieldMapper.class);
    }

    public MappingLookup mappers() {
        return this.mappingLookup;
    }

    public ParsedDocument parse(SourceToParse source) throws MapperParsingException {
        return documentParser.parseDocument(source, mappingLookup);
    }

    public ParsedDocument createDeleteTombstoneDoc(String index, String id) throws MapperParsingException {
        final SourceToParse emptySource = new SourceToParse(index, id, new BytesArray("{}"), XContentType.JSON);
        return documentParser.parseDocument(emptySource, deleteTombstoneMetadataFieldMappers, mappingLookup).toTombstone();
    }

    public ParsedDocument createNoopTombstoneDoc(String index, String reason) throws MapperParsingException {
        final String id = ""; // _id won't be used.
        final SourceToParse sourceToParse = new SourceToParse(index, id, new BytesArray("{}"), XContentType.JSON);
        final ParsedDocument parsedDoc = documentParser.parseDocument(sourceToParse, noopTombstoneMetadataFieldMappers, mappingLookup)
            .toTombstone();
        // Store the reason of a noop as a raw string in the _source field
        final BytesRef byteRef = new BytesRef(reason);
        parsedDoc.rootDoc().add(new StoredField(SourceFieldMapper.NAME, byteRef.bytes, byteRef.offset, byteRef.length));
        return parsedDoc;
    }

    public DocumentMapper merge(Mapping mapping, MergeReason reason) {
        Mapping merged = this.mapping().merge(mapping, reason);
        return new DocumentMapper(mappingLookup.getIndexSettings(), mappingLookup.getIndexAnalyzers(), documentParser, merged);
    }

    public void validate(IndexSettings settings, boolean checkLimits) {
        this.mapping().validate(this.mappingLookup);
        if (settings.getIndexMetadata().isRoutingPartitionedIndex()) {
            if (routingFieldMapper().required() == false) {
                throw new IllegalArgumentException("mapping type [" + type() + "] must have routing "
                    + "required for partitioned index [" + settings.getIndex().getName() + "]");
            }
        }
        if (settings.getIndexSortConfig().hasIndexSort() && mappers().hasNested()) {
            throw new IllegalArgumentException("cannot have nested fields when index sort is activated");
        }
        if (checkLimits) {
            this.mappingLookup.checkLimits(settings);
        }
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        return mapping().toXContent(builder, params);
    }
}


text:
#ifndef GrVkMemory_DEFINED
#define GrVkMemory_DEFINED

#include "vk/GrVkDefines.h"

class GrVkGpu;

namespace GrVkMemory {
    /**
    * Allocates vulkan device memory and binds it to the gpu's device for the given object.
    * Returns true of allocation succeeded.
    */
    bool AllocAndBindBufferMemory(const GrVkGpu* gpu,
                                  VkBuffer buffer,
                                  const VkMemoryPropertyFlags flags,
                                  VkDeviceMemory* memory);

    bool AllocAndBindImageMemory(const GrVkGpu* gpu,
                                 VkImage image,
                                 const VkMemoryPropertyFlags flags,
                                 VkDeviceMemory* memory);

    VkPipelineStageFlags LayoutToPipelineStageFlags(const VkImageLayout layout);

    VkAccessFlags LayoutToSrcAccessMask(const VkImageLayout layout);
}

#endif

redpajama_set_name: RedPajamaGithub


text:
import { Controller } from '@hotwired/stimulus';
import $ from 'jquery';
import 'parsleyjs';

export default class extends Controller {
  connect() {
    $(this.element).parsley({
      errorClass: 'has-danger',
      successClass: 'has-success',
      errorsWrapper: '

',
      errorTemplate: '',
      classHandler(ParsleyField) {
        return ParsleyField.$element.parent();
      },
    });
  }
}


text:
module Goods
  class Catalog
    attr_reader :url, :name, :company, :categories, :currencies, :offers
    attr_reader :delivery_options

    def initialize io:, url:, encoding:
      if io
        from_io_or_string(io, url, encoding)
      else
        raise ArgumentError, "should provide either :string or :url param"
      end
    end

    def prune(level)
      @offers.prune_categories(level)
      @categories.prune(level)
    end

    def convert_currency(other_currency)
      @offers.convert_currency(other_currency)
    end

    def date
      @xml.generation_date
    end

    private

    def from_io_or_string(xml_io, url, encoding)
      @xml = XML.new(xml_io, url, encoding)

      @name = @xml.name
      @company = @xml.company
      @url = @xml.url

      @categories = CategoriesList.new(@xml.categories)
      @currencies = CurrenciesList.new(@xml.currencies)
      @delivery_options = @xml.delivery_options
      @offers = OffersList.new(@categories, @currencies, @xml.offers)
    end
  end
end


text:
<component name="libraryTable">
  <library name="SBT: com.codahale.metrics:metrics-json:3.0.0">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/com.codahale.metrics/metrics-json/bundles/metrics-json-3.0.0.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
int ZWEventP::s_zwEventType = -1;

ZWEvent::ZWEvent(OpenZWave::Notification const* ntf)
    : QEvent((QEvent::Type)ZWEventP::s_zwEventType)
    , d_ptr(new ZWEventP)
{
    d_ptr->type = ntf->GetType();
    d_ptr->home = ntf->GetHomeId();
    d_ptr->node = ntf->GetNodeId();
    d_ptr->vid = ntf->GetValueID().GetId();
    d_ptr->string = QString::fromStdString(ntf->GetAsString());
    d_ptr->code = 0;
    d_ptr->event = 0;

    if (d_ptr->type == Notification::Type_Notification) {
        d_ptr->code = ntf->GetNotification();
    } else if (d_ptr->type == Notification::Type_ControllerCommand) {
        d_ptr->code = ntf->GetNotification();
        d_ptr->event = ntf->GetEvent();
    }
}

ZWEvent::~ZWEvent()
{
    delete d_ptr;
    d_ptr = NULL;
}

Notification::NotificationType ZWEvent::type() const
{
    return d_ptr->type;
}

uint32 ZWEvent::home() const
{
    return d_ptr->home;
}

uint8 ZWEvent::node() const
{
    return d_ptr->node;
}

uint64 ZWEvent::vid() const
{
    return d_ptr->vid;
}

QString ZWEvent::string() const
{
    return d_ptr->string;
}

uint8 ZWEvent::code() const
{
    return d_ptr->code;
}

uint8 ZWEvent::event() const
{
    return d_ptr->event;
}

int ZWEvent::ZWEventType()
{
    return ZWEventP::s_zwEventType;
}

void ZWEvent::registerZWEventType()
{
    if (ZWEventP::s_zwEventType == -1) {
        ZWEventP::s_zwEventType = QEvent::registerEventType();
    }
}


text:
namespace edash_packager {

/// This class is an MpdNotifier which will try its best to generate a
/// DASH IF IOPv3 compliant MPD.
/// e.g.
/// All <ContentProtection> elements must be right under
/// <AdaptationSet> and cannot be under <Representation>.
/// All video Adaptation Sets have Role set to "main".
class DashIopMpdNotifier : public MpdNotifier {
 public:
  DashIopMpdNotifier(DashProfile dash_profile,
                     const MpdOptions& mpd_options,
                     const std::vector<std::string>& base_urls,
                     const std::string& output_path);
  ~DashIopMpdNotifier() override;

  /// None of the methods write out the MPD file until Flush() is called.
  /// @name MpdNotifier implemetation overrides.
  /// @{
  bool Init() override;
  bool NotifyNewContainer(const MediaInfo& media_info, uint32_t* id) override;
  bool NotifySampleDuration(uint32_t container_id,
                            uint32_t sample_duration) override;
  bool NotifyNewSegment(uint32_t id,
                        uint64_t start_time,
                        uint64_t duration,
                        uint64_t size) override;
  bool NotifyEncryptionUpdate(uint32_t container_id,
                              const std::string& drm_uuid,
                              const std::vector<uint8_t>& new_key_id,
                              const std::vector<uint8_t>& new_pssh) override;
  bool AddContentProtectionElement(
      uint32_t id,
      const ContentProtectionElement& content_protection_element) override;
  bool Flush() override;
  /// @}

 private:
  friend class DashIopMpdNotifierTest;

  // Maps representation ID to Representation.
  typedef std::map<uint32_t, Representation*> RepresentationMap;

  // Maps AdaptationSet ID to ProtectedContent.
  typedef std::map<uint32_t, MediaInfo::ProtectedContent> ProtectedContentMap;

  // Checks the protected_content field of media_info and returns a non-null
  // AdaptationSet* for a new Representation.
  // This does not necessarily return a new AdaptationSet. If
  // media_info.protected_content completely matches with an existing
  // AdaptationSet, then it will return the pointer.
  AdaptationSet* GetAdaptationSetForMediaInfo(const std::string& key,
                                              const MediaInfo& media_info);

  // Sets a group id for |adaptation_set| if applicable.
  // If a group ID is already assigned, then this returns immediately.
  void SetGroupId(const std::string& key, AdaptationSet* adaptation_set);

  // Helper function to get a new AdaptationSet; registers the values
  // to the fields (maps) of the instance.
  // If the media is encrypted, registers data to protected_content_map_.
  AdaptationSet* NewAdaptationSet(const MediaInfo& media_info,
                                  std::list<AdaptationSet*>* adaptation_sets);

  // Testing only method. Returns a pointer to MpdBuilder.
  MpdBuilder* MpdBuilderForTesting() const {
    return mpd_builder_.get();
  }

  // Testing only method. Sets mpd_builder_.
  void SetMpdBuilderForTesting(scoped_ptr<MpdBuilder> mpd_builder) {
    mpd_builder_ = mpd_builder.Pass();
  }

  std::map<std::string, std::list<AdaptationSet*>> adaptation_set_list_map_;
  RepresentationMap representation_map_;

  // Used to check whether a Representation should be added to an AdaptationSet.
  ProtectedContentMap protected_content_map_;

  // MPD output path.
  std::string output_path_;
  scoped_ptr<MpdBuilder> mpd_builder_;
  base::Lock lock_;

  // Next group ID to use for AdapationSets that can be grouped.
  int next_group_id_;

  // Maps Representation ID to AdaptationSet. This is for updating the PSSH.
  std::map<uint32_t, AdaptationSet*> representation_id_to_adaptation_set_;
};

}  // namespace edash_packager

#endif  // MPD_BASE_DASH_IOP_MPD_NOTIFIER_H_


text:
from __future__ import print_function
import contextlib
import os
import re
import six
from six.moves import input
from six import string_types
import sys
import yaml

from rdopkg import exception
from rdopkg.utils import log
from rdopkg.utils.cmd import run

if six.PY2:
    from collections import Iterable
else:
    from collections.abc import Iterable

def confirm(msg, default_yes=True):
    if sys.stdout.isatty():
        if default_yes:
            options = '[Yn]'
        else:
            options = '[Ny]'
        print('')
        i = input(log.term.important("%s %s " % (msg, options))).lower()
        if not i:
            if default_yes:
                return
            else:
                raise exception.UserAbort()
        if i != 'y' and i != 'yes':
            raise exception.UserAbort()
        print('')
    else:
        if default_yes:
            return
        else:
            raise exception.UserAbort()

def download_file(url):
    run('curl', '-L', '-f', '-O', url, direct=True)

def edit(path):
    editor = os.environ.get('EDITOR')
    if not editor:
        editor = 'vim'
        log.info("$EDITOR not set. Falling back to %s." % editor)
    try:
        r = run(editor, path, direct=True)
    except exception.CommandNotFound:
        raise exception.CommandNotFound(
            msg='Failed to find suitable text editor ({0}).  '
                'Please set $EDITOR environment variable.'.format(editor))
    return r.success

def ensure_dir(path):
    if os.path.exists(path):
        if not os.path.isdir(path):
            raise exception.NotADirectory(path=path)
    else:
        os.makedirs(path)

def ensure_new_file_dirs(path):
    if path[-1] == os.sep:
        raise exception.NotAFile(path=path)
    _dir = os.path.dirname(path)
    if _dir:
        ensure_dir(_dir)

def find_files(path, ext=None):
    paths = [os.path.join(path, f) for f in os.listdir(path)
             if os.path.isfile(os.path.join(path, f))]
    if ext:
        paths = [p for p in paths if p.endswith(ext)]
    return paths

def print_list(line_to_print, pre='- ', nl_before=False, nl_after=False):
    if nl_before:
        print("")
    for e in line_to_print:
        print('%s%s' % (pre, e))
    if nl_after:
        print("")

def action_required(msg):
    print("\n{t.important}Action required: {t.normal}{t.bold}{msg}{t.normal}"
          .format(t=log.term, msg=msg))
    print("\nOnce done, run `rdopkg -c` to continue.\n")

def is_same_hash(h1, h2):
    if h1 is None or h2 is None:
        return False
    if h1 == h2 or h1.startswith(h2) or h2.startswith(h1):
        return True
    return False

def strip_patch_subject(subj):
    return re.sub(r'^\[PATCH\]\s+', '', subj.strip())

def is_same_subject(s1, s2):
    if s1 is None or s2 is None:
        return False
    if strip_patch_subject(s1) == strip_patch_subject(s2):
        return True
    return False

@contextlib.contextmanager
def cdir(path):
    prev_cwd = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(prev_cwd)

@contextlib.contextmanager
def setenv(**env_dict):
    orig_env = os.environ.copy()
    for k, v in env_dict.items():
        os.environ[k] = str(v)
    try:
        yield
    finally:
        for k, v in env_dict.items():
            del os.environ[k]
        for k, v in orig_env.items():
            os.environ[k] = v

def print_keyval(key, val, kb=True, vb=False):
    if kb:
        fmt = '{t.bold}{key}{t.normal}: '
    else:
        fmt = '{key}'
    if vb:
        fmt += '{t.bold}{val}{t.bold}'
    else:
        fmt += '{val}'
    if not isinstance(
            val,
            string_types) and isinstance(
            val,
            Iterable):
        vals = "\n" + "\n".join(map(lambda x: '- ' + str(x), val))
    else:
        vals = str(val)
    print(fmt.format(t=log.term, key=key, val=vals))

class DictPrinter(object):
    # Very simple and stupid dict printer.

    def __init__(self, header=None, first=None, last=None):
        self.first = first or []
        self.last = last or []
        self.header = header

    def __call__(self, d):
        dd = d.copy()
        # print header
        if self.header:
            hdr = dd.pop(self.header, '')
            print_keyval(self.header, hdr, kb=True, vb=True)
        # print first fields
        for key in self.first:
            if key not in dd:
                continue
            val = dd.pop(key)
            print_keyval(key, val)
        # filter out last fields
        last_items = []
        for key in self.last:
            if key not in dd:
                continue
            last_items.append((key, dd.pop(key)))
        if dd:
            print(yaml.dump(dd, default_flow_style=False).rstrip())
        for key, val in last_items:
            print_keyval(key, val)


text: export { default } from './eachOf';


text:
<?php

/**
 * @file
 * Definition of Drupal\node\Tests\NodeAccessLanguageTest.
 */

namespace Drupal\node\Tests;

use Drupal\Core\Language\Language;

/**
 * Verifies node_access() functionality for multiple languages.
 */
class NodeAccessLanguageTest extends NodeTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('language', 'node_access_test');

  public static function getInfo() {
    return array(
      'name' => 'Node access language',
      'description' => 'Test node_access and db_select() with node_access tag functionality with multiple languages with a test node access module that is not language-aware.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    // After enabling a node access module, the access table has to be rebuild.
    node_access_rebuild();

    // Enable the private node feature of the node_access_test module.
    \Drupal::state()->set('node_access_test.private', TRUE);

    // Add Hungarian and Catalan.
    $language = new Language(array(
      'id' => 'hu',
    ));
    language_save($language);
    $language = new Language(array(
      'id' => 'ca',
    ));
    language_save($language);
  }

  /**
   * Tests node_access() with multiple node languages and no private nodes.
   */
  function testNodeAccess() {
    $web_user = $this->drupalCreateUser(array('access content'));

    $expected_node_access = array('view' => TRUE, 'update' => FALSE, 'delete' => FALSE);
    $expected_node_access_no_access = array('view' => FALSE, 'update' => FALSE, 'delete' => FALSE);

    // Creating a public node with langcode Hungarian, will be saved as the
    // fallback in node access table.
    $node_public = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'hu', 'private' => FALSE));
    $this->assertTrue($node_public->langcode == 'hu', 'Node created as Hungarian.');

    // Tests the default access is provided for the public Hungarian node.
    $this->assertNodeAccess($expected_node_access, $node_public, $web_user);

    // Tests that Hungarian provided specifically results in the same.
    $this->assertNodeAccess($expected_node_access, $node_public, $web_user, 'hu');

    // There is no specific Catalan version of this node and Croatian is not
    // even set up on the system in this scenario, so the user will not get
    // access to these nodes.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user, 'ca');
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user, 'hr');

    // Creating a public node with no special langcode, like when no language
    // module enabled.
    $node_public_no_language = $this->drupalCreateNode(array('private' => FALSE));
    $this->assertTrue($node_public_no_language->langcode == Language::LANGCODE_NOT_SPECIFIED, 'Node created with not specified language.');

    // Tests that access is granted if requested with no language.
    $this->assertNodeAccess($expected_node_access, $node_public_no_language, $web_user);

    // Tests that access is not granted if requested with Hungarian language.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public_no_language, $web_user, 'hu');

    // There is no specific Catalan version of this node and Croatian is not
    // even set up on the system in this scenario, so the user will not get
    // access to these nodes.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public_no_language, $web_user, 'ca');
    $this->assertNodeAccess($expected_node_access_no_access, $node_public_no_language, $web_user, 'hr');

    // Reset the node access cache and turn on our test node_access() code.
    drupal_static_reset('node_access');
    variable_set('node_access_test_secret_catalan', 1);

    // Tests that access is granted if requested with no language.
    $this->assertNodeAccess($expected_node_access, $node_public_no_language, $web_user);

    // Tests that Hungarian is still not accessible.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public_no_language, $web_user, 'hu');

    // Tests that Catalan is still not accessible.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public_no_language, $web_user, 'ca');
  }

  /**
   * Tests node_access() with multiple node languages and private nodes.
   */
  function testNodeAccessPrivate() {
    $web_user = $this->drupalCreateUser(array('access content'));

    $node = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'hu'));
    $this->assertTrue($node->langcode == 'hu', 'Node created as Hungarian.');
    $expected_node_access = array('view' => TRUE, 'update' => FALSE, 'delete' => FALSE);
    $expected_node_access_no_access = array('view' => FALSE, 'update' => FALSE, 'delete' => FALSE);

    // Creating a private node with langcode Hungarian, will be saved as the
    // fallback in node access table.
    $node_public = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'hu', 'private' => TRUE));
    $this->assertTrue($node_public->langcode == 'hu', 'Node created as Hungarian.');

    // Tests the default access is not provided for the private Hungarian node.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user);

    // Tests that Hungarian provided specifically results in the same.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user, 'hu');

    // There is no specific Catalan version of this node and Croatian is not
    // even set up on the system in this scenario, so the user will not get
    // access to these nodes.
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user, 'ca');
    $this->assertNodeAccess($expected_node_access_no_access, $node_public, $web_user, 'hr');

    // Creating a private node with no special langcode, like when no language
    // module enabled.
    $node_private_no_language = $this->drupalCreateNode(array('private' => TRUE));
    $this->assertTrue($node_private_no_language->langcode == Language::LANGCODE_NOT_SPECIFIED, 'Node created with not specified language.');

    // Tests that access is not granted if requested with no language.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user);

    // Tests that access is not granted if requested with Hungarian language.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user, 'hu');

    // There is no specific Catalan version of this node and Croatian is not
    // even set up on the system in this scenario, so the user will not get
    // access to these nodes.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user, 'ca');
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user, 'hr');

    // Reset the node access cache and turn on our test node_access() code.
    entity_access_controller('node')->resetCache();
    \Drupal::state()->set('node_access_test_secret_catalan', 1);

    // Tests that access is not granted if requested with no language.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user);

    // Tests that Hungarian is still not accessible.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user, 'hu');

    // Tests that Catalan is still not accessible.
    $this->assertNodeAccess($expected_node_access_no_access, $node_private_no_language, $web_user, 'ca');
  }

  /**
   * Tests db_select() with a 'node_access' tag and langcode metadata.
   */
  function testNodeAccessQueryTag() {
    // Create a normal authenticated user.
    $web_user = $this->drupalCreateUser(array('access content'));

    // Load the user 1 user for later use as an admin user with permission to
    // see everything.
    $admin_user = user_load(1);

    // Creating a private node with langcode Hungarian, will be saved as
    // the fallback in node access table.
    $node_private = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'hu', 'private' => TRUE));
    $this->assertTrue($node_private->langcode == 'hu', 'Node created as Hungarian.');

    // Creating a public node with langcode Hungarian, will be saved as
    // the fallback in node access table.
    $node_public = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'hu', 'private' => FALSE));
    $this->assertTrue($node_public->langcode == 'hu', 'Node created as Hungarian.');

    // Creating a public node with no special langcode, like when no language
    // module enabled.
    $node_no_language = $this->drupalCreateNode(array('private' => FALSE));
    $this->assertTrue($node_no_language->langcode == Language::LANGCODE_NOT_SPECIFIED, 'Node created with not specified language.');

    // Query the nodes table as the web user with the node access tag and no
    // specific langcode.
    $select = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->addMetaData('account', $web_user)
    ->addTag('node_access');
    $nids = $select->execute()->fetchAllAssoc('nid');

    // The public node and no language node should be returned. Because no
    // langcode is given it will use the fallback node.
    $this->assertEqual(count($nids), 2, 'db_select() returns 2 node');
    $this->assertTrue(array_key_exists($node_public->id(), $nids), 'Returned node ID is public node.');
    $this->assertTrue(array_key_exists($node_no_language->id(), $nids), 'Returned node ID is no language node.');

    // Query the nodes table as the web user with the node access tag and
    // langcode de.
    $select = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->addMetaData('account', $web_user)
    ->addMetaData('langcode', 'de')
    ->addTag('node_access');
    $nids = $select->execute()->fetchAllAssoc('nid');

    // Because no nodes are created in German, no nodes are returned.
    $this->assertTrue(empty($nids), 'db_select() returns an empty result.');

    // Query the nodes table as admin user (full access) with the node access
    // tag and no specific langcode.
    $select = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->addMetaData('account', $admin_user)
    ->addTag('node_access');
    $nids = $select->execute()->fetchAllAssoc('nid');

    // All nodes are returned.
    $this->assertEqual(count($nids), 3, 'db_select() returns all three nodes.');

    // Query the nodes table as admin user (full access) with the node access
    // tag and langcode de.
    $select = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->addMetaData('account', $admin_user)
    ->addMetaData('langcode', 'de')
    ->addTag('node_access');
    $nids = $select->execute()->fetchAllAssoc('nid');

    // All nodes are returned because node access tag is not invoked when the
    // user is user 1.
    $this->assertEqual(count($nids), 3, 'db_select() returns all three nodes.');
  }

}


text:
include_recipe 'runit'

node['graphite']['carbon']['caches'].each do |key,data|
  runit_service "carbon-cache-#{key}" do
    run_template_name 'carbon'
    log_template_name 'carbon'
    finish_script_template_name 'carbon'
    finish true
    options(:name => "cache", :instance => key)
    subscribes :restart, "template[#{node['graphite']['base_dir']}/conf/carbon.conf]"
  end
end


text:
<?php
/**
 * Nuwani-v2 Bot Framework
 *
 * This file is part of the Nuwani v2 Bot Framework, a simple set of PHP classes which allow
 * you to set-up and run your own bot. It features advanced, PHP-5.3 based syntax for
 * optimal performance and security.
 *
 * Author: Peter Beverloo
 *         peter@lvp-media.com
 */

use Nuwani \ Bot;

class Command implements Serializable, ArrayAccess
{
	/**
	 * Property: m_sCommand
	 *
	 * The actual command name, e.g. "test". The prefix is NOT included in this,
	 * seeing we want to have that private.
	 */

	private $m_sCommand;

	/**
	 * Property: m_sCode
	 *
	 * Contains the PHP code for the command. For performance reasons this will
	 * be cached in another property, as an anonymous function.
	 */

	private $m_sCode;

	/**
	 * Property: m_nLevel
	 *
	 * Sets the security level associated with this command. Level is related
	 * to the secutity providers which registered themselfes with the module.
	 */

	private $m_nLevel;

	/**
	 * Property: m_pCachedCommand
	 *
	 * The cached command is a anonymous function that'll execute the command's
	 * code. Reason for this is that it's faster when cached.
	 */

	private $m_pCachedCommand;

	/**
	 * Property: m_aNetworks
	 *
	 * The networks on which this command will be executed on. If it's empty,
	 * it will be executed on all networks. The networks should be supplied as
	 * the name given to them in config.php.
	 */

	private $m_aNetworks;

	/**
	 * Property: m_aChannels
	 *
	 * The channels this command will be permitted to execute on. If it's empty,
	 * all channels are allowed.
	 */

	private $m_aChannels;

	/**
	 * Property: m_aStatistics
	 *
	 * The array holding all of the statistics of this command.
	 */

	private $m_aStatistics;

	/**
	 * Property: m_bInternal
	 *
	 * Indicates whether this command is an internal command or one added by the
	 * user. Internal commands should not be serialized to Commands.dat.
	 */

	private $m_bInternal;

	/**
	 * Function: __construct
	 * Argument: sCommand (string) - Command that should be executed
	 * Argument: sCode (string) - Code that should be executed for the command.
	 *
	 * The constructor will initialise the basic variables in this class, and, incase
	 * required and possible, initialise the cached handler as well.
	 */

	public function __construct ($sCommand = '', $sCode = '')
	{
		$this -> m_sCode          = $sCode;
		$this -> m_sCommand       = $sCommand;
		$this -> m_bInternal	  = false;
		$this -> m_pCachedCommand = null;
		$this -> m_nLevel         = -1;

		$this -> m_aNetworks      = array ();
		$this -> m_aChannels      = array ();

		$this -> m_aStatistics    = array
		(
			'Executed' => 0,
			'TotalTime' => 0.0,
			'LastTime' => 0,
		);

		if ($this -> m_sCode != '')
			$this -> cache ();
	}

	/**
	 * Function: getCommand
	 *
	 * This function returns the name of the command which will be executed,
	 * pretty much returning the m_sCommand property.
	 */

	public function getCommand ()
	{
		return $this -> m_sCommand;
	}

	/**
	 * Function: getCode
	 *
	 * Returns the code which has been associated with this command. Making changes or
	 * whatsoever is not possible using this.
	 */

	public function getCode ()
	{
		return $this -> m_sCode;
	}

	/**
	 * Function: getSecurityLevel
	 *
	 * This function retuns the security level associated with this command,
	 * enabling you to check whether this use can execute this.
	 */

	public function getSecurityLevel ()
	{
		return $this -> m_nLevel;
	}

	/**
	 * Function: getNetworks
	 *
	 * This function returns the networks on which this command is allowed
	 * to execute.
	 */

	public function getNetworks ()
	{
		return $this -> m_aNetworks;
	}

	/**
	 * Function: getChannels
	 *
	 * This function will return an array with the channels this command is
	 * allowed to execute in.
	 */

	public function getChannels ()
	{
		return $this -> m_aChannels;
	}

	/**
	 * Function: getStatistics
	 *
	 * Retrieves the array containing the statistics of this command.
	 */

	public function getStatistics ()
	{
		return $this -> m_aStatistics;
	}

	/**
	 * Function: setCommand
	 * Argument: sCommand (string) - New name of this command
	 *
	 * This function will set the actual command's name, to change it's name this function
	 * should be called. Purely for internal reference sake though.
	 */

	public function setCommand ($sCommand)
	{
		$this -> m_sCommand = $sCommand;
	}

	/**
	 * Function: setCode
	 * Argument: sCode (string) - Code this command should be executing.
	 *
	 * This function will update the code associated with this command. The caching will
	 * automatically be re-initialised for performance reasons.
	 */

	public function setCode ($sCode)
	{
		$this -> m_sCode = $sCode;
		$this -> cache ();
	}

	/**
	 * Function: setSecurityLevel
	 * Argument: nLevel (integer) - Security Level to apply to this command.
	 *
	 * A simple function which allows you to update the security level required
	 * to execute this command properly, will be checked externally.
	 */

	public function setSecurityLevel ($nLevel)
	{
		$this -> m_nLevel = $nLevel;
	}

	/**
	 * Function: setSecurityLevel
	 * Argument: aNetworks (array) - The networks to apply to this command.
	 *
	 * This function will let you add all the networks you want to give this
	 * command at once.
	 */

	public function setNetworks ($aNetworks)
	{
		if (count ($aNetworks) == 1 && $aNetworks [0] == '-')
			return $this -> m_aNetworks = array ();

		$this -> m_aNetworks = $aNetworks;
	}

	/**
	 * Function: addNetwork
	 * Argument: sNetwork (string) - The network to add to this command.
	 *
	 * Adds a single network entry to the networks array.
	 */

	public function addNetwork ($sNetwork)
	{
		if (!in_array ($sNetwork, $this -> m_aNetworks))
			$this -> m_aNetworks [] = $sNetwork;
	}

	/**
	 * Function: checkNetwork
	 * Argument: sNetwork (string) - The network to check for.
	 *
	 * This function checks if this command if allowed to execute on the given
	 * network.
	 */

	public function checkNetwork ($sNetwork)
	{
		if (empty ($this -> m_aNetworks))
			return true;

		return in_array ($sNetwork, $this -> m_aNetworks);
	}

	/**
	 * Function: setChannels
	 * Argument: aChannels (array) - The channels to apply to this command.
	 *
	 * This function allows you to set the array of channels in which this
	 * command is allowed to execute in.
	 */

	public function setChannels ($aChannels)
	{
		if (count ($aChannels) == 1 && $aChannels [0] == '-')
			return $this -> m_aChannels = array ();

		$this -> m_aChannels = array_map ('strtolower', $aChannels);
	}

	/**
	 * Function: addChannel
	 * Argument: sChannel (string) - The channel to add.
	 *
	 * This function lets you add a channel to the array of allowed channels.
	 */

	public function addChannel ($sChannel)
	{
		$sChannel = strtolower ($sChannel);

		if (!in_array ($sChannel, $this -> m_aChannels))
			$this -> m_aChannels [] = $sChannel;
	}

	/**
	 * Function: checkChannel
	 * Argument: sChannel (string) - The channel to check.
	 *
	 * This function checks if this command is allowed to execute in the
	 * given channel.
	 */
	public function checkChannel ($sChannel)
	{
		if (empty ($this -> m_aChannels))
			return true;

		return in_array (strtolower ($sChannel), $this -> m_aChannels);
	}

	/**
	 * Function: cache
	 *
	 * The cache function will cache the actual command's code, to make sure the
	 * performance loss of eval() only occurs once, rather than every time.
	 */

	private function cache ()
	{
		$this -> m_pCachedCommand = create_function ('$pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage', $this -> m_sCode);
                if ($this -> m_pCachedCommand === false)
                {
                        echo $this -> m_sCode;
                }
	}

	/**
	 * Function: serialize
	 *
	 * This function returns this command in a serialized form, so it can be stored
	 * in a file and re-created later on, using the unserialize function (suprise!)
	 */

	public function serialize ()
	{
		return serialize (array
		(
			$this -> m_bInternal,
			$this -> m_sCommand,
			$this -> m_sCode,
			$this -> m_nLevel,
			$this -> m_aNetworks,
			$this -> m_aChannels,
			$this -> m_aStatistics
		));
	}

	/**
	 * Function: unserialize
	 *
	 * The unserialize method will, yes, unserialize a previously serialized command
	 * so we can use it again. Quite convenient for various reasons.
	 */

	public function unserialize ($sData)
	{
		$aInformation = unserialize ($sData);

		$this -> m_bInternal = $aInformation [0];
		$this -> m_sCommand  = $aInformation [1];
		$this -> m_sCode     = $aInformation [2];
		$this -> m_nLevel    = $aInformation [3];

		if (isset ($aInformation [4]))
			$this -> m_aNetworks = $aInformation [4];

		if (isset ($aInformation [6])) {
			$this -> m_aChannels   = $aInformation [5];
			$this -> m_aStatistics = $aInformation [6];
		} else if (isset ($aInformation [5])) {
			$this -> m_aStatistics = $aInformation [5];
		}

		$this -> cache ();
	}

	/**
	 * Function: __invoke
	 * Argument: aArguments (array) - Arguments as passed on to this command.
	 *
	 * The invoking function which allows us to use fancy syntax for commands. It allows the user
	 * and bot-system to directly invoke the object variable.
	 */

	public function __invoke (Bot $pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage)
	{
		if (is_callable ($this -> m_pCachedCommand) &&
		    $this -> checkNetwork($pBot ['Network']) &&
		    $this -> checkChannel($sChannel))
		{
			$sFunction = $this -> m_pCachedCommand;
			$this -> m_aStatistics ['Executed'] ++;
			$this -> m_aStatistics ['LastTime'] = time();

			Nuwani\ErrorExceptionHandler :: $Source = $sDestination ;

			ob_start ();

			$fStart = microtime (true);
			$sFunction ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage);
			$this -> m_aStatistics ['TotalTime'] += microtime (true) - $fStart;

			$aOutput = explode (NL, trim (ob_get_clean ()));
			if (isset ($pBot) && $pBot instanceof Bot)
			{
				foreach ($aOutput as $sLine)
				{
					$pBot -> send ('PRIVMSG ' . $sDestination . ' :' . trim ($sLine), false);
					echo '[' . $sDestination . '] <' . $pBot ['Nickname'] . '> ' . trim ($sLine) . NL;
				}
			}
		}

		return false ;
	}

	/**
	 * Function: __toString
	 *
	 * This magic method enables this object to be echo'd, without calling
	 * methods. Useful for quick retrieval of which command this is.
	 */

	public function __toString()
	{
		return $this -> m_sCommand;
	}

	// -------------------------------------------------------------------//
	// Region: ArrayAccess                                                //
	// -------------------------------------------------------------------//

	/**
	 * Function: offsetExists
	 * Argument: sOffset (string) - The setting or statistic to check
	 *
	 * Check whether the offset exists within this command.
	 */
	public function offsetExists ($sOffset)
	{
		return (in_array ($sOffset, array ('Command', 'Code', 'Level', 'Networks')) ||
			isset ($this -> m_aStatistics [$sOffset]));
	}

	/**
	 * Function: offsetGet
	 * Argument: sOffset (string) - The setting or statistic to get
	 *
	 * Gets a specific setting or statistic of this command.
	 * Returns false if no setting or statistic has been found.
	 */
	public function offsetGet ($sOffset)
	{
		switch ($sOffset)
		{
			case 'Command':  return $this -> m_sCommand;
			case 'Code':     return $this -> m_sCode;
			case 'Level':    return $this -> m_nLevel;
			case 'Networks': return $this -> m_aNetworks;
			case 'Internal': return $this -> m_bInternal;
		}

		if (isset ($this -> m_aStatistics [$sOffset]))
			return $this -> m_aStatistics [$sOffset];

		return false;
	}

	/**
	 * Function: offsetSet
	 * Argument: sOffset (string) - The setting to set
	 * Argument: mValue (mixed) - The value
	 *
	 * Quickly set a certain setting for this command.
	 */
	public function offsetSet ($sOffset, $mValue)
	{
		switch ($sOffset)
		{
			case 'Command':  $this -> m_sCommand  = $mValue;
			case 'Code':     $this -> m_sCode     = $mValue;
			case 'Level':    $this -> m_nLevel    = $mValue;
			case 'Networks': $this -> m_aNetworks = $mValue;
		}
	}

	/**
	 * Function: offsetUnset
	 * Argument: sOffset (string) - The setting to unset
	 *
	 * This is very much not allowed, since setting defaults could
	 * break the command or even more.
	 */
	public function offsetUnset ($sOffset)
	{
		return ;
	}

};

?>


text:
package net.ripe.db.whois.update.autokey;

import net.ripe.db.whois.common.domain.CIString;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.rpsl.ValidationMessages;
import net.ripe.db.whois.update.autokey.dao.NicHandleRepository;
import net.ripe.db.whois.update.dao.CountryCodeRepository;
import net.ripe.db.whois.update.domain.NicHandle;
import net.ripe.db.whois.update.domain.UpdateMessages;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class NicHandleFactoryTest {
    private static final String SOURCE = "RIPE";

    @Mock NicHandleRepository nicHandleRepository;
    @Mock CountryCodeRepository countryCodeRepository;
    @InjectMocks NicHandleFactory subject;

    @Before
    public void setUp() throws Exception {
        subject.setSource(SOURCE);

        when(countryCodeRepository.getCountryCodes()).thenReturn(Collections.<CIString>emptySet());
    }

    @Test
    public void isKeyPlaceHolder_AUTO() {
        assertThat(subject.isKeyPlaceHolder("AUTO"), is(false));
    }

    @Test
    public void isKeyPlaceHolder_AUTO_() {
        assertThat(subject.isKeyPlaceHolder("AUTO-"), is(false));
    }

    @Test
    public void isKeyPlaceHolder_AUTO_1() {
        assertThat(subject.isKeyPlaceHolder("AUTO-1"), is(true));
    }

    @Test
    public void isKeyPlaceHolder_AUTO_100() {
        assertThat(subject.isKeyPlaceHolder("AUTO-100"), is(true));
    }

    @Test
    public void isKeyPlaceHolder_AUTO_100NL() {
        assertThat(subject.isKeyPlaceHolder("AUTO-100NL"), is(true));
    }

    @Test
    public void isKeyPlaceHolder_AUTO_100_NL() {
        assertThat(subject.isKeyPlaceHolder("AUTO-100-NL"), is(false));
    }

    @Test(expected = IllegalArgumentException.class)
    public void generate_invalid_placeHolder() {
        subject.generate("AUTO", RpslObject.parse("person: name"));
    }

    @Test
    public void generate_specified_space() {
        when(nicHandleRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new NicHandle("DW", 10, SOURCE));

        final NicHandle nicHandle = subject.generate("AUTO-1234567DW", RpslObject.parse("person: name\nnic-hdl: AUTO-1234567DW"));
        assertThat(nicHandle.toString(), is("DW10-RIPE"));
    }

    @Test
    public void generate_unspecified_space() {
        when(nicHandleRepository.claimNextAvailableIndex("JAS", SOURCE)).thenReturn(new NicHandle("JAS", 10, SOURCE));

        final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: John Archibald Smith\nnic-hdl: AUTO-111"));
        assertThat(nicHandle.toString(), is("JAS10-RIPE"));
    }

    @Test
    public void generate_unspecified_lower() {
        when(nicHandleRepository.claimNextAvailableIndex("SN", SOURCE)).thenReturn(new NicHandle("SN", 10, SOURCE));

        final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: some name\nnic-hdl: AUTO-111"));
        assertThat(nicHandle.toString(), is("SN10-RIPE"));
    }

    @Test
    public void generate_unspecified_long() {
        when(nicHandleRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new NicHandle("SATG", 10, SOURCE));

        final NicHandle nicHandle = subject.generate("AUTO-1234567", RpslObject.parse("person: Satellite advisory Technologies Group Ltd\nnic-hdl: AUTO-1234567"));
        assertThat(nicHandle.toString(), is("SATG10-RIPE"));
    }

    @Test
    public void getAttributeType() {
        assertThat(subject.getAttributeType(), is(AttributeType.NIC_HDL));
    }

    @Test
    public void claim() throws Exception {
        final NicHandle nicHandle = new NicHandle("DW", 10, "RIPE");
        when(nicHandleRepository.claimSpecified(nicHandle)).thenReturn(true);
        assertThat(subject.claim("DW10-RIPE"), is(nicHandle));
    }

    @Test
    public void claim_not_available() {
        when(nicHandleRepository.claimSpecified(new NicHandle("DW", 10, "RIPE"))).thenReturn(false);
        try {
            subject.claim("DW10-RIPE");
            fail("Claim succeeded?");
        } catch (ClaimException e) {
            assertThat(e.getErrorMessage(), is(UpdateMessages.nicHandleNotAvailable("DW10-RIPE")));
        }
    }

    @Test
    public void claim_invalid_handle() {
        try {
            subject.claim("INVALID_HANDLE");
            fail("Claim succeeded?");
        } catch (ClaimException e) {
            assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("INVALID_HANDLE")));
        }
    }
}


text:
require 'json/jwt'
require 'faraday'
require 'faraday_middleware'

module RooOnRails
  module Rack
    class PopulateEnvFromJWT
      UnacceptableKeyError = Class.new(RuntimeError)
      VALID_PREFIXES_KEY = 'VALID_IDENTITY_URL_PREFIXES'.freeze
      DEFAULT_MAPPED_URLS = {
        'https://test.deliveroo.co.uk/' => 'https://orderweb.rooenv-staging.io/',
        'https://deliveroo.co.uk/' => 'https://orderweb.deliverooapp.com/',
        'https://identity-staging.deliveroo.com/' => 'https://internal-identity.rooenv-staging.io/',
        'https://identity.deliveroo.com/' => 'https://internal-identity.deliverooapp.com/'
      }.freeze

      def self.configured?
        ENV[VALID_PREFIXES_KEY].present?
      end

      def initialize(app, logger:, skip_sig_verify: true, url_mappings: DEFAULT_MAPPED_URLS)
        @app = app
        @logger = logger
        @url_mappings = url_mappings
        @keys = {}
        @mapped_urls = {}

        if skip_sig_verify && non_prod?
          @logger.warn "JWTs signature verifification has been switched off in development."
          @verify_sigs = false
        else
          @verify_sigs = true
        end
      end

      def call(env)
        env['roo.identity'] = decode_authorization_header(env['HTTP_AUTHORIZATION'])
        @app.call(env)

      # Other exceptions will bubble up, allowing the higher middleware to return a 500, which is
      # intentional.
      rescue UnacceptableKeyError, JSON::JWT::Exception => e
        # Identifying user is clearly attempting to hack or has been given a totally incorrect
        # token, log this and flag as Forbidden, without executing the rest of the middleware stack.
        Raven.report_exception(e) if defined?(Raven)
        [401, {}, []]
      end

      private

      def key_prefixes
        return [] unless self.class.configured?
        ENV[VALID_PREFIXES_KEY].split(',')
      end

      def non_prod?
        if ENV['RACK_ENV'].nil?
          @logger.warn "Your RACK_ENV isn't set. You probably want it set to 'development' in dev."
        end

        %w(development test).include? ENV['RACK_ENV']
      end

      # @raise [UnacceptableKeyError,Faraday::Error,OpenSSL::OpenSSLError] From `#public_key`
      # @raise [JSON::JWT::Exception] Bubble ups from `JSON::JWT.decode`
      # @return [JSON::JWT] The list of claims this header makes by way of a JWS token. Will be an
      #   empty hash for invalid or absent tokens.
      def decode_authorization_header(header_value)
        return JSON::JWT.new unless (header_value || '').starts_with?('Bearer ')
        jws_token = header_value[7..-1]

        JSON::JWT.decode(jws_token, :skip_verification).tap do |jwt|
          jwt.verify!(public_key(jwt.header[:jku])) if @verify_sigs
        end
      end

      def acceptable_key?(key_url)
        return false if key_url.nil?
        key_prefixes.any? { |acceptable| key_url.starts_with?(acceptable) }
      end

      # @raise [UnacceptableKeyError] When the key URL is not from a trusted location
      # @raise [Faraday::Error] When the JWK at the given URL is not retrievable for some reason.
      #   See: https://github.com/lostisland/faraday/blob/master/lib/faraday/error.rb
      # @return [JSON::JWK] The JWK for the specified URL
      def public_key(key_url)
        unless acceptable_key?(key_url)
          raise UnacceptableKeyError, "#{key_url} is not a valid Deliveroo Key URL"
        end

        # NB. don't use ||= memoization, or this middleware can be attacked by
        # being asked to decode large numbers of non-existant key-ids, each of
        # which would fill the @keys hash with a tuple.
        return @keys[key_url] if @keys.key?(key_url)

        @logger.info "Downloading identity public key from #{key_url}"
        json = http_request.get(mapped_url(key_url)).body
        @keys[key_url] = JSON::JWK.new(json)
      rescue Faraday::ParsingError
        raise JSON::JWT::InvalidFormat, 'Downloaded JWK is not a valid JSON file'
      end

      def http_request
        Faraday.new do |conf|
          conf.response :json
          conf.response :raise_error
          conf.request :json

          conf.adapter Faraday.default_adapter
        end
      end

      # Allows us to use internal URLs instead of external ones where appropriate
      def mapped_url(url)
        return @mapped_urls[url] unless @mapped_urls[url].nil?

        @url_mappings.each do |prefix, replacement|
          next unless url.starts_with?(prefix)
          mapped = url.sub(prefix, replacement)
          @mapped_urls[url] = mapped
          return mapped
        end

        url
      end
    end
  end
end


text:
class RbenvBinstubs < Formula
  desc "Make rbenv aware of bundler binstubs"
  homepage "https://github.com/ianheggie/rbenv-binstubs"
  url "https://github.com/ianheggie/rbenv-binstubs/archive/v1.4.tar.gz"
  sha256 "2d8fcb626d1ff47dc490d459999b5779802c3a0b0a319fd33750d63590beacb6"
  head "https://github.com/ianheggie/rbenv-binstubs.git"

  bottle :unneeded

  depends_on :rbenv

  def install
    prefix.install Dir["*"]
  end

  test do
    assert_match "rbenv-binstubs.bash", shell_output("rbenv hooks exec")
  end
end


text:
<?php

namespace App\Events\Api\Account;

use Krucas\Settings\Facades\Settings;
use Illuminate\Support\Facades\Redis;
use App\Http\Models\API\Account;
use Illuminate\Support\Facades\Log;
use App\Events\Api\ApiRequestEvent;

class AccountRestored extends ApiRequestEvent
{

    /**
     * AccountRestored constructor.
     * @param Account $account
     */
    public function __construct(Account $account)
    {
        parent::__construct();

        $logMessage = 'restored account - ';
        $logContext = [
            'action' => 'restore',
            'model' => 'account',
            'account_id' => $account->id,
            'account_identifier' => $account->identifier,
            'account_username' => $account->username,
            'account_name_first' => $account->name_first,
            'account_name_last' => $account->name_last,
            'account_name' => $account->format_full_name(true),
            'account_created' => $account->created_at,
            'account_updated' => $account->updated_at,
            'requester_id' => 0,
            'requester_name' => 'System',
            'requester_ip' => getRequestIP(),
            'request_proxy_ip' => getRequestIP(true),
            'request_method' => \Request::getMethod(),
            'request_url' => \Request::fullUrl(),
            'request_uri' => \Request::getRequestUri(),
            'request_scheme' => \Request::getScheme(),
            'request_host' => \Request::getHost()
        ];

        if (auth()->user()) {

            $logMessage = auth()->user()->name . ' ' . $logMessage;
            $logContext['requester_id'] = auth()->user()->id;
            $logContext['requester_name'] = auth()->user()->name;

            if (Settings::get('broadcast-events', false)) {

                $account->primary_duty = $account->primaryDuty;
                $trans = $account->toArray();
                $trans['name_full'] = $account->format_full_name(true);

                if ($account->should_propagate_password) {
                    $trans['password'] = generateStrongPassword(16);
                }

                if (array_key_exists('birth_date', $trans) && !empty($trans['birth_date'])) {
                    $trans['birth_date'] = decrypt($trans['birth_date']);
                }
                $trans['username'] = strtolower($trans['username']);
                if (empty($trans['name_middle'])) unset($trans['name_middle']);

                $data_to_secure = json_encode([
                    'data' => $trans,
                    'conf' => [
                        'ldap' => ldap_config()
                    ]
                ]);

                $secure_data = encrypt_broadcast_data($data_to_secure);

                $message = [
                    'event' => 'restored',
                    'type' => 'account',
                    'encrypted' => $secure_data
                ];

                Redis::publish('events', json_encode($message));
            }

            history()->log(
                'Account',
                'restored an account for ' . $account->format_full_name() . ' [' . $account->identifier . ']',
                $account->id,
                'user-circle',
                'bg-lime'
            );
        }

        Log::info($logMessage, $logContext);

        /**
         * Ugly but will prevent passwords from being set in future requests
         */
        $account->set_propagate_password();
    }
}


text:
project_path: /web/fundamentals/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: There are right ways of using notifications, and ways of using them better. Learn what makes a good notification. We won't just show you what to do. We'll show you how to do it.

{# wf_updated_on: 2019-06-15 #}
{# wf_published_on: 2017-03-30 #}
{# wf_blink_components: Blink>PushAPI #}

# Web Push: Common Issues and Reporting Bugs {: .page-title }

{% include "web/_shared/contributors/mattgaunt.html" %}

When you hit an issue with web push, it can be difficult to debug the issue or
find help. This doc outlines some of the common issues and what you should
do if you've found a bug in Chrome or Firefox.

Before we dive into debugging push, you may be hitting issues with debugging
service workers themselves, the file not updating, failing to register or
generally just unusual behavior. There is an
[awesome document on debugging service workers](/web/fundamentals/getting-started/codelabs/debugging-service-workers/)
that I strongly recommend checking out if you are new to
service worker development.

There are two distinct stages to check off when developing and testing web push,
each with its own set of common issues / problems:

- **Sending a Message:** Make sure that sending messages is successful.
   You should be getting a 201 HTTP code. If you aren't :
    - **Check for Authorization Errors:** If you receive an authorization
       error message see the
       [Authorization Issues section](#authorization_issues).
    - **Other API Errors:** If you receive a non-201 status code response,
       see the [HTTP Status Codes section](#http_status_codes) for
       guidance on the cause of the issue.
- **Receiving a Message**: If you're able to send a message successfully,
   but the message is not received on the browser:
    - **Check for Encryption Issues:** See the [Payload Encryption
       Issue Section](#payload_encryption_issue).
    - **Check for Connection Issues:** If the problem is on Chrome, it
       may be a connection. See [Connection Issues section](#connection_issue)
       for more info.

If you aren't able to send and receive a push message and the relevant sections
in this doc aren't helping debug the problem then you may have found a
bug in the push mechanism itself. In this case, refer to the
[Raising Bug Reports](#raising_bug_reports)
section to file a good bug report with all the necessary information to expedite
the bug fixing process.

One thing I'd like to call out before we start is that **Firefox and the
Mozilla AutoPush Service have great error messages.** If you get stuck and
are not sure what the problem is, then test in Firefox and see if you
get a more helpful error message.

## Authorization Issues

Authorization issues are one of the most common issues developers hit when
starting out with web push. This is normally a problem with the configuration of a
site's [Application Server Keys (a.k.a. VAPID keys)
](https://tools.ietf.org/html/draft-ietf-webpush-vapid-02).

The easiest way to support push in both Firefox and Chrome is to supply an
`applicationServerKey` in the `subscribe()` call. The down side is that
any discrepancy between your front end and server's keys will result in an
authorization error.

### On Chrome + FCM

For Chrome, which uses FCM as a push service, you'll receive an
`UnauthorizedRegistration` response from FCM for a range of different
errors, all involving the application server keys.

You'll receive an `UnauthorizedRegistration` error in any of the following
situations:

* If you fail to define an `Authorization` header in the request to FCM.
* Your application key used to subscribe the user doesn't match the key used
  to sign the Authorization header.
* The expiration is invalid in your JWT, i.e. the expiration exceeds 24 hours or
  the JWT has expired.
* The JWT is malformed or has invalid values.

The full error response looks like this:

```
<HTML>\n<HEAD>\n<TITLE>UnauthorizedRegistration</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>UnauthorizedRegistration</H1>\n<H2>Error 400</H2>\n</BODY>\n</HTML>\n
```
If you receive this error message in Chrome, consider testing in Firefox to see
if it'll provide more insight to the problem.

### Firefox and Mozilla AutoPush

Firefox and Mozilla AutoPush provide a friendly set of error messages for
`Authorization` issues.

You'll also receive an `Unauthorized` error response from
Mozilla AutoPush if the `Authorization` header is not included in your push
request.

```
{
	"errno": 109,
	"message": "Request did not validate missing authorization header",
	"code": 401,
	"more_info": "http://autopush.readthedocs.io/en/latest/http.html\#error-codes",
	"error": "Unauthorized"
}
```

If the expiration in your JWT has expired, you'll also receive an
`Unauthorized` error with a message that explains that the token has
expired.

```
{
	"code": 401,
	"errno": 109,
	"error": "Unauthorized",
	"more_info": "http://autopush.readthedocs.io/en/latest/http.html\#error-codes",
	"message": "Request did not validate Invalid bearer token: Auth expired"
}
```

If the application server keys are different between when the user was
subscribed and when the Authorization header was signed, a `Not Found`
error will be returned:

```
{
	"errno": 102,
	"message": "Request did not validate invalid token",
	"code": 404,
	"more_info": "http://autopush.readthedocs.io/en/latest/http.html\#error-codes",
	"error": "Not Found"
}
```

Lastly, if you have an invalid value in your JWT (for example if the "alg" value
is an unexpected value), you'll receive the following error from Mozilla
AutoPush:

```
{
	"code": 401,
	"errno": 109,
	"error": "Unauthorized",
	"more_info": "http://autopush.readthedocs.io/en/latest/http.html\#error-codes",
	"message": "Request did not validate Invalid Authorization Header"
}
```

## HTTP Status Codes

There are a range of issues that can result in a non-201 response code from a
push service. Below is a list of HTTP status codes and what they mean in relation
to web push.

Status Code
Description

429
Too many requests. Your application server has reached a rate limit with a
push service. The response from the service should include a 'Retry-After' header to
indicate how long before another request can be made.

400
Invalid request. One of your headers is invalid or
poorly formatted.

404
Not Found. In this case you should delete the PushSubscription from your
back end and wait for an opportunity to resubscribe the user.

410
Gone. The subscription is no longer valid and should be removed from your
back end. This can be reproduced by calling `unsubscribe()` on a
`PushSubscription`.

413
Payload size too large. The minimum size payload a push service must
support is 4096 bytes (or 4kb). Anything larger can result in this error.

If the HTTP status code is not in this list and the error message is not
helpful, check the [Web Push Protocol
spec](https://tools.ietf.org/html/draft-ietf-webpush-protocol) to see if the
status code is referenced along with a scenario of when that status code can
be used.

## Payload Encryption Issue

If you can successfully trigger a push message (i.e. send a message to a web
push service and receive a 201 response code) but the push event never fires in
your service worker, this normally indicates that the browser failed to
decrypt the message it received.

If this is the case, you should see an error message in Firefox's DevTools
console like so:

![Firefox DevTools with decryption message](./images/ff-devtools-decryption-msg.png)

To check if this is the issue in Chrome, do the following:

1. Go to chrome://gcm-internals and click the "Start Recording" button.

![Chrome GCM internals record](./images/gcm-internals-start-recording.png)

1. Trigger a push message, and look under the "Message Decryption Failure Log".

![GCM internals decryption log](./images/gcm-internals-decryption-log.png)

If there is an issue with the decryption of the payload, you'll see an error
similar to the one displayed above. (Notice the `AES-GCM decryption failed`
message in the details column.)

There are a few tools which may help debug encryption if this is your issue:

* [Push Encryption Verifier tool by Peter
  Beverloo](https://tests.peter.sh/push-encryption-verifier/).
* [Web Push: Data Encryption Test Page by
  Mozilla](https://mozilla-services.github.io/WebPushDataTestPage/)

## Connection Issue

If you aren't receiving a push event in your service worker and you aren't
seeing any decryption errors, then the browser may be failing to connect to
a push service.

In Chrome, you can check whether the browser is receiving messages by examining
the 'Receive Message Log' (sic) in `chrome://gcm-internals`.

![GCM internals receive message log](./images/gcm-internals-receive-log.png)

If you aren't seeing the message arrive in a timely fashion, then make sure that
the connection status of your browser is `CONNECTED`:

![GCM internals connection state](./images/gcm-internals-connection-state.png)

If it's **not** 'CONNECTED', you may need to delete your current profile and
[create a new one](https://support.google.com/chrome/answer/2364824). If that
still doesn't solve the issue, please raise a bug report as suggested below.

## Raising Bug Reports

If none of the above helps with your issue and there is no sign of what the
problem could be, please raise an issue against the browser you are having an
issue with:

For Chrome, you'd raise the issue here:
[https://bugs.chromium.org/p/chromium/issues/list](https://bugs.chromium.org/p/chromium/issues/list)
For Firefox, you should raise the issue on:
[https://bugzilla.mozilla.org/](https://bugzilla.mozilla.org/)

To provide a good bug report, you should provide the following details:

* Browsers you've tested in (e.g. Chrome version 50, Chrome version 51, Firefox
  version 50, Firefox version 51).
* An example `PushSubscription` that demonstrates the problem.
* Include any example requests (i.e. content of network requests to a push
  service, including headers).
* Include any example responses from network requests as well.

If you can provide a reproducible example, either source code or a hosted web
site, it often speeds up diagnosing and solving the problem.

## Feedback {: #feedback }

{% include "web/_shared/helpful.html" %}


text:
var createInputFile = function (fig) {
    var my = {},
        self = createBaseInput(fig, my);

    self.getType = function () {
        return 'file';
    };

    self.get = function () {
        return last(self.$().val().split('\\'));
    };

    self.clear = function () {
        // http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery
        this.$().each(function () {
            $(this).wrap('<form>').closest('form').get(0).reset();
            $(this).unwrap();
        });
    };

    self.$().change(function (e) {
        my.publishChange(e, this);
        // self.publish('change', self);
    });

    return self;
};


text:
"""This module is deprecated. Please use :mod:`airflow.providers.google.cloud.operators.spanner`."""

import warnings

from airflow.providers.google.cloud.operators.spanner import (
    SpannerDeleteDatabaseInstanceOperator,
    SpannerDeleteInstanceOperator,
    SpannerDeployDatabaseInstanceOperator,
    SpannerDeployInstanceOperator,
    SpannerQueryDatabaseInstanceOperator,
    SpannerUpdateDatabaseInstanceOperator,
)

warnings.warn(
    "This module is deprecated. Please use `airflow.providers.google.cloud.operators.spanner`.",
    DeprecationWarning,
    stacklevel=2,
)

class CloudSpannerInstanceDatabaseDeleteOperator(SpannerDeleteDatabaseInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerDeleteDatabaseInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)

class CloudSpannerInstanceDatabaseDeployOperator(SpannerDeployDatabaseInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerDeployDatabaseInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)

class CloudSpannerInstanceDatabaseQueryOperator(SpannerQueryDatabaseInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerQueryDatabaseInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)

class CloudSpannerInstanceDatabaseUpdateOperator(SpannerUpdateDatabaseInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerUpdateDatabaseInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)

class CloudSpannerInstanceDeleteOperator(SpannerDeleteInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerDeleteInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)

class CloudSpannerInstanceDeployOperator(SpannerDeployInstanceOperator):
    """
    This class is deprecated.
    Please use `airflow.providers.google.cloud.operators.spanner.SpannerDeployInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(
            self.__doc__,
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(*args, **kwargs)


text:
Dir[File.join(File.dirname(__FILE__), 'wire', '*.rb')].each do |file|
  require file
end


text:
'use strict';

var test = require('tape');
var sinon = require('sinon');
var proxyquire = require('proxyquire');

test('render without layout gets some html anyways', function (t) {
  var state = {
    defaults: {},
    getPartial: function (action, vm, done) { done(null,'action:' + action + ',vm:' + JSON.stringify(vm)); }
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'text/html'
    },
    query: {},
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    send: sinon.spy()
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  t.ok(res.send.calledOnce, 'called res.send');
  t.deepEqual(res.send.firstCall.args, ['
{\n  "model": {},\n  "action": "foo/bar",\n  "taunus": {},\n  "partial": "action:foo/bar,vm:{\\"taunus\\":{}}"\n}
'], 'got html response anyways');
  t.end();
});

test('render with layout gets some plain text', function (t) {
  var state = {
    defaults: {},
    getPartial: function (action, vm, done) { done(null,'action:' + action + ',
vm:' + JSON.stringify(vm)); },
    layout: function (data) { return '
' + data.partial + '
'; }
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'text/plain'
    },
    query: {},
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    send: sinon.spy()
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  t.ok(res.send.calledOnce, 'called res.send');
  t.deepEqual(res.send.firstCall.args, ['action:foo/bar, vm:{"taunus":{}}'], 'got plaintext response');
  t.end();
});

test('setting model.action uses different action', function (t) {
  var state = {
    defaults: {},
    getPartial: function (action, vm, done) { done(null,'action:' + action + ',vm:' + JSON.stringify(vm)); }
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {model:{action:'bar/baz'}};
  var req = {
    headers: {
      accept: 'text/html'
    },
    query: {},
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    send: sinon.spy()
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  t.ok(res.send.calledOnce, 'called res.send');
  t.deepEqual(res.send.firstCall.args, ['
{\n  "model": {\n    "action": "bar/baz"\n  },\n  "action": "bar/baz",\n  "taunus": {},\n  "partial": "action:bar/baz,vm:{\\"action\\":\\"bar/baz\\",\\"taunus\\":{}}"\n}
'], 'got model\'s action');
  t.end();
});

test('render sets cache headers', function (t) {
  var state = {
    defaults: {},
    getPartial: function (action, vm, done) { done(null,'action:' + action + ',vm:' + JSON.stringify(vm)); }
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {};
  var req = {
    url: '/foo',
    headers: {
      accept: 'text/html'
    },
    query: {},
    params: {}
  };
  var res = {
    set: sinon.spy(),
    send: sinon.spy()
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  t.ok(res.set.calledWith('Vary', 'Accept'), 'vary accept header');
  t.ok(res.set.calledWith('ETag'), 'etag header');
  t.ok(res.set.calledWith('cache-control', 'private, must-revalidate, max-age=0'), 'cache control header');
  t.end();
});

test('render JSON just gets json', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {},
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { model: {}, version: '1' });
    t.end();
  }
});

test('flash and user are forwarded from model', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {},
    params: {},
    url: '/bar',
    flash: function () { return { candy: 'cane' }; },
    user: { corsair: 'interstellar' }
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { model: { flash: { candy: 'cane' }, user: { corsair: 'interstellar' } }, version: '1' });
    t.end();
  }
});

test('render JSON demanding controller gets bundled controller', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state,
    './bro': bro
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {
      controller: ''
    },
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  function bro (file, compiled) {
    t.equal(file, 'client/js/controllers/foo/bar.js', 'asked for controller according to convention');
    t.ok(typeof compiled === 'function', 'got done callback');
    compiled(null, 'foo');
  }
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { controller: 'foo', model: {}, version: '1' });
    t.end();
  }
});

test('render JSON demanding template gets bundled template', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state,
    './bro': bro
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {
      template: ''
    },
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  function bro (file, compiled) {
    t.equal(file, '.bin/views/foo/bar.js', 'asked for view template according to convention');
    t.ok(typeof compiled === 'function', 'got done callback');
    compiled(null, 'foo');
  }
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { template: 'foo', model: {}, version: '1' });
    t.end();
  }
});

test('render JSON demanding things gets bundled components', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state,
    './bro': bro
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {
      controller: '',
      template: ''
    },
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  function bro (file, compiled) {
    var map = {
      '.bin/views/foo/bar.js': 'foo',
      'client/js/controllers/foo/bar.js': 'bar'
    };
    t.ok(map[file], 'asked for expected component according to convention');
    t.ok(typeof compiled === 'function', 'got done callback');
    compiled(null, map[file]);
  }
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { controller: 'bar', template: 'foo', model: {}, version: '1' });
    t.end();
  }
});

test('render JSON demanding things gets bundled components for different action when hijacked', function (t) {
  var state = {
    defaults: {}, // set at mountpoint
    version: '1' // set at mountpoint
  };
  var render = proxyquire('../../lib/render', {
    './state': state,
    './bro': bro
  });
  var vm = {};
  var req = {
    headers: {
      accept: 'application/json'
    },
    query: {
      hijacker: 'foo/mar',
      controller: '',
      template: ''
    },
    params: {},
    url: '/bar'
  };
  var res = {
    set: sinon.spy(),
    json: json
  };
  function next () {}
  function bro (file, compiled) {
    var map = {
      '.bin/views/foo/bar.js': 'tar',
      'client/js/controllers/foo/bar.js': 'taint',
      '.bin/views/foo/mar.js': 'foo',
      'client/js/controllers/foo/mar.js': 'bar'
    };
    t.ok(map[file], 'asked for expected component according to convention');
    t.ok(typeof compiled === 'function', 'got done callback');
    compiled(null, map[file]);
  }
  render({ action: 'foo/bar' }, vm, req, res, next);
  function json (data) {
    t.deepEqual(data, { controller: 'bar', template: 'foo', version: '1' });
    t.end();
  }
});


text:
version = ${shell cat VERSION}
distdir = grk-${version}
cvsroot = flits.cs.vu.nl:/home/ralf/cvsroot
project = cvsprojects/grk

all:
	cd grammars/vscobolii; make
	chmod -fR go+rX .

test: all
	cd grammars/vscobolii; make test

clean:
	cd lib;      make clean
	cd tools;    make clean
	cd grammars; make clean
	rm -f *~
	rm -rf temp
	rm -rf ${distdir}*

# To be used by developer at cs.vu.nl
dist:
	rm -rf temp
	rm -rf ${distdir}*
	mkdir temp
	cd temp; cvs -d ${cvsroot} checkout ${project}
	mv temp/${project} ${distdir}
	rm -rf temp
	cd ${distdir}; find . -depth -name CVS -exec rm -rf \{\} \;
	tar -cvf ${distdir}.tar ${distdir}
	gzip ${distdir}.tar
	mv ${distdir}.tar.gz ${HOME}/archive
	chmod go+rX ${HOME}/archive/${distdir}.tar.gz
	rm -rf ${distdir}*
	cd ${HOME}/www/grammarware; \
	rm -f ${distdir}.tar.gz; \
	ln -s ${HOME}/archive/${distdir}.tar.gz


text:
package com.chinamobile.bcbsp.ml.distance;

import com.chinamobile.bcbsp.ml.math.DoubleVector;

/**
 * a {@link DistanceMeasurer} is responsible for calculating the distance
 * between {@link DoubleVector}s or Arrays of {@code double}s
 */
public interface DistanceMeasurer {

  /**
   * Calculates the distance between two arrays of {@code double}s
   *
   * @param set1 an array of {@code double}
   * @param set2 an array of {@code double}
   * @return a {@code double} representing the distance
   */
  public double measureDistance(double[] set1, double[] set2);

  /**
   * Calculates the distance between two {@link DoubleVector}
   *
   * @param vec1 a {@link DoubleVector}
   * @param vec2 a {@link DoubleVector}
   * @return a {@code double} representing the distance
   */
  public double measureDistance(DoubleVector vec1, DoubleVector vec2);

}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { AccountComponent } from './account/account.component';
import { AuthGuardLogin } from './services/auth-guard-login.service';
import { AuthGuardAdmin } from './services/auth-guard-admin.service';
import { AdminComponent } from './admin/admin.component';

import { EntreprisesPalmaresComponent } from './entreprises_palmares/entreprises-palmares.component';
import { EntreprisePageComponent } from './entreprise_page/entreprise-page.component';
import { StagesRechercheComponent } from './stages_recherche/stages-recherche.component';
import { StagesResultatComponent } from './stages_resultat/stages-resultat.component';
import { ModifierProfilComponent } from './modifier_profil/modifier-profil.component';
import { StageEnregistrementComponent } from './stage_enregistrement/stage-enregistrement.component';
import { EntretienEnregistrementComponent } from './entretien_enregistrement/entretien-enregistrement.component';
import { AccueilComponent } from './accueil/accueil.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { TestComponent } from './test/test.component';

const routes: Routes = [
  { path: '', component: AccueilComponent, canActivate: [AuthGuardLogin] },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'logout', component: LogoutComponent },
  { path: 'account', component: AccountComponent, canActivate: [AuthGuardLogin] },
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuardAdmin] },
  { path: 'test', component: TestComponent, canActivate: [AuthGuardAdmin] },

  { path: 'entreprises_palmares', component: EntreprisesPalmaresComponent, canActivate: [AuthGuardLogin] },
  { path: 'entreprise/:id', component: EntreprisePageComponent, canActivate: [AuthGuardLogin] },
  { path: 'stages_recherche', component: StagesRechercheComponent, canActivate: [AuthGuardLogin] },
  { path: 'stages_resultat', component: StagesResultatComponent, canActivate: [AuthGuardLogin] },
  { path: 'stages_resultat/:criteres', component: StagesResultatComponent, canActivate: [AuthGuardLogin] },
  { path: 'modifier_profil', component: ModifierProfilComponent, canActivate: [AuthGuardLogin] },
  { path: 'stage_enregistrement', component: StageEnregistrementComponent, canActivate: [AuthGuardLogin] },
  { path: 'entretien_enregistrement', component: EntretienEnregistrementComponent, canActivate: [AuthGuardLogin] },
  { path: 'accueil', component: AccueilComponent, canActivate: [AuthGuardLogin] },
  { path: 'header', component: HeaderComponent },
  { path: 'footer', component: FooterComponent },
  { path: '**', redirectTo: 'accueil'}
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

export class RoutingModule {}


text:
import {loadCardsPage} from './cardsPage'

export function loadFactsPageData(regionCode) {
  return (dispatch, getState) => {
    const {allCardsPages} = getState()
    allCardsPages.forEach(page => {
      page.cards.forEach(card => {
        dispatch(loadCardsPage(regionCode, page.name, {
          cardName: card.name,
          tabName: 'latest'
        }))
      })
    })
  }
}


text:
package org.knowm.xchange.okcoin.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Instances of this class represent all holdings related to a specific contract, e.g. `this_week`.
 * If you have 2 open positions for this week then all fields (buy/sell) will be fully populated. If
 * you have multiple contracts open (`this_week`, `next_week`, ..) then each contract will be its
 * own instance.
 */
public class OkCoinPosition {

  private final long contractId;

  private final int status;

  private final String symbol;

  private final String type;

  private final BigDecimal rate;

  private final Date createDate;

  private BigDecimal buyAmount;

  private BigDecimal buyAmountAvailable;

  private BigDecimal buyProfitReal;

  private BigDecimal buyPriceAvg;

  private BigDecimal sellAmount;

  private BigDecimal sellAmountAvailable;

  private BigDecimal sellProfitReal;

  private BigDecimal sellPriceAvg;

  public OkCoinPosition(
      @JsonProperty("contract_id") final long orderId,
      @JsonProperty("status") final int status,
      @JsonProperty("symbol") final String symbol,
      @JsonProperty("type") final String type,
      @JsonProperty("lever_rate") final BigDecimal rate,
      @JsonProperty("buy_amount") final BigDecimal buyAmount,
      @JsonProperty("buy_available") final BigDecimal buyAmountAvailable,
      @JsonProperty("buy_profit_real") final BigDecimal buyProfitReal,
      @JsonProperty("buy_price_avg") final BigDecimal buyPriceAvg,
      @JsonProperty("sell_amount") final BigDecimal sellAmount,
      @JsonProperty("sell_available") final BigDecimal sellAmountAvailable,
      @JsonProperty("sell_profit_real") final BigDecimal sellProfitReal,
      @JsonProperty("sell_price_avg") final BigDecimal sellPriceAvg,
      @JsonProperty("create_date") final Date createDate) {

    this.contractId = orderId;
    this.status = status;
    this.symbol = symbol;
    this.type = type;
    this.rate = rate;

    this.buyAmount = buyAmount;
    this.buyAmountAvailable = buyAmountAvailable;
    this.buyProfitReal = buyProfitReal;
    this.buyPriceAvg = buyPriceAvg;

    this.sellAmount = sellAmount;
    this.sellAmountAvailable = sellAmountAvailable;
    this.sellProfitReal = sellProfitReal;
    this.sellPriceAvg = sellPriceAvg;

    this.createDate = createDate;
  }

  public long getContractId() {

    return contractId;
  }

  public int getStatus() {

    return status;
  }

  public String getSymbol() {

    return symbol;
  }

  public String getType() {

    return type;
  }

  public BigDecimal getRate() {

    return rate;
  }

  public Date getCreateDate() {

    return createDate;
  }

  public BigDecimal getBuyAmount() {

    return buyAmount;
  }

  public BigDecimal getBuyAmountAvailable() {

    return buyAmountAvailable;
  }

  public BigDecimal getBuyProfitReal() {

    return buyProfitReal;
  }

  public BigDecimal getBuyPriceAvg() {

    return buyPriceAvg;
  }

  public BigDecimal getSellAmount() {

    return sellAmount;
  }

  public BigDecimal getSellAmountAvailable() {

    return sellAmountAvailable;
  }

  public BigDecimal getSellProfitReal() {

    return sellProfitReal;
  }

  public BigDecimal getSellPriceAvg() {

    return sellPriceAvg;
  }

  @Override
  public String toString() {
    return "OkCoinPosition{"
        + "contractId="
        + contractId
        + ", status="
        + status
        + ", symbol='"
        + symbol
        + '\''
        + ", type='"
        + type
        + '\''
        + ", rate="
        + rate
        + ", createDate="
        + createDate
        + ", buyAmount="
        + buyAmount
        + ", buyAmountAvailable="
        + buyAmountAvailable
        + ", buyProfitReal="
        + buyProfitReal
        + ", buyPriceAvg="
        + buyPriceAvg
        + ", sellAmount="
        + sellAmount
        + ", sellAmountAvailable="
        + sellAmountAvailable
        + ", sellProfitReal="
        + sellProfitReal
        + ", sellPriceAvg="
        + sellPriceAvg
        + '}';
  }
}


text:
<idea-plugin version="2">
    <id>com.umu.langtip</id>
    <name>lang tip</name>
    <version>1.0</version>
    <vendor email="daoyu@umu.com" url="http://www.fleven.com">daoyuly</vendor>

    <description><![CDATA[

language text tip

     umu内部开发插件,快速提示多语言词条占位符所表示的中文意思,方便开发使用

使用

选中占位符lang_xxx

按下 SHIFT Ctrl P (Command SHIFT P on a Mac) 或者右键点击"多语言占位符提示"

代码窗口显示红色hint提示

    ]]></description>

    <change-notes><![CDATA[
    Version 1.0: Initial version.
    ]]>
    </change-notes>

    <idea-version since-build="131"/>

    <depends>com.intellij.modules.platform</depends>

    <extensions defaultExtensionNs="com.intellij">

    </extensions>

    <application-components>

    </application-components>

    <project-components>

    </project-components>

    <actions>

        <action id="TestLocator" class="com.karateca.protractor.TestLocatorAction"
                text="多语占位符提示"
                description="Test the selected locator with the element explorer"
                icon="/umu.png">
            <keyboard-shortcut keymap="$default" first-keystroke="shift ctrl P"/>
            <keyboard-shortcut keymap="Mac OS X" first-keystroke="shift meta P"/>
            <keyboard-shortcut keymap="Mac OS X 10.5+" first-keystroke="shift meta P"/>
            <add-to-group group-id="EditorPopupMenu"/>
        </action>
    </actions>

</idea-plugin>


text:
package org.apache.hadoop.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * A wrapper for Writable instances.
 *

 * When two sequence files, which have same Key type but different Value
 * types, are mapped out to reduce, multiple Value types is not allowed.
 * In this case, this class can help you wrap instances with different types.
 *

 *
 *

 * Compared with ObjectWritable, this class is much more effective,
 * because ObjectWritable will append the class declaration as a String
 * into the output file in every Key-Value pair.
 *

 *
 * how to use it:

 * 1. Write your own class, such as GenericObject, which extends GenericWritable.

 * 2. Implements the abstract method getTypes(), defines
 *    the classes which will be wrapped in GenericObject in application.
 *    Attention: this classes defined in getTypes() method, must
 *    implement Writable interface.
 *

 *
 * The code looks like this:
 *

 * public class GenericObject extends GenericWritable {
 *
 *   private static Class[] CLASSES = {
 *               ClassType1.class,
 *               ClassType2.class,
 *               ClassType3.class,
 *               };
 *
 *   protected Class[] getTypes() {
 *       return CLASSES;
 *   }
 *
 * }
 *

 *
 * @author Feng Jiang (Feng.a.Jiang@gmail.com)
 * @since Nov 8, 2006
 */
public abstract class GenericWritable implements Writable {

  private static final byte NOT_SET = -1;

  private byte type = NOT_SET;

  private Writable instance;

  /**
   * Set the instance that is wrapped.
   *
   * @param obj
   */
  public void set(Writable obj) {
    instance = obj;
    Class[] clazzes = getTypes();
    for (int i = 0; i < clazzes.length; i++) {
      Class clazz = clazzes[i];
      if (clazz.isInstance(instance)) {
        type = (byte) i;
        return;
      }
    }
    throw new RuntimeException("The type of instance is: "
                + instance.getClass() + ", which is NOT registered.");
  }

  /**
   * Return the wrapped instance.
   */
  public Writable get() {
    return instance;
  }

  public void readFields(DataInput in) throws IOException {
    type = in.readByte();
    Class clazz = getTypes()[type];
    try {
      instance = (Writable) clazz.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException("Cannot initialize the class: " + clazz);
    }
    instance.readFields(in);
  }

  public void write(DataOutput out) throws IOException {
    if (type == NOT_SET || instance == null)
      throw new IOException("The GenericWritable has NOT been set correctly. type="
                            + type + ", instance=" + instance);
    out.writeByte(type);
    instance.write(out);
  }

  /**
   * Return all classes that may be wrapped.  Subclasses should implement this
   * to return a constant array of classes.
   */
  abstract protected Class[] getTypes();

}


text:
package com.spotify.helios.master.resources;

import com.spotify.helios.common.PomVersion;
import com.spotify.helios.common.Version;
import com.spotify.helios.common.VersionCheckResponse;
import com.spotify.helios.common.VersionCompatibility;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Timed;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import static com.google.common.base.Strings.isNullOrEmpty;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;

@Path("version")
public class VersionResource {

  /**
   * Returns the server version string.
   * @return The server version.
   */
  @GET
  @Produces(TEXT_PLAIN)
  @Timed
  @ExceptionMetered
  public String version() {
    // wrap in double quotes to make valid json
    return String.format("\"%s\"", Version.POM_VERSION);
  }

  /**
   * Given the client version, returns the version status, i.e. whether or not they should be
   * compatible or not.
   * @param client The client version.
   * @return The VersionCheckResponse object.
   */
  @GET
  @Path("/check")
  @Produces(APPLICATION_JSON)
  @Timed
  @ExceptionMetered
  public VersionCheckResponse versionCheck(
      @QueryParam("client") @DefaultValue("") final String client) {
    final PomVersion serverVersion = PomVersion.parse(Version.POM_VERSION);
    final VersionCompatibility.Status status;

    if (isNullOrEmpty(client)) {
      return new VersionCheckResponse(VersionCompatibility.Status.MISSING,
                                      serverVersion, Version.RECOMMENDED_VERSION);
    }

    final PomVersion clientVersion = PomVersion.parse(client);
    status = VersionCompatibility.getStatus(serverVersion, clientVersion);
    return new VersionCheckResponse(status, serverVersion, Version.RECOMMENDED_VERSION);
  }
}