text:
package org.apache.shindig.config;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Base class for container configurations.
 */
public abstract class AbstractContainerConfig implements ContainerConfig {
  public String getString(String container, String property) {
    Object value = getProperty(container, property);
    if (value == null) {
      return null;
    }
    return value.toString();
  }

  public int getInt(String container, String property) {
    Object value = getProperty(container, property);
    if (value instanceof Number) {
      return ((Number) value).intValue();
    }
    return 0;
  }

  @SuppressWarnings("unchecked")
  public boolean getBool(String container, String property) {
    Object value = getProperty(container, property);
    if (value instanceof Boolean) {
      return ((Boolean) value).booleanValue();
    }
    return false;
  }

  @SuppressWarnings("unchecked")
  public List<Object> getList(String container, String property) {
    Object value = getProperty(container, property);
    if (value instanceof List) {
      return (List<Object>) value;
    }
    return Collections.emptyList();
  }

  @SuppressWarnings("unchecked")
  public Map<String, Object> getMap(String container, String property) {
    Object value = getProperty(container, property);
    if (value instanceof Map) {
      return (Map<String, Object>) value;
    }
    return Collections.emptyMap();
  }

  public Collection<String> getContainers() {
    throw new UnsupportedOperationException();
  }

  public Map<String, Object> getProperties(String container) {
    throw new UnsupportedOperationException();
  }

  public abstract Object getProperty(String container, String name);
}


text: {{ site.data.global.footer_text }}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/ax5ui/ax5ui-layout.svg?branch=master)](https://travis-ci.org/ax5ui/ax5ui-layout)
[![npm version](https://badge.fury.io/js/ax5ui-layout.svg)](https://badge.fury.io/js/ax5ui-layout)
[![](https://img.shields.io/npm/dm/ax5ui-layout.svg)](https://www.npmjs.com/package/ax5ui-layout)

# ax5ui-layout
"layout" helps users set position and size of multiple panels on a page.

> *Dependencies*
> * _[jQuery 1.X+](http://jquery.com/)_
> * _[ax5core](http://ax5.io/ax5core)_
> * _[bootstrap](http://getbootstrap.com/)_

### Install with bower
```sh
bower install ax5ui-layout
```
[bower](http://bower.io/#install-bower) is web front-end package manager.
When you install `bower`, it will be installed under the `bower_components` folder to resolve the plug-in dependencies.
(You can change the folder location. [.bowerrc](http://bower.io/docs/config/#bowerrc-specification) )

It is recommended that you install by using `bower`.
If you've never used bower, please refer to [http://bower.io/#install-bower](http://bower.io/#install-bower).

### Install with npm
If you do not use bower, it also can be installed by using npm as an alternative.
In case of npm, which is the package manager for the front end, you need to solve the problem of plug-in dependencies.

```sh
npm install jquery
npm install ax5core
npm install ax5ui-layout
```

After downloading the install file of npm, you will need to copy it to the location where you want to use as a resource for the project.
If the copy process is inconvenient, it also can be done easily by using `gulp` or `grunt`.

### Download code
- [ax5core Github releases](https://github.com/ax5ui/ax5core/releases)
- [ax5ui-layout Github releases](https://github.com/ax5ui/ax5ui-layout/releases)

### Insert "ax5layout" in HTML HEAD.

Folder location can be any for your project. However, please be sure to assign the right path in the project.

```html
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/ax5ui/ax5ui-layout/master/dist/ax5layout.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/ax5ui/ax5core/master/dist/ax5core.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/ax5ui/ax5ui-layout/master/dist/ax5layout.min.js"></script>
```

**CDN urls**
This is a list of CDN urls for ax5ui-layout. ax5ui offers the CDN services through rawgit.
```
https://cdn.rawgit.com/ax5ui/ax5ui-layout/master/dist/ax5layout.css
https://cdn.rawgit.com/ax5ui/ax5ui-layout/master/dist/ax5layout.js
https://cdn.rawgit.com/ax5ui/ax5ui-layout/master/dist/ax5layout.min.js
```

### Basic Usage
```html
<div data-ax5layout="ax1" data-config='{layout:"dock-panel"}' style="height: 100%;border:1px solid #ccc;">
    <div data-dock-panel='{dock:"top", split:true, height: 200, maxHeight: 300}'></div>
    <div data-dock-panel='{dock:"bottom", split:"true", height: 200, minHeight: 50, maxHeight: 300}'></div>
    <div data-dock-panel='{dock:"left", split:true, width: 200, minWidth: 50, maxWidth: 300}'></div>
    <div data-dock-panel='{dock:"right", split:true, width: "10%", minWidth: 50, maxWidth: 300}'>

    </div>
    <div data-dock-panel='{dock:"center"}' style="padding: 5px;">

    </div>
</div>
```

```js
$(document.body).ready(function () {
    jQuery('[data-ax5layout="ax1"]').ax5layout();
});
```

***

### Preview
- [See Demonstration](http://ax5.io/ax5ui-layout/demo/index.html)

If you have any questions, please refer to the following [gitHub](https://github.com/ax5ui/ax5ui-kernel)

## Question
- https://jsdev.kr/c/axisj/ax5ui
- https://github.com/ax5ui/ax5ui-kernel/issues

[![axisj-contributed](https://img.shields.io/badge/AXISJ.com-Contributed-green.svg)](https://github.com/axisj)
![](https://img.shields.io/badge/Seowoo-Mondo&Thomas-red.svg)


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

package com.google.gerrit.server.index;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.CharMatcher;
import com.google.common.base.Preconditions;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.TrackingFooters;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;

import org.eclipse.jgit.lib.Config;

/**
 * Definition of a field stored in the secondary index.
 *
 * @param <I> input type from which documents are created and search results are
 *     returned.
 * @param <T> type that should be extracted from the input object when converting
 *     to an index document.
 */
public abstract class FieldDef<I, T> {
  /** Definition of a single (non-repeatable) field. */
  public abstract static class Single<I, T> extends FieldDef<I, T> {
    protected Single(String name, FieldType<T> type, boolean stored) {
      super(name, type, stored);
    }

    @Override
    public final boolean isRepeatable() {
      return false;
    }
  }

  /** Definition of a repeatable field. */
  public abstract static class Repeatable<I, T>
      extends FieldDef<I, Iterable<T>> {
    protected Repeatable(String name, FieldType<T> type, boolean stored) {
      super(name, type, stored);
      Preconditions.checkArgument(type != FieldType.INTEGER_RANGE,
          "Range queries against repeated fields are unsupported");
    }

    @Override
    public final boolean isRepeatable() {
      return true;
    }
  }

  /** Arguments needed to fill in missing data in the input object. */
  public static class FillArgs {
    public final TrackingFooters trackingFooters;
    public final boolean allowsDrafts;

    @Inject
    FillArgs(TrackingFooters trackingFooters,
        @GerritServerConfig Config cfg) {
      this.trackingFooters = trackingFooters;
      this.allowsDrafts = cfg == null
          ? true
          : cfg.getBoolean("change", "allowDrafts", true);
    }
  }

  private final String name;
  private final FieldType<?> type;
  private final boolean stored;

  private FieldDef(String name, FieldType<?> type, boolean stored) {
    this.name = checkName(name);
    this.type = type;
    this.stored = stored;
  }

  private static String checkName(String name) {
    CharMatcher m = CharMatcher.anyOf("abcdefghijklmnopqrstuvwxyz0123456789_");
    checkArgument(m.matchesAllOf(name), "illegal field name: %s", name);
    return name;
  }

  /** @return name of the field. */
  public final String getName() {
    return name;
  }

  /**
   * @return type of the field; for repeatable fields, the inner type, not the
   *     iterable type.
   */
  public final FieldType<?> getType() {
    return type;
  }

  /** @return whether the field should be stored in the index. */
  public final boolean isStored() {
    return stored;
  }

  /**
   * Get the field contents from the input object.
   *
   * @param input input object.
   * @param args arbitrary arguments needed to fill in indexable fields of the
   *     input object.
   * @return the field value(s) to index.
   *
   * @throws OrmException
   */
  public abstract T get(I input, FillArgs args) throws OrmException;

  /** @return whether the field is repeatable. */
  public abstract boolean isRepeatable();
}


text:
from elasticsearch import helpers, TransportError
from elasticsearch.serializer import JSONSerializer

from . import ElasticsearchTestCase
from ..test_cases import SkipTest, TestCase

class TestChunkActions(TestCase):
    def setUp(self):
        super(TestChunkActions, self).setUp()
        self.actions = [({'index': {}}, {'some': 'data', 'i': i}) for i in range(100)]

    def test_chunks_are_chopped_by_byte_size(self):
        self.assertEquals(100, len(list(helpers._chunk_actions(self.actions, 100000, 1, JSONSerializer()))))

    def test_chunks_are_chopped_by_chunk_size(self):
        self.assertEquals(10, len(list(helpers._chunk_actions(self.actions, 10, 99999999, JSONSerializer()))))

class FailingBulkClient(object):
    def __init__(self, client, fail_at=1):
        self.client = client
        self._called = -1
        self._fail_at = fail_at
        self.transport = client.transport

    def bulk(self, *args, **kwargs):
        self._called += 1
        if self._called == self._fail_at:
            raise TransportError(599, "Error!", "INFO")
        return  self.client.bulk(*args, **kwargs)

class TestStreamingBulk(ElasticsearchTestCase):
    def test_actions_remain_unchanged(self):
        actions = [{'_id': 1}, {'_id': 2}]
        for ok, item in helpers.streaming_bulk(self.client, actions, index='test-index', doc_type='answers'):
            self.assertTrue(ok)
        self.assertEquals([{'_id': 1}, {'_id': 2}], actions)

    def test_all_documents_get_inserted(self):
        docs = [{"answer": x, '_id': x} for x in range(100)]
        for ok, item in helpers.streaming_bulk(self.client, docs, index='test-index', doc_type='answers', refresh=True):
            self.assertTrue(ok)

        self.assertEquals(100, self.client.count(index='test-index', doc_type='answers')['count'])
        self.assertEquals({"answer": 42}, self.client.get(index='test-index', doc_type='answers', id=42)['_source'])

    def test_all_errors_from_chunk_are_raised_on_failure(self):
        self.client.indices.create("i",
            {
                "mappings": {"t": {"properties": {"a": {"type": "integer"}}}},
                "settings": {"number_of_shards": 1, "number_of_replicas": 0}
            })
        self.client.cluster.health(wait_for_status="yellow")

        try:
            for ok, item in helpers.streaming_bulk(self.client, [{"a": "b"},
                {"a": "c"}], index="i", doc_type="t", raise_on_error=True):
                self.assertTrue(ok)
        except helpers.BulkIndexError as e:
            self.assertEquals(2, len(e.errors))
        else:
            assert False, "exception should have been raised"

    def test_different_op_types(self):
        if self.es_version < (0, 90, 1):
            raise SkipTest('update supported since 0.90.1')
        self.client.index(index='i', doc_type='t', id=45, body={})
        self.client.index(index='i', doc_type='t', id=42, body={})
        docs = [
            {'_index': 'i', '_type': 't', '_id': 47, 'f': 'v'},
            {'_op_type': 'delete', '_index': 'i', '_type': 't', '_id': 45},
            {'_op_type': 'update', '_index': 'i', '_type': 't', '_id': 42, 'doc': {'answer': 42}}
        ]
        for ok, item in helpers.streaming_bulk(self.client, docs):
            self.assertTrue(ok)

        self.assertFalse(self.client.exists(index='i', doc_type='t', id=45))
        self.assertEquals({'answer': 42}, self.client.get(index='i', id=42)['_source'])
        self.assertEquals({'f': 'v'}, self.client.get(index='i', id=47)['_source'])

    def test_transport_error_can_becaught(self):
        failing_client = FailingBulkClient(self.client)
        docs = [
            {'_index': 'i', '_type': 't', '_id': 47, 'f': 'v'},
            {'_index': 'i', '_type': 't', '_id': 45, 'f': 'v'},
            {'_index': 'i', '_type': 't', '_id': 42, 'f': 'v'},
        ]

        results = list(helpers.streaming_bulk(failing_client, docs, raise_on_exception=False, raise_on_error=False, chunk_size=1))
        self.assertEquals(3, len(results))
        self.assertEquals([True, False, True], [r[0] for r in results])

        exc = results[1][1]['index'].pop('exception')
        self.assertIsInstance(exc, TransportError)
        self.assertEquals(599, exc.status_code)
        self.assertEquals(
            {
                'index': {
                    '_index': 'i',
                    '_type': 't',
                    '_id': 45,

                    'data': {'f': 'v'},
                    'error': "TransportError(599, 'Error!')",
                    'status': 599
                }
            },
            results[1][1]
        )

class TestBulk(ElasticsearchTestCase):
    def test_bulk_works_with_single_item(self):
        docs = [{"answer": 42, '_id': 1}]
        success, failed = helpers.bulk(self.client, docs, index='test-index', doc_type='answers', refresh=True)

        self.assertEquals(1, success)
        self.assertFalse(failed)
        self.assertEquals(1, self.client.count(index='test-index', doc_type='answers')['count'])
        self.assertEquals({"answer": 42}, self.client.get(index='test-index', doc_type='answers', id=1)['_source'])

    def test_all_documents_get_inserted(self):
        docs = [{"answer": x, '_id': x} for x in range(100)]
        success, failed = helpers.bulk(self.client, docs, index='test-index', doc_type='answers', refresh=True)

        self.assertEquals(100, success)
        self.assertFalse(failed)
        self.assertEquals(100, self.client.count(index='test-index', doc_type='answers')['count'])
        self.assertEquals({"answer": 42}, self.client.get(index='test-index', doc_type='answers', id=42)['_source'])

    def test_stats_only_reports_numbers(self):
        docs = [{"answer": x} for x in range(100)]
        success, failed = helpers.bulk(self.client, docs, index='test-index', doc_type='answers', refresh=True, stats_only=True)

        self.assertEquals(100, success)
        self.assertEquals(0, failed)
        self.assertEquals(100, self.client.count(index='test-index', doc_type='answers')['count'])

    def test_errors_are_reported_correctly(self):
        self.client.indices.create("i",
            {
                "mappings": {"t": {"properties": {"a": {"type": "integer"}}}},
                "settings": {"number_of_shards": 1, "number_of_replicas": 0}
            })
        self.client.cluster.health(wait_for_status="yellow")

        success, failed = helpers.bulk(
            self.client,
            [{"a": 42}, {"a": "c", '_id': 42}],
            index="i",
            doc_type="t",
            raise_on_error=False
        )
        self.assertEquals(1, success)
        self.assertEquals(1, len(failed))
        error = failed[0]
        self.assertEquals('42', error['index']['_id'])
        self.assertEquals('t', error['index']['_type'])
        self.assertEquals('i', error['index']['_index'])
        print(error['index']['error'])
        self.assertTrue('MapperParsingException' in repr(error['index']['error']) or 'mapper_parsing_exception' in repr(error['index']['error']))

    def test_error_is_raised(self):
        self.client.indices.create("i",
            {
                "mappings": {"t": {"properties": {"a": {"type": "integer"}}}},
                "settings": {"number_of_shards": 1, "number_of_replicas": 0}
            })
        self.client.cluster.health(wait_for_status="yellow")

        self.assertRaises(helpers.BulkIndexError, helpers.bulk,
            self.client,
            [{"a": 42}, {"a": "c"}],
            index="i",
            doc_type="t"
        )

    def test_errors_are_collected_properly(self):
        self.client.indices.create("i",
            {
                "mappings": {"t": {"properties": {"a": {"type": "integer"}}}},
                "settings": {"number_of_shards": 1, "number_of_replicas": 0}
            })
        self.client.cluster.health(wait_for_status="yellow")

        success, failed = helpers.bulk(
            self.client,
            [{"a": 42}, {"a": "c"}],
            index="i",
            doc_type="t",
            stats_only=True,
            raise_on_error=False
        )
        self.assertEquals(1, success)
        self.assertEquals(1, failed)

class TestScan(ElasticsearchTestCase):
    def test_order_can_be_preserved(self):
        bulk = []
        for x in range(100):
            bulk.append({"index": {"_index": "test_index", "_type": "answers", "_id": x}})
            bulk.append({"answer": x, "correct": x == 42})
        self.client.bulk(bulk, refresh=True)

        docs = list(helpers.scan(self.client, index="test_index", doc_type="answers", size=2, query={"sort": ["answer"]}, preserve_order=True))

        self.assertEquals(100, len(docs))
        self.assertEquals(list(map(str, range(100))), list(d['_id'] for d in docs))
        self.assertEquals(list(range(100)), list(d['_source']['answer'] for d in docs))

    def test_all_documents_are_read(self):
        bulk = []
        for x in range(100):
            bulk.append({"index": {"_index": "test_index", "_type": "answers", "_id": x}})
            bulk.append({"answer": x, "correct": x == 42})
        self.client.bulk(bulk, refresh=True)

        docs = list(helpers.scan(self.client, index="test_index", doc_type="answers", size=2))

        self.assertEquals(100, len(docs))
        self.assertEquals(set(map(str, range(100))), set(d['_id'] for d in docs))
        self.assertEquals(set(range(100)), set(d['_source']['answer'] for d in docs))

class TestReindex(ElasticsearchTestCase):
    def setUp(self):
        super(TestReindex, self).setUp()
        bulk = []
        for x in range(100):
            bulk.append({"index": {"_index": "test_index", "_type": "answers" if x % 2 == 0 else "questions", "_id": x}})
            bulk.append({"answer": x, "correct": x == 42})
        self.client.bulk(bulk, refresh=True)

    def test_reindex_passes_kwargs_to_scan_and_bulk(self):
        helpers.reindex(self.client, "test_index", "prod_index", scan_kwargs={'doc_type': 'answers'}, bulk_kwargs={'refresh': True})

        self.assertTrue(self.client.indices.exists("prod_index"))
        self.assertFalse(self.client.indices.exists_type(index='prod_index', doc_type='questions'))
        self.assertEquals(50, self.client.count(index='prod_index', doc_type='answers')['count'])

        self.assertEquals({"answer": 42, "correct": True}, self.client.get(index="prod_index", doc_type="answers", id=42)['_source'])

    def test_reindex_accepts_a_query(self):
        helpers.reindex(self.client, "test_index", "prod_index", query={"query": {"filtered": {"filter": {"term": {"_type": "answers"}}}}})
        self.client.indices.refresh()

        self.assertTrue(self.client.indices.exists("prod_index"))
        self.assertFalse(self.client.indices.exists_type(index='prod_index', doc_type='questions'))
        self.assertEquals(50, self.client.count(index='prod_index', doc_type='answers')['count'])

        self.assertEquals({"answer": 42, "correct": True}, self.client.get(index="prod_index", doc_type="answers", id=42)['_source'])

    def test_all_documents_get_moved(self):
        helpers.reindex(self.client, "test_index", "prod_index")
        self.client.indices.refresh()

        self.assertTrue(self.client.indices.exists("prod_index"))
        self.assertEquals(50, self.client.count(index='prod_index', doc_type='questions')['count'])
        self.assertEquals(50, self.client.count(index='prod_index', doc_type='answers')['count'])

        self.assertEquals({"answer": 42, "correct": True}, self.client.get(index="prod_index", doc_type="answers", id=42)['_source'])

class TestParentChildReindex(ElasticsearchTestCase):
    def setUp(self):
        super(TestParentChildReindex, self).setUp()
        body={
            'settings': {"number_of_shards": 1, "number_of_replicas": 0},
            'mappings': {
                'question': {
                },
                'answer': {
                    '_parent': {'type': 'question'},
                }
            }
        }
        self.client.indices.create(index='test-index', body=body)
        self.client.indices.create(index='real-index', body=body)

        self.client.index(
            index='test-index',
            doc_type='question',
            id=42,
            body={},
        )
        self.client.index(
            index='test-index',
            doc_type='answer',
            id=47,
            body={'some': 'data'},
            parent=42
        )
        self.client.indices.refresh(index='test-index')

    def test_children_are_reindexed_correctly(self):
        helpers.reindex(self.client, 'test-index', 'real-index')

        q = self.client.get(
            index='real-index',
            doc_type='question',
            id=42,
            fields=['_source']
        )
        if 'fields' in q:
            q.update(q.pop('fields'))
        self.assertEquals(
            {
                '_id': '42',
                '_index': 'real-index',
                '_source': {},
                '_type': 'question',
                '_version': 1,
                'found': True
            }, q
        )
        q = self.client.get(
            index='test-index',
            doc_type='answer',
            id=47,
            parent=42,
            fields=['_source', '_parent']
        )
        if 'fields' in q:
            q.update(q.pop('fields'))
        if '_routing' in q:
            self.assertEquals(q.pop('_routing'), '42')
        self.assertEquals(
            {
                '_id': '47',
                '_index': 'test-index',
                '_source': {'some': 'data'},
                '_type': 'answer',
                '_version': 1,
                '_parent': '42',
                'found': True
            }, q
        )


text:
require 'spec_helper'

describe Embryo::Person, type: :model do
  it { is_expected.to belong_to(:gender) }
end


text:
<?php namespace Anomaly\FizlPages\Page\Command;

use Anomaly\FizlPages\Page\Contract\Page;

/**
 * Class LoadPageHeadersCommand
 *
 * @package Anomaly\FizlPages\Page\Command
 */
class LoadPageHeadersCommand
{

    /**
     * @var Page
     */
    protected $page;

    /**
     * @param Page $page
     */
    public function __construct(Page $page)
    {
        $this->page = $page;
    }

    /**
     * @return Page
     */
    public function getPage()
    {
        return $this->page;
    }

}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.21-9-c-ii-24
description: >
    Array.prototype.reduce - string primitive can be used as
    accumulator
---*/

        var accessed = false;
        function callbackfn(prevVal, curVal, idx, obj) {
            accessed = true;
            return prevVal === "hello_";
        }

        var obj = { 0: 11, length: 1 };

assert.sameValue(Array.prototype.reduce.call(obj, callbackfn, "hello_"), true, 'Array.prototype.reduce.call(obj, callbackfn, "hello_")');
assert(accessed, 'accessed !== true');


text:
using LabelPrinter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Collections.Generic;

namespace LabelPrinter.Test
{
    [TestClass()]
    public class LabelStorageTest
    {
        [TestMethod()]
        public void ReadSaveTest()
        {
            var labels = new[] {
                new Label("Addressee 1", 124323, "Address 1", "City 1"),
                new Label("Addressee 2", 324536, "Address 2", "City 2"),
                new Label("Addressee 3", 676775, "Address 3", "City 3")
            };
            var file = "test1.labels";
            LabelStorage.Save(file, labels);

            var labels1 = LabelStorage.Read(file);
            Assert.IsTrue(labels1
                .Zip(labels, (l1, l) => l1.Address == l.Address
                                     && l1.Addressee == l.Addressee
                                     && l1.PostalCode == l.PostalCode
                                     && l1.City == l.City)
                .All(it => it));
        }
    }
}


text:
package org.itevents.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.itevents.controller.converter.FilterConverter;
import org.itevents.controller.wrapper.FilterWrapper;
import org.itevents.dao.model.Event;
import org.itevents.dao.model.User;
import org.itevents.service.EventService;
import org.itevents.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.sql.SQLException;
import java.util.List;

@RestController
@Api("Events")
@RequestMapping("/events")
@Validated
public class EventRestController {
    @Inject
    private EventService eventService;
    @Inject
    private UserService userService;
    @Inject
    private FilterConverter filterConverter;

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    @ApiOperation(value = "Returns one event with the given id")
    public Event getEventById(@PathVariable("id") int id) {
        return eventService.getEvent(id);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "Returns events with the given parameters ")
    public List<Event> getFilteredEvents(@ModelAttribute FilterWrapper wrapper) throws SQLException {
        return eventService.getFilteredEvents(filterConverter.toFilter(wrapper));
    }

    @RequestMapping(method = RequestMethod.POST, value = "/{event_id}/assign")
    @ApiOperation(value = "Assigns logged in user to event")
    @ResponseStatus(value = HttpStatus.OK)
    public void assign(@PathVariable("event_id") int futureEventId) {
        eventService.assignAuthorizedUserToEvent(futureEventId);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/{event_id}/unassign")
    @ApiOperation(value = "Unassigns logged in user from event")
    @ResponseStatus(value = HttpStatus.OK)
    public void unassign(
            @PathVariable("event_id") int futureEventId,
            @Length(max = 250)
            @RequestParam("unassign_reason")
            String unassignReason ) {
        eventService.unassignAuthorizedUserFromEvent(futureEventId, unassignReason);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{event_id}/visitors")
    @ApiOperation(value = "Returns list of visitors of event")
    @ResponseStatus(HttpStatus.OK)
    public List<User> getUsersByEvent(@PathVariable("event_id") int id) {
        return userService.getUsersByEvent(id);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{event_id}/register")
    @ApiOperation(value = "Redirects to to given event page")
    @ResponseStatus(HttpStatus.OK)
    public String redirectToEventSite(@PathVariable("event_id") int eventId) {
        return eventService.redirectToEventSite(eventId);
    }
}


text:
<?php
/**
 * The header for our theme.
 *
 * Displays all of the  section and everything up till

 *
 * @package PMP Megaphone
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

<?php wp_head(); ?>

<body <?php body_class(); ?>>

	<?php esc_html_e( 'Skip to content', 'pmp_megaphone' ); ?>

				<?php if (get_theme_mod('station_logo')) :?>

					<a href="<?php echo esc_url(get_theme_mod('station_link')) ;?>"><img src="<?php echo esc_url(get_theme_mod('station_logo')) ;?>" alt="<?php echo get_theme_mod('station_callsign') ;?> logo" title="<?php echo get_theme_mod('station_callsign') ;?>" />

				<?php endif; ?>

					<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Menu', 'pmp_megaphone' ); ?></button>
					<button class="search-toggle" aria-controls="primary-search" aria-expanded="false"><?php esc_html_e( 'Search', 'pmp_megaphone' ); ?></button>

				<?php if (get_theme_mod('station_logo')) :?>

					<a href="<?php echo esc_url(get_theme_mod('station_link')) ;?>"><img src="<?php echo esc_url(get_theme_mod('station_logo')) ;?>" alt="<?php echo get_theme_mod('station_callsign') ;?> logo" title="<?php echo get_theme_mod('station_callsign') ;?>" />

				<?php endif; ?>
				<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?>
				<?php if ( is_active_sidebar( 'nav-right-1' ) ) :?>

					<?php dynamic_sidebar( 'nav-right-1' ); ?>

				<?php endif; ?>

				<?php if ( get_header_image() ) : ?>
				<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
					<img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="">

				<?php else : ?>
					<?php if ( is_front_page() && is_home() ) : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

					<?php else : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

					<?php endif; ?>
				<?php endif; // End header image check. ?>


text:
import sys,os,requests,re,glob

############ getfiledoi.py part
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice, TagExtractor
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.cmapdb import CMapDB
from pdfminer.layout import LAParams
from pdfminer.image import ImageWriter

class stdmodel(object):
	'''a class to model stdout for pdfminer file parameter
	Can get context use get() method'''

	# saved string
	_str=""

	def __str__(self):
		return self._str

	def reset(self):
		'''Reset the saved string'''
		self._str=""
	def get(self):
		'''Get the saved string'''
		return self._str

	def write(self,line):
		'''model write method of file'''
		self._str+=line

	def open(self,*args):
		'''model open method of file'''
		self._str=""

	def close(self):
		'''model close method of file'''
		self._str=""

	def read(self):
		'''model read method of file'''
		return self._str

####### Setup for pdfminer ############

# debug option
debug = 0
PDFDocument.debug = debug
PDFParser.debug = debug
CMapDB.debug = debug
PDFResourceManager.debug = debug
PDFPageInterpreter.debug = debug
PDFDevice.debug = debug

#only first page
pagenos=set([0])
pageno = 1

#outfp = sys.stdout
outfp = stdmodel()

codec = 'utf-8'
showpageno = True
scale = 1
password = ''
maxpages = 0
rotation = 0
imagewriter = None
laparams = LAParams()

# ResourceManager facilitates reuse of shared resources
# such as fonts and images so that large objects are not
# allocated multiple times.
#### This will cause some problem when set to default True.
caching = False
rsrcmgr = PDFResourceManager(caching=caching)

# Important Main converter for pdf file
device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams,
                               imagewriter=imagewriter)

####### Functions for read doi ############

def GetFirstPage(fname):
	'''Get First Page contents of PDF, return string'''
	fp = file(fname, 'rb')
	interpreter = PDFPageInterpreter(rsrcmgr, device)
	for page in PDFPage.get_pages(fp, pagenos,
	                              maxpages=maxpages, password=password,
	                              caching=caching, check_extractable=True):
		page.rotate = (page.rotate+rotation) % 360
		interpreter.process_page(page)
	fp.close()
	outstr=outfp.get()
	outfp.reset()
	return outstr

# avoid repeat generate doipattern
doipattern=re.compile("\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\|\"&\'<>])\\S)+)(?:\+?|\\b)")

def getdoi(instr):
	'''Get DOI number of input string'''
	match=doipattern.search(instr)
	if (match):
		return match.group()
	else:
		return ""

def getfiledoi(fname):
	'''Get DOI number from first page of PDF.
	If not found, return "" '''
	outs=GetFirstPage(fname)
	return getdoi(outs)

def getfilepossibledoi(fname):
	'''Get possible doi (list) from first page
	If not found, return []'''
	outs=GetFirstPage(fname)
	return doipattern.findall(outs)

def doirenamefile(fname, doi):
	'''Rename file based on doi number'''
	realdoi=getdoi(doi)
	if ( realdoi is not "" ):
		fnames=os.path.split(os.path.abspath(fname))
		newname=realdoi.replace("/","@")+".pdf"
		if (os.path.exists(fnames[0]+os.sep+newname)):
			print 'Same name? for '+fname+" doi: "+realdoi
			return
		os.renames(fname,
			fnames[0]+os.sep+newname)
	#else don't rename it

####### End getfiledoi.py part #############

pdoiwebt=re.compile(r"<title>.*?</title>")
#pdoiweba=re.compile(r'(?<=<a href=")http.*?(?=">)')
def checkdoiweb(doi):
	'''Check whether valid doi by doi.org'''
	doi=doi.strip().lower()
	if (doi.find("10.")!=0):
		return False
	link="http://dx.doi.org/"+doi
	r=requests.get(link,allow_redirects=False)
	title=pdoiwebt.search(r.text).group().lower()
	if ("redirect" in title):
		return True
	return False

if __name__=="__main__":
	if (not os.path.exists("FailDOI")): os.makedirs("FailDOI")
	if (not os.path.exists("FailDOI/Unknown")): os.makedirs("FailDOI/Unknown")
	if (not os.path.exists("Done")): os.makedirs("Done")
	fglob=glob.iglob("10.*.pdf")
	for fname in fglob:
		fnamelist=os.path.splitext(fname)
		doi=fnamelist[0].replace('@','/').lower()
		#check rational doi
		if (not checkdoiweb(doi)):
			print "Error: Fail DOI: "+doi
			os.renames(fname,"FailDOI/"+fname)
			continue
		#check doi in file
		finddoi=getfilepossibledoi(fname)
		if (not doi in finddoi):
			print "Error: Fail find DOI "+doi+" in PDF: "+str(finddoi)
			os.renames(fname,"FailDOI/Unknown/"+fname)
		else:
			os.renames(fname,"Done/"+fname)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Voy. Indes Or. , Bot. 2: 154 (1834)

#### Original name
Exidia polytricha Mont., 1834

### Remarks
null


text:
package controllers

import play.api._
import play.api.mvc._
import org.jsoup.Jsoup

import collection.immutable._

import play.api.db.DB
import anorm._
import anorm.SqlParser._
import play.api.Play.current
import models._

import play.api.data._
import play.api.data.Forms._

import collection.JavaConversions._

object BondETF extends Controller {
   val bondportfolio = {
     get[Long]("id") ~
     get[String]("symbol") ~
     get[String]("descr") map {
      case id~symbol~descr => BondPortfolio(id, symbol, descr, 1.0f)
     }
   }

   def all(): List[BondPortfolio] = DB.withConnection { implicit c =>
      SQL("select * from bondportfolio").as(bondportfolio *)
   }

   def show(symbol: String) = Action {

     Ok("Bond ETF " + symbol + all())
   }

   val bondPortfolioForm = Form(
      tuple(
        "symbol" -> nonEmptyText,
        "descr" -> nonEmptyText
      )
   )

   def bondportfolios() = Action {
      val portfolios = all()
      val rates = portfolios.map(p => (p.symbol, Application.etfYield(p.symbol))).toMap
      Ok(views.html.bondportfolios(portfolios, rates, bondPortfolioForm))
   }

   def newBondPortfolio() = Action { implicit req =>
     bondPortfolioForm.bindFromRequest.fold(
       errors => BadRequest(views.html.bondportfolios(all(), Map.empty, errors)),
       x => {
             BondPortfolio.create(x._1, x._2, 4.0f)
             Redirect(routes.BondETF.bondportfolios)
       })
   }
}


text:
package org.elasticsearch.transport;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.network.HandlingTimeTracker;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.network.NetworkUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.MockPageCacheRecycler;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.MockLogAppender;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.hamcrest.Matcher;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsInstanceOf.instanceOf;

/** Unit tests for {@link TcpTransport} */
public class TcpTransportTests extends ESTestCase {

    /** Test ipv4 host with a default port works */
    public void testParseV4DefaultPort() throws Exception {
        TransportAddress[] addresses = TcpTransport.parse("127.0.0.1", 1234);
        assertEquals(1, addresses.length);

        assertEquals("127.0.0.1", addresses[0].getAddress());
        assertEquals(1234, addresses[0].getPort());
    }

    /** Test ipv4 host with port works */
    public void testParseV4WithPort() throws Exception {
        TransportAddress[] addresses = TcpTransport.parse("127.0.0.1:2345", 1234);
        assertEquals(1, addresses.length);

        assertEquals("127.0.0.1", addresses[0].getAddress());
        assertEquals(2345, addresses[0].getPort());
    }

    /** Test unbracketed ipv6 hosts in configuration fail. Leave no ambiguity */
    public void testParseV6UnBracketed() throws Exception {
        try {
            TcpTransport.parse("::1", 1234);
            fail("should have gotten exception");
        } catch (IllegalArgumentException expected) {
            assertTrue(expected.getMessage().contains("must be bracketed"));
        }
    }

    /** Test ipv6 host with a default port works */
    public void testParseV6DefaultPort() throws Exception {
        TransportAddress[] addresses = TcpTransport.parse("[::1]", 1234);
        assertEquals(1, addresses.length);

        assertEquals("::1", addresses[0].getAddress());
        assertEquals(1234, addresses[0].getPort());
    }

    /** Test ipv6 host with port works */
    public void testParseV6WithPort() throws Exception {
        TransportAddress[] addresses = TcpTransport.parse("[::1]:2345", 1234);
        assertEquals(1, addresses.length);

        assertEquals("::1", addresses[0].getAddress());
        assertEquals(2345, addresses[0].getPort());
    }

    public void testRejectsPortRanges() {
        expectThrows(NumberFormatException.class, () -> TcpTransport.parse("[::1]:100-200", 1000));
    }

    public void testDefaultSeedAddressesWithDefaultPort() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder(
                "[::1]:9300",
                "[::1]:9301",
                "[::1]:9302",
                "[::1]:9303",
                "[::1]:9304",
                "[::1]:9305",
                "127.0.0.1:9300",
                "127.0.0.1:9301",
                "127.0.0.1:9302",
                "127.0.0.1:9303",
                "127.0.0.1:9304",
                "127.0.0.1:9305"
            )
            : containsInAnyOrder(
                "127.0.0.1:9300",
                "127.0.0.1:9301",
                "127.0.0.1:9302",
                "127.0.0.1:9303",
                "127.0.0.1:9304",
                "127.0.0.1:9305"
            );
        testDefaultSeedAddresses(Settings.EMPTY, seedAddressMatcher);
    }

    public void testDefaultSeedAddressesWithNonstandardGlobalPortRange() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder(
                "[::1]:9500",
                "[::1]:9501",
                "[::1]:9502",
                "[::1]:9503",
                "[::1]:9504",
                "[::1]:9505",
                "127.0.0.1:9500",
                "127.0.0.1:9501",
                "127.0.0.1:9502",
                "127.0.0.1:9503",
                "127.0.0.1:9504",
                "127.0.0.1:9505"
            )
            : containsInAnyOrder(
                "127.0.0.1:9500",
                "127.0.0.1:9501",
                "127.0.0.1:9502",
                "127.0.0.1:9503",
                "127.0.0.1:9504",
                "127.0.0.1:9505"
            );
        testDefaultSeedAddresses(Settings.builder().put(TransportSettings.PORT.getKey(), "9500-9600").build(), seedAddressMatcher);
    }

    public void testDefaultSeedAddressesWithSmallGlobalPortRange() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder("[::1]:9300", "[::1]:9301", "[::1]:9302", "127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302")
            : containsInAnyOrder("127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302");
        testDefaultSeedAddresses(Settings.builder().put(TransportSettings.PORT.getKey(), "9300-9302").build(), seedAddressMatcher);
    }

    public void testDefaultSeedAddressesWithNonstandardProfilePortRange() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder(
                "[::1]:9500",
                "[::1]:9501",
                "[::1]:9502",
                "[::1]:9503",
                "[::1]:9504",
                "[::1]:9505",
                "127.0.0.1:9500",
                "127.0.0.1:9501",
                "127.0.0.1:9502",
                "127.0.0.1:9503",
                "127.0.0.1:9504",
                "127.0.0.1:9505"
            )
            : containsInAnyOrder(
                "127.0.0.1:9500",
                "127.0.0.1:9501",
                "127.0.0.1:9502",
                "127.0.0.1:9503",
                "127.0.0.1:9504",
                "127.0.0.1:9505"
            );
        testDefaultSeedAddresses(
            Settings.builder()
                .put(TransportSettings.PORT_PROFILE.getConcreteSettingForNamespace(TransportSettings.DEFAULT_PROFILE).getKey(), "9500-9600")
                .build(),
            seedAddressMatcher
        );
    }

    public void testDefaultSeedAddressesWithSmallProfilePortRange() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder("[::1]:9300", "[::1]:9301", "[::1]:9302", "127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302")
            : containsInAnyOrder("127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302");
        testDefaultSeedAddresses(
            Settings.builder()
                .put(TransportSettings.PORT_PROFILE.getConcreteSettingForNamespace(TransportSettings.DEFAULT_PROFILE).getKey(), "9300-9302")
                .build(),
            seedAddressMatcher
        );
    }

    public void testDefaultSeedAddressesPrefersProfileSettingToGlobalSetting() {
        final Matcher<Iterable<? extends String>> seedAddressMatcher = NetworkUtils.SUPPORTS_V6
            ? containsInAnyOrder("[::1]:9300", "[::1]:9301", "[::1]:9302", "127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302")
            : containsInAnyOrder("127.0.0.1:9300", "127.0.0.1:9301", "127.0.0.1:9302");
        testDefaultSeedAddresses(
            Settings.builder()
                .put(TransportSettings.PORT_PROFILE.getConcreteSettingForNamespace(TransportSettings.DEFAULT_PROFILE).getKey(), "9300-9302")
                .put(TransportSettings.PORT.getKey(), "9500-9600")
                .build(),
            seedAddressMatcher
        );
    }

    public void testDefaultSeedAddressesWithNonstandardSinglePort() {
        testDefaultSeedAddresses(
            Settings.builder().put(TransportSettings.PORT.getKey(), "9500").build(),
            NetworkUtils.SUPPORTS_V6 ? containsInAnyOrder("[::1]:9500", "127.0.0.1:9500") : containsInAnyOrder("127.0.0.1:9500")
        );
    }

    private void testDefaultSeedAddresses(final Settings settings, Matcher<Iterable<? extends String>> seedAddressesMatcher) {
        final TestThreadPool testThreadPool = new TestThreadPool("test");
        try {
            final TcpTransport tcpTransport = new TcpTransport(
                settings,
                Version.CURRENT,
                testThreadPool,
                new MockPageCacheRecycler(settings),
                new NoneCircuitBreakerService(),
                writableRegistry(),
                new NetworkService(Collections.emptyList())
            ) {
                @Override
                protected void doStart() {
                    throw new UnsupportedOperationException();
                }

                @Override
                protected TcpServerChannel bind(String name, InetSocketAddress address) {
                    throw new UnsupportedOperationException();
                }

                @Override
                protected TcpChannel initiateChannel(DiscoveryNode node) {
                    throw new UnsupportedOperationException();
                }

                @Override
                protected void stopInternal() {
                    throw new UnsupportedOperationException();
                }
            };

            assertThat(tcpTransport.getDefaultSeedAddresses(), seedAddressesMatcher);
        } finally {
            testThreadPool.shutdown();
        }
    }

    public void testReadMessageLengthWithIncompleteHeader() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('S');
        streamOutput.write(1);
        streamOutput.write(1);

        assertEquals(-1, TcpTransport.readMessageLength(streamOutput.bytes()));
    }

    public void testReadPingMessageLength() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('S');
        streamOutput.writeInt(-1);

        assertEquals(0, TcpTransport.readMessageLength(streamOutput.bytes()));
    }

    public void testReadPingMessageLengthWithStartOfSecondMessage() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('S');
        streamOutput.writeInt(-1);
        streamOutput.write('E');
        streamOutput.write('S');

        assertEquals(0, TcpTransport.readMessageLength(streamOutput.bytes()));
    }

    public void testReadMessageLength() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('S');
        streamOutput.writeInt(2);
        streamOutput.write('M');
        streamOutput.write('A');

        assertEquals(2, TcpTransport.readMessageLength(streamOutput.bytes()));

    }

    public void testInvalidLength() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('S');
        streamOutput.writeInt(-2);
        streamOutput.write('M');
        streamOutput.write('A');

        try {
            TcpTransport.readMessageLength(streamOutput.bytes());
            fail("Expected exception");
        } catch (Exception ex) {
            assertThat(ex, instanceOf(StreamCorruptedException.class));
            assertEquals("invalid data length: -2", ex.getMessage());
        }
    }

    public void testInvalidHeader() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('E');
        streamOutput.write('C');
        byte byte1 = randomByte();
        byte byte2 = randomByte();
        streamOutput.write(byte1);
        streamOutput.write(byte2);
        streamOutput.write(randomByte());
        streamOutput.write(randomByte());
        streamOutput.write(randomByte());

        try {
            TcpTransport.readMessageLength(streamOutput.bytes());
            fail("Expected exception");
        } catch (Exception ex) {
            assertThat(ex, instanceOf(StreamCorruptedException.class));
            String expected = "invalid internal transport message format, got (45,43,"
                + Integer.toHexString(byte1 & 0xFF)
                + ","
                + Integer.toHexString(byte2 & 0xFF)
                + ")";
            assertEquals(expected, ex.getMessage());
        }
    }

    public void testHTTPRequest() throws IOException {
        String[] httpHeaders = { "GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "PATCH", "TRACE" };

        for (String httpHeader : httpHeaders) {
            BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);

            for (char c : httpHeader.toCharArray()) {
                streamOutput.write((byte) c);
            }
            streamOutput.write(new byte[6]);

            try {
                TcpTransport.readMessageLength(streamOutput.bytes());
                fail("Expected exception");
            } catch (Exception ex) {
                assertThat(ex, instanceOf(TcpTransport.HttpRequestOnTransportException.class));
                assertEquals("This is not an HTTP port", ex.getMessage());
            }
        }
    }

    public void testTLSHeader() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);

        streamOutput.write(0x16);
        streamOutput.write(0x03);
        byte byte1 = randomByte();
        streamOutput.write(byte1);
        byte byte2 = randomByte();
        streamOutput.write(byte2);
        streamOutput.write(randomByte());
        streamOutput.write(randomByte());
        streamOutput.write(randomByte());

        try {
            TcpTransport.readMessageLength(streamOutput.bytes());
            fail("Expected exception");
        } catch (Exception ex) {
            assertThat(ex, instanceOf(StreamCorruptedException.class));
            String expected = "SSL/TLS request received but SSL/TLS is not enabled on this node, got (16,3,"
                + Integer.toHexString(byte1 & 0xFF)
                + ","
                + Integer.toHexString(byte2 & 0xFF)
                + ")";
            assertEquals(expected, ex.getMessage());
        }
    }

    public void testHTTPResponse() throws IOException {
        BytesStreamOutput streamOutput = new BytesStreamOutput(1 << 14);
        streamOutput.write('H');
        streamOutput.write('T');
        streamOutput.write('T');
        streamOutput.write('P');
        streamOutput.write(randomByte());
        streamOutput.write(randomByte());

        try {
            TcpTransport.readMessageLength(streamOutput.bytes());
            fail("Expected exception");
        } catch (Exception ex) {
            assertThat(ex, instanceOf(StreamCorruptedException.class));
            assertEquals(
                "received HTTP response on transport port, ensure that transport port "
                    + "(not HTTP port) of a remote node is specified in the configuration",
                ex.getMessage()
            );
        }
    }

    @TestLogging(reason = "testing logging", value = "org.elasticsearch.transport.TcpTransport:INFO")
    public void testInfoExceptionHandling() throws IllegalAccessException {
        testExceptionHandling(
            false,
            new ElasticsearchException("simulated"),
            true,
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.ERROR, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.WARN, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.INFO, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.DEBUG, "*")
        );

        testExceptionHandling(
            new ElasticsearchException("simulated"),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.WARN,
                "exception caught on transport layer [*], closing connection"
            )
        );

        for (final String message : new String[] {
            "Connection timed out",
            "Connection reset",
            "Broken pipe",
            "An established connection was aborted by the software in your host machine",
            "An existing connection was forcibly closed by remote host" }) {
            testExceptionHandling(
                new ElasticsearchException(message),
                new MockLogAppender.SeenEventExpectation(
                    message,
                    "org.elasticsearch.transport.TcpTransport",
                    Level.INFO,
                    "close connection exception caught on transport layer [*], disconnecting from relevant node: " + message
                )
            );
        }
    }

    @TestLogging(reason = "testing logging", value = "org.elasticsearch.transport.TcpTransport:DEBUG")
    public void testDebugExceptionHandling() throws IllegalAccessException {
        testExceptionHandling(
            false,
            new ElasticsearchException("simulated"),
            true,
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.ERROR, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.WARN, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.INFO, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.DEBUG, "*")
        );
        testExceptionHandling(
            new ElasticsearchException("simulated"),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.WARN,
                "exception caught on transport layer [*], closing connection"
            )
        );
        testExceptionHandling(
            new ClosedChannelException(),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.DEBUG,
                "close connection exception caught on transport layer [*], disconnecting from relevant node"
            )
        );

        // INFO leve
        for (final String message : new String[] {
            "Connection timed out",
            "Connection reset",
            "Broken pipe",
            "An established connection was aborted by the software in your host machine",
            "An existing connection was forcibly closed by remote host" }) {
            testExceptionHandling(
                new ElasticsearchException(message),
                new MockLogAppender.SeenEventExpectation(
                    message,
                    "org.elasticsearch.transport.TcpTransport",
                    Level.INFO,
                    "close connection exception caught on transport layer [*], disconnecting from relevant node"
                )
            );
        }

        // DEBUG level
        for (final String message : new String[] { "Socket is closed", "Socket closed", "SSLEngine closed already" }) {
            testExceptionHandling(
                new ElasticsearchException(message),
                new MockLogAppender.SeenEventExpectation(
                    message,
                    "org.elasticsearch.transport.TcpTransport",
                    Level.DEBUG,
                    "close connection exception caught on transport layer [*], disconnecting from relevant node"
                )
            );
        }

        testExceptionHandling(
            new BindException(),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.DEBUG,
                "bind exception caught on transport layer [*]"
            )
        );
        testExceptionHandling(
            new CancelledKeyException(),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.DEBUG,
                "cancelled key exception caught on transport layer [*], disconnecting from relevant node"
            )
        );
        testExceptionHandling(
            true,
            new TcpTransport.HttpRequestOnTransportException("test"),
            false,
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.ERROR, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.WARN, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.INFO, "*"),
            new MockLogAppender.UnseenEventExpectation("message", "org.elasticsearch.transport.TcpTransport", Level.DEBUG, "*")
        );
        testExceptionHandling(
            new StreamCorruptedException("simulated"),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.WARN,
                "simulated, [*], closing connection"
            )
        );
        testExceptionHandling(
            new TransportNotReadyException(),
            new MockLogAppender.SeenEventExpectation(
                "message",
                "org.elasticsearch.transport.TcpTransport",
                Level.DEBUG,
                "transport not ready yet to handle incoming requests on [*], closing connection"
            )
        );
    }

    private void testExceptionHandling(Exception exception, MockLogAppender.LoggingExpectation... expectations)
        throws IllegalAccessException {
        testExceptionHandling(true, exception, true, expectations);
    }

    private void testExceptionHandling(
        boolean startTransport,
        Exception exception,
        boolean expectClosed,
        MockLogAppender.LoggingExpectation... expectations
    ) throws IllegalAccessException {
        final TestThreadPool testThreadPool = new TestThreadPool("test");
        MockLogAppender appender = new MockLogAppender();

        try {
            appender.start();

            Loggers.addAppender(LogManager.getLogger(TcpTransport.class), appender);
            for (MockLogAppender.LoggingExpectation expectation : expectations) {
                appender.addExpectation(expectation);
            }

            final Lifecycle lifecycle = new Lifecycle();

            if (startTransport) {
                lifecycle.moveToStarted();
            }

            final FakeTcpChannel channel = new FakeTcpChannel();
            final PlainActionFuture<Void> listener = new PlainActionFuture<>();
            channel.addCloseListener(listener);

            TcpTransport.handleException(
                channel,
                exception,
                lifecycle,
                new OutboundHandler(
                    randomAlphaOfLength(10),
                    Version.CURRENT,
                    new StatsTracker(),
                    testThreadPool,
                    new BytesRefRecycler(new MockPageCacheRecycler(Settings.EMPTY)),
                    new HandlingTimeTracker()
                )
            );

            if (expectClosed) {
                assertTrue(listener.isDone());
                assertThat(listener.actionGet(), nullValue());
            } else {
                assertFalse(listener.isDone());
            }

            appender.assertAllExpectationsMatched();

        } finally {
            Loggers.removeAppender(LogManager.getLogger(TcpTransport.class), appender);
            appender.stop();
            ThreadPool.terminate(testThreadPool, 30, TimeUnit.SECONDS);
        }
    }
}


text:
import unittest

from wds.igor.job import JobBuilder, JobStatus, Job
from mock import Mock
from uuid import uuid4

class JobTest (unittest.TestCase):

    def test_can_create_a_job(self):
        json = {'projects': [{'name': 'project1', 's3_path': 'folder1/project1',
                                                      'artifact': 'project1-v57.tgz',
                                                      'version': 'v57', 'type': 'maven', 'folder': 'folderName'},
                                                     {'name': 'project2', 's3_path': 'folder2/project2',
                                                      'artifact': 'project2-v189.tgz',
                                                      'version': 'v189', 'type': 'play', 'folder': 'folderName'}]}
        jobs = JobBuilder.build_jobs(json)
        self.assertEquals(2, len(jobs))
        self.assertEquals(JobStatus.pending, jobs[0].get_status())
        self.assertEquals(JobStatus.pending, jobs[1].get_status())

        self.assertEquals({'name': 'project1', 's3_path': 'folder1/project1', 'artifact': 'project1-v57.tgz',
                           'version': 'v57', 'type': 'maven', 'folder': 'folderName'}, jobs[0].get_project())
        self.assertEquals({'name': 'project2', 's3_path': 'folder2/project2', 'artifact': 'project2-v189.tgz',
                           'version': 'v189', 'type': 'play', 'folder': 'folderName'}, jobs[1].get_project())

        self.assertTrue(jobs[0].get_id() is not None)
        self.assertTrue(jobs[1].get_id() is not None)

        self.assertNotEqual(jobs[0].get_id, jobs[1].get_id)
        self.assertRegexpMatches(str(jobs[0]), "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}")
        self.assertRegexpMatches(str(jobs[0]), "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}")

    def test_we_can_update_the_status_of_a_job(self):
        unit = Job(None)
        self.assertEquals(JobStatus.pending, unit.get_status())
        unit.set_status(JobStatus.done)
        self.assertEquals(JobStatus.done, unit.get_status())
        unit.set_status(JobStatus.failed)
        self.assertEquals(JobStatus.failed, unit.get_status())


text:
package org.apache.flink.runtime.jobmaster.slotpool;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;

/**
 * This class tracks a fulfillability timeout of a bulk of physical slot requests.
 *
 * <p>The check stops when all pending physical slot requests of {@link PhysicalSlotRequestBulk} are fulfilled
 * by available or newly allocated slots. The bulk is fulfillable if all its physical slot requests can be fulfilled
 * either by available or newly allocated slots or slots which currently used by other job subtasks.
 * The bulk gets canceled if the timeout occurs and the bulk is not fulfillable.
 * The timeout timer is not running while the bulk is fulfillable but not fulfilled yet.
 */
public interface PhysicalSlotRequestBulkChecker {
	/**
	 * Starts the bulk checker by initializing the main thread executor.
	 *
	 * @param mainThreadExecutor the main thread executor of the job master
	 */
	void start(ComponentMainThreadExecutor mainThreadExecutor);

	/**
	 * Starts tracking the fulfillability of a {@link PhysicalSlotRequestBulk} with timeout.
	 *
	 * @param bulk {@link PhysicalSlotRequestBulk} to track
	 * @param timeout timeout after which the bulk should be canceled if it is still not fulfillable.
	 */
	void schedulePendingRequestBulkTimeoutCheck(PhysicalSlotRequestBulk bulk, Time timeout);
}


text:
using System;
using Azure.Core;

namespace Azure.ResourceManager.DataProtectionBackup.Models
{
    /// <summary> Class encapsulating target details, used where the destination is not a datasource. </summary>
    public partial class RestoreFilesTargetDetails
    {
        /// <summary> Initializes a new instance of RestoreFilesTargetDetails. </summary>
        /// <param name="filePrefix">
        /// Restore operation may create multiple files inside location pointed by Url
        /// Below will be the common prefix for all of them
        /// </param>
        /// <param name="restoreTargetLocationType">
        /// Denotes the target location where the data will be restored,
        /// string value for the enum {Microsoft.Internal.AzureBackup.DataProtection.Common.Interface.RestoreTargetLocationType}
        /// </param>
        /// <param name="uri"> Url denoting the restore destination. It can point to container / file share etc. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="filePrefix"/> or <paramref name="uri"/> is null. </exception>
        public RestoreFilesTargetDetails(string filePrefix, RestoreTargetLocationType restoreTargetLocationType, Uri uri)
        {
            Argument.AssertNotNull(filePrefix, nameof(filePrefix));
            Argument.AssertNotNull(uri, nameof(uri));

            FilePrefix = filePrefix;
            RestoreTargetLocationType = restoreTargetLocationType;
            Uri = uri;
        }

        /// <summary>
        /// Restore operation may create multiple files inside location pointed by Url
        /// Below will be the common prefix for all of them
        /// </summary>
        public string FilePrefix { get; }
        /// <summary>
        /// Denotes the target location where the data will be restored,
        /// string value for the enum {Microsoft.Internal.AzureBackup.DataProtection.Common.Interface.RestoreTargetLocationType}
        /// </summary>
        public RestoreTargetLocationType RestoreTargetLocationType { get; }
        /// <summary> Url denoting the restore destination. It can point to container / file share etc. </summary>
        public Uri Uri { get; }
    }
}


text:
layout: post
title: "High resolution DLI maps of the United States"
share-img: "https://c2.staticflickr.com/6/5610/15552816385_9fac3dffd6_b_d.jpg"
tags: [light, climate]
---

James Faust and Joanne Logan wrote a review of daily light integral (DLI) in the [September issue of *HortScience*](https://dx.doi.org/10.21273/HORTSCI13144-18).

They have also prepared [high resolution maps of the United States](https://arcg.is/X4G4K). If you click on a location on the map, a table and chart will display with the average annual and monthly DLI.

<iframe width="100%" height="800px" src="https://webgis.coe.clemson.edu/storymaps/light-integral-map/" frameborder="0" scrolling="no"></iframe>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using ZimmerBot.Core.Knowledge;
using ZimmerBot.Core.Statements;

namespace ZimmerBot.Core.Tests.ConfigParser
{
  [TestFixture]
  public class OutputSequenceTests : TestHelper
  {
    [Test]
    public void CanParseOutputSequence()
    {
      StandardRule r = ParseRule(@"
> Yo
: First sentence.
+: Second sentence\
with a newline.
+: Third sentence.");

      Assert.AreEqual(1, r.Statements.Count);
      Assert.IsInstanceOf<OutputTemplateStatement>(r.Statements[0]);

      OutputTemplateStatement s = (OutputTemplateStatement)r.Statements[0];
      Assert.AreEqual(3, s.Template.Outputs.Count);
      Assert.AreEqual("default", s.Template.TemplateName);
      Assert.AreEqual("First sentence.", s.Template.Outputs[0]);
      Assert.AreEqual("Second sentence\nwith a newline.", s.Template.Outputs[1]);
      Assert.AreEqual("Third sentence.", s.Template.Outputs[2]);
    }

    [Test]
    public void CanParseNamedOutputSequence()
    {
      StandardRule r = ParseRule(@"
> Yo
{xxx}: First sentence.
+: Second sentence\
with a newline.
+: Third sentence.");

      Assert.AreEqual(1, r.Statements.Count);
      Assert.IsInstanceOf<OutputTemplateStatement>(r.Statements[0]);

      OutputTemplateStatement s = (OutputTemplateStatement)r.Statements[0];
      Assert.AreEqual(3, s.Template.Outputs.Count);
      Assert.AreEqual("xxx", s.Template.TemplateName);
      Assert.AreEqual("First sentence.", s.Template.Outputs[0]);
      Assert.AreEqual("Second sentence\nwith a newline.", s.Template.Outputs[1]);
      Assert.AreEqual("Third sentence.", s.Template.Outputs[2]);
    }
  }
}


text:
using LogBook.Entities;
using LogBook.Entities.Entities;
using LogBook.Services.Models;
using System;

namespace LogBook.Services.Internal
{
    internal class WriteService
    {
        #region Dependencies

        internal readonly LogBookEntityModel _context;

        internal WriteService(LogBookEntityModel context)
        {
            _context = context;
        }

        #endregion Dependencies

        internal void WriteLog(LogType logType, string source, Exception exception, string message, string userName)
        {
            var logEntry = new LogEntry
            {
                LogType = Convert.ToInt32(logType),
                HostName = Environment.MachineName,
                Source = source,
                Message = message,
                UserName = userName,
                LogTime = DateTime.Now
            };

            if (exception != null)
            {
                var logException = new LogException
                {
                    LogEntry = logEntry,
                    ExceptionDetail = exception.ToString()
                };

                _context.LogExceptions.Add(logException);
            }

            _context.LogEntries.Add(logEntry);

            _context.SaveChanges();
        }
    }
}


text:
using System;
using System.Collections.Generic;

public static class Program
{

  public static void Main(string[] args)
  {

    var slist = new List<string> { "zero", "one", "two", "three" };

    // collection test are already implemented in ListiCollection.cs

    // NOTE: JSIL is quite forgiving when implementing the interface - it does not take into account the returning parameter type
    //       so "object get_Item(i)" can also implement "T get_Item(int)". The listExternals implementation as a little bit
    //       loosey goosey. To be strict, different types of collection (ArrayList, List<T> should really have slightly
    //       different method signatures for get_item, set_Item and others - this is currenlty only partially covverred in JSIL.Bootsrap.js)
    Console.WriteLine("----- interface ----");

    var list = (IList<string>) slist;

    Console.WriteLine(list.Count);
    Console.WriteLine(list[0]);
    Console.WriteLine(list[1]);
    Console.WriteLine(list[2]);
    Console.WriteLine(list[3]);

    Console.WriteLine(list.IndexOf("two"));

    list.Insert(1,"inserted");
    Console.WriteLine(list.Count);
    Console.WriteLine(list[4]);

    list.RemoveAt(2);
    Console.WriteLine(list.Count);
    Console.WriteLine(list[3]);

    list[2] = "modified";
    Console.WriteLine(list[2]);

    // also check item acecssor throw class (not the interface)
    slist = new List<string> { "zero", "one", "two", "three" };

    Console.WriteLine("----- class ----");

    Console.WriteLine(slist.Count);
    Console.WriteLine(slist[0]);
    Console.WriteLine(slist[1]);
    Console.WriteLine(slist[2]);
    Console.WriteLine(slist[3]);

   Console.WriteLine(slist.IndexOf("two"));

    slist.Insert(1,"inserted");
    Console.WriteLine(slist.Count);
    Console.WriteLine(slist[4]);

    slist.RemoveAt(2);
    Console.WriteLine(slist.Count);
    Console.WriteLine(slist[3]);

    slist[2] = "modified";
    Console.WriteLine(slist[2]);

  }

}


text:
import numpy as np
import pandas as pd

from bokeh.plotting import figure, show, output_file
from bokeh.palettes import brewer

N = 20
categories = ['y' + str(x) for x in range(10)]
data = {}
data['x'] = np.arange(N)
for cat in categories:
    data[cat] = np.random.randint(10, 100, size=N)

df = pd.DataFrame(data)
df = df.set_index(['x'])

def stacked(df, categories):
    areas = dict()
    last = np.zeros(len(df[categories[0]]))
    for cat in categories:
        next = last + df[cat]
        areas[cat] = np.hstack((last[::-1], next))
        last = next
    return areas

areas = stacked(df, categories)

colors = brewer["Spectral"][len(areas)]

x2 = np.hstack((data['x'][::-1], data['x']))

p = figure(x_range=(0, 19), y_range=(0, 800))
p.grid.minor_grid_line_color = '#eeeeee'

p.patches([x2] * len(areas), [areas[cat] for cat in categories],
          color=colors, alpha=0.8, line_color=None)

output_file("brewer.html", title="brewer.py example")

show(p)


text:
package org.apache.hive.service.auth;

import org.junit.BeforeClass;

public class TestTrustDomainAuthenticationHttp extends TrustDomainAuthenticationTest {

    @BeforeClass
    public static void setUp() throws Exception {
        initialize(HS2_TRANSPORT_MODE_HTTP, true);
    }
}


text:
package com.veniosg.dir.mvvm.model.storage.operation;

import android.support.annotation.NonNull;

import java.io.File;

import static java.util.UUID.randomUUID;

public abstract class FileOperation<A extends FileOperation.Arguments> {
    protected final int id = randomUUID().hashCode();

    /**
     * @return Whether the operation was successful.
     */
    public abstract boolean operate(A args);

    /**
     * Try the operation using SAF facilities
     * Triggered if {@link #operate(Arguments)} returns false and we have write permissions.
     *
     * @return Whether the operation was successful.
     */
    public abstract boolean operateSaf(A args);

    /**
     * Good place to show initial UI, or prepare any dialogs etc.
     * Called right before running the operation. Can be called multiple times.
     *
     * @param args Original arguments for the invocation that is getting started.
     */
    abstract void onStartOperation(A args);

    /**
     * Good place to show final result (success/failure) UI.
     * No other callbacks will happen after this.
     *
     * @param success Whether the invocation was successful.
     * @param args    Original arguments for the invocation that just finished.
     */
    abstract void onResult(boolean success, A args);

    /**
     * Called if the user has denied storage write permissions on the parent volume of {@link Arguments#target}.
     * No other callbacks will happen after this.
     */
    abstract void onAccessDenied();

    /**
     * Good place to hide any progress UI. You may still get calls to onResult()/onAccessDenied() after this.
     */
    abstract void onRequestingAccess();

    /**
     * @return Whether this type of operation can fail because of lack of storage write permissions.
     */
    public abstract boolean needsWriteAccess();

    public static abstract class Arguments {
        @NonNull
        private final File target;

        protected Arguments(@NonNull File target) {
            this.target = target;
        }

        @NonNull
        protected File getTarget() {
            return target;
        }
    }
}


text:
<?php
App::uses('AppModel', 'Model');
/**
 * Task Model
 *
 */
class Task extends AppModel {
 public $actsAs = array('Containable');

public function afterFind($results, $primary = false) {
    foreach ($results as $key => $val) {
		if(isset($results[$key]['Task']['category'])){
        $results[$key]['Task']['category'] = explode(",",$val['Task']['category']);
		}
    }
    return $results;
}

private function isValidURL($url) { return (bool)parse_url($url); }
private function hrefify($url) {
    if($this->isValidURL($url)){
        return "" . $url . "";
    } else {
        return $url;
    }
}

public function beforeSave($options = array()) {
    if(isset( $this->data['Task']['category'])){
    $this->data['Task']['category'] = implode(",",$this->data['Task']['category']);
    }
    if(!(empty($this->data['Task']['background'])&&
        empty($this->data['Task']['action'])&&
        empty($this->data['Task']['references'])&&
        empty($this->data['Task']['modify']))){

    $back = $this->data['Task']['background'];
    $act = $this->data['Task']['action'];
    $ref = $this->data['Task']['references'];
    $mod = $this->data['Task']['modify'];
    $back = "
" . implode( "
\n\n
", preg_split( '/\n(?:\s*\n)+/', $back ) ) . "
";
    $act = "
" . implode( "
\n\n
", preg_split( '/\n(?:\s*\n)+/', $act ) ) . "
";
    if(strlen($ref)>3) {$ref = "References:

" . implode( "
\n\n
", array_filter(array_map($this->hrefify,explode( "\n", $ref )))) . "

";} else {$ref = '';}
    if(strlen($mod)>3) {$mod = "Modify:

" . implode( "
\n\n
", array_filter(array_map($this->hrefify,explode("\n", $mod )))) . "

";} else {$mod = '';}
    $this->data['Task']['description'] = $back.$act.$ref.$mod;}
    return true;
}

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'title';

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'title' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'description' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'action' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
		'mentors' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'beginner' => array(
			'boolean' => array(
				'rule' => array('boolean'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'length' => array(
			'numeric' => array(
				'rule' => array('numeric'),
                                //'message' => 'Your custom message here',
                                //'allowEmpty' => false,
                                //'required' => true,
                                //'last' => false, // Stop validation after this rule
                                //'on' => 'create', // Limit validation to 'create' or 'update' operations
                        ),
			'range' => array(
				'rule' => array('range',71.9,720.1),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => true,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	public $hasAndBelongsToMany = array(
                'Mentor' => array(
                        'className' => 'Mentor',
                        'joinTable' => 'mentors_tasks',
                        'foreignKey' => 'task_id',
                        'associationForeignKey' => 'mentor_id',
                        'unique' => 'keepExisting',
                        'conditions' => '',
                        'fields' => '',
                        'order' => '',
                        'limit' => '',
                        'offset' => '',
                        'finderQuery' => '',
                )
        );
}


text:
import java.collections.HashMap;

public class OneOne {

    public boolean hasUniqueChars(String input) {
        if (input.length < 2){
            return true;
        }
        HashMap map = new HashMap<char,boolean>();

        return true;
    }

    public static void main(String[] args){
        System.out.println("Hello World");

    }
}


text:
'use strict';

const { expect } = require('chai');
const RC = require('../../RC');
const TestUtil = require('../../../TestUtil');

describe('ClientLabelTest', function () {
    let cluster;
    let client;
    let member;

    const testFactory = new TestUtil.TestFactory();

    before(async function () {
        cluster = await testFactory.createClusterForParallelTests();
        member = await RC.startMember(cluster.id);
    });

    afterEach(async function () {
        await client.shutdown();
    });

    after(async function () {
        await testFactory.shutdownAll();
    });

    it('labels should be received on member side', async function () {
        client = await testFactory.newHazelcastClientForParallelTests({
            clusterName: cluster.id,
            clientLabels: ['testLabel']
        }, member);

        const script = 'var client = instance_0.getClientService().getConnectedClients().iterator().next();\n' +
            'result = client.getLabels().iterator().next();\n';
        const res = await RC.executeOnController(cluster.id, script, 1);
        expect(res.result).to.not.be.null;
        expect(res.result.toString()).to.equal('testLabel');
    });
});


text:
package org.apache.activemq.openwire.codec.v8;

import org.apache.activemq.openwire.codec.OpenWireInteropTests;

public class OpenWireV8Test extends OpenWireInteropTests {

    /**
     * @param tightEncodingEnabled
     */
    public OpenWireV8Test(boolean tightEncodingEnabled) {
        super(tightEncodingEnabled);
    }

    @Override
    protected int getOpenWireVersion() {
        return 8;
    }
}


text:
import build_server
# Copy all the files necessary to run the server. These are cleaned up when the
# server quits.
build_server.main()

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from local_renderer import LocalRenderer
import logging
import optparse
import os
import sys
import time

def _GetLocalPath():
  if os.sep in sys.argv[0]:
    return os.path.join(sys.argv[0].rsplit(os.sep, 1)[0], os.pardir, os.pardir)
  return os.path.join(os.pardir, os.pardir)

def _Render(base_dir, path):
  renderer = LocalRenderer(base_dir)
  content, status, headers = renderer.Render(path, always_online=True)
  while status in [301, 302]:
    redirect = headers['Location'].lstrip('/')
    sys.stderr.write('<!-- Redirected %s to %s -->\n' % (path, redirect))
    content, status, headers = renderer.Render(redirect, always_online=True)
  return (content, status, headers)

class RequestHandler(BaseHTTPRequestHandler):
  class Factory(object):
    def __init__(self, base_dir):
      self._base_dir = base_dir

    def Create(self, *args):
      return RequestHandler(self._base_dir, *args)

  def __init__(self, base_dir, *args):
    self._base_dir = base_dir
    BaseHTTPRequestHandler.__init__(self, *args)

  """A HTTPRequestHandler that outputs the docs page generated by Handler.
  """
  def do_GET(self):
    content, status, headers = _Render(self._base_dir, self.path)
    self.send_response(status)
    for k, v in headers.iteritems():
      self.send_header(k, v)
    self.end_headers()
    self.wfile.write(content)

if __name__ == '__main__':
  parser = optparse.OptionParser(
      description='Runs a server to preview the extension documentation.',
      usage='usage: %prog [option]...')
  parser.add_option('-p', '--port', default='8000',
      help='port to run the server on')
  parser.add_option('-d', '--directory', default=_GetLocalPath(),
      help='extensions directory to serve from - '
           'should be chrome/common/extensions within a Chromium checkout')
  parser.add_option('-r', '--render', default='',
      help='statically render a page and print to stdout rather than starting '
           'the server, e.g. apps/storage.html. The path may optionally end '
           'with #n where n is the number of times to render the page before '
           'printing it, e.g. apps/storage.html#50, to use for profiling.')
  parser.add_option('-t', '--time', action='store_true',
      help='Print the time taken rendering rather than the result.')

  (opts, argv) = parser.parse_args()

  if (not os.path.isdir(opts.directory) or
      not os.path.isdir(os.path.join(opts.directory, 'docs')) or
      not os.path.isdir(os.path.join(opts.directory, 'api'))):
    print('Specified directory does not exist or does not contain extension '
          'docs.')
    exit()

  if opts.render:
    if opts.render.find('#') >= 0:
      (path, iterations) = opts.render.rsplit('#', 1)
      extra_iterations = int(iterations) - 1
    else:
      path = opts.render
      extra_iterations = 0

    if opts.time:
      start_time = time.time()

    content, status, headers = _Render(opts.directory, path)
    if status != 200:
      print('Error status: %s' % status)
      exit(1)

    for _ in range(extra_iterations):
      _Render(opts.directory, path)

    if opts.time:
      print('Took %s seconds' % (time.time() - start_time))
    else:
      # Static paths will show up as /stable/static/foo but this only makes
      # sense from a webserver.
      print(content.replace('/stable/static', 'static'))
    exit()

  print('Starting previewserver on port %s' % opts.port)
  print('')
  print('The extension documentation can be found at:')
  print('')
  print('  http://localhost:%s/extensions/' % opts.port)
  print('')
  print('The apps documentation can be found at:')
  print('')
  print('  http://localhost:%s/apps/' % opts.port)
  print('')

  logging.getLogger().setLevel(logging.INFO)
  server = HTTPServer(('', int(opts.port)),
                      RequestHandler.Factory(opts.directory).Create)
  try:
    server.serve_forever()
  finally:
    server.socket.close()