text:
package com.spotify.heroic.aggregation;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.spotify.heroic.grammar.Expression;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Utility class to contain a set of arguments and keywords in order to match the to aggregation
 * parameters and guarantee that all are consumed.
 */
public class AggregationArguments {
    private final LinkedList<Expression> args;
    private final Map<String, Expression> kw;

    public AggregationArguments(
        final List<? extends Expression> args, final Map<String, ? extends Expression> kw
    ) {
        this.args = new LinkedList<>(args);
        this.kw = new HashMap<>(kw);
    }

    /**
     * Take all arguments as a list with the given type.
     */
    public <T extends Expression> List<T> takeArguments(final Class<T> expected) {
        final List<T> result =
            ImmutableList.copyOf(args.stream().map(v -> v.cast(expected)).iterator());
        args.clear();
        return result;
    }

    public Optional<Expression> getNext() {
        if (!args.isEmpty()) {
            return Optional.of(args.removeFirst());
        }

        return Optional.empty();
    }

    public <T extends Expression> Optional<T> getNext(final String key, Class<T> expected) {
        if (!args.isEmpty()) {
            return Optional.of(args.removeFirst().cast(expected));
        }

        return Optional.ofNullable(kw.remove(key)).map(v -> v.cast(expected));
    }

    public <T extends Expression> Optional<T> positional(Class<T> expected) {
        if (args.isEmpty()) {
            return Optional.empty();
        }

        return Optional.of(args.removeFirst().cast(expected));
    }

    public <T extends Expression> Optional<T> keyword(final String key, Class<T> expected) {
        return Optional.ofNullable(kw.remove(key)).map(v -> v.cast(expected));
    }

    public void throwUnlessEmpty(final String name) {
        if (!args.isEmpty() || !kw.isEmpty()) {
            final List<String> parts = new ArrayList<>();
            final Joiner on = Joiner.on(" and ");

            if (!args.isEmpty()) {
                parts.add(
                    args.size() == 1 ? "argument " + args.iterator().next() : "arguments " + args);
            }

            if (!kw.isEmpty()) {
                parts.add((kw.size() == 1 ? "keyword " : "keywords ") + kw);
            }

            throw new IllegalStateException(name + ": has trailing " + on.join(parts));
        }
    }
}


text:
from django.views import generic

class Home(generic.TemplateView):
    template_name = "home.html"

redpajama_set_name: RedPajamaGithub


text:
package ru.org.linux.topic

import java.util.List
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation._
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.util.UriComponentsBuilder
import ru.org.linux.auth.AccessViolationException
import ru.org.linux.section.SectionService
import ru.org.linux.site.Template
import ru.org.linux.user._

@Controller
@RequestMapping(Array("/people/{nick}"))
class UserTopicListController @Autowired()
(
  topicListService: TopicListService,
  userDao: UserDao,
  userService: UserService,
  sectionService: SectionService,
  prepareService: TopicPrepareService,
  topicPermissionService: TopicPermissionService
) {
  @RequestMapping(value = Array("favs"), params = Array("!output"))
  def showUserFavs(
    request: HttpServletRequest,
    @PathVariable nick: String,
    @RequestParam(value = "offset", defaultValue = "0") rawOffset: Int
  ): ModelAndView = {
    val (modelAndView, user) = mkModel(nick)

    modelAndView.addObject("url",
      UriComponentsBuilder.fromUriString("/people/{nick}/favs").buildAndExpand(nick).encode.toUriString)

    modelAndView.addObject("ptitle", s"Избранные сообщения ${user.getNick}")
    modelAndView.addObject("navtitle", s"Избранные сообщения")

    val offset = topicListService.fixOffset(rawOffset)
    modelAndView.addObject("offset", offset)
    val messages = topicListService.getUserTopicsFeed(user, offset, true, false)
    prepareTopicsForPlainOrRss(request, modelAndView, rss = false, messages)
    modelAndView.setViewName("user-topics")

    modelAndView
  }

  @RequestMapping(value = Array("drafts"))
  def showUserDrafts(
    request: HttpServletRequest,
    @PathVariable nick: String,
    @RequestParam(value = "offset", defaultValue = "0") rawOffset: Int
  ): ModelAndView = {
    val tmpl = Template.getTemplate(request)
    val (modelAndView, user) = mkModel(nick)

    if (!tmpl.isModeratorSession && !(user == tmpl.getCurrentUser)) {
      throw new AccessViolationException("Вы не можете смотреть черновики другого пользователя")
    }

    modelAndView.addObject("url",
      UriComponentsBuilder.fromUriString("/people/{nick}/drafts").buildAndExpand(nick).encode.toUriString)

    modelAndView.addObject("ptitle", s"Черновики ${user.getNick}")
    modelAndView.addObject("navtitle", s"Черновики")
    val offset = topicListService.fixOffset(rawOffset)
    modelAndView.addObject("offset", offset)
    val messages = topicListService.getDrafts(user, offset)
    prepareTopicsForPlainOrRss(request, modelAndView, rss = false, messages)
    modelAndView.setViewName("user-topics")

    modelAndView
  }

  @RequestMapping
  def showUserTopics(
    request: HttpServletRequest,
    @PathVariable nick: String,
    response: HttpServletResponse,
    @RequestParam(value = "offset", defaultValue = "0") rawOffset: Int,
    @RequestParam(value = "section", defaultValue = "0") sectionId: Int,
    @RequestParam(value = "output", required = false) output: String
  ): ModelAndView = {
    TopicListController.setExpireHeaders(response, null, null)

    val (modelAndView, user) = mkModel(nick)

    val section = if (sectionId != 0) {
      sectionService.idToSection.get(sectionId)
    } else {
      None
    }

    val userInfo = userDao.getUserInfoClass(user)

    if (topicPermissionService.followAuthorLinks(user)) {
      modelAndView.addObject("meLink", userInfo.getUrl)
    }

    modelAndView.addObject("nick", user.getNick)
    modelAndView.addObject("url",
      UriComponentsBuilder.fromUriString("/people/{nick}/").buildAndExpand(nick).encode.toUriString)
    modelAndView.addObject("ptitle", s"Сообщения ${user.getNick}")
    modelAndView.addObject("navtitle", s"Сообщения")
    modelAndView.addObject("rssLink",
      UriComponentsBuilder.fromUriString("/people/{nick}/?output=rss").buildAndExpand(nick).encode.toUriString)

    val offset = topicListService.fixOffset(rawOffset)
    modelAndView.addObject("offset", offset)
    val messages = topicListService.getUserTopicsFeed(user, section.orNull, null, offset, false, false)

    val rss = "rss" == output
    if (!rss) {
      section.foreach { section ⇒ modelAndView.addObject("section", section)}
      modelAndView.addObject("sectionList", sectionService.getSectionList)
    }

    modelAndView.addObject("params", section.map(s ⇒ s"section=${s.getId}").getOrElse(""))

    prepareTopicsForPlainOrRss(request, modelAndView, rss, messages)

    if (!rss) {
      modelAndView.setViewName("user-topics")
    }

    modelAndView.addObject("showSearch", true)

    modelAndView
  }

  @RequestMapping(value = Array("tracked"), params = Array("!output"))
  def showUserWatches(
    request: HttpServletRequest,
    @PathVariable nick: String,
    @RequestParam(value = "offset", defaultValue = "0") rawOffset: Int
  ): ModelAndView = {
    val tmpl = Template.getTemplate(request)

    val (modelAndView, user) = mkModel(nick)

    if (!tmpl.isModeratorSession && !(user == tmpl.getCurrentUser)) {
      throw new AccessViolationException("Вы не можете смотреть отслеживаемые темы другого пользователя")
    }

    modelAndView.addObject("url",
      UriComponentsBuilder.fromUriString("/people/{nick}/tracked").buildAndExpand(nick).encode.toUriString)

    modelAndView.addObject("ptitle", s"Отслеживаемые сообщения ${user.getNick}")
    modelAndView.addObject("navtitle", s"Отслеживаемые сообщения")

    val offset = topicListService.fixOffset(rawOffset)
    modelAndView.addObject("offset", offset)

    val messages = topicListService.getUserTopicsFeed(user, offset, true, true)
    prepareTopicsForPlainOrRss(request, modelAndView, rss = false, messages)
    modelAndView.setViewName("user-topics")

    modelAndView
  }

  private def prepareTopicsForPlainOrRss(
    request: HttpServletRequest,
    modelAndView: ModelAndView,
    rss: Boolean,
    messages: List[Topic]
  ):Unit = {
    if (rss) {
      modelAndView.addObject("messages", prepareService.prepareMessages(messages, request.isSecure))
      modelAndView.setViewName("section-rss")
    } else {
      val tmpl = Template.getTemplate(request)
      modelAndView.addObject("messages",
        prepareService.prepareMessagesForUser(messages, request.isSecure, tmpl.getCurrentUser, tmpl.getProf, false))
    }
  }

  private def mkModel(nick: String): (ModelAndView, User) = {
    val modelAndView = new ModelAndView()

    val user = userService.getUserCached(nick)

    if (user.getId == User.ANONYMOUS_ID) {
      throw new UserErrorException("Лента для пользователя anonymous не доступна")
    }

    modelAndView.addObject("user", user)
    modelAndView.addObject("whoisLink",
      UriComponentsBuilder.fromUriString("/people/{nick}/profile").buildAndExpand(nick).encode.toUriString)

    (modelAndView, user)
  }

  @ExceptionHandler(Array(classOf[UserNotFoundException]))
  @ResponseStatus(HttpStatus.NOT_FOUND)
  def handleNotFoundException = new ModelAndView("errors/code404")
}


text:
package org.checkerframework.afu.annotator.tests;

public class EnumListAnnotationParameter {
  public void foo() {}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Vladimir
 * Date: 3.4.2017.
 * Time: 23:50
 */
use PHPUnit\Framework\TestCase;

$applicationRoot = dirname( dirname(__FILE__ ) );

require_once $applicationRoot . "/connectors/Sms.php";

/**
 * @covers Sms
 * @covers Zang_Connector
 * @covers Zang_Helpers
 * @covers Zang_Related
 * @covers Zang_Schemas
 * @covers ZangException
 */
final class SmsTest extends TestCase {

    public function testViewSms(){
            $smsInstance = Sms::getInstance();
            $res = $smsInstance->viewSms(array(
                "SMSMessageSid" => "TestSmsSid"
            ));
            $this->checkResponse($res->getResponse());
    }

    public function testSendSms()
    {
            $smsInstance = Sms::getInstance(array(
                "account_sid" => $_ENV["ACCOUNT_SID"],
                "auth_token" => $_ENV["AUTH_TOKEN"]
            ));

            $res = $smsInstance->sendSms(array(
                'To' => "+123456",
                'Body' => "test from java",
                "From" => "+654321",
                "StatusCallbackMethod" => "GET",
                'AllowMultiple' => "False"
            ));
            $this->checkResponse($res->getResponse());
    }

    public function testListSms(){
            $smsInstance = Sms::getInstance(array(
                "account_sid" => $_ENV["ACCOUNT_SID"],
                "auth_token" => $_ENV["AUTH_TOKEN"]
            ));
            $res = $smsInstance->listSMS(array(
                "To" => '%2B123456',
                "Page" => "0",
                "PageSize" => "10"
            ));
            $this->assertObjectHasAttribute("sms_messages", $res->getResponse());
    }

    private function checkResponse($response){
        $this -> assertObjectHasAttribute("body", $response);
        $this -> assertObjectHasAttribute("status", $response);
        $this -> assertObjectHasAttribute("direction", $response);
        $this -> assertObjectHasAttribute("date_updated", $response);
        $this -> assertObjectHasAttribute("price", $response);
        $this -> assertObjectHasAttribute("from", $response);
        $this -> assertObjectHasAttribute("uri", $response);
        $this -> assertObjectHasAttribute("account_sid", $response);
        $this -> assertObjectHasAttribute("to", $response);
        $this -> assertObjectHasAttribute("sid", $response);
        $this -> assertObjectHasAttribute("date_sent", $response);
        $this -> assertObjectHasAttribute("date_created", $response);
        $this -> assertObjectHasAttribute("api_version", $response);
    }
}


text:
from setuptools import setup

setup(
    name='CaseInsensitiveDict',
    version='1.0.0',
    description='Case insensitive dictionary',
    long_description='Case insensitive dictionary supporting nested structures',
    url='https://github.com/tivvit/python-case-insensitive-dict',
    author='Vit Listik',
    author_email='tivvit@seznam.cz',
    license='MIT',
    classifiers=[
        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',
        'Topic :: Software Development :: Libraries',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    keywords='dict dictionary case-insensitive',
    packages=["CaseInsensitiveDict"],
)


text:
Package.describe({
    name: 'softbricks:user-management-bootstrap',
    version: '0.0.1',
    // Brief, one-line summary of the package.
    summary: '',
    // URL to the Git repository containing the source code for this package.
    git: '',
    // By default, Meteor will default to using README.md for documentation.
    // To avoid submitting documentation, set this field to null.
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.0.3.1');

    api.use(['templating', 'session', 'underscore'], 'client');

    api.use('useraccounts:bootstrap', ['client', 'server']);
    api.use('softbricks:user-management', ['client', 'server']);
    api.use('twbs:bootstrap', ['client']);

    api.imply('softbricks:user-management@0.0.1', ['client', 'server']);

    api.addFiles(['lib/templates/users/showUsers.html'], 'client');
    api.addFiles(['lib/templates/users/showUsers.js'], 'client');
    api.addFiles(['lib/stylesheets/userList.css'], 'client');

    api.addFiles(['lib/templates/users/showUser.html'], 'client');
    api.addFiles(['lib/templates/users/showUser.js'], 'client');

    api.addFiles(['lib/templates/users/editUser.html'], 'client');
    api.addFiles(['lib/templates/users/editUser.js'], 'client');

    api.addFiles(['lib/templates/users/createUser.html'], 'client');
    api.addFiles(['lib/templates/users/createUser.js'], 'client');

});


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Pages */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'meta_title')->textInput(['maxlength' => true]) ?>

    <?php echo $form->field($model, 'meta_keywords')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'meta_description')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
def ex_handler_factory(creating_plan=False, no_throw=False):
    def _polish_bad_errors(ex):
        import json
        from azure.cli.core.util import CLIError
        try:
            detail = json.loads(ex.response.text)['Message']
            if creating_plan:
                if 'Requested features are not supported in region' in detail:
                    detail = ("Plan with linux worker is not supported in current region. For " +
                              "supported regions, please refer to https://docs.microsoft.com/en-us/"
                              "azure/app-service-web/app-service-linux-intro")
                elif 'Not enough available reserved instance servers to satisfy' in detail:
                    detail = ("Plan with Linux worker can only be created in a group " +
                              "which has never contained a Windows worker, and vice versa. " +
                              "Please use a new resource group. Original error:" + detail)
            ex = CLIError(detail)
        except Exception:  # pylint: disable=broad-except
            pass
        if no_throw:
            return ex
        raise ex
    return _polish_bad_errors

def web_client_factory(**_):
    from azure.mgmt.web import WebSiteManagementClient
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    return get_mgmt_service_client(WebSiteManagementClient)

def cf_plans(_):
    return web_client_factory().app_service_plans

def cf_providers(_):
    return web_client_factory().provider  # pylint: disable=no-member

def cf_web_client(_):
    return web_client_factory()


text:
package play.api.libs.ws.ahc

import javax.cache.Cache

import akka.stream.Materializer
import play.api.libs.ws.ahc.cache.{ EffectiveURIKey, ResponseEntry }
import play.api.libs.ws.{ WSClient, WSRequest }

/**
 * Async WS Client backed by AsyncHttpClient.
 *
 * See https://www.playframework.com/documentation/latest/ScalaWS for documentation.
 */
class AhcWSClient(underlyingClient: StandaloneAhcWSClient) extends WSClient {
  /**
   * The underlying implementation of the client, if any.  You must cast explicitly to the type you want.
   *
   * @tparam T the type you are expecting (i.e. isInstanceOf)
   * @return the backing class.
   */
  override def underlying[T]: T = underlyingClient.underlying[T]

  /**
   * Generates a WS Request.  This is a builder that can be used to build up an
   * HTTP request, finally calling a termination method like `get()` or `execute()`
   * which returns a `Future[WSResponse]`.
   *
   * @param url The base URL to make HTTP requests to.
   * @return a request
   * @throws java.lang.IllegalArgumentException if the URL is invalid.
   */
  @throws[IllegalArgumentException]
  override def url(url: String): WSRequest = {
    AhcWSRequest(underlyingClient.url(url).asInstanceOf[StandaloneAhcWSRequest])
  }

  /** Closes this client, and releases underlying resources. */
  override def close(): Unit = underlyingClient.close()
}

object AhcWSClient {

  private[ahc] val loggerFactory = new AhcLoggerFactory()

  /**
   * Convenient factory method that uses a play.api.libs.ws.WSClientConfig value for configuration instead of
   * an [[http://static.javadoc.io/org.asynchttpclient/async-http-client/2.0.0/org/asynchttpclient/AsyncHttpClientConfig.html org.asynchttpclient.AsyncHttpClientConfig]].
   *
   * Typical usage:
   *
   * {{{
   *   implicit val materializer = ...
   *   val client = AhcWSClient()
   *   val request = client.url(someUrl).get()
   *   request.foreach { response =>
   *     doSomething(response)
   *     client.close()
   *   }
   * }}}
   *
   * @param config configuration settings, AhcWSClientConfig() by default
   * @param cache enables HTTP cache-control, None by default
   */
  def apply(
    config: AhcWSClientConfig = AhcWSClientConfig(),
    cache: Option[Cache[EffectiveURIKey, ResponseEntry]] = None)(implicit materializer: Materializer): AhcWSClient = {
    new AhcWSClient(StandaloneAhcWSClient(config, cache))
  }
}


text:
layout: page
title: Dominguez Family Reunion
date: 2016-05-24
author: Lisa Hinton
tags: weekly links, java
status: published
summary: Curabitur ac facilisis nulla, at.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 12/30/2019
  endDate: 01/01/2020
  ctyhocn: LACOLHX
  groupCode: DFR
published: true
---
Vestibulum euismod massa eget aliquam vehicula. Maecenas convallis arcu nec facilisis sollicitudin. Cras consequat erat vitae libero maximus, quis efficitur nulla convallis. Etiam eget sagittis magna, id imperdiet ex. Nullam hendrerit rutrum vulputate. Praesent ante est, iaculis et ipsum sed, porttitor elementum lectus. Donec nibh lorem, finibus vel dui id, scelerisque posuere nisl. Integer rhoncus elit rhoncus nisi tristique pharetra. Etiam tellus tortor, sodales quis velit eget, pharetra ultrices elit. Sed tristique odio justo, sed luctus nisi dignissim eget. Cras sit amet lacus consequat, porttitor elit et, viverra velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In hac habitasse platea dictumst. Suspendisse malesuada hendrerit convallis.

* Praesent eu tortor non urna tristique sollicitudin
* Donec sodales arcu eget mauris feugiat ultricies
* Mauris blandit odio eu varius iaculis
* Suspendisse facilisis velit id sem euismod sodales.

Aliquam commodo posuere sem, in dapibus ex viverra sed. Integer sit amet risus ut dui dignissim tincidunt. Nulla vestibulum ut ligula vitae convallis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed venenatis augue non egestas lacinia. Mauris tincidunt ante dignissim augue bibendum pellentesque. Ut eu dui leo. Phasellus porta blandit aliquam. Nunc fringilla quam at odio bibendum, vel tempor ligula vulputate. Pellentesque a augue quis ex imperdiet pretium. Mauris pellentesque vel ex eget ultricies. Fusce vehicula nisi tellus, ut tempus nisl aliquam quis.


text:
package nablarch.core.dataformat.convertor.datatype;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.Charset;

import nablarch.core.dataformat.FieldDefinition;
import nablarch.core.dataformat.InvalidDataFormatException;
import nablarch.core.dataformat.SyntaxErrorException;

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * {@link SignedNumberStringDecimal}の固定長テスト。
 *
 * @author TIS
 */
public class SignedNumberStringDecimalTest {

    private SignedNumberStringDecimal sut = new SignedNumberStringDecimal();
    private final FieldDefinition field = new FieldDefinition().setEncoding(Charset.forName("ms932")).setName("test");

    @Rule
    public ExpectedException exception = ExpectedException.none();

    /**
     * 初期化時にnullをわたすと例外がスローされること。
     */
    @Test
    public void testInitializeNull() {
        exception.expect(SyntaxErrorException.class);
        exception.expectMessage("initialize parameter was null. parameter must be specified. convertor=[SignedNumberStringDecimal].");

        sut.initialize((Object[]) null);
    }

    /**
     * 初期化時にnullが渡されたときのテスト。
     */
    @Test
    public void testInitialize1stParameterNull() {
        exception.expect(SyntaxErrorException.class);
        exception.expectMessage("1st parameter was null. parameter=[null, hoge]. convertor=[SignedNumberStringDecimal].");

        sut.initialize(null, "hoge");
    }

    /**
     * 初期化時のバイト長が不正。
     * 空の配列。
     */
    @Test
    public void testInitializeEmpty() throws Exception {
        exception.expect(SyntaxErrorException.class);
        exception.expectMessage("parameter was not specified. parameter must be specified. convertor=[SignedNumberStringDecimal].");

        sut.initialize(new Object[]{});
    }

    /**
     * 初期化時のバイト長が不正。
     * 文字列。
     */
    @Test
    public void testInitializeString() throws Exception {
        exception.expect(SyntaxErrorException.class);
        exception.expectMessage("invalid parameter type was specified. 1st parameter must be Integer. parameter=[abc]. convertor=[SignedNumberStringDecimal].");

        sut.initialize("abc");
    }

    /**
     * 空文字列を0として読み込む場合のテスト。
     */
    @Test
    public void testReadEmpty() {
        sut.init(field, 10, "");
        sut.setConvertEmptyToNull(false);

        assertThat(sut.convertOnRead(""), is(BigDecimal.ZERO));
    }

    /**
     * 空文字列を{@code null}として読み込む場合のテスト。
     */
    @Test
    public void testReadEmptyToNull() {
        sut.init(field, 10, "");

        assertThat(sut.convertOnRead(""), is(nullValue()));
    }

    /**
     * null, 空文字を書き込む場合のテスト。
     */
    @Test
    public void testWriteNullOrEmpty() {
        sut.init(field, 10, "");

        assertThat(sut.convertOnWrite(null), is("0000000000".getBytes()));
        assertThat(sut.convertOnWrite(""), is("0000000000".getBytes()));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系読み込みテスト。
     * トリムが正常に行われることを確認。
     */
    @Test
    public void testReadNormalNotRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnRead(toBytes("0000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("+000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("-000012340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の異常系読み込みテスト。
     * 符号が不正。
     */
    @Test
    public void testReadAbnormalNotRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [[+-]?0*[0-9]+(\\.[0-9]*[0-9])?]. parameter=[■00012340].");

        sut.convertOnRead(toBytes("■00012340"));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の異常系読み込みテスト。
     * 符号の位置が不正。
     */
    @Test
    public void testReadAbnormalNotRequiredSignIllegalSignPosition() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [[+-]?0*[0-9]+(\\.[0-9]*[0-9])?]. parameter=[0000+12340].");

        sut.convertOnRead(toBytes("0000+12340"));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の異常系読み込みテスト。
     * 数値部分に符号が含まれる。
     */
    @Test
    public void testReadAbnormalNotRequiredSignIllegalSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [[+-]?0*[0-9]+(\\.[0-9]*[0-9])?]. parameter=[+000+12340].");

        sut.convertOnRead(toBytes("+000+12340"));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系読み込みテスト。
     * パディング(トリム)文字を変更しても正常にトリムされることを確認。
     */
    @Test
    public void testReadNormalNotRequiredSignWithOtherTrimString() throws Exception {
        FieldDefinition field = new FieldDefinition().setEncoding(Charset.forName("ms932")).setName("test");
        field.setPaddingValue(" ");
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnRead(toBytes("     12340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("+    12340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("-    12340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系読み込みテスト。
     * クラス拡張することで、符号文字を変更できることを確認。
     */
    @Test
    public void testReadNormalNotRequiredSignExtendDataType() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, "");

        assertThat(sut.convertOnRead(toBytes("0000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("■00012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("▲00012340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置固定かつ符号必須の場合の正常系読み込みテスト。
     * トリムが正常に行われることを確認。
     */
    @Test
    public void testReadNormalFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "", true, true);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnRead(toBytes("+000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("-000012340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置固定かつ符号必須の場合の異常系読み込みテスト。
     * 符号が指定されていないケース。
     */
    @Test
    public void testReadAbnormalFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "", true, true);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(true);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [[+-]0*[0-9]+(\\.[0-9]*[0-9])?]. parameter=[0000012340].");

        sut.convertOnRead(toBytes("0000012340"));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の正常系読み込みテスト。
     * トリムが正常に行われることを確認。
     */
    @Test
    public void testReadNormalNonFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, "", false, false);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnRead(toBytes("0000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("0000+12340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("0000-12340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の異常系読み込みテスト。
     * 符号の右にトリム文字があるケース。
     */
    @Test
    public void testReadAbnormalNonFixSignPositionNotRequiredSign() throws Exception {
        FieldDefinition field = new FieldDefinition().setEncoding(Charset.forName("ms932")).setName("test");
        field.setPaddingValue(" ");
        sut.init(field, 10, "", false, false);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [ *[+-]?[0-9]+(\\.[0-9]*[0-9])?]. parameter=[+    12340].");

        sut.convertOnRead(toBytes("+    12340"));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の正常系読み込みテスト。
     * クラス拡張することで、符号文字を変更できることを確認。
     * 現状、先頭の符号以外には対応していない。
     */
    @Ignore
    @Test
    public void testReadNormalNonFixSignPositionNotRequiredSignExtendDataType() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, "");
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnRead(toBytes("0000012340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("000■12340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("000▲12340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置非固定かつ符号必須の場合の正常系読み込みテスト。
     * トリムが正常に行われることを確認。
     */
    @Test
    public void testReadNormalNonFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "", false, true);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnRead(toBytes("0000+12340")), is(new BigDecimal("12340")));
        assertThat(sut.convertOnRead(toBytes("0000-12340")), is(new BigDecimal("-12340")));
    }

    /**
     * 符号位置非固定かつ符号必須の場合の異常系読み込みテスト。
     * 符号が指定されていない。
     */
    @Test
    public void testReadAbnormalNonFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "", false, false);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(true);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter format was specified. parameter format must be [0*[+-][0-9]+(\\.[0-9]*[0-9])?]. parameter=[0000012340].");

        sut.convertOnRead(toBytes("0000012340"));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系書き込みテスト。
     * 出力データは符号あり整数(文字列)。
     */
    @Test
    public void testWriteNumberStringFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("+1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("-000001234")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系書き込みテスト。
     * 出力データは符号あり小数(文字列)。
     */
    @Test
    public void testWriteDecimalFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, 2);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("+1234.56"), is(toBytes("0001234.56")));
        assertThat(sut.convertOnWrite("-1234.56"), is(toBytes("-001234.56")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系書き込みテスト。
     * 出力データはBigDecimal(文字列)。
     */
    @Test
    public void testWriteBigDecimalFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, 0);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite(new BigDecimal("-1234")), is(toBytes("-000001234")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系書き込みテスト。
     * パディング文字を変更。
     */
    @Test
    public void testWriteOtherPaddingStringFixSignPositionNotRequiredSign() throws Exception {
        FieldDefinition field = new FieldDefinition().setEncoding(Charset.forName("ms932")).setName("test");
        field.setPaddingValue(" ");
        sut.init(field, 10, 2);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite(new BigDecimal("-1234.56")), is(toBytes("-  1234.56")));
    }

    /**
     * 符号位置固定かつ符号非必須の場合の正常系書き込みテスト。
     * 拡張したデータタイプによって符号を変更。
     */
    @Test
    public void testWriteWithExtendDataTypeFixSignPositionNotRequiredSign() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, 0, true, false);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("+1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("▲00001234")));
    }

    /**
     * 符号位置固定かつ符号必須の場合の書き込みテスト。
     * 出力データは符号あり整数(文字列)。
     */
    @Test
    public void testWriteNumberStringFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnWrite("1234"), is(toBytes("+000001234")));
        assertThat(sut.convertOnWrite("+1234"), is(toBytes("+000001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("-000001234")));
    }

    /**
     * 符号位置固定かつ符号必須の場合の正常系書き込みテスト。
     * 拡張したデータタイプによって符号を変更。
     */
    @Test
    public void testWriteWithExtendDataTypeFixSignPositionRequiredSign() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, 0, true, false);
        sut.setFixedSignPosition(true);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnWrite("+1234"), is(toBytes("■00001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("▲00001234")));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の書き込みテスト。
     * 出力データは符号あり整数(文字列)。
     */
    @Test
    public void testWriteNumberStringNonFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("+1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("00000-1234")));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の正常系書き込みテスト。
     * 出力データは符号あり小数(文字列)。
     */
    @Test
    public void testWriteDecimaNonFixSignPositionNotRequiredSign() throws Exception {
        sut.init(field, 10, 2);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("+1234.56"), is(toBytes("0001234.56")));
        assertThat(sut.convertOnWrite("-1234.56"), is(toBytes("00-1234.56")));
    }

    /**
     * 符号位置非固定かつ符号非必須の場合の正常系書き込みテスト。
     * 拡張したデータタイプによって符号を変更。
     */
    @Test
    public void testWriteWithExtendDataTypeNonFixSignPositionNotRequiredSign() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, 0, false, false);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(false);

        assertThat(sut.convertOnWrite("+1234"), is(toBytes("0000001234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("0000▲1234")));
    }

    /**
     * 符号位置非固定かつ符号必須の場合の書き込みテスト。
     * 出力データは符号あり整数(文字列)。
     */
    @Test
    public void testWriteNumberStringNonFixSignPositionRequiredSign() throws Exception {
        sut.init(field, 10, "");
        sut.setRequiredDecimalPoint(true);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnWrite("1234"), is(toBytes("00000+1234")));
        assertThat(sut.convertOnWrite("+1234"), is(toBytes("00000+1234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("00000-1234")));
    }

    /**
     * 符号位置非固定かつ符号必須の場合の正常系書き込みテスト。
     * 拡張したデータタイプによって符号を変更。
     */
    @Test
    public void testWriteWithExtendDataTypeNonFixSignPositionRequiredSign() throws Exception {
        SignedNumberStringDecimal sut = (SignedNumberStringDecimal) new SignedNumberStringDecimalExtends().init(field, 10, 0, true, false);
        sut.setRequiredDecimalPoint(true);
        sut.setFixedSignPosition(false);
        sut.setRequiredPlusSign(true);

        assertThat(sut.convertOnWrite("+1234"), is(toBytes("0000■1234")));
        assertThat(sut.convertOnWrite("-1234"), is(toBytes("0000▲1234")));
    }

    /**
     * 書き込み時、出力対象のバイト長が大きい場合に例外を送出すること。
     */
    @Test
    public void testWriteLargeByteLength() throws Exception {
        sut.init(field, 10);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter was specified. too large data. field size = '10' data size = '11'. data: 12345678901");

        sut.convertOnWrite("12345678901");
    }

    /**
     * 負数で桁数を超過した場合に例外が送出されること。
     */
    @Test
    public void testWriteNegativeLargeByteLength() throws Exception {
        sut.init(field, 10);

        exception.expect(InvalidDataFormatException.class);
        exception.expectMessage("invalid parameter was specified. too large data. field size = '10' data size = '11'. data: -1234512345");

        sut.convertOnWrite("-1234512345");
    }

    /**
     * {@link DataType#removePadding}のテスト。
     * パディングされていたらトリム。されていなければ、そのまま。
     */
    @Test
    public void testRemovePadding() {
        sut.init(field, 10);

        String data = "001234";
        String expectedString = "1234";
        BigDecimal expected = new BigDecimal("1234");

        assertThat(sut.removePadding(data), is(expected));
        assertThat(sut.removePadding(expectedString), is(expected));
        assertThat(sut.removePadding(expected), is(expected));
    }

    /**
     * 符号として'■'および'▲'を使用する拡張クラス。
     *
     * @author TIS
     */
    private class SignedNumberStringDecimalExtends extends SignedNumberStringDecimal {
        @Override
        protected String getPlusSign() {
            return "■";
        }
        @Override
        protected String getMinusSign() {
            return "▲";
        }
    }

    /** 文字列をバイトに変換する */
    private byte[] toBytes(String str) throws UnsupportedEncodingException {
        return str.getBytes("ms932");
    }

}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**update** | [**models.OrganizationUpdate**](models.OrganizationUpdate.md) |  | [default to null]


text:
=============
``libthirty``
=============

``libthirty`` is a python module that wraps the 30loops_ REST api in a easy to
use programming API. It's purpose is to function as a low level library that
can be used by other tools to provide a high level view on the 30loops_
platform.

Documentation still needs to be added, but you can check the ``thirty-cli``
package for a reference.


text:
package org.xbib.catalog.entities.pica.zdb.bibdat;

import org.xbib.catalog.entities.CatalogEntity;

import java.util.Map;

/**
 *
 */
public class LibraryServiceOrganization extends CatalogEntity {

    public LibraryServiceOrganization(Map<String, Object> params) {
        super(params);
    }
}


text:
require File.dirname(__FILE__) + '/../../../test/test_helper'
require File.dirname(__FILE__) + '/../../spec_helper'
require 'admin/content_controller'

require 'http_mock'

# Re-raise errors caught by the controller.
module Admin
end

class Admin::ContentController; def rescue_action(e) raise e end; end

describe Admin::ContentController do
  integrate_views

  before do
    request.session = { :user => users(:tobi).id }
  end

  def test_index
    get :index
    assert_template 'index'
  end

  def test_list
    get :list
    assert_template 'index'
    assert_template_has 'articles'
  end

  def test_show
    get :show, 'id' => contents(:article1).id
    assert_template 'show'
    assert_template_has 'article'
    assert_valid assigns(:article)
    assert_not_nil assigns(:article)
  end

  def test_new
    get :new
    assert_template 'new'
    assert_template_has 'article'
  end

  def test_create_no_comments
    post(:new, 'article' => { :title => "posted via tests!", :body => "You can't comment",
                              :keywords => "tagged",
                              :allow_comments => '0', :allow_pings => '1' },
               'categories' => [categories(:software).id])
    assert !assigns(:article).allow_comments?
    assert  assigns(:article).allow_pings?
    assert  assigns(:article).published?
  end

  def test_create_with_no_pings
    post(:new, 'article' => { :title => "posted via tests!", :body => "You can't ping!",
                              :keywords => "tagged",
                              :allow_comments => '1', :allow_pings => '0' },
               'categories' => [categories(:software).id])
    assert  assigns(:article).allow_comments?
    assert !assigns(:article).allow_pings?
    assert  assigns(:article).published?
  end

  def test_create
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []
    num_articles = Article.count_published_articles
    emails = ActionMailer::Base.deliveries
    tags = ['foo', 'bar', 'baz bliz', 'gorp gack gar']
    post :new, 'article' => { :title => "posted via tests!", :body => "Foo", :keywords => "foo bar 'baz bliz' \"gorp gack gar\""}, 'categories' => [categories(:software).id]
    assert_response :redirect, :action => 'show'

    assert_equal num_articles + 1, Article.count_published_articles

    new_article = Article.find(:first, :order => "id DESC")
    assert_equal users(:tobi), new_article.user
    assert_equal 1, new_article.categories.size
    assert_equal [categories(:software)], new_article.categories
    assert_equal 4, new_article.tags.size

    assert_equal(1, emails.size)
    assert_equal('randomuser@example.com', emails.first.to[0])
  ensure
    ActionMailer::Base.perform_deliveries = false
  end

  def test_create_future_article
    num_articles = Article.count_published_articles
    post(:new,
         :article => { :title => "News from the future!",
                       :body => "The future's cool!",
                       :published_at => Time.now + 1.hour })
    assert_response :redirect, :action => 'show'
    assert ! assigns(:article).published?
    assert_equal num_articles, Article.count_published_articles
    assert_equal 1, Trigger.count
  end

  def test_request_fires_triggers
    art = Article.create!(:title => 'future article',
                          :body => 'content',
                          :published_at => Time.now + 2.seconds,
                          :published => true)
    assert !art.published?
    sleep 3
    get(:show, :id => art.id)
    assert assigns(:article).published?
  end

  def test_create_filtered
    body = "body via *textile*"
    extended="*foo*"
    post :new, 'article' => { :title => "another test", :body => body, :extended => extended}
    assert_response :redirect, :action => 'show'

    new_article = Article.find(:first, :order => "created_at DESC")
    assert_equal body, new_article.body
    assert_equal extended, new_article.extended
    assert_equal "textile", new_article.text_filter.name
    assert_equal "
body via textile
", new_article.html(:body)
    assert_equal "
foo
", new_article.html(:extended)
  end

  def test_edit
    get :edit, 'id' => contents(:article1).id
    assert_equal assigns(:selected), contents(:article1).categories.collect {|c| c.id}
    assert_template 'edit'
    assert_template_has 'article'
    assert_valid assigns(:article)
  end

  def test_update
    ActionMailer::Base.perform_deliveries = true
    emails = ActionMailer::Base.deliveries
    emails.clear

    art_id = contents(:article1).id

    body = "another *textile* test"
    post :edit, 'id' => art_id, 'article' => {:body => body, :text_filter => 'textile'}
    assert_response :redirect, :action => 'show', :id => art_id

    article = contents(:article1).reload
    assert_equal "textile", article.text_filter.name
    assert_equal body, article.body

    assert_equal 0, emails.size
  ensure
    ActionMailer::Base.perform_deliveries = false
  end

  def test_destroy
    art_id = contents(:article1).id
    assert_not_nil Article.find(art_id)

    get :destroy, 'id' => art_id
    assert_response :success

    post :destroy, 'id' => art_id
    assert_response :redirect, :action => 'index'

    assert_raise(ActiveRecord::RecordNotFound) {
      article = Article.find(art_id)
    }
  end

  def test_resource_add
    art_id = contents(:article1).id
    get :resource_add, :id => art_id, :resource_id => resources(:resource1).id

    assert_template '_show_resources'
    assert_valid assigns(:article)
    assert_valid assigns(:resource)
    assert Article.find(art_id).resources.include?(resources(:resource1))
    assert_not_nil assigns(:article)
    assert_not_nil assigns(:resource)
    assert_not_nil assigns(:resources)
  end

  def test_resource_remove
    art_id = contents(:article1).id
    get :resource_remove, :id => art_id, :resource_id => resources(:resource1).id

    assert_template '_show_resources'
    assert_valid assigns(:article)
    assert_valid assigns(:resource)
    assert !Article.find(art_id).resources.include?(resources(:resource1))
    assert_not_nil assigns(:article)
    assert_not_nil assigns(:resource)
    assert_not_nil assigns(:resources)
  end

  it 'should return foo for keywords fo' do
    get :auto_complete_for_article_keywords, :article => {:keywords => 'fo'}
    response.should be_success
    response.body.should == '

foo

'
  end

  it 'should return nothing for hello' do
    get :auto_complete_for_article_keywords, :article => {:keywords => 'hello'}
    response.should be_success
    response.body.should == '

'
  end

  it 'should return bar and baz for ba keyword' do
    get :auto_complete_for_article_keywords, :article => {:keywords => 'ba'}
    response.should be_success
    response.body.should == '

bar

bazz

'
  end

end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Form extends MY_Controller {

	function __construct(){
		parent::__construct();
		$this->load->database();
		$this->load->model(array('privilege','category','item','file'));
		$this->load->helper(array('form','url'));
		$this->load->library(array('form_validation','session'));
		$this->last_insert_result=null;

		#detect maintenance mode
		parent::set_maintenance();

		$this->session_privileges=array();
		$this->session_categories=array();
		$this->session_sub_categories=array();
		$this->session_category_is_accessible=0;

		self::load_privileges();
		self::load_menu();
		self::get_parent_categories();
		self::get_children_categories();
		self::get_item_details();

	}

	/*
	 * Load account privileges
	 *
	 * */

	public function load_privileges(){
		$this->session_privileges=($this->privilege->get_privilege(@$_SESSION['priv']));
	}

	public function load_menu(){

		$this->menu=array(
			'category'=>1,
			'permission'=>$this->privilege->is_allowed_to_grant_role(),
			'materials'=>$this->privilege->is_allowed_to_write_materials()

		);

	}

	/**
	 * Get children categories
	 *
	 * Display subcategories depending upon user/category privilege.
	 * It relies on get parameter to detect its parent
	 * @return array(data,param,details,items)
	 */

	public function get_children_categories(){
		$this->session_sub_categories=($this->category->get_children_categories(@$this->session_privileges[0]->role_id,$this->input->get('id',true)));
	}

	public function get_parent_categories(){

		$this->session_categories=($this->category->get_parent_categories(@$this->session_privileges[0]->role_id));

	}

	public function get_categories(){

		return array('data'=>$this->session_categories,'sub'=>$this->session_sub_categories,'param'=>$this->input->get(),'details'=>self::get_category_details(),'items'=>self::get_items(),'menu'=>$this->menu);
	}

	/**
	 * Get details
	 *
	 * Display category details
	 * @return array()
	 */

	public function get_category_details(){

		$this->category_details=array();

		if($this->category->is_accessible(@$this->session_privileges[0]->role_id,$this->input->get('id',true))){

			$this->category_details=$this->category->get_category_details(@$this->session_privileges[0]->role_id,$this->input->get('id',true));

		}

		return $this->data=$this->category_details;

	}

	/**
	 * Get Items
	 *
	 * Display all items that fall under this category
	 * @return array()
	 */

	public function get_items(){

		$this->items=$this->item->get_items($this->input->get('id',true),$this->input->get('page',true));
		return $this->data=$this->items;
	}

	/**
	 * Get Item details
	 *
	 * Display all information aof the item
	 * Items under a private category are only accessible by admin accounts
	 * @return array()
	 */

	public function get_item_details(){

		$this->item_details=$this->item->get_item_details($this->input->get('item_id',true));

	}

	public function set_item(){
		return $this->data=array('data'=>$this->item->set_item($this->input->post(),$this->session->id));
	}

	public function update_item(){
		return $this->data=array('data'=>$this->item->update_item($this->input->post()));
	}

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{

		$this->load->view('pages/header.php');
		$this->load->view('pages/navigation.php',self::get_categories());

		$this->form_validation->set_error_delimiters('
<pclass="text-danger">', '
');
		$this->form_validation->set_rules('title', 'Title', 'required');
		//$this->form_validation->set_rules('content_description', 'Description', 'required');
		$this->form_validation->set_rules('series', 'Series', 'callback_series_check');

		/*
		 * Permission denied if add menu is not allowed
		 */
		if(!$this->menu['materials']){
			$this->load->view('errors/html/error_permission');
		}else{
			self::_validate_form();
		}

		$this->load->view('pages/footer.php');

	}

	public function series_check($str)
    {
    	if($str<=0){
    		$this->form_validation->set_message('series_check', 'Invalid series');
        	return FALSE;
    	}

    	return TRUE;

    }

	private function _validate_form(){

		#get category details using ITEM category_id
		$category_details=($this->category->get_category_details(@$this->session_privileges[0]->role_id,@$this->item_details[0]->cat_id));

		#update form requires category_details
		#this is not required for add form
		if(isset($category_details[0])){
			if(!@$category_details[0]->update_privilege||!@$category_details[0]->write_privilege){
				$this->load->view('errors/html/error_permission');
				return 0;
			}
		}

		if ($this->form_validation->run() == FALSE)
        {
        		//clear cookies
        		setcookie("dms-upload-redirect-to",str_replace('||','&',$this->input->get('redirect_url')),1,'/');

        		//update
        		if($this->input->get('item_id')){
        			//set redirect URL
        			setcookie("dms-upload-redirect-to",str_replace('||','&',$this->input->get('redirect_url')),time()+3600,'/');
        			#$this->load->view('forms/item.php',array('data'=>$this->session_sub_categories,'param'=>$this->input->get(),'items'=>$this->item_details));
        			$this->load->view('forms/item.php',array('param'=>$this->input->get(),'items'=>$this->item_details));
        		}else{
        			//add new
        			$this->load->view('forms/item.php');
        		}

        }
        else
        {

        		if(is_null($this->input->post('id'))||empty($this->input->post('id'))){
        			//create new
            		$this->last_insert_result=self::set_item();

            		$redirect_url=site_url().'?item_id='.$this->last_insert_result['data'].'&id='.$this->input->post('series').'&category=true&title=true';

            		//set redirect URL
        			setcookie("dms-upload-redirect-to",str_replace('||','&',$redirect_url),time()+3600,'/');

            	}else{

					//update
            		$this->last_insert_result=self::update_item();

            	}

				#clear OLD cookies
            	setcookie("dms-upload-id",$this->last_insert_result['data'],1,'/');
            	setcookie("dms-upload-cat",$this->input->post('series'),1,'/');

            	#set NEW cookies
            	if(is_null($this->input->post('id'))||empty($this->input->post('id'))){
            		setcookie("dms-upload-id",$this->last_insert_result['data'],time()+3600,'/');
            	}else{
            		setcookie("dms-upload-id",$this->input->post('id'),time()+3600,'/');
            	}

            	setcookie("dms-upload-cat",$this->input->post('series'),time()+3600,'/');

            	sleep(1);
            	header('location:'.site_url().'form/upload_multiple');

        }
	}

	public function upload(){

		$this->load->view('pages/header.php');
		$this->load->view('pages/navigation.php',self::get_categories());
		if(isset($_COOKIE['dms-upload-id'])&&isset($_COOKIE['dms-upload-cat'])){
                $this->load->view('pages/file-upload.php',array('last_id'=>@$_COOKIE['dms-upload-id']));
         }
		$this->load->view('pages/footer.php');
	}

	public function upload_multiple(){

		$this->load->view('pages/header.php');
		$this->load->view('pages/navigation.php',self::get_categories());
		if(isset($_COOKIE['dms-upload-id'])&&isset($_COOKIE['dms-upload-cat'])){
                $this->load->view('pages/file-upload-multiple.php',array('last_id'=>@$_COOKIE['dms-upload-id']));
         }
		$this->load->view('pages/footer.php');
	}

	public function file(){

		if(isset($_COOKIE['dms-upload-id'])){

			if(!isset($_FILES['file'])){
				$error = array('error' => 'invalid file');
                 echo json_encode($error);
                 exit;
			}

			$inf=pathinfo($_FILES['file']['name']);

			#config
 			$config['file_name']          = @$_COOKIE['dms-upload-id'].'.'.@$inf['extension'];
			$config['upload_path']          = '../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'];
            $config['allowed_types']        = 'gif|jpg|png|jpeg|pdf|bmp';
            $config['max_size']             = 50000;
            $config['overwrite'] = TRUE;

			$this->load->library('upload', $config);

			#create directory
            if(!is_dir('../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'])){
            	mkdir('../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'],0777,true);
            }

           #upload file

            if (!$this->upload->do_upload('file'))
            {
                    $error = array('error' => $this->upload->display_errors());
                    echo json_encode($error);

            }
            else
            {

            		$is_name_updated=$this->file->change_file_name(@$_COOKIE['dms-upload-id'],$_FILES['file']['name'],$config['file_name']);

            		if($is_name_updated==1){
            			$data = array('upload_data' => $this->upload->data());

	                    echo json_encode(array('data'=>$this->upload->data('file_name')));
	                    #expire the cookie
	                    setcookie("dms-upload-id",'',1);
	                     setcookie("dms-upload-cat",'',1);
	                 }else{
	                 	$error = array('error' => 'Oops Something went wrong. Please check file name and size.');
                    	echo json_encode($error);
	                 }

            }

            //$this->load->view('ajax/file.php');

         }

	}

	public function file_multiple(){
		if(isset($_COOKIE['dms-upload-id'])){

			if(!isset($_FILES['file'])){
				$error = array('error' => 'invalid file');
                 echo json_encode($error);
                 exit;
			}

			$inf = pathinfo($_FILES['file']['name']);

			#config
 			$config['file_name']          = @$_COOKIE['dms-upload-id'].''.time().'.'.@$inf['extension'];
			$config['upload_path']          = '../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'];
            $config['allowed_types']        = 'gif|jpg|png|jpeg|pdf|bmp';
            $config['max_size']             = 50000;
            $config['overwrite'] = TRUE;

			$this->load->library('upload', $config);

			#create directory
            if(!is_dir('../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'])){
            	mkdir('../uploads/'.@$_COOKIE['dms-upload-cat'].'/'.@$_COOKIE['dms-upload-id'],0777,true);
            }

           #upload file

            if (!$this->upload->do_upload('file'))
            {
                    $error = array('error' => $this->upload->display_errors());
                    echo json_encode($error);
            }
            else
            {

            		$is_name_updated = $this->file->save(@$_COOKIE['dms-upload-id'],$_FILES['file']['name'],$config['file_name']);

            		if($is_name_updated==1){
            			$data = array('upload_data' => $this->upload->data());

	                    echo json_encode(array('data'=>$this->upload->data('file_name')));
	                    #expire the cookie
	                    setcookie("dms-upload-id",'',1);
	                     setcookie("dms-upload-cat",'',1);
	                 }else{
	                 	$error = array('error' => 'Oops Something went wrong. Please check file name and size.');
                    	echo json_encode($error);
	                 }

            }

            //$this->load->view('ajax/file.php');

         }
	}

	public function success(){

		$this->load->view('pages/header.php');
		$this->load->view('pages/navigation.php',self::get_categories());
		$this->load->view('pages/add-success.php');
		$this->load->view('pages/footer.php');
	}

}


text:
using System.Linq;
using System.Threading.Tasks;

namespace Oort.AzureStorage.Multiplex
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;
    using Async;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Table;
    using Mockable;

    public class MultiTableReference
    {
        private readonly ICloudTable[] _tables;
        private readonly int[] _defaultSpread;

        public MultiTableReference(string tableName, params ICloudStorageAccount[] accounts)
        {
            var clients = accounts.Select(a => a.CreateCloudTableClient()).ToArray();
            _tables = clients.Select(c => c.GetTableReference(tableName)).ToArray();

            var spread = new List<int>();
            for (int i = 1; i < _tables.Length; i*=2)
            {
                spread.Add(i);
            }
            spread.Add(_tables.Length);
            _defaultSpread = spread.ToArray();
        }

        public Task<MultiTableResult> ExecuteAllAsync(TableOperation operation)
        {
            return MultiTableResult.AllFromOperation(operation, _tables);
        }

        public Task<TableResult> ExecuteAnyAsync(TableOperation operation, TableRequestOptions requestOptions = default(TableRequestOptions), OperationContext operationContext = default (OperationContext))
        {
            return ExecuteAnyAsync(operation, _defaultSpread, requestOptions, operationContext);
        }

        public async Task<TableResult> ExecuteAnyAsync(TableOperation operation, int[] spread, TableRequestOptions requestOptions = default(TableRequestOptions), OperationContext operationContext = default (OperationContext))
        {
            TryResult<TableResult> tryResult = null;

            foreach (int t in spread)
            {
                int use = t;
                tryResult = use == 1 ?
                    await TryAsync.Execute(() => _tables[0].ExecuteAsync(operation, requestOptions, operationContext), IsSuccess)
                    :
                    await TryAsync.Execute(() => ExecuteAnyAsync(operation, use, requestOptions, operationContext), IsSuccess);
                if (tryResult.Success)
                {
                    return tryResult.Result;
                }
            }

            throw tryResult != null ?
                new MultiplexException("Operation failed on all accounts.", tryResult.Exception)
                :
                new MultiplexException("Operation failed on all accounts.");
        }

        private Task<TableResult> ExecuteAnyAsync(TableOperation operation, int spread, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            var cts = new CancellationTokenSource();
            return Async.FirstCompleted(_tables.Take(spread).Select(t => t.ExecuteAsync(operation, requestOptions, operationContext, cts.Token)), cts);
        }

        private static bool IsSuccess(TableResult result)
        {
            return result.HttpStatusCode > 199 && result.HttpStatusCode < 300;
        }
    }
}


text:
/*jslint node:true, nomen:true, plusplus:true, regexp:true, vars:true, continue:true, bitwise:true */
'use strict';

var pkg = require('../package.json');

var util = require('util');
var path = require('path');
var opts = require('opts');
var reichatServer = require('reichat-server');

opts.parse([
	{
		short: 'v',
		long: 'version',
		description: 'Show version and exit',
		callback: function () {

			console.log(pkg.version);
			process.exit(0);
		}
	},
	{
		long: 'config',
		description: 'Load a config file',
		value: true
	},
	{
		long: 'host',
		description: 'Listening host',
		value: true
	},
	{
		long: 'port',
		description: 'Listening port',
		value: true
	},
	{
		long: 'title',
		description: 'Title of chat room',
		value: true
	},
	{
		long: 'canvas-width',
		description: 'Width of canvas',
		value: true
	},
	{
		long: 'canvas-height',
		description: 'Height of canvas',
		value: true
	},
	{
		long: 'redis-host',
		description: 'Redis host',
		value: true
	},
	{
		long: 'redis-port',
		description: 'Redis port',
		value: true
	},
	{
		long: 'redis-password',
		description: 'Redis password',
		value: true
	},
	{
		long: 'redis-key-prefix',
		value: true
	},
	{
		long: 'data-dir',
		description: 'Data saving directory',
		value: true
	},
	{
		long: 'data-file-prefix',
		value: true
	},
	{
		long: 'max-paint-log-count',
		value: true
	},
	{
		long: 'max-chat-log-count',
		value: true
	},
	{
		long: 'forwarded-header',
		value: true
	}
].reverse(), true);

var config = opts.get('config') ? require(opts.get('config')) : {};

config.host = opts.get('host') || config.host || process.env.HOST || '0.0.0.0';
config.port = opts.get('port') || config.port || process.env.PORT || 10133;
config.title = opts.get('title') || config.title || process.env.TITLE || 'PaintChat';

config.canvasWidth = parseInt(opts.get('canvas-width') || config.canvasWidth || process.env.CANVAS_WIDTH || 1920, 10);
config.canvasHeight = parseInt(opts.get('canvas-height') || config.canvasHeight || process.env.CANVAS_HEIGHT || 1080, 10);
config.redisHost = opts.get('redis-host') || config.redisHost || process.env.REDIS_HOST || '';
config.redisPort = parseInt(opts.get('redis-port') || config.redisPort || process.env.REDIS_PORT || 6379, 10);
config.redisPassword = opts.get('redis-password') || config.redisPassword || process.env.REDIS_PASSWORD || '';
config.redisKeyPrefix = opts.get('redis-key-prefix') || config.redisKeyPrefix || process.env.REDIS_KEY_PREFIX || '';
config.dataDir = opts.get('data-dir') || config.dataDir || process.env.DATA_DIR || require('os').tmpdir();
config.dataFilePrefix = opts.get('data-file-prefix') || config.dataFilePrefix || process.env.DATA_FILE_PREFIX || 'reichat_';
config.maxPaintLogCount = parseInt(opts.get('max-paint-log-count') || config.maxPaintLogCount || process.env.MAX_PAINT_LOG_COUNT || 2000, 10);
config.maxChatLogCount = parseInt(opts.get('max-chat-log-count') || config.maxChatLogCount || process.env.MAX_CHAT_LOG_COUNT || 100, 10);
config.forwardedHeaderType = opts.get('forwarded-header') || config.forwardedHeader || process.env.FORWARDED_HEADER || '';

config.layerCount = 3;
config.clientDir = [__dirname, 'client'].join(path.sep);
config.clientVersion = pkg.version;

reichatServer.createServer(config).once('ready', function () {

	process.title = 'reichat server - ' + this.id;

	this.listen(config.port, config.host, null, function () {
		util.log(util.format('listening on %s:%s', config.host, config.port));
	});

	util.log(util.format('created server id: %s', this.id));
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
<TITLE>Dialog Verfügbare asymmetrische Schlüsselpaare</TITLE>
<link rel="stylesheet" type="text/css" href="CrypTool_Help.css">

<OBJECT TYPE="application/x-oleobject" CLASSID="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" VIEWASTEXT>
	<PARAM NAME="Keyword" VALUE="Dialog (Übersicht aller Dialoge)">
	<PARAM NAME="Keyword" VALUE="Asymmetrisch">
	<PARAM NAME="Keyword" VALUE="Schlüssel">
</OBJECT>

Dialog Verfügbare asymmetrische Schlüsselpaare

Der Dialog wird über den Befehl Schlüssel anzeigen/exportieren aus dem Menü Digitale Signaturen/PKI \ PKI geöffnet.

In diesem Dialog werden alle verfügbaren asymmetrischen Schlüsselpaare angezeigt.

Mit den Auswahlknöpfen RSA-Schlüssel, DSA-Schlüssel und EC-Schlüssel können Sie auswählen, welche Schlüssel in der Liste angezeigt werden.

Mit Hilfe der Knöpfe Öffentliche Parameter anzeigen, Alle Parameter anzeigen und Zertifikat anzeigen können Sie sich den Inhalt des ausgewählten Zertifikats anzeigen lassen. Um alle Parameter anzuzeigen, wird die PIN der PSE benötigt. Nicht alle Daten sind für alle Zertifikatstypen (RSA, DSA, EC) verfügbar.

Mit dem Knopf Eintrag löschen können Sie nicht mehr benötigte Schlüsselpaare löschen.

Schlüsselpaare können mit PSE exportieren (PKCS #12) in das standardisierte PKCS #12-Format exportiert werden.

Schließen beendet den Dialog.


text:
#include "config.h"
#include "Int32Array.h"

namespace WebCore {

PassRefPtr<Int32Array> Int32Array::create(unsigned length)
{
    return TypedArrayBase<int>::create<Int32Array>(length);
}

PassRefPtr<Int32Array> Int32Array::create(int* array, unsigned length)
{
    return TypedArrayBase<int>::create<Int32Array>(array, length);
}

PassRefPtr<Int32Array> Int32Array::create(PassRefPtr<ArrayBuffer> buffer, unsigned byteOffset, unsigned length)
{
    return TypedArrayBase<int>::create<Int32Array>(buffer, byteOffset, length);
}

Int32Array::Int32Array(PassRefPtr<ArrayBuffer> buffer, unsigned byteOffset, unsigned length)
    : IntegralTypedArrayBase<int>(buffer, byteOffset, length)
{
}

PassRefPtr<Int32Array> Int32Array::subarray(int start) const
{
    return subarray(start, length());
}

PassRefPtr<Int32Array> Int32Array::subarray(int start, int end) const
{
    return subarrayImpl<Int32Array>(start, end);
}

}


text:
'use strict';

(function () {
   var chartarea = document.getElementById("myChart").getContext("2d");
   var apiUrlPolls = 'https://votingapp-naiyucko.c9users.io/api/polls';

   function ready (fn) {
      if (typeof fn !== 'function') {
         return;
      }

      if (document.readyState === 'complete') {
         return fn();
      }

      document.addEventListener('DOMContentLoaded', fn, false);
   }

   function ajaxRequest (method, url, callback) {
      var xmlhttp = new XMLHttpRequest();

      xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            callback(xmlhttp.response);
         }
      };

      xmlhttp.open(method, url, true);
      xmlhttp.send();
   }

    function updateClickCount (data) {
        var goddamn = JSON.parse(data);
        var currenthome = window.location.href.substring( 0, window.location.href.length - 4);
        document.querySelector('#ummm').innerHTML = "<h1>" + goddamn.title + "</h1>";
        document.querySelector('#wellthen').innerHTML = 'Share this voting Link: <input type="text" name="country" value="' + currenthome + '" readonly></input>';
        var keystuff = Object.keys(goddamn);
        var data3 = {};
        keystuff.splice(0, 2);
        data3.labels = keystuff;
        data3.datasets = [];
        var valuesofdata = [];
        for (var v = 0; v < keystuff.length; v++)
        {
            valuesofdata[v] = goddamn[keystuff[v]];
        }
        data3.datasets[0] = {
            label: "My First dataset",
            fillColor: "rgba(49,75,112,0.5)",
            strokeColor: "rgba(49,75,112,0.8)",
            highlightFill: "rgba(49,75,112,0.75)",
            highlightStroke: "rgba(49,75,112,1)",
            data: valuesofdata
        };
        var myLineChart = new Chart(chartarea).Bar(data3);
   }

   ready(ajaxRequest('POST', window.location.href, updateClickCount));
})();


text:
<!--
  ~ Copyright (c) 2016.
  ~
  ~ Rex M. Torres <rexmtorres@gmail.com>
  -->

<resources>

    <!-- Base application theme. -->
    <style name="AppThemeDot" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="patternLockViewStyle">@style/MyPatternLockDot</item>
    </style>

    <style name="AppThemeDroid" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="patternLockViewStyle">@style/MyPatternLockDroid</item>
    </style>

    <style name="MyPatternLockDot">
        <item name="regularColor">@color/colorPrimaryDark</item>
        <item name="pathColor">@color/colorPrimary</item>
        <item name="successColor">@color/holoGreenDark</item>
        <item name="errorColor">@color/holoRedLight</item>
    </style>

    <style name="MyPatternLockDroid">
        <item name="dotBitmap">@mipmap/ic_launcher</item>
        <item name="regularColor">@color/colorPrimaryDark</item>
        <item name="pathColor">@color/colorPrimary</item>
        <item name="successColor">@color/holoGreenDark</item>
        <item name="errorColor">@color/holoRedLight</item>
    </style>

    <style name="AppThemeDot.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppThemeDroid.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>

    <style name="AppThemeDot.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <style name="AppThemeDot.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>

</resources>


text:
#import <Foundation/Foundation.h>

/**
 * The log levels used by internal logging.
 */
typedef NS_ENUM(NSInteger, GULLoggerLevel) {
  /** Error level, matches ASL_LEVEL_ERR. */
  GULLoggerLevelError = 3,
  /** Warning level, matches ASL_LEVEL_WARNING. */
  GULLoggerLevelWarning = 4,
  /** Notice level, matches ASL_LEVEL_NOTICE. */
  GULLoggerLevelNotice = 5,
  /** Info level, matches ASL_LEVEL_INFO. */
  GULLoggerLevelInfo = 6,
  /** Debug level, matches ASL_LEVEL_DEBUG. */
  GULLoggerLevelDebug = 7,
  /** Minimum log level. */
  GULLoggerLevelMin = GULLoggerLevelError,
  /** Maximum log level. */
  GULLoggerLevelMax = GULLoggerLevelDebug
} NS_SWIFT_NAME(GoogleLoggerLevel);


text:
"""
    Server API

    Reference for Server API (REST/Json)

    OpenAPI spec version: 2.0.21

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.video_stats_videos_watching_response import VideoStatsVideosWatchingResponse

class TestVideoStatsVideosWatchingResponse(unittest.TestCase):
    """ VideoStatsVideosWatchingResponse unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testVideoStatsVideosWatchingResponse(self):
        """
        Test VideoStatsVideosWatchingResponse
        """
        model = kinow_client.models.video_stats_videos_watching_response.VideoStatsVideosWatchingResponse()

if __name__ == '__main__':
    unittest.main()


text:
CREATE DATABASE IF NOT EXISTS gearsloth
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;

GRANT ALL PRIVILEGES ON gearsloth.*
  TO 'sloth'@'%'
  IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON gearsloth.*
  TO 'sloth'@'localhost'
  IDENTIFIED BY 'password';

FLUSH PRIVILEGES;


text:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from . import views

urlpatterns = patterns(
    '',
    url('program_export/', views.program_export, name='program_export'),

    # Venue pages.
    url(r"^venue/$",
        TemplateView.as_view(template_name="venue/detail.html"),
        name="venue_detail"),
    url(r"^venue/bars/$",
        TemplateView.as_view(template_name="venue/bars.html"),
        name="bars"),
    url(r"^venue/directions/$",
        TemplateView.as_view(template_name="venue/directions.html"),
        name="directions"),
    url(r"^venue/explore/$",
        TemplateView.as_view(template_name="venue/explore.html"),
        name="explore"),
    url(r"^venue/getting-around/$",
        TemplateView.as_view(template_name="venue/getting_around.html"),
        name="getting_around"),
    url(r"^venue/hotels/$",
        TemplateView.as_view(template_name="venue/hotels.html"),
        name="hotels"),
    url(r"^venue/restaurants/$",
        TemplateView.as_view(template_name="venue/restaurants.html"),
        name="restaurants"),
    url(r"^venue/share-room/$",
        TemplateView.as_view(template_name="venue/share_room.html"),
        name="share_room"),
    url(r"^venue/shopping/$",
        TemplateView.as_view(template_name="venue/shopping.html"),
        name="shopping"),
    url(r"^venue/traveling/$",
        TemplateView.as_view(template_name="venue/traveling.html"),
        name="traveling"),
    url(r"^venue/weather/$",
        TemplateView.as_view(template_name="venue/weather.html"),
        name="weather"),
)


text:
#pragma once

#include "CachedImage.h"
#include "CachedResourceHandle.h"
#include "StyleImage.h"
#include <wtf/IsoMalloc.h>

namespace WebCore {

class CachedImage;
class RenderElement;

class RenderImageResource {
    WTF_MAKE_NONCOPYABLE(RenderImageResource); WTF_MAKE_ISO_ALLOCATED(RenderImageResource);
public:
    RenderImageResource();
    virtual ~RenderImageResource() = default;

    virtual void initialize(RenderElement& renderer) { initialize(renderer, nullptr); }
    virtual void shutdown();

    void setCachedImage(CachedImage*);
    CachedImage* cachedImage() const { return m_cachedImage.get(); }

    void resetAnimation();

    virtual RefPtr<Image> image(const IntSize& size = { }) const;
    virtual bool errorOccurred() const { return m_cachedImage && m_cachedImage->errorOccurred(); }

    virtual void setContainerContext(const IntSize&, const URL&);

    virtual bool imageHasRelativeWidth() const { return m_cachedImage && m_cachedImage->imageHasRelativeWidth(); }
    virtual bool imageHasRelativeHeight() const { return m_cachedImage && m_cachedImage->imageHasRelativeHeight(); }

    inline LayoutSize imageSize(float multiplier) const { return imageSize(multiplier, CachedImage::UsedSize); }
    inline LayoutSize intrinsicSize(float multiplier) const { return imageSize(multiplier, CachedImage::IntrinsicSize); }

    virtual WrappedImagePtr imagePtr() const { return m_cachedImage.get(); }

protected:
    RenderElement* renderer() const { return m_renderer; }
    void initialize(RenderElement&, CachedImage*);

private:
    virtual LayoutSize imageSize(float multiplier, CachedImage::SizeType) const;

    RenderElement* m_renderer { nullptr };
    CachedResourceHandle<CachedImage> m_cachedImage;
    bool m_cachedImageRemoveClientIsNeeded { true };
};

} // namespace WebCore


text:
set -e
case $1 in
  mpich1) set -x;
    sudo apt-get install -q gfortran mpich-shmem-bin libmpich-shmem1.0-dev;;
  mpich2) set -x;
    sudo apt-get install -q gfortran mpich2 libmpich2-dev;;
  mpich3) set -x;
    sudo apt-get install -q gfortran libcr0 default-jdk;
    wget -q http://www.cebacad.net/files/mpich/ubuntu/mpich-3.1/mpich_3.1-1ubuntu_amd64.deb;
    sudo dpkg -i ./mpich_3.1-1ubuntu_amd64.deb;
    rm -f ./mpich_3.1-1ubuntu_amd64.deb;;
  openmpi) set -x;
    sudo apt-get install -q gfortran openmpi-bin openmpi-common libopenmpi-dev;;
  *)
    echo "Unknown MPI implementation:" $1; exit 1;;
esac


text:
set -e

revision="$1"

if [ -z "$revision" ]
then
  echo "Usage: $0 git-revision-full-sha1" >&2
  exit 1
fi

[ -f "chromium-bidi.zip" ] && rm "chromium-bidi.zip"
[ -d "src" ] && rm --recursive --force "src"

wget --output-document="chromium-bidi.zip" "https://github.com/GoogleChromeLabs/chromium-bidi/archive/$revision.zip"
unzip "chromium-bidi.zip"
mv "chromium-bidi-$revision" src

date=$(date "+%Y-%m-%d")
sha512=$(sha512sum --binary "chromium-bidi.zip" | cut --fields=1 --delimiter=' ')
rm "chromium-bidi.zip"
echo "$date,$revision,$sha512" > "revision.info"


text:
package UI;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Canvas;

import swing2swt.layout.BorderLayout;

import org.eclipse.ui.forms.widgets.FormToolkit;

import FDM.Fdm;
import FDM.ReadFile;
import FDM.WriteFile;

import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;

public class ChlorideAttackSimulatorApp {

	protected Shell shell;

	private Fdm fdm = null;
	private final FormToolkit formToolkit = new FormToolkit(Display.getDefault());

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			ChlorideAttackSimulatorApp window = new ChlorideAttackSimulatorApp();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setModified(true);
		shell.setSize(600, 600);
		shell.setText("Chloride Attack Simulator 2014 - SungYong");
		shell.setLayout(new BorderLayout(0, 0));

		SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
		sashForm.setLocation(0, 0);
		formToolkit.adapt(sashForm);
		formToolkit.paintBordersFor(sashForm);

		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
		mntmFile.setText("File");

		Menu menu_1 = new Menu(mntmFile);
		mntmFile.setMenu(menu_1);

		MenuItem mntmNew = new MenuItem(menu_1, SWT.CASCADE);
		mntmNew.setText("New");

		Menu menu_2 = new Menu(mntmNew);
		mntmNew.setMenu(menu_2);

		MenuItem mntmSimpleChloride = new MenuItem(menu_2, SWT.NONE);
		mntmSimpleChloride.setText("Simple Chloride");

		MenuItem mntmOpenFile = new MenuItem(menu_1, SWT.NONE);
		mntmOpenFile.setText("Open File");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem mntmClose = new MenuItem(menu_1, SWT.NONE);
		mntmClose.setText("Close");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem mntmSave = new MenuItem(menu_1, SWT.NONE);
		mntmSave.setText("Save");

		MenuItem mntmSaveAs = new MenuItem(menu_1, SWT.NONE);
		mntmSaveAs.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				WriteFile writeFile = new WriteFile(shell, fdm);
			}
		});
		mntmSaveAs.setText("Save As");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem mntmRecent = new MenuItem(menu_1, SWT.NONE);
		mntmRecent.setText("Recent 0");

		MenuItem mntmRecent_1 = new MenuItem(menu_1, SWT.NONE);
		mntmRecent_1.setText("Recent 1");

		MenuItem mntmRecent_2 = new MenuItem(menu_1, SWT.NONE);
		mntmRecent_2.setText("Recent 2");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
		mntmExit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shell.dispose();
			}
		});
		mntmExit.setText("Exit");

		MenuItem mntmView = new MenuItem(menu, SWT.CASCADE);
		mntmView.setText("View");

		Menu menu_5 = new Menu(mntmView);
		mntmView.setMenu(menu_5);

		MenuItem mntmNodesHistory = new MenuItem(menu_5, SWT.NONE);
		mntmNodesHistory.setEnabled(false);
		mntmNodesHistory.setText("Nodes' history");

		final MenuItem mntmSolve = new MenuItem(menu, SWT.CASCADE);
		mntmSolve.setEnabled(false);
		mntmSolve.setText("Solve");

		Menu menu_3 = new Menu(mntmSolve);
		mntmSolve.setMenu(menu_3);

		final MenuItem mntmSolve_1 = new MenuItem(menu_3, SWT.NONE);
		mntmSolve_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				fdm.solve(2000);

			}
		});
		mntmSolve_1.setEnabled(false);
		mntmSolve_1.setText("Solve");

		MenuItem mntmHelp = new MenuItem(menu, SWT.CASCADE);
		mntmHelp.setText("Help");

		Menu menu_4 = new Menu(mntmHelp);
		mntmHelp.setMenu(menu_4);

		MenuItem mntmWelcome = new MenuItem(menu_4, SWT.NONE);
		mntmWelcome.setText("Welcome");

		new MenuItem(menu_4, SWT.SEPARATOR);

		MenuItem mntmAboutCas = new MenuItem(menu_4, SWT.NONE);
		mntmAboutCas.setText("About CAS2014");

		final Canvas canvas = new Canvas(sashForm, SWT.BORDER);
		final ProblemCanvas problemCanvas = new ProblemCanvas(canvas);

		final StyledText styledText = new StyledText(sashForm, SWT.BORDER | SWT.V_SCROLL);
		styledText.append( "Welcome >");
		styledText.setCaretOffset( styledText.getCharCount() );
		styledText.addVerifyKeyListener(new VerifyKeyListener() {
			public void verifyKey(VerifyEvent keyEvent) {
				String thisLine = styledText.getLine( styledText.getLineCount() - 1);
				if(keyEvent.keyCode == 13 || keyEvent.keyCode == 16777296){

					String response = commandCenter(  thisLine );

					styledText.append("\n" + response + "\n>");

					keyEvent.doit = false;
					styledText.setCaretOffset( styledText.getCharCount() );
				}

				int lastLineLength = styledText.getLine( styledText.getLineCount() -1 ).length();
				if( styledText.getCaretOffset() < styledText.getCharCount() - lastLineLength +2 ){
					if( keyEvent.keyCode == 8 ){
						keyEvent.doit = false;
					}

				}
			}
		});

		formToolkit.adapt(styledText);
		formToolkit.paintBordersFor(styledText);
		sashForm.setWeights(new int[] {2, 1});

		Label lblStatus = new Label(shell, SWT.NONE);
		lblStatus.setLayoutData(BorderLayout.SOUTH);
		formToolkit.adapt(lblStatus, true, true);
		lblStatus.setText("Status");

		mntmOpenFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				System.out.println("Open file selected");
				ReadFile readfile = new ReadFile(shell);
				fdm = readfile.getFdm();

				mntmSolve.setEnabled( fdm != null);
				mntmSolve_1.setEnabled(fdm != null);

				String terminalStatus = readfile.getFileName();
				styledText.append("\n" + terminalStatus + " >");
				styledText.setCaretOffset( styledText.getCharCount() );
				if( fdm != null ){
					problemCanvas.canvas(fdm);
					canvas.redraw();
				}
			}
		});

	}

	private String commandCenter(String command){
		String trimmedLine = command.trim();
		String realCommand = trimmedLine.split(">")[1].trim().toLowerCase();

		String response = "";
		if( realCommand.startsWith("open")){
			response = "Not implemented yet. Sorry. \nYou can open a file with the menu.";
		}
		else if(realCommand.startsWith("solve")){

		}
		else{
			response = "No Such command \""+realCommand + "\"";
		}
		return response;
	}
}


text:
#include <ros/ros.h>
#include <ros/console.h>
#include <p5glove_ros/GloveData.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/Header.h>

#include <p5glove_ros/p5glove.h>
#include <errno.h>
//#include <tf/tf.h>
//#include <tf/LinearMath.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <math.h>

int main(int argc, char **argv)
{
  P5Glove glove;
  glove=p5glove_open(0);
  if (glove == NULL) {
    ROS_FATAL("%s: Can't open glove interface\n", argv[0]);
    return 1;
  }

  ros::init(argc, argv, "p5glove_node");
  ros::NodeHandle nh;
  ros::Publisher pub = nh.advertise<p5glove_ros::GloveData>("glove_data", 100);
  ros::Publisher pub_pose = nh.advertise<geometry_msgs::PoseStamped>("glove_posestamped", 100);
  ros::Publisher pub_pose2 = nh.advertise<geometry_msgs::PoseStamped>("glove_posestamped2", 100);
  ros::Publisher pub_pose3 = nh.advertise<geometry_msgs::PoseStamped>("glove_posestamped3", 100);

  // variables used for low level data acquisition
  uint32_t buttons;
  double clench;
  double pos[3];
  double axis[3],angle;

  while(ros::ok())
  {
    p5glove_ros::GloveData msg;
    const int err=p5glove_sample(glove, -1);
    if (err < 0 && errno == EAGAIN)
      continue;
    if (err < 0) {
      ROS_ERROR("Glove Failure, detector not finding it, stopped publishing data.");
      continue;
    }

    p5glove_get_buttons(glove,&buttons);
    msg.buttonA = (buttons & P5GLOVE_BUTTON_A) ? 1 : 0;
    msg.buttonB = (buttons & P5GLOVE_BUTTON_B) ? 1 : 0;
    msg.buttonC = (buttons & P5GLOVE_BUTTON_C) ? 1 : 0;
    ROS_DEBUG_STREAM("ButtonA: " << msg.buttonA
                  << "ButtonB: " << msg.buttonB
                  << "ButtonC: " << msg.buttonC);

    for(int i=0; i < 5; ++i)
    {
      p5glove_get_finger(glove,i,&clench);
      msg.fingers.push_back(clench);
      ROS_DEBUG_STREAM("Finger #" << i << " :" << clench);
    }

    p5glove_get_position(glove, pos);
//    msg.pose.position.x = pos[0];
//    msg.pose.position.y = pos[1];
//    msg.pose.position.z = pos[2];

    /* they use weird axis */
    msg.pose.position.x = - pos[2]; // X on gloves axis (see PDF)
    msg.pose.position.y = - pos[0]; // Y
    msg.pose.position.z = pos[1];   // Z
    ROS_DEBUG_STREAM("Position:("
                     << pos[0] << ","
                     << pos[1] << ","
                     << pos[2] << ")");

    p5glove_get_rotation(glove, &angle, axis);
    // from axis-angle representation to Quaternion, but i think this axis is wrong as the position
    tf::Quaternion quat (tf::Vector3(- axis[2], - axis[0], axis[1]), angle * M_PI / 180.0);
    msg.pose.orientation.x = quat.getX();
    msg.pose.orientation.y = quat.getY();
    msg.pose.orientation.z = quat.getZ();
    msg.pose.orientation.w = quat.getW();

    ROS_DEBUG_STREAM("Orientation:("
                     << msg.pose.orientation.x << ","
                     << msg.pose.orientation.y << ","
                     << msg.pose.orientation.z << ","
                     << msg.pose.orientation.w << ")");

    msg.header.stamp = ros::Time::now();
    pub.publish(msg);
    geometry_msgs::PoseStamped posestamped;
    posestamped.pose = msg.pose;
    posestamped.header.stamp= ros::Time::now();
    posestamped.header.frame_id = "base_link";
    pub_pose.publish(posestamped);

    ros::spinOnce();
  }
  p5glove_close(glove);
  return 0;
}


text:
package org.springframework.boot.test.web.client;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.mock.env.MockEnvironment;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link LocalHostUriTemplateHandler}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Eddú Meléndez
 */
public class LocalHostUriTemplateHandlerTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void createWhenEnvironmentIsNullShouldThrowException() {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Environment must not be null");
		new LocalHostUriTemplateHandler(null);
	}

	@Test
	public void createWhenSchemeIsNullShouldThrowException() {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Scheme must not be null");
		new LocalHostUriTemplateHandler(new MockEnvironment(), null);
	}

	@Test
	public void getRootUriShouldUseLocalServerPort() throws Exception {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("local.server.port", "1234");
		LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
				environment);
		assertThat(handler.getRootUri()).isEqualTo("http://localhost:1234");
	}

	@Test
	public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() throws Exception {
		MockEnvironment environment = new MockEnvironment();
		LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
				environment);
		assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080");
	}

	@Test
	public void getRootUriUsesCustomScheme() {
		MockEnvironment environment = new MockEnvironment();
		LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment,
				"https");
		assertThat(handler.getRootUri()).isEqualTo("https://localhost:8080");
	}

	@Test
	public void getRootUriShouldUseContextPath() throws Exception {
		MockEnvironment environment = new MockEnvironment();
		environment.setProperty("server.servlet.context-path", "/foo");
		LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
				environment);
		assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo");
	}

}


text:
class QHexDocument: public QObject
{
    Q_OBJECT

    private:
        explicit QHexDocument(QHexBuffer* buffer, QObject *parent = NULL);

    public:
        bool isEmpty() const;
        bool atEnd() const;
        bool canUndo() const;
        bool canRedo() const;
        int length() const;
        int baseAddress() const;
        QHexCursor* cursor() const;
        QHexMetadata* metadata() const;

    public:
        void removeSelection();
        QByteArray read(int offset, int len = 0);
        QByteArray selectedBytes() const;
        char at(int offset) const;
        void setBaseAddress(int baseaddress);
        void sync();

    public slots:
        void undo();
        void redo();
        void cut(bool hex = false);
        void copy(bool hex = false);
        void paste(bool hex = false);
        void insert(int offset, uchar b);
        void replace(int offset, uchar b);
        void insert(int offset, const QByteArray& data);
        void replace(int offset, const QByteArray& data);
        void remove(int offset, int len);
        QByteArray read(int offset, int len) const;
        bool saveTo(QIODevice* device);

    public:
        template<typename T> static QHexDocument* fromDevice(QIODevice* iodevice, QObject* parent = NULL);
        template<typename T> static QHexDocument* fromFile(QString filename, QObject* parent = NULL);
        template<typename T> static QHexDocument* fromMemory(char *data, int size, QObject* parent = NULL);
        template<typename T> static QHexDocument* fromMemory(const QByteArray& ba, QObject* parent = NULL);

    signals:
        void canUndoChanged();
        void canRedoChanged();
        void documentChanged();
        void lineChanged(int line);

    private:
        QHexBuffer* m_buffer;
        QHexMetadata* m_metadata;
        QUndoStack m_undostack;
        QHexCursor* m_cursor;
        int m_baseaddress;
};

template<typename T> QHexDocument* QHexDocument::fromDevice(QIODevice* iodevice, QObject *parent)
{
    bool needsclose = false;

    if(!iodevice->isOpen())
    {
        needsclose = true;
        iodevice->open(QIODevice::ReadWrite);
    }

    QHexBuffer* hexbuffer = new T();
    hexbuffer->read(iodevice);

    if(needsclose)
        iodevice->close();

    return new QHexDocument(hexbuffer, parent);
}

template<typename T> QHexDocument* QHexDocument::fromFile(QString filename, QObject *parent)
{
    QFile f(filename);
    f.open(QFile::ReadOnly);

    QHexDocument* doc = QHexDocument::fromDevice<T>(&f, parent);
    f.close();
    return doc;
}

template<typename T> QHexDocument* QHexDocument::fromMemory(char *data, int size, QObject *parent)
{
    QHexBuffer* hexbuffer = new T();
    hexbuffer->read(data, size);
    return new QHexDocument(hexbuffer, parent);
}

template<typename T> QHexDocument* QHexDocument::fromMemory(const QByteArray& ba, QObject *parent)
{
    QHexBuffer* hexbuffer = new T();
    hexbuffer->read(ba);
    return new QHexDocument(hexbuffer, parent);
}

#endif // QHEXEDITDATA_H


text:
#ifndef ART_COMPILER_BUFFERED_OUTPUT_STREAM_H_
#define ART_COMPILER_BUFFERED_OUTPUT_STREAM_H_

#include "output_stream.h"

#include "globals.h"

namespace art {

class BufferedOutputStream : public OutputStream {
 public:
  explicit BufferedOutputStream(OutputStream* out);

  virtual ~BufferedOutputStream() {
    delete out_;
  }

  virtual bool WriteFully(const void* buffer, int64_t byte_count);

  virtual off_t Seek(off_t offset, Whence whence);

 private:
  static const size_t kBufferSize = 8 * KB;

  bool Flush();

  OutputStream* const out_;

  uint8_t buffer_[kBufferSize];

  size_t used_;

  DISALLOW_COPY_AND_ASSIGN(BufferedOutputStream);
};

}  // namespace art

#endif  // ART_COMPILER_BUFFERED_OUTPUT_STREAM_H_


text:
<?xml version="1.0" encoding="GBK"?>

<resultMap id="BaseResultMap" type="com.cardpay.pccredit.bank.model.XmAccCredit">
	<!-- <result column="CREATE_TIME" jdbcType="DATE_NOW" index="" style="yyyyMMdd"/> -->
	<result column="KHNM" jdbcType="VARCHAR" index="1" />

	<result column="TZH" jdbcType="VARCHAR" index="2" />

	<result column="CCZL" jdbcType="VARCHAR" index="3" />

	<result column="CCMC" jdbcType="VARCHAR" index="4" />

	<result column="SL" jdbcType="VARCHAR" index="5" />

	<result column="DW" jdbcType="VARCHAR" index="6" />

	<result column="GZRQ" jdbcType="VARCHAR" index="7" />

	<result column="ZCYZ" jdbcType="VARCHAR" index="8" />

	<result column="PGJZ" jdbcType="VARCHAR" index="9" />

	<result column="PGRQ" jdbcType="VARCHAR" index="10" />

	<result column="ZL" jdbcType="VARCHAR" index="13" />

	<result column="ID" jdbcType="VARCHAR" index="19" />

</resultMap>