text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>2. API Basics — Apache CouchDB 1.4 Manual</title>

    <link rel="stylesheet" href="_static/rtd.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="top" title="Apache CouchDB 1.4 Manual" href="index.html" />
    <link rel="next" title="3. Configuration" href="configuring.html" />
    <link rel="prev" title="1. Introduction" href="intro.html" />

Navigation

          index

          next |

          previous |

Apache CouchDB 1.4 Manual »

2. API Basics¶

The CouchDB API is the primary method of interfacing to a CouchDB
instance. Requests are made using HTTP and requests are used to request
information from the database, store new data, and perform views and
formatting of the information stored within the documents.

Requests to the API can be categorised by the different areas of the
CouchDB system that you are accessing, and the HTTP method used to send
the request. Different methods imply different operations, for example
retrieval of information from the database is typically handled by the
<tt class="docutils literal">GET</tt> operation, while updates are handled by either a <tt class="docutils literal">POST</tt> or
<tt class="docutils literal">PUT</tt> request. There are some differences between the information that
must be supplied for the different methods. For a guide to the basic
HTTP methods and request structure, see Request Format and Responses.

For nearly all operations, the submitted data, and the returned data
structure, is defined within a JavaScript Object Notation (JSON) object.
Basic information on the content and data types for JSON are provided in
JSON Basics.

Errors when accessing the CouchDB API are reported using standard HTTP
Status Codes. A guide to the generic codes returned by CouchDB are
provided in HTTP Status Codes.

When accessing specific areas of the CouchDB API, specific information
and examples on the HTTP methods and request, JSON structures, and error
codes are provided. For a guide to the different areas of the API, see
API Reference.

2.1. Request Format and Responses¶

CouchDB supports the following HTTP request methods:

<tt class="docutils literal">GET</tt>

Request the specified item. As with normal HTTP requests, the format
of the URL defines what is returned. With CouchDB this can include
static items, database documents, and configuration and statistical
information. In most cases the information is returned in the form of
a JSON document.

<tt class="docutils literal">HEAD</tt>

The <tt class="docutils literal">HEAD</tt> method is used to get the HTTP header of a <tt class="docutils literal">GET</tt>
request without the body of the response.

<tt class="docutils literal">POST</tt>

Upload data. Within CouchDB <tt class="docutils literal">POST</tt> is used to set values, including
uploading documents, setting document values, and starting certain
administration commands.

<tt class="docutils literal">PUT</tt>

Used to put a specified resource. In CouchDB <tt class="docutils literal">PUT</tt> is used to
create new objects, including databases, documents, views and design
documents.

<tt class="docutils literal">DELETE</tt>

Deletes the specified resource, including documents, views, and
design documents.

<tt class="docutils literal">COPY</tt>

A special method that can be used to copy documents and objects.

If you use the an unsupported HTTP request type with a URL that does not
support the specified type, a 405 error will be returned, listing the
supported HTTP methods. For example:

{
    "error":"method_not_allowed",
    "reason":"Only GET,HEAD allowed"
}

The CouchDB design document API and the functions when returning HTML
(for example as part of a show or list) enables you to include custom
HTTP headers through the <tt class="docutils literal">headers</tt> block of the return object.

2.2. HTTP Headers¶

Because CouchDB uses HTTP for all communication, you need to ensure that
the correct HTTP headers are supplied (and processed on retrieval) so
that you get the right format and encoding. Different environments and
clients will be more or less strict on the effect of these HTTP headers
(especially when not present). Where possible you should be as specific
as possible.

2.2.1. Request Headers¶

<tt class="docutils literal">Content-type</tt>

Specifies the content type of the information being supplied within
the request. The specification uses MIME type specifications. For the
majority of requests this will be JSON (<tt class="docutils literal">application/json</tt>). For
some settings the MIME type will be plain text. When uploading
attachments it should be the corresponding MIME type for the
attachment or binary (<tt class="docutils literal">application/octet-stream</tt>).

The use of the <tt class="docutils literal">Content-type</tt> on a request is highly recommended.

<tt class="docutils literal">Accept</tt>

Specifies the list of accepted data types to be returned by the
server (i.e. that are accepted/understandable by the client). The
format should be a list of one or more MIME types, separated by
colons.

For the majority of requests the definition should be for JSON data
(<tt class="docutils literal">application/json</tt>). For attachments you can either specify the
MIME type explicitly, or use <tt class="docutils literal">*/*</tt> to specify that all file types
are supported. If the <tt class="docutils literal">Accept</tt> header is not supplied, then the
<tt class="docutils literal">*/*</tt> MIME type is assumed (i.e. client accepts all formats).

The use of <tt class="docutils literal">Accept</tt> in queries for CouchDB is not required, but is
highly recommended as it helps to ensure that the data returned can
be processed by the client.

If you specify a data type using the <tt class="docutils literal">Accept</tt> header, CouchDB will
honor the specified type in the <tt class="docutils literal">Content-type</tt> header field
returned. For example, if you explicitly request <tt class="docutils literal">application/json</tt>
in the <tt class="docutils literal">Accept</tt> of a request, the returned HTTP headers will use
the value in the returned <tt class="docutils literal">Content-type</tt> field.

For example, when sending a request without an explicit <tt class="docutils literal">Accept</tt>
header, or when specifying <tt class="docutils literal">*/*</tt>:

GET /recipes HTTP/1.1
Host: couchdb:5984
Accept: */*

The returned headers are:

Server: CouchDB/1.0.1 (Erlang OTP/R13B)
Date: Thu, 13 Jan 2011 13:39:34 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 227
Cache-Control: must-revalidate

Note that the returned content type is <tt class="docutils literal">text/plain</tt> even though the
information returned by the request is in JSON format.

Explicitly specifying the <tt class="docutils literal">Accept</tt> header:

GET /recipes HTTP/1.1
Host: couchdb:5984
Accept: application/json

The headers returned include the <tt class="docutils literal">application/json</tt> content type:

Server: CouchDB/|version| (Erlang OTP/R13B)
Date: Thu, 13 Jan 2011 13:40:11 GMT
Content-Type: application/json
Content-Length: 227
Cache-Control: must-revalidate

2.2.2. Response Headers¶

Response headers are returned by the server when sending back content
and include a number of different header fields, many of which are
standard HTTP response header and have no significance to CouchDB
operation. The list of response headers important to CouchDB are listed
below.

<tt class="docutils literal">Content-type</tt>

Specifies the MIME type of the returned data. For most request, the
returned MIME type is <tt class="docutils literal">text/plain</tt>. All text is encoded in Unicode
(UTF-8), and this is explicitly stated in the returned
<tt class="docutils literal">Content-type</tt>, as <tt class="docutils literal">text/plain;charset=utf-8</tt>.

<tt class="docutils literal">Cache-control</tt>

The cache control HTTP response header provides a suggestion for
client caching mechanisms on how to treat the returned information.
CouchDB typically returns the <tt class="docutils literal">must-revalidate</tt>, which indicates
that the information should be revalidated if possible. This is used
to ensure that the dynamic nature of the content is correctly
updated.

<tt class="docutils literal">Content-length</tt>

The length (in bytes) of the returned content.

<tt class="docutils literal">Etag</tt>

The <tt class="docutils literal">Etag</tt> HTTP header field is used to show the revision for a
document, or a view.

ETags have been assigned to a map/reduce group (the collection of
views in a single design document). Any change to any of the indexes
for those views would generate a new ETag for all view URL’s in a
single design doc, even if that specific view’s results had not
changed.

Each <tt class="docutils literal">_view</tt> URL has its own ETag which only gets updated when
changes are made to the database that effect that index. If the
index for that specific view does not change, that view keeps the
original ETag head (therefore sending back 304 Not Modified more
often).

2.3. JSON Basics¶

The majority of requests and responses to CouchDB use the JavaScript
Object Notation (JSON) for formatting the content and structure of the
data and responses.

JSON is used because it is the simplest and easiest to use solution for
working with data within a web browser, as JSON structures can be
evaluated and used as JavaScript objects within the web browser
environment. JSON also integrates with the server-side JavaScript used
within CouchDB.

JSON supports the same basic types as supported by JavaScript, these
are:

Number (either integer or floating-point).

String; this should be enclosed by double-quotes and supports Unicode
characters and backslash escaping. For example:

"A String"

Boolean - a <tt class="docutils literal">true</tt> or <tt class="docutils literal">false</tt> value. You can use these strings
directly. For example:

{ "value": true}

Array - a list of values enclosed in square brackets. For example:

["one", "two", "three"]

Object - a set of key/value pairs (i.e. an associative array, or
hash). The key must be a string, but the value can be any of the
supported JSON values. For example:

{
   "servings" : 4,
   "subtitle" : "Easy to make in advance, and then cook when ready",
   "cooktime" : 60,
   "title" : "Chicken Coriander"
}

In CouchDB, the JSON object is used to represent a variety of
structures, including the main CouchDB document.

Parsing JSON into a JavaScript object is supported through the
<tt class="docutils literal">JSON.parse()</tt> function in JavaScript, or through various libraries that
will perform the parsing of the content into a JavaScript object for
you. Libraries for parsing and generating JSON are available in many
languages, including Perl, Python, Ruby, Erlang and others.

Warning

Care should be taken to ensure that your JSON structures are
valid, invalid structures will cause CouchDB to return an HTTP status code
of 500 (server error).

2.4. HTTP Status Codes¶

With the interface to CouchDB working through HTTP, error codes and
statuses are reported using a combination of the HTTP status code
number, and corresponding data in the body of the response data.

A list of the error codes returned by CouchDB, and generic descriptions
of the related errors are provided below. The meaning of different
status codes for specific request types are provided in the
corresponding API call reference.

<tt class="docutils literal">200 - OK</tt>

Request completed successfully.

<tt class="docutils literal">201 - Created</tt>

Document created successfully.

<tt class="docutils literal">202 - Accepted</tt>

Request has been accepted, but the corresponding operation may not
have completed. This is used for background operations, such as
database compaction.

<tt class="docutils literal">304 - Not Modified</tt>

The additional content requested has not been modified. This is used
with the ETag system to identify the version of information returned.

<tt class="docutils literal">400 - Bad Request</tt>

Bad request structure. The error can indicate an error with the
request URL, path or headers. Differences in the supplied MD5 hash
and content also trigger this error, as this may indicate message
corruption.

<tt class="docutils literal">401 - Unauthorized</tt>

The item requested was not available using the supplied
authorization, or authorization was not supplied.

<tt class="docutils literal">403 - Forbidden</tt>

The requested item or operation is forbidden.

<tt class="docutils literal">404 - Not Found</tt>

The requested content could not be found. The content will include
further information, as a JSON object, if available. The structure
will contain two keys, <tt class="docutils literal">error</tt> and <tt class="docutils literal">reason</tt>. For example:

{"error":"not_found","reason":"no_db_file"}

<tt class="docutils literal">405 - Resource Not Allowed</tt>

A request was made using an invalid HTTP request type for the URL
requested. For example, you have requested a <tt class="docutils literal">PUT</tt> when a <tt class="docutils literal">POST</tt>
is required. Errors of this type can also triggered by invalid URL
strings.

<tt class="docutils literal">406 - Not Acceptable</tt>

The requested content type is not supported by the server.

<tt class="docutils literal">409 - Conflict</tt>

Request resulted in an update conflict.

<tt class="docutils literal">412 - Precondition Failed</tt>

The request headers from the client and the capabilities of the
server do not match.

<tt class="docutils literal">415 - Bad Content Type</tt>

The content types supported, and the content type of the information
being requested or submitted indicate that the content type is not
supported.

<tt class="docutils literal">416 - Requested Range Not Satisfiable</tt>

The range specified in the request header cannot be satisfied by the
server.

<tt class="docutils literal">417 - Expectation Failed</tt>

When sending documents in bulk, the bulk load operation failed.

<tt class="docutils literal">500 - Internal Server Error</tt>

The request was invalid, either because the supplied JSON was
invalid, or invalid information was supplied as part of the request.

2.5. HTTP Range Requests¶

HTTP allows you to specify byte ranges for requests. This allows the
implementation of resumable downloads and skippable audio and video
streams alike. This is available for all attachments inside CouchDB.

This is just a real quick run through how this looks under the hood.
Usually, you will have larger binary files to serve from CouchDB, like
MP3s and videos, but to make things a little more obvious, I use a text
file here (Note that I use the <tt class="docutils literal">application/octet-stream</tt> Content-Type
instead of <tt class="docutils literal">text/plain</tt>).

shell> cat file.txt
My hovercraft is full of eels!

Now let’s store this text file as an attachment in CouchDB. First, we
create a database:

shell> curl -X PUT http://127.0.0.1:5984/test
{"ok":true}

Then we create a new document and the file attachment in one go:

shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
            -H "Content-Type: application/octet-stream" -d@file.txt
{"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}

Now we can request the whole file easily:

shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
My hovercraft is full of eels!

But say we only want the first 13 bytes:

shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
            -H "Range: bytes=0-12"
My hovercraft

HTTP supports many ways to specify single and even multiple byte
ranges. Read all about it in RFC 2616.

Note

Databases that have been created with CouchDB 1.0.2 or earlier will
support range requests in 1.4, but they are using a less-optimal
algorithm. If you plan to make heavy use of this feature, make sure
to compact your database with CouchDB 1.4 to take advantage of a
better algorithm to find byte ranges.

Quick Search

<form class="search" action="search.html" method="get">
<input type="text" name="q">
<input type="submit" value="Go">
<input type="hidden" name="check_keywords" value="yes">
<input type="hidden" name="area" value="default">
</form>

Table Of Contents

2. API Basics

2.1. Request Format and Responses

2.2. HTTP Headers

2.2.1. Request Headers

2.2.2. Response Headers

2.3. JSON Basics

2.4. HTTP Status Codes

2.5. HTTP Range Requests

Previous topic

1. Introduction

Next topic

3. Configuration

More Help

Homepage

Wiki

Mailing Lists

IRC

Issues

Navigation

          index

          next |

          previous |

Apache CouchDB 1.4 Manual »

        © Copyright 2013, The Apache Software Foundation.
      Created using Sphinx 1.1.3.

     Brought to you by Read the Docs

latest

1.4.x

1.3.x


text:
"""Tests for the URL-generation aspect of :class:`Bundle`.

However, URL generation that is associated with a special feature is
more likely` found in `test_bundle_various.py``.
"""

from __future__ import with_statement

from nose.tools import assert_raises, assert_equal
from nose import SkipTest

from webassets import Bundle
from webassets.exceptions import BundleError
from webassets.test import TempEnvironmentHelper, TempDirHelper

from tests.test_bundle_build import AppendFilter

class BaseUrlsTester(TempEnvironmentHelper):
    """Baseclass to test the url generation

    It defines a mock bundle class that intercepts calls to build().
    This allows us to test the Bundle.url() method up to it calling
    into Bundle.build().
    """

    default_files = {'a': '', 'b': '', 'c': '', '1': '', '2': ''}

    def setup(self):
        TempEnvironmentHelper.setup(self)

        self.env.url_expire = False

        self.build_called = build_called = []
        self.makeurl_called = makeurl_called = []
        env = self.env
        class MockBundle(Bundle):
            def __init__(self, *a, **kw):
                Bundle.__init__(self, *a, **kw)
                self.env = env
            def _build(self, *a, **kw):
                build_called.append(self.output)
            def _make_url(self, *a, **kw):
                makeurl_called.append(self.output)
                return Bundle._make_url(self, *a, **kw)
        self.MockBundle = MockBundle

class TestUrlsVarious(BaseUrlsTester):
    """Other, general tests for the urls() method.

    The TestUrls()* classes test the logic behind urls(). The ``url_expire``
    option is part of ``TestVersionFeatures``.
    """

    def test_erroneous_debug_value(self):
        """Test the exception Bundle.urls() throws if debug is an invalid
        value."""
        # On the bundle level
        b = self.MockBundle('a', 'b', debug="invalid")
        assert_raises(BundleError, b.urls, env=self.env)

        # On the environment level
        self.env.debug = "invalid"
        b = self.MockBundle('a', 'b')
        assert_raises(BundleError, b.urls, env=self.env)

        # Self-check - this should work if this test works.
        self.env.debug = True  # valid again
        self.MockBundle('a', 'b', debug="merge").urls()

    def test_pass_down_env(self):
        """[Regression] When a root *container* bundle is connected
        to an environment, the child bundles do not have to be.
        """
        child = Bundle('1', '2')
        child.env = None
        root = self.MockBundle(child)
        root.env = self.env
        # Does no longer raise an "unconnected env" exception
        assert root.urls() == ['/1', '/2']

    def test_invalid_source_file(self):
        """If a source file is missing, an error is raised even when rendering
        the urls (as opposed to just outputting the url to the missing file
        (this is cached and only done once).

        It's helpful for debugging (in particular when rewriting takes place by
        things like the django-staticfiles extension, or Flask's blueprints).
        """
        self.env.debug = True
        bundle = self.mkbundle('non-existent-file', output="out")
        assert_raises(BundleError, bundle.urls)

    def test_filters_in_debug_mode(self):
        """Test that if a filter is used which runs in debug mode, the bundle
        is forcibly merged (unless overridden)
        """
        self.env.debug = True
        test_filter = AppendFilter()
        bundle = self.MockBundle('a', filters=test_filter, output='out')

        # We get the source files...
        assert bundle.urls() == ['/a']
        assert len(self.build_called) == 0

        # ...until the filter is switched to 'always run'
        test_filter.max_debug_level = None
        assert bundle.urls() == ['/out']
        assert len(self.build_called) == 1

        # An explicit bundle debug=True overrides the behavior.
        bundle.debug = True
        assert bundle.urls() == ['/a']
        assert len(self.build_called) == 1  # no change

    def test_external_refs(self):
        """If a bundle contains absolute paths outside of the
        media directory, to generate a url they are copied in.
        """
        try:
            from nose.tools import assert_regex
        except ImportError:
            raise SkipTest("Assertion method only present in 2.7+")
        self.env.debug = True
        with TempDirHelper() as h:
            h.create_files(['foo.css'])
            bundle = self.mkbundle(h.path('foo.css'))
            urls = bundle.urls()
            assert len(urls) == 1
            assert_regex(urls[0], r'.*/webassets-external/[\da-z]*_foo.css')

class TestUrlsWithDebugFalse(BaseUrlsTester):
    """Test url generation in production mode - everything is always built.
    """

    def test_simple_bundle(self):
        bundle = self.MockBundle('a', 'b', 'c', output='out')
        assert bundle.urls() == ['/out']
        assert len(self.build_called) == 1

    def test_nested_bundle(self):
        bundle = self.MockBundle(
            'a', self.MockBundle('d', 'childout'), 'c', output='out')
        assert bundle.urls() == ['/out']
        assert len(self.build_called) == 1

    def test_container_bundle(self):
        """A bundle that has only child bundles and does not specify
        an output target of its own will simply build its child
        bundles separately.
        """
        bundle = self.MockBundle(
            self.MockBundle('a', output='child1'),
            self.MockBundle('a', output='child2'))
        assert bundle.urls() == ['/child1', '/child2']
        assert len(self.build_called) == 2

    def test_source_bundle(self):
        """If a bundle does neither specify an output target nor any
        filters, its file are always sourced directly.
        """
        bundle = self.MockBundle('a', self.MockBundle('d', output='childout'))
        assert bundle.urls() == ['/a', '/childout']
        assert len(self.build_called) == 1

    def test_root_bundle_switching_to_merge(self):
        """A bundle explicitly says it wants to be merged, wanting to override
        the  global "debug=False" setting. This is ineffectual (and anyway
        does not affect url generation).
        """
        bundle = self.MockBundle('1', '2', output='childout', debug='merge')
        assert_equal(bundle.urls(), ['/childout'])
        assert len(self.build_called) == 1

    def test_root_bundle_switching_to_debug_true(self):
        """A bundle explicitly says it wants to be processed in debug
        mode, wanting overriding the global "debug=False" setting. This is
        ineffectual.
        """
        bundle = self.MockBundle('1', '2', output='childout', debug=True)
        assert_equal(bundle.urls(), ['/childout'])
        assert len(self.build_called) == 1

    def test_root_debug_true_and_child_debug_false(self):
        """The root bundle explicitly says it wants to be processed in
        debug mode, overriding the global "debug" setting, and a child
        bundle asks for debugging to be disabled again.

        None of this has any effect, since Environment.debug=False.
        """
        bundle = self.MockBundle(
                '1', '2',
                self.MockBundle('a', output='child1', debug=False),
                output='rootout', debug=True)
        assert_equal(bundle.urls(), ['/rootout'])

class TestUrlsWithDebugTrue(BaseUrlsTester):
    """Test url generation in debug mode.
    """

    def setup(self):
        BaseUrlsTester.setup(self)
        self.env.debug = True

    def test_simple_bundle(self):
        bundle = self.MockBundle('a', 'b', 'c', output='out')
        assert_equal(bundle.urls(), ['/a', '/b', '/c'])
        assert_equal(len(self.build_called), 0)

    def test_nested_bundle(self):
        bundle = self.MockBundle(
            'a', self.MockBundle('1', '2', output='childout'), 'c', output='out')
        assert bundle.urls() == ['/a', '/1', '/2', '/c']
        assert len(self.build_called) == 0

    def test_container_bundle(self):
        """A bundle that has only sub bundles and does not specify
        an output target of its own.
        """
        bundle = self.MockBundle(
            self.MockBundle('a', output='child1'),
            self.MockBundle('a', output='child2'))
        assert bundle.urls() == ['/a', '/a']
        assert len(self.build_called) == 0

    def test_url_source(self):
        """[Regression] Test a Bundle that contains a source URL.
        """
        bundle = self.MockBundle('http://test.de', output='out')
        assert_equal(bundle.urls(), ['http://test.de'])
        assert_equal(len(self.build_called), 0)

        # This is the important test. It proves that the url source
        # was handled separately, and not processed like any other
        # source file, which would be passed through makeurl().
        # This is a bit convoluted to test because the code that
        # converts a bundle content into an url operates just fine
        # on a url source, so there is no easy other way to determine
        # whether the url source was treated special.
        assert_equal(len(self.makeurl_called), 0)

    def test_root_bundle_switching_to_debug_false(self):
        """A bundle explicitly says it wants to be processed with
        debug=False, overriding the global "debug=True" setting.
        """
        bundle = self.MockBundle('1', '2', output='childout', debug=False)
        assert_equal(bundle.urls(), ['/childout'])
        assert len(self.build_called) == 1

    def test_root_bundle_switching_to_merge(self):
        """A bundle explicitly says it wants to be merged, overriding
        the global "debug=True" setting.
        """
        bundle = self.MockBundle('1', '2', output='childout', debug='merge')
        assert_equal(bundle.urls(), ['/childout'])
        assert len(self.build_called) == 1

    def test_child_bundle_switching(self):
        """A child bundle explicitly says it wants to be processed in
        "merge" mode, overriding the global "debug=True" setting, with the
        root bundle not having an opinion.
        """
        bundle = self.MockBundle(
            'a', self.MockBundle('1', '2', output='childout', debug='merge'),
            'c', output='out')
        assert_equal(bundle.urls(), ['/a', '/childout', '/c'])
        assert len(self.build_called) == 1

class TestUrlsWithDebugMerge(BaseUrlsTester):

    def setup(self):
        BaseUrlsTester.setup(self)
        self.env.debug = 'merge'

    def test_simple_bundle(self):
        bundle = self.MockBundle('a', 'b', 'c', output='out')
        assert bundle.urls() == ['/out']
        assert len(self.build_called) == 1

    def test_nested_bundle(self):
        bundle = self.MockBundle('a', self.MockBundle('d', 'childout'), 'c', output='out')
        assert bundle.urls() == ['/out']
        assert len(self.build_called) == 1

    def test_child_bundle_switching_to_debug_false(self):
        """A child bundle explicitly says it wants to be processed in
        full production mode, with overriding the global "debug" setting.

        This makes no difference to the urls that are generated.
        """
        bundle = self.MockBundle(
            'a', self.MockBundle('1', '2', output='childout', debug=False),
            'c', output='out')
        assert_equal(bundle.urls(), ['/out'])
        assert len(self.build_called) == 1

    def test_root_bundle_switching_to_debug_true(self):
        """A bundle explicitly says it wants to be processed in debug mode,
        overriding the global ``debug=merge"`` setting. This is ineffectual.
        """
        bundle = self.MockBundle(
            'a', self.MockBundle('1', '2', output='childout', debug=True),
            'c', output='out')
        assert_equal(bundle.urls(), ['/out'])
        assert len(self.build_called) == 1

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using LeanIX.Api.Common;
using LeanIX.Api.Models;
namespace LeanIX.Api {
	public class BusinessCapabilitiesApi {
		private readonly ApiClient apiClient = ApiClient.GetInstance();

		public ApiClient getClient() {
			return apiClient;
		}

		/// <summary>
		/// Read all Bus. Capability
		/// </summary>
		/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
		/// <param name="filter">Full-text filter</param>
		/// <returns></returns>
		public List<BusinessCapability> getBusinessCapabilities (bool relations, string filter) {
			// create path and map variables
			var path = "/businessCapabilities".Replace("{format}","json");

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			string paramStr = null;
			if (relations != null){
				paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
				queryParams.Add("relations", paramStr);
			}
			if (filter != null){
				paramStr = (filter != null && filter is DateTime) ? ((DateTime)(object)filter).ToString("u") : Convert.ToString(filter);
				queryParams.Add("filter", paramStr);
			}
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (List<BusinessCapability>) ApiClient.deserialize(response, typeof(List<BusinessCapability>));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Create a new Bus. Capability
		/// </summary>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public BusinessCapability createBusinessCapability (BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities".Replace("{format}","json");

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Read a Bus. Capability by a given ID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
		/// <returns></returns>
		public BusinessCapability getBusinessCapability (string ID, bool relations) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			if (relations != null){
				paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
				queryParams.Add("relations", paramStr);
			}
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Update a Bus. Capability by a given ID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public BusinessCapability updateBusinessCapability (string ID, BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Delete a Bus. Capability by a given ID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <returns></returns>
		public void deleteBusinessCapability (string ID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
				if(response != null){
					return ;
				}
				else {
					return ;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return ;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Read all of relation
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <returns></returns>
		public List<BusinessCapability> getBusinessCapabilities (string ID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/businessCapabilities".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (List<BusinessCapability>) ApiClient.deserialize(response, typeof(List<BusinessCapability>));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Create a new relation
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public BusinessCapability createBusinessCapability (string ID, BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/businessCapabilities".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Read by relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <returns></returns>
		public BusinessCapability getBusinessCapability (string ID, string relationID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/businessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Update relation by a given relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public BusinessCapability updateBusinessCapability (string ID, string relationID, BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/businessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
				if(response != null){
					return (BusinessCapability) ApiClient.deserialize(response, typeof(BusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Delete relation by a given relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <returns></returns>
		public void deleteBusinessCapability (string ID, string relationID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/businessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
				if(response != null){
					return ;
				}
				else {
					return ;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return ;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Read all of relation
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <returns></returns>
		public List<ServiceHasBusinessCapability> getServiceHasBusinessCapabilities (string ID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/serviceHasBusinessCapabilities".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (List<ServiceHasBusinessCapability>) ApiClient.deserialize(response, typeof(List<ServiceHasBusinessCapability>));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Create a new relation
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public ServiceHasBusinessCapability createServiceHasBusinessCapability (string ID, BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/serviceHasBusinessCapabilities".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
				if(response != null){
					return (ServiceHasBusinessCapability) ApiClient.deserialize(response, typeof(ServiceHasBusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Read by relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <returns></returns>
		public ServiceHasBusinessCapability getServiceHasBusinessCapability (string ID, string relationID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/serviceHasBusinessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
				if(response != null){
					return (ServiceHasBusinessCapability) ApiClient.deserialize(response, typeof(ServiceHasBusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Update relation by a given relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <param name="body">Message-Body</param>
		/// <returns></returns>
		public ServiceHasBusinessCapability updateServiceHasBusinessCapability (string ID, string relationID, BusinessCapability body) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/serviceHasBusinessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
				if(response != null){
					return (ServiceHasBusinessCapability) ApiClient.deserialize(response, typeof(ServiceHasBusinessCapability));
				}
				else {
					return null;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return null;
				}
				else {
					throw ex;
				}
			}
		}
		/// <summary>
		/// Delete relation by a given relationID
		/// </summary>
		/// <param name="ID">Unique ID</param>
		/// <param name="relationID">Unique ID of the Relation</param>
		/// <returns></returns>
		public void deleteServiceHasBusinessCapability (string ID, string relationID) {
			// create path and map variables
			var path = "/businessCapabilities/{ID}/serviceHasBusinessCapabilities/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));

			// query params
			var queryParams = new Dictionary<String, String>();
			var headerParams = new Dictionary<String, String>();

			// verify required params are set
			if (ID == null || relationID == null ) {
				throw new ApiException(400, "missing required params");
			}
			string paramStr = null;
			try {
				var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
				if(response != null){
					return ;
				}
				else {
					return ;
				}
			} catch (ApiException ex) {
				if(ex.ErrorCode == 404) {
					return ;
				}
				else {
					throw ex;
				}
			}
		}
		}
	}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cenangium sebastianiae Henn.

### Remarks
null


text:
package main

import (
	"errors"
	"net/http"

	"github.com/mendersoftware/log"
)

var (
	ErrorBootstrapFailed   = errors.New("Bootstraping failed")
	ErrorBootstrapNoClient = errors.New("Error initializing client for bootstrapping to server.")
)

func (c *httpsClient) Bootstrap(server string) error {

	r, err := c.makeAndSendRequest(http.MethodGet, server)

	if err != nil {
		return err
	}

	return processBootstrapResponse(r, nil)
}

// This will be called from the command line ONLY
func doBootstrap(conf httpsClientConfig, server string) error {
	// for bootstrapping we need https connection
	client := NewHttpsClient(conf)
	if client == nil {
		return ErrorBootstrapNoClient
	}

	if err := client.Bootstrap(server); err != nil {
		return err
	}

	//TODO: store bootstrap credentials so that we will be able to reuse in future
	return nil
}

func processBootstrapResponse(response *http.Response, data interface{}) error {
	if response.StatusCode != http.StatusOK {
		log.Error("Received failed reply for bootstrap request: " + response.Status)
		return ErrorBootstrapFailed
	}
	return nil
}


text:
package com.wuyin.supermarket.view;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;

import com.wuyin.supermarket.utils.UIUtils;

/**
 * Created by wuyin on 2016/5/28.
 */
public class DrawableUtils {

    /**
     * 创建弧度背景
     * @param color  背景颜色
     * @return  弧度图片
     */
    public static GradientDrawable createShape(int color) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(UIUtils.dip2px(5));  //设置4个角的弧度
        drawable.setColor(color);
        return drawable;
    }

    /**
     * 创建状态选择器
     *
     * @param pressDrawable  按下图片
     * @param normalDrawable 正常图片
     * @return  选择器
     */
    public static StateListDrawable createSelectorDrawable(Drawable pressDrawable, Drawable normalDrawable) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressDrawable);//按下显示的图片
        stateListDrawable.addState(new int[]{}, normalDrawable); //默认显示的图片
        return stateListDrawable;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?NLS TYPE="org.eclipse.help.toc"?>

<toc label="Data Manipulation" link_to="..\org.knime.base\tocs\manipulation.xml#manipulation">
<topic href="PLUGINS_ROOT/com.mind_era.knime.util\html\nodes\Pivot.html" label="Pivot"/>
<topic href="PLUGINS_ROOT/com.mind_era.knime.util\html\nodes\Unpivot.html" label="Unpivot"/>
</toc>


text:
import * as React from 'react';

export const withState = (state: string, handler: string, v: any) => W => {
  return class extends React.Component<any, any> {
    constructor(props) {
      super(props);
      //this[handler] = this.addHandler(handler, state);
      this[handler] = this[handler].bind(this);
    }
    state = {
      [state]: v
    };
    [handler](value: any) {
      this.setState({
        [state]: value
      });
    }
    addHandler = (handlerName, state) => value => {
      this[handlerName] = () => {
        this.setState({
          [state]: value
        });
      };
    }
    render() {
      const b = (
        <W {...this.props} {...this.state} {...{ [handler]: this[handler] }} />
      );
      const props = Object.assign({}, b.props, {
        name: b.props.name + ' hijacked!'
      });
      const res = Object.assign({}, b, { props: props });
      return res;
    }
  };
};

const Text = ({ setName, ...rest }) =>

 setName(Math.random().toFixed(3))}>
    {/*name

        {JSON.stringify(rest, null, 2)}

*/}
    <button onClick={() => {
      // let y = Math.floor(Math.random() * rest.rowCount) + 1;
      rest.debug(1);
      rest.showMatrices();
      //rest.test().then(console.log);
    }}>
      view matrices
    </button>

;
export const HText = withState('name', 'setName', 'lamine')(Text);


text:
package org.sfm.benchmark.db.sfm;

public enum AsmSatus {
    FULL_ASM, PARTIAL_ASM, NO_ASM;
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour {

	public float timeLeft;
	private Text timerText;
	private GameObject gameManager;
	public float explosionTime;
	private Coroutine lastRoutine = null;
	// Use this for initialization
	void Start () {
		timerText = GameObject.FindGameObjectWithTag ("Timer").GetComponent<Text>();
		gameManager = GameObject.FindGameObjectWithTag ("GameController");
		lastRoutine = StartCoroutine (countDown ());
	}

	IEnumerator countDown() {
		while (timeLeft >= 0) {
			setText ();
			yield return new WaitForSeconds (1f);
			timeLeft -= 1;
		}
		gameManager.GetComponent<GameManager> ().gameOver ();

	}

	private void setText() {
		timerText.text = timeLeft + " seconds";
	}

	public void stopTimer() {
		Debug.Log ("StoppingTimer");
		StopCoroutine (lastRoutine);
	}

}


text:
package com.gentics.mesh.core.data;

import static com.gentics.mesh.core.data.perm.InternalPermission.CREATE_PERM;
import static com.gentics.mesh.core.data.perm.InternalPermission.READ_PERM;
import static com.gentics.mesh.core.rest.error.Errors.error;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.util.ArrayList;
import java.util.List;

import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.data.dao.TagDao;
import com.gentics.mesh.core.data.dao.TagFamilyDao;
import com.gentics.mesh.core.data.dao.UserDao;
import com.gentics.mesh.core.data.project.HibProject;
import com.gentics.mesh.core.data.tag.HibTag;
import com.gentics.mesh.core.data.tagfamily.HibTagFamily;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.rest.tag.TagListUpdateRequest;
import com.gentics.mesh.core.rest.tag.TagReference;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.json.JsonUtil;

/**
 * A taggable element is a graph element that can reference Tags
 */
public interface Taggable {
	/**
	 * Project to which the element belongs.
	 *
	 * @return Project of the element
	 */
	HibProject getProject();

	/**
	 * Extract the tags to be set from the TagListUpdateRequest which is expected to be in the body of the action context.
	 *
	 * @param ac action context
	 * @param batch search queue batch
	 * @return list of tags
	 */
	default List<HibTag> getTagsToSet(InternalActionContext ac, EventQueueBatch batch) {
		TagListUpdateRequest request = JsonUtil.readValue(ac.getBodyAsString(), TagListUpdateRequest.class);
		return getTagsToSet(request.getTags(), ac, batch);
	}

	/**
	 * Try to load the tags which should be set.
	 * @param list List of references which should be loaded
	 * @param ac
	 * @param batch
	 * @return
	 */
	default List<HibTag> getTagsToSet(List<TagReference> list, InternalActionContext ac, EventQueueBatch batch) {
		List<HibTag> tags = new ArrayList<>();
		HibProject project = getProject();
		UserDao userDao = Tx.get().userDao();
		TagDao tagDao = Tx.get().tagDao();
		TagFamilyDao tagFamilyDao = Tx.get().tagFamilyDao();

		HibUser user = ac.getUser();
		for (TagReference tagReference : list) {
			if (!tagReference.isSet()) {
				throw error(BAD_REQUEST, "tag_error_name_or_uuid_missing");
			}
			if (isEmpty(tagReference.getTagFamily())) {
				throw error(BAD_REQUEST, "tag_error_tagfamily_not_set");
			}
			// 1. Locate the tag family
			HibTagFamily tagFamily = tagFamilyDao.findByName(project, tagReference.getTagFamily());
			// Tag Family could not be found so lets create a new one
			if (tagFamily == null) {
				throw error(NOT_FOUND, "tagfamily_not_found", tagReference.getTagFamily());
			}
			// 2. The uuid was specified so lets try to load the tag this way
			if (!isEmpty(tagReference.getUuid())) {
				HibTag tag = tagDao.findByUuid(tagFamily, tagReference.getUuid());
				if (tag == null) {
					throw error(NOT_FOUND, "tag_not_found", tagReference.getUuid());
				}
				if (!userDao.hasPermission(user, tag, READ_PERM)) {
					throw error(FORBIDDEN, "error_missing_perm", tag.getUuid(), READ_PERM.getRestPerm().getName());
				}
				tags.add(tag);
			} else {
				HibTag tag = tagDao.findByName(tagFamily, tagReference.getName());
				// Tag with name could not be found so create it
				if (tag == null) {
					if (userDao.hasPermission(user, tagFamily, CREATE_PERM)) {
						tag = tagDao.create(tagFamily, tagReference.getName(), project, user);
						userDao.inheritRolePermissions(user, tagFamily, tag);
						batch.add(tag.onCreated());
					} else {
						throw error(FORBIDDEN, "tag_error_missing_perm_on_tag_family", tagFamily.getName(), tagFamily.getUuid(), tagReference
							.getName());
					}
				} else if (!userDao.hasPermission(user, tag, READ_PERM)) {
					throw error(FORBIDDEN, "error_missing_perm", tag.getUuid(), READ_PERM.getRestPerm().getName());
				}

				tags.add(tag);
			}
		}
		return tags;
	}
}


text:
<?php

namespace Phig;

/**
 * Migration Adapter interface defines all functions necessary to store,
 * retrieve and in general manipulate the executed migrations.
 */
interface AdapterInterface
{
	const UP = 'UP';
	const DOWN = 'DW';

	/**
	 * Returns all the executed migrations as an associative array.
	 * The key holds the migration reference number
	 * @return array
	 */
	public function getMigrations();

	/**
	 * Adds the provided migration with the given reference number to the list
	 * of executed migrations
	 * @param \Phig\MigratableInterface $migration migration object
	 * @param string $ref reference number of the provided migration
	 */
	public function addMigration(MigratableInterface $migration, $ref);

		/**
	 * Removes the provided migration from the list of the executed migrations
	 * @param \Phig\MigratableInterface $migration migration object
	 * @param string $ref reference number of the provided migration
	 */
	public function removeMigration(MigratableInterface $migration, $ref);
}


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class
    name="com.krishagni.catissueplus.core.biospecimen.domain.SpecimenList"
    table="CATISSUE_SPECIMENLIST_TAGS">

    <id name="id" column="IDENTIFIER">
      <generator class="native">
        <param name="sequence">CATISSUE_SPECIMEN_LIST_SEQ</param>
      </generator>
    </id>

    <property name="name" column="TAG_LABEL"/>

    <many-to-one
      name="owner"
      class="com.krishagni.catissueplus.core.administrative.domain.User"
      cascade="none"
      column="USER_ID"
     />

    <set
      name="sharedWith"
      table="SHARED_SPECIMENLIST_TAGS">
      <key column="TAG_ID"/>
      <many-to-many class="com.krishagni.catissueplus.core.administrative.domain.User" column="USER_ID"/>
    </set>

    <set
      name="specimens"
      table="CATISSUE_SPEC_TAG_ITEMS">
      <key column="TAG_ID"/>
      <many-to-many class="com.krishagni.catissueplus.core.biospecimen.domain.Specimen" column="OBJ_ID" />
    </set>

    <property name="deletedOn" column="DELETED_ON"/>

    <query name="getSpecimenListsByUser">
      select
        distinct l
      from
        SpecimenList l inner join l.owner owner left join l.sharedWith sharedWith
      where
        (owner.id = :userId or sharedWith.id = :userId)
        and l.deletedOn is null
      order by
        l.name
    </query>
  </class>
</hibernate-mapping>


text:
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
    //后台主页模板
    public function index(){

    	return view('admin.index.index',['title'=>'后台']);
    }
}


text:
class Mutt < Formula
  desc "Mongrel of mail user agents (part elm, pine, mush, mh, etc.)"
  homepage "http://www.mutt.org/"
  url "https://bitbucket.org/mutt/mutt/downloads/mutt-1.7.0.tar.gz"
  mirror "ftp://ftp.mutt.org/pub/mutt/mutt-1.7.0.tar.gz"
  sha256 "1d3e987433d8c92ef88a604f4dcefdb35a86ce73f3eff0157e2e491e5b55b345"

  bottle do
    sha256 "d6d8b79f1b714d1d6f94b82e81825958ea7aa507fa47d8aacdf9bee93132d5b7" => :el_capitan
    sha256 "90db768f00dc9d6c8e96a98f5d8f5a74c605b5bc46ea98871d99611da25184fb" => :yosemite
    sha256 "63d588e1c1487ff6bfffc51180ff644307ffc8e6463436b9a001706dffcc1368" => :mavericks
  end

  head do
    url "https://dev.mutt.org/hg/mutt#default", :using => :hg

    resource "html" do
      url "https://dev.mutt.org/doc/manual.html", :using => :nounzip
    end
  end

  option "with-debug", "Build with debug option enabled"
  option "with-s-lang", "Build against slang instead of ncurses"

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "openssl"
  depends_on "tokyo-cabinet"
  depends_on "gettext" => :optional
  depends_on "gpgme" => :optional
  depends_on "libidn" => :optional
  depends_on "s-lang" => :optional

  conflicts_with "tin",
    :because => "both install mmdf.5 and mbox.5 man pages"

  def install
    user_admin = Etc.getgrnam("admin").mem.include?(ENV["USER"])

    args = %W[
      --disable-dependency-tracking
      --disable-warnings
      --prefix=#{prefix}
      --with-ssl=#{Formula["openssl"].opt_prefix}
      --with-sasl
      --with-gss
      --enable-imap
      --enable-smtp
      --enable-pop
      --enable-hcache
      --with-tokyocabinet
      --enable-sidebar
    ]

    # This is just a trick to keep 'make install' from trying
    # to chgrp the mutt_dotlock file (which we can't do if
    # we're running as an unprivileged user)
    args << "--with-homespool=.mbox" unless user_admin

    args << "--disable-nls" if build.without? "gettext"
    args << "--enable-gpgme" if build.with? "gpgme"
    args << "--with-slang" if build.with? "s-lang"

    if build.with? "debug"
      args << "--enable-debug"
    else
      args << "--disable-debug"
    end

    system "./prepare", *args
    system "make"

    # This permits the `mutt_dotlock` file to be installed under a group
    # that isn't `mail`.
    # https://github.com/Homebrew/homebrew/issues/45400
    if user_admin
      inreplace "Makefile", /^DOTLOCK_GROUP =.*$/, "DOTLOCK_GROUP = admin"
    end

    system "make", "install"
    doc.install resource("html") if build.head?
  end

  test do
    system bin/"mutt", "-D"
  end
end


text:
require 'spec_helper'

describe RbtcArbitrage do
  describe ".clients" do
    it "includes clients" do
      clients = RbtcArbitrage.clients
      clients.should include(RbtcArbitrage::Clients::CampbxClient)
      clients.should include(RbtcArbitrage::Clients::BitstampClient)
    end
  end
end


text:
package org.estatio.module.capex.integtests.order;

import java.math.BigDecimal;

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.fixtures.FixtureClock;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.queryresultscache.QueryResultsCache;
import org.apache.isis.applib.services.sudo.SudoService;
import org.apache.isis.applib.services.wrapper.HiddenException;
import org.apache.isis.applib.services.wrapper.InvalidException;

import org.estatio.module.asset.dom.Property;
import org.estatio.module.asset.fixtures.person.enums.Person_enum;
import org.estatio.module.asset.fixtures.property.enums.PropertyAndUnitsAndOwnerAndManager_enum;
import org.estatio.module.capex.app.OrderMenu;
import org.estatio.module.capex.dom.invoice.IncomingInvoiceType;
import org.estatio.module.capex.dom.order.Order;
import org.estatio.module.capex.dom.order.OrderItem;
import org.estatio.module.capex.dom.order.approval.OrderApprovalState;
import org.estatio.module.capex.dom.order.approval.transitions.Order_approvalTransitions;
import org.estatio.module.capex.dom.order.approval.triggers.Order_completeWithApproval;
import org.estatio.module.capex.dom.project.Project;
import org.estatio.module.capex.fixtures.order.enums.NumeratorForOrder_enum;
import org.estatio.module.capex.fixtures.project.enums.Project_enum;
import org.estatio.module.capex.integtests.CapexModuleIntegTestAbstract;
import org.estatio.module.charge.dom.Charge;
import org.estatio.module.capex.fixtures.charge.builders.IncomingChargesItaXlsxFixture;
import org.estatio.module.charge.fixtures.incoming.enums.IncomingCharge_enum;
import org.estatio.module.numerator.dom.Numerator;
import org.estatio.module.party.dom.Organisation;
import org.estatio.module.party.dom.Person;
import org.estatio.module.party.fixtures.organisation.enums.Organisation_enum;

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

public class OrderMenu_IntegTest extends CapexModuleIntegTestAbstract {

    @Inject OrderMenu orderMenu;

    @Inject SudoService sudoService;

    @Inject QueryResultsCache queryResultsCache;

    public static class CreateOrder extends OrderMenu_IntegTest {

        @Before
        public void setupData() {
            runFixtureScript(new FixtureScript() {
                @Override
                protected void execute(ExecutionContext executionContext) {
                    executionContext.executeChild(this, Organisation_enum.TopModelIt.builder());
                    executionContext.executeChild(this, PropertyAndUnitsAndOwnerAndManager_enum.RonIt.builder());
                    executionContext.executeChild(this, new IncomingChargesItaXlsxFixture());
                    executionContext.executeChild(this, Project_enum.RonProjectIt.builder());
                    executionContext.executeChild(this, Person_enum.CarmenIncomingInvoiceManagerIt.builder());
                    executionContext.executeChild(this, Person_enum.JonathanIncomingInvoiceManagerGb.builder());
                    executionContext.executeChild(this, NumeratorForOrder_enum.ItaScopedToHelloWorldIt.builder());
                }
            });
        }

        @Test
        public void createOrderForItaly_happyCase_with_property() throws Exception {
            // given
            final Property property = PropertyAndUnitsAndOwnerAndManager_enum.RonIt.getProperty_d().findUsing(serviceRegistry);
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.HelloWorldIt.findUsing(serviceRegistry);
            final Numerator numerator = NumeratorForOrder_enum.ItaScopedToHelloWorldIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.CarmenIncomingInvoiceManagerIt.findUsing(serviceRegistry);

            // when
            queryResultsCache.resetForNextTransaction(); // workaround: clear MeService#me cache
            final Order order = sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(property, null, project, charge, buyer, null, orderMenu.default6CreateOrder(), null, null, null));

            // then
            assertThat(order.getOrderNumber()).isEqualTo("0001/RON/001/001");
            assertThat(order.getProperty()).isEqualTo(property);
            assertThat(order.getApprovalState()).isEqualTo(OrderApprovalState.NEW);
            assertThat(mixin(Order_approvalTransitions.class, order).coll()).hasSize(2);

            assertThat(order.getItems()).hasSize(1);
            final OrderItem item = order.getItems().first();

            assertThat(item.getProperty()).isEqualTo(property);
            assertThat(item.getProject()).isEqualTo(project);
            assertThat(item.getCharge()).isEqualTo(charge);

        }

        @Test
        public void createOrderForItaly_and_approve_happyCase_with_multi_property_ref() throws Exception {
            // given
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.HelloWorldIt.findUsing(serviceRegistry);
            final Organisation supplier = Organisation_enum.TopModelIt.findUsing(serviceRegistry);
            final Numerator numerator = NumeratorForOrder_enum.ItaScopedToHelloWorldIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.CarmenIncomingInvoiceManagerIt.findUsing(serviceRegistry);

            // when
            queryResultsCache.resetForNextTransaction(); // workaround: clear MeService#me cache
            final Order order = sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(null, "GEN", project, charge, buyer, supplier, orderMenu.default6CreateOrder(), new BigDecimal("1000.00"), null, "some order description"));

            // then
            assertThat(order.getOrderNumber()).isEqualTo("0001/GEN/001/001");
            assertThat(order.getProperty()).isNull();
            assertThat(order.getApprovalState()).isEqualTo(OrderApprovalState.NEW);
            assertThat(order.getType()).isEqualTo(IncomingInvoiceType.ITA_ORDER_INVOICE);
            assertThat(mixin(Order_approvalTransitions.class, order).coll()).hasSize(2);

            assertThat(order.getItems()).hasSize(1);
            final OrderItem item = order.getItems().first();

            assertThat(item.getProperty()).isNull();
            assertThat(item.getProject()).isEqualTo(project);
            assertThat(item.getCharge()).isEqualTo(charge);

            // and when
            queryResultsCache.resetForNextTransaction(); // workaround: clear MeService#me cache
            sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(mixin(Order_completeWithApproval.class, order)).act(incomingInvoiceManager, FixtureClock.getTimeAsLocalDate(), "approved"));

            // then
            assertThat(order.getApprovalState()).isEqualTo(OrderApprovalState.APPROVED);

        }

        @Test
        public void createOrderForItaly_sadCase_hidden_for_non_italians() throws Exception {
            // given
            final Property property = PropertyAndUnitsAndOwnerAndManager_enum.RonIt.getProperty_d().findUsing(serviceRegistry);
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.HelloWorldIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.JonathanIncomingInvoiceManagerGb.findUsing(serviceRegistry);

            // then
            expectedExceptions.expect(HiddenException.class);

            // when
            sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(property, null, project, charge, buyer, null, orderMenu.default6CreateOrder(), null, null, null));
        }

        @Test
        public void createOrderForItaly_sadCase_both_property_and_ref() throws Exception {
            // given
            final Property property = PropertyAndUnitsAndOwnerAndManager_enum.RonIt.getProperty_d().findUsing(serviceRegistry);
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.HelloWorldIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.CarmenIncomingInvoiceManagerIt.findUsing(serviceRegistry);

            // then
            expectedExceptions.expect(InvalidException.class);
            expectedExceptions.expectMessage("Can not define both property and multi property reference");

            // when
            sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(property, "GEN", project, charge, buyer, null, orderMenu.default6CreateOrder(), null, null, null));
        }

        @Test
        public void createOrderForItaly_sadCase_neither_property_or_ref() throws Exception {
            // given
            final Property property = PropertyAndUnitsAndOwnerAndManager_enum.RonIt.getProperty_d().findUsing(serviceRegistry);
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.HelloWorldIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.CarmenIncomingInvoiceManagerIt.findUsing(serviceRegistry);

            // then
            expectedExceptions.expect(InvalidException.class);
            expectedExceptions.expectMessage("Either a property or a reference for multiple properties must be defined");

            // when
            sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(null, null, project, charge, buyer, null, orderMenu.default6CreateOrder(), null, null, null));
        }

        @Test
        public void createOrderForItaly_sadCase_no_numerator() throws Exception {
            // given
            final Property property = PropertyAndUnitsAndOwnerAndManager_enum.RonIt.getProperty_d().findUsing(serviceRegistry);
            final Project project = Project_enum.RonProjectIt.findUsing(serviceRegistry);
            final Charge charge = IncomingCharge_enum.ItAcquisition.findUsing(serviceRegistry);
            final Organisation buyer = Organisation_enum.TopModelIt.findUsing(serviceRegistry);

            final Person incomingInvoiceManager = Person_enum.CarmenIncomingInvoiceManagerIt.findUsing(serviceRegistry);

            // then
            expectedExceptions.expect(InvalidException.class);
            expectedExceptions.expectMessage("No order number numerator found for this buyer");

            // when
            final Order order = sudoService.sudo(incomingInvoiceManager.getUsername(), () ->
                    wrap(orderMenu).createOrder(property, null, project, charge, buyer, null, orderMenu.default6CreateOrder(), null, null, null));
        }
    }
}


text:
/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */

package org.hipparchus.analysis.solvers;

import org.hipparchus.analysis.UnivariateFunction;
import org.hipparchus.exception.MathIllegalStateException;
import org.hipparchus.util.FastMath;
import org.junit.Assert;
import org.junit.Test;

/**
 * Test case for {@link RegulaFalsiSolver Regula Falsi} solver.
 *
 */
public final class RegulaFalsiSolverTest extends BaseSecantSolverAbstractTest {
    /** {@inheritDoc} */
    @Override
    protected UnivariateSolver getSolver() {
        UnivariateSolver solver = new RegulaFalsiSolver();
        checktype(solver, BaseSecantSolver.Method.REGULA_FALSI);
        return solver;
    }

    /** {@inheritDoc} */
    @Override
    protected int[] getQuinticEvalCounts() {
        // While the Regula Falsi method guarantees convergence, convergence
        // may be extremely slow. The last test case does not converge within
        // even a million iterations. As such, it was disabled.
        return new int[] {3, 7, 8, 19, 18, 11, 67, 55, 288, 151, -1};
    }

    @Test(expected=MathIllegalStateException.class)
    public void testIssue631() {
        final UnivariateFunction f = new UnivariateFunction() {
                /** {@inheritDoc} */
                public double value(double x) {
                    return FastMath.exp(x) - FastMath.pow(Math.PI, 3.0);
                }
            };

        final UnivariateSolver solver = new RegulaFalsiSolver();
        final double root = solver.solve(3624, f, 1, 10);
        Assert.assertEquals(3.4341896575482003, root, 1e-15);
    }
}


text:
/**
    @author Benjamin Livshits <livshits@cs.stanford.edu>

    $Id: Basic21.java,v 1.7 2006/04/04 20:00:40 livshits Exp $
 */
package securibench.micro.basic;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;

/**
 *  @servlet description="SQL injection with less commonly used methods"
 *  @servlet vuln_count = "4"
 *  */
public class Basic21 extends BasicTestCase implements MicroTestCase {
    private static final String FIELD_NAME = "name";

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s = req.getParameter(FIELD_NAME);
        String name = s.toLowerCase(Locale.UK);

        Connection con = null;
        try {
            con = DriverManager.getConnection(MicroTestCase.CONNECTION_STRING);
            Statement stmt = con.createStatement();
            stmt.executeUpdate("select * from Users where name=" + name);       /* BAD */
            stmt.executeUpdate("select * from Users where name=" + name, 0);    /* BAD */
            stmt.executeUpdate("select * from Users where name=" + name,        /* BAD */
                new String[] {});
            stmt.executeQuery("select * from Users where name=" + name);        /* BAD */
        } catch (SQLException e) {
            System.err.println("An error occurred");
        } finally {
            try {
                if(con != null) con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public String getDescription() {
        return "SQL injection with less commonly used methods";
    }

    public int getVulnerabilityCount() {
        return 4;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="345">
	<title>Data Bases; Computers, and the Social Sciences	</title>
	<author>Bisco, R.L.	</author>
	<text>
		  This book was written with several diverse audiences in mind: (1)
		social and behavioral scientists and their students, (2) librarians and
		library-science students who are favorable about employing computers
		and computer-usable information in their work and classes, and (3)
		archivists and their employees who desire to have more than a current
		overview of the problems and their tentative solutions.  Because of the
		diversity of material, it is not expected that all readers will use the book
		in the same way.  Rather, it is assumed that readers will supplement a
		subset of the book with bibliographical materials from the reference
		sections.
	</text>
</article>


text:
package org.diirt.graphene;

import org.diirt.util.stats.Range;
import javafx.scene.paint.Color;
import java.util.List;
import org.diirt.util.array.ListNumber;

/**
 * A numeric color map defined by interpolated colors (gradients).
 *
 * @author sjdallst
 */
class NumberColorMapGradient implements NumberColorMap {

    private final List<Color> colors;
    private final ListNumber positions;
    private final boolean relative;
    private final Color nanColor;
    private final String name;

    /**
     * Creates a new color map.
     * <p>
     *
     * @param colors
     */
    public NumberColorMapGradient(List<Color> colors, ListNumber positions,
            boolean relative, Color nanColor, String name) {

        if(colors.size()!=positions.size())
            throw new IllegalArgumentException("Number of colors and number of positions don't match");
        if(nanColor==null)
            throw new IllegalArgumentException("NanColor should not be null");
        if(name==null || name.isEmpty() )
            throw new IllegalArgumentException("Name should not be empty or null");

        for (int i =0; i<positions.size(); ++i)   {
            //if using a relative scale, value should be bewteen 0.0 and 1.0
            if(relative && !(positions.getDouble(i) >=0 && positions.getDouble(i) <=1)){
                throw new RuntimeException("Position for relative scale should be between 0.0 and 1.0");
            }
            //check position values are in strictly increasing order
            if (i!=0 && positions.getDouble(i-1) >= positions.getDouble(i)){
                throw new RuntimeException("Position should be strictly increasing");
            }
        }

        this.colors = colors;
        this.relative = relative;
        this.name = name;
        this.nanColor = nanColor;
        this.positions = positions;
    }

    public List<Color> getColors() {
        return colors;
    }

    @Override
    public NumberColorMapInstance createInstance(Range range) {

        if(range==null) throw new NullPointerException("Range cannot be null");

        return new ValueColorSchemeInstanceGradient(range);
    }

    class ValueColorSchemeInstanceGradient implements NumberColorMapInstance {

        protected int nanColorInt;
        protected Range range;
        private final double fullRange;
        public ValueColorSchemeInstanceGradient(Range range) {
            this.range = range;
            fullRange = range.getMaximum() - range.getMinimum();
            int red = (int)(255*nanColor.getRed());
            int green = (int)(255*nanColor.getGreen());
            int blue = (int)(255*nanColor.getBlue());
            this.nanColorInt = (255 << 24) | (red<< 16) | (green<< 8) | blue;
        }

        @Override
        public int colorFor(double value) {
            if (Double.isNaN(value)) {
                return nanColorInt;
            }

            if (relative) {
                // Relative scale
                return relativeColorFor(value);
            } else {
                // Absolute scale
                return absoluteColorFor(value);
            }

        }

        private int relativeColorFor(double value) {
            int alpha = 0, red = 0, green = 0, blue = 0;

            if (value > range.getMaximum()) {

                alpha = 255;
                red = (int) (255 * (colors.get(colors.size() - 1).getRed()));
                green = (int) (255 * (colors.get(colors.size() - 1).getGreen()));
                blue = (int) (255 * (colors.get(colors.size() - 1).getBlue()));
                return (alpha << 24) | (red << 16) | (green << 8) | blue;
            }
            if (value < range.getMinimum()) {
                alpha = 255;
                red = (int) (255 * (colors.get(0).getRed()));
                green = (int) (255 * (colors.get(0).getGreen()));
                blue = (int) (255 * (colors.get(0).getBlue()));
                return (alpha << 24) | (red << 16) | (green << 8) | blue;
            }

            if (fullRange > 0) {
                for (int i = 0; i < positions.size() - 1; i++) {
                    if (range.getMinimum() + positions.getDouble(i) * fullRange <= value && value <= range.getMinimum() + positions.getDouble(i + 1) * fullRange) {
                        double normalValue = MathUtil.normalize(value, range.getMinimum() + positions.getDouble(i) * fullRange, range.getMinimum() + positions.getDouble(i + 1) * fullRange);
                        normalValue = Math.min(normalValue, 1.0);
                        normalValue = Math.max(normalValue, 0.0);
                        alpha = 255;
                        red = (int) (255*(colors.get(i).getRed() + (colors.get(i + 1).getRed() - colors.get(i).getRed()) * normalValue));
                        green = (int)( 255*(colors.get(i).getGreen() + (colors.get(i + 1).getGreen() - colors.get(i).getGreen()) * normalValue));
                        blue = (int) (255*(colors.get(i).getBlue() + (colors.get(i + 1).getBlue() - colors.get(i).getBlue()) * normalValue));
                    }
                }
            } else {
                for (int i = 0; i < positions.size() - 1; i++) {
                    if (positions.getDouble(i) <= .5 && .5 <= positions.getDouble(i + 1)) {
                        double normalValue = 0;
                        normalValue = Math.min(normalValue, 1.0);
                        normalValue = Math.max(normalValue, 0.0);
                        alpha = 255;
                        red = (int)( 255*(colors.get(i).getRed() + (colors.get(i + 1).getRed() - colors.get(i).getRed()) * normalValue));
                        green = (int)(255* (colors.get(i).getGreen() + (colors.get(i + 1).getGreen() - colors.get(i).getGreen()) * normalValue));
                        blue = (int) (255*(colors.get(i).getBlue() + (colors.get(i + 1).getBlue() - colors.get(i).getBlue()) * normalValue));
                    }
                }
            }

            return (alpha << 24) | (red << 16) | (green << 8) | blue;
        }

        private int absoluteColorFor(double value){

            int alpha = 0, red = 0, green = 0, blue = 0;

            if (value > positions.getDouble(positions.size() - 1)) {
                alpha = 255;
                red = (int) (255 * (colors.get(colors.size() - 1).getRed()));
                green = (int) (255 * (colors.get(colors.size() - 1).getGreen()));
                blue = (int) (255 * (colors.get(colors.size() - 1).getBlue()));
                return (alpha << 24) | (red << 16) | (green << 8) | blue;
            }

            if (value < positions.getDouble(0)) {
                alpha = 255;
                red = (int) (255 * (colors.get(0).getRed()));
                green = (int) (255 * (colors.get(0).getGreen()));
                blue = (int) (255 * (colors.get(0).getBlue()));
                return (alpha << 24) | (red << 16) | (green << 8) | blue;
            }

            for (int i = 0; i < positions.size() - 1; ++i) {
                if (positions.getDouble(i) <= value && value <= positions.getDouble(i + 1)) {
                    double normalValue = MathUtil.normalize(value, positions.getDouble(i), positions.getDouble(i + 1));

                    normalValue = Math.min(normalValue, 1.0);
                    normalValue = Math.max(normalValue, 0.0);
                    alpha = 255;
                    red = (int) (255*(colors.get(i).getRed() + (colors.get(i + 1).getRed() - colors.get(i).getRed()) * normalValue));
                    green = (int)(255* (colors.get(i).getGreen() + (colors.get(i + 1).getGreen() - colors.get(i).getGreen()) * normalValue));
                    blue = (int) (255*(colors.get(i).getBlue() + (colors.get(i + 1).getBlue() - colors.get(i).getBlue()) * normalValue));
                }
            }

            return (alpha << 24) | (red << 16) | (green << 8) | blue;
        }

        @Override
        public String toString() {
            return name + " " + range;
        }

    }

    @Override
    public String toString() {
        return name;
    }

}


text:
import org.junit.Test;

import static org.junit.Assert.*;

public class PhoneNumberTest {

    @Test
    public void cleansNumber() {
        final String expectedNumber = "1234567890";
        final String actualNumber = new PhoneNumber("(123) 456-7890").getNumber();

        assertEquals(
            expectedNumber, actualNumber
        );
    }

    @Test
    public void cleansNumberWithDots() {
        final String expectedNumber = "1234567890";
        final String actualNumber = new PhoneNumber("123.456.7890").getNumber();

        assertEquals(
            expectedNumber, actualNumber
        );
    }

    @Test
    public void validWhen11DigitsAndFirstIs1() {
        final String expectedNumber = "1234567890";
        final String actualNumber = new PhoneNumber("11234567890").getNumber();

        assertEquals(
            expectedNumber, actualNumber
        );
    }

    @Test
    public void invalidWhenOnly11Digits() {
        final String expectedNumber = "0000000000";
        final String actualNumber = new PhoneNumber("21234567890").getNumber();

        assertEquals(
            expectedNumber, actualNumber
        );
    }

    @Test
    public void invalidWhen9Digits() {
        final String expectedNumber = "0000000000";
        final String actualNumber = new PhoneNumber("123456789").getNumber();

        assertEquals(
            expectedNumber, actualNumber
        );
    }

    @Test
    public void areaCode() {
        final String expectedAreaCode = "123";
        final String actualAreaCode = new PhoneNumber("1234567890").getAreaCode();

        assertEquals(
            expectedAreaCode, actualAreaCode
        );
    }

    @Test
    public void prettyPrint() {
        final String expectedPrettyNumber = "(123) 456-7890";
        final String actualPrettyNumber = new PhoneNumber("1234567890").pretty();

        assertEquals(
            expectedPrettyNumber, actualPrettyNumber
        );
    }

    @Test
    public void prettyPrintWithFullUSPhoneNumber() {
        final String expectedPrettyNumber = "(123) 456-7890";
        final String actualPrettyNumber = new PhoneNumber("11234567890").pretty();

        assertEquals(
            expectedPrettyNumber, actualPrettyNumber
        );
    }

}


text:
require_relative 'boot'
require 'rails/all'
require './lib/middleware/pronto'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Champaign
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    config.assets.enabled = true
    config.assets.version = '1.0'

    config.i18n.available_locales = %i[en fr de es pt nl ar]
    config.i18n.enforce_available_locales = true
  end
end

Rails.application.routes.default_url_options[:host] = Settings.host


text:
[![Build Status](https://travis-ci.org/mrijk/speculaas.svg)](https://travis-ci.org/mrijk/speculaas)
[![Quality Gate](https://sonarcloud.io/api/badges/gate?key=mrijk:speculaas)](https://sonarcloud.io/dashboard?id=mrijk:speculaas)
[![Coverage Status](https://coveralls.io/repos/github/mrijk/speculaas/badge.svg?branch=master)](https://coveralls.io/github/mrijk/speculaas?branch=master)
[![Known Vulnerabilities](https://snyk.io/test/npm/speculaas/badge.svg)](https://snyk.io/test/npm/speculaas)
[![npm version](https://badge.fury.io/js/speculaas.svg)](https://badge.fury.io/js/speculaas)
[![Join the chat at https://gitter.im/speculaas/Lobby](https://badges.gitter.im/speculaas/Lobby.svg)](https://gitter.im/speculaas/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Speculaas
======

NodeJS version of [clojure.spec](http://clojure.org/about/spec)

## Installation

`npm install speculaas`

## Example

```js
const s = require('speculaas');
const {isString} = s.utils;

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/

s.def('emailType', s.and(isString, s => emailRegex.test(s)));

s.def('first-name', isString);
s.def('last-name', isString);
s.def('email', 'emailType');
s.def('phone', isString);

// First name, last name and email are required. Phone number is optional
s.def('person', s.keys({req: ['first-name', 'last-name', 'email'], opt: ['phone']}));

s.isValid('person',
{
    'first-name': 'Elon',
    'last-name': 'Musk',
    'email': 'elon@example.com'
});
// true
```

## Usage

[Documentation](https://mrijk.github.io/speculaas) is in progress.

## Tests

Unit tests:

`npm test`

Test coverage:

`npm run cover`

Run [ESlint](http://eslint.org):

`npm run lint`

## FAQ

Q: what kind of a silly name is speculaas?

A: [nodespec](https://www.npmjs.com/package/nodespec) and [node-spec](https://www.npmjs.com/package/node-spec) were already taken. [Speculaas](https://en.wikipedia.org/wiki/Speculaas) is a kind of a Dutch/Belgium biscuit.

Q: any alternatives for your code?

A: for an alternative look at [js.spec](https://prayerslayer.gitbooks.io/js-spec/content/)

## Contributing

If you want to contribute, you are more than welcome!


text:
"""Parsing and processing of CLI input (args, auth credentials, files, stdin).

"""
import enum
import re

URL_SCHEME_RE = re.compile(r'^[a-z][a-z0-9.+-]*://', re.IGNORECASE)

HTTP_POST = 'POST'
HTTP_GET = 'GET'

# Various separators used in args
SEPARATOR_HEADER = ':'
SEPARATOR_HEADER_EMPTY = ';'
SEPARATOR_CREDENTIALS = ':'
SEPARATOR_PROXY = ':'
SEPARATOR_DATA_STRING = '='
SEPARATOR_DATA_RAW_JSON = ':='
SEPARATOR_FILE_UPLOAD = '@'
SEPARATOR_FILE_UPLOAD_TYPE = ';type='  # in already parsed file upload path only
SEPARATOR_DATA_EMBED_FILE_CONTENTS = '=@'
SEPARATOR_DATA_EMBED_RAW_JSON_FILE = ':=@'
SEPARATOR_QUERY_PARAM = '=='

# Separators that become request data
SEPARATOR_GROUP_DATA_ITEMS = frozenset({
    SEPARATOR_DATA_STRING,
    SEPARATOR_DATA_RAW_JSON,
    SEPARATOR_FILE_UPLOAD,
    SEPARATOR_DATA_EMBED_FILE_CONTENTS,
    SEPARATOR_DATA_EMBED_RAW_JSON_FILE
})

SEPARATORS_GROUP_MULTIPART = frozenset({
    SEPARATOR_DATA_STRING,
    SEPARATOR_DATA_EMBED_FILE_CONTENTS,
    SEPARATOR_FILE_UPLOAD,
})

# Separators for items whose value is a filename to be embedded
SEPARATOR_GROUP_DATA_EMBED_ITEMS = frozenset({
    SEPARATOR_DATA_EMBED_FILE_CONTENTS,
    SEPARATOR_DATA_EMBED_RAW_JSON_FILE,
})

# Separators for raw JSON items
SEPARATOR_GROUP_RAW_JSON_ITEMS = frozenset([
    SEPARATOR_DATA_RAW_JSON,
    SEPARATOR_DATA_EMBED_RAW_JSON_FILE,
])

# Separators allowed in ITEM arguments
SEPARATOR_GROUP_ALL_ITEMS = frozenset({
    SEPARATOR_HEADER,
    SEPARATOR_HEADER_EMPTY,
    SEPARATOR_QUERY_PARAM,
    SEPARATOR_DATA_STRING,
    SEPARATOR_DATA_RAW_JSON,
    SEPARATOR_FILE_UPLOAD,
    SEPARATOR_DATA_EMBED_FILE_CONTENTS,
    SEPARATOR_DATA_EMBED_RAW_JSON_FILE,
})

# Output options
OUT_REQ_HEAD = 'H'
OUT_REQ_BODY = 'B'
OUT_RESP_HEAD = 'h'
OUT_RESP_BODY = 'b'

OUTPUT_OPTIONS = frozenset({
    OUT_REQ_HEAD,
    OUT_REQ_BODY,
    OUT_RESP_HEAD,
    OUT_RESP_BODY
})

# Pretty
PRETTY_MAP = {
    'all': ['format', 'colors'],
    'colors': ['colors'],
    'format': ['format'],
    'none': []
}
PRETTY_STDOUT_TTY_ONLY = object()

DEFAULT_FORMAT_OPTIONS = [
    'headers.sort:true',
    'json.format:true',
    'json.indent:4',
    'json.sort_keys:true',
]
SORTED_FORMAT_OPTIONS = [
    'headers.sort:true',
    'json.sort_keys:true',
]
SORTED_FORMAT_OPTIONS_STRING = ','.join(SORTED_FORMAT_OPTIONS)
UNSORTED_FORMAT_OPTIONS_STRING = ','.join(
    option.replace('true', 'false') for option in SORTED_FORMAT_OPTIONS)

# Defaults
OUTPUT_OPTIONS_DEFAULT = OUT_RESP_HEAD + OUT_RESP_BODY
OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED = OUT_RESP_BODY
OUTPUT_OPTIONS_DEFAULT_OFFLINE = OUT_REQ_HEAD + OUT_REQ_BODY

class RequestType(enum.Enum):
    FORM = enum.auto()
    MULTIPART = enum.auto()
    JSON = enum.auto()


text:
/*
 * tuplestorenew.h
 * 	A better tuple store
 */

#ifndef TUPSTORE_NEW_H
#define TUPSTORE_NEW_H

#include "executor/tuptable.h"
#include "utils/workfile_mgr.h"

typedef struct NTupleStorePos
{
	long blockn;
	int slotn;
} NTupleStorePos;

/* Opaque data types */
typedef struct NTupleStoreAccessor NTupleStoreAccessor;
typedef struct NTupleStore NTupleStore;

/* Instrument tuple store
 * Caller must ensure ins ptr remain valid during the lifetype of the tuple store
 */
void ntuplestore_setinstrument(NTupleStore* ts, struct Instrumentation *ins);

/* Tuple store method */
extern NTupleStore *ntuplestore_create(int64 maxBytes, char *operation_name);
extern NTupleStore *ntuplestore_create_readerwriter(const char* filename, int64 maxBytes, bool isWriter);
extern bool ntuplestore_is_readerwriter_reader(NTupleStore* nts);
extern void ntuplestore_flush(NTupleStore *ts);
extern void ntuplestore_destroy(NTupleStore *ts);

/* Tuple store accessor method
 * Create Accessor: current we support 1 writer, many reader per store.  After created, the accessor
 * is positioned at the first tuple or eof (if there is no tuple).
 */
extern NTupleStoreAccessor *ntuplestore_create_accessor(NTupleStore *ts, bool isWriter);
extern void ntuplestore_destroy_accessor(NTupleStoreAccessor *acc);

/* Put slot/data and automatically position the accessor to the last entry */
extern void ntuplestore_acc_put_tupleslot(NTupleStoreAccessor *tsa, TupleTableSlot *slot);
extern void ntuplestore_acc_put_data(NTupleStoreAccessor *tsa, void *data, int len);

/* return true if success, false if beyond last (first) valid position */
extern bool ntuplestore_acc_advance(NTupleStoreAccessor *tsa, int n);

/* Get data.  The slot/pointer returned is guaranteed to be valid till the accessor
 * call advance.
 * NOTE: trim may make current position of an accessor invalid.  It is caller's reponsibilty
 * to make sure trim does not trim too far ahead
 */
extern bool ntuplestore_acc_current_tupleslot(NTupleStoreAccessor *tsa, TupleTableSlot *slot);
extern bool ntuplestore_acc_current_data(NTupleStoreAccessor *tsa, void **data, int *len);

/* Tell/seek position of accessor. */

/* Tell fill in the pos, return false if accessor points to an invalid position.
 * Caller can pass in pos = NULL to simply tell if the accessor is at a valid position.
 */
extern bool ntuplestore_acc_tell(NTupleStoreAccessor *tsa, NTupleStorePos *pos);

/* put the current row at a certain pos (or first/last).  Return false pos is invalid */
extern bool ntuplestore_acc_seek(NTupleStoreAccessor *tsa, NTupleStorePos *pos);
extern bool ntuplestore_acc_seek_first(NTupleStoreAccessor *tsa);
extern bool ntuplestore_acc_seek_last(NTupleStoreAccessor *tsa);
extern void ntuplestore_acc_seek_bof(NTupleStoreAccessor *tsa);
extern void ntuplestore_acc_seek_eof(NTupleStoreAccessor *tsa);

#endif /* TUPSTORE_NEW_H */


text:
@interface TFViewController() {

}

@end

@implementation TFViewController {

}

#pragma mark - Life cycle
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)loadView {
    if (nil != self.nibName) {
        [super loadView];
    } else {
        self.view = [[UIView alloc] init];
        self.view.autoresizesSubviews = YES;
        self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark -

#pragma mark - Memory Warning
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - Actions

- (void)onViewClick:(id)sender {

}
#pragma mark - Delegates

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="app_bar_height">200dp</dimen>
    <dimen name="item_width">200dp</dimen>
    <dimen name="text_margin">16dp</dimen>
</resources>