text:
package org.spincast.plugins.routing;

import java.lang.annotation.Annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spincast.core.exchange.DefaultRequestContext;
import org.spincast.core.exchange.RequestContext;
import org.spincast.core.guice.SpincastGuiceModuleBase;
import org.spincast.core.guice.SpincastGuiceScopes;
import org.spincast.core.routing.ETagFactory;
import org.spincast.core.routing.Handler;
import org.spincast.core.routing.RedirectRuleBuilder;
import org.spincast.core.routing.RedirectRuleBuilderFactory;
import org.spincast.core.routing.Route;
import org.spincast.core.routing.RouteBuilder;
import org.spincast.core.routing.RouteBuilderFactory;
import org.spincast.core.routing.RouteHandlerMatch;
import org.spincast.core.routing.Router;
import org.spincast.core.routing.RoutingRequestContextAddon;
import org.spincast.core.routing.StaticResource;
import org.spincast.core.routing.StaticResourceBuilder;
import org.spincast.core.routing.StaticResourceBuilderFactory;
import org.spincast.core.routing.StaticResourceCacheConfig;
import org.spincast.core.routing.StaticResourceCorsConfig;
import org.spincast.core.routing.StaticResourceFactory;
import org.spincast.core.routing.hotlinking.HotlinkingManager;
import org.spincast.core.routing.hotlinking.HotlinkingManagerDefault;
import org.spincast.core.websocket.DefaultWebsocketContext;
import org.spincast.core.websocket.WebsocketContext;
import org.spincast.core.websocket.WebsocketRoute;
import org.spincast.core.websocket.WebsocketRouteBuilder;
import org.spincast.core.websocket.WebsocketRouteBuilderFactory;
import org.spincast.core.websocket.WebsocketRouteHandler;
import org.spincast.core.websocket.WebsocketRouteHandlerFactory;
import org.spincast.plugins.routing.utils.SpincastRoutingUtils;
import org.spincast.plugins.routing.utils.SpincastRoutingUtilsDefault;

import com.google.inject.Key;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;

public class SpincastRoutingPluginModule extends SpincastGuiceModuleBase {

    protected static final Logger logger = LoggerFactory.getLogger(SpincastRoutingPluginModule.class);

    private Class<? extends Router<?, ?>> specificRouterImplementationClass;

    public SpincastRoutingPluginModule() {
        this(null, null, null);
    }

    public SpincastRoutingPluginModule(Class<? extends Router<?, ?>> specificRouterImplementationClass) {
        this(null, null, specificRouterImplementationClass);
    }

    public SpincastRoutingPluginModule(Class<? extends RequestContext<?>> requestContextImplementationClass,
                                       Class<? extends WebsocketContext<?>> websocketContextImplementationClass) {
        this(requestContextImplementationClass, websocketContextImplementationClass, null);
    }

    public SpincastRoutingPluginModule(Class<? extends RequestContext<?>> requestContextImplementationClass,
                                       Class<? extends WebsocketContext<?>> websocketContextImplementationClass,
                                       Class<? extends Router<?, ?>> specificRouterImplementationClass) {
        super(requestContextImplementationClass, websocketContextImplementationClass);
        this.specificRouterImplementationClass = specificRouterImplementationClass;
    }

    protected Class<? extends Router<?, ?>> getSpecificRouterImplementationClass() {
        return this.specificRouterImplementationClass;
    }

    @Override
    protected void configure() {

        //==========================================
        // Validate the requirements
        //==========================================
        validateRequirements();

        //==========================================
        // Bind the router
        //==========================================
        bindRouter();

        //==========================================
        // The assisted factory to create routes
        //==========================================
        bindRouteFactory();

        //==========================================
        // The assisted factory to create route builders
        //==========================================
        bindRouteBuilderFactory();

        //==========================================
        // The assisted factory to create redirect rules builders
        //==========================================
        bindRedirectRuleBuilderFactory();

        //==========================================
        // The assisted factory to create route handler matches
        //==========================================
        bindRouteHandlerMatchFactory();

        //==========================================
        // The assisted factory to create static resources
        //==========================================
        bindStaticResourceFactory();

        //==========================================
        // The assisted factory to create static resources
        // builders.
        //==========================================
        bindStaticResourceBuilderFactory();

        //==========================================
        // The assisted factory to create static resources
        // cors config
        //==========================================
        bindStaticResourceCorsConfigFactory();

        //==========================================
        // The assisted factory to create static resources
        // cache config
        //==========================================
        bindStaticResourceCacheConfigFactory();

        //==========================================
        // The HotlinkingManager to use.
        //==========================================
        bindStaticResourceHotlinkingManager();

        //==========================================
        // The request context add-on
        //==========================================
        bindRequestContextAddon();

        //==========================================
        // The assisted factory to create Websocket routes
        //==========================================
        bindWebsocketRouteFactory();

        //==========================================
        // The assisted factory to create Websocket route builders
        //==========================================
        bindWebsocketRouteBuilderFactory();

        //==========================================
        // The assisted factory to create
        // Websocket route handler.
        //==========================================
        bindWebsocketRouteHandlerFactory();

        //==========================================
        // The ETag factory
        //==========================================
        bindETagFactory();

        //==========================================
        // The Spincast routing utils
        //==========================================
        bindSpincastRoutingUtils();

    }

    protected void validateRequirements() {
        requireBinding(SpincastRouterConfig.class);
    }

    protected Key<?> getRouterImplementationKey() {

        //==========================================
        // Specific Router implementation class to use?
        //==========================================
        if (getSpecificRouterImplementationClass() != null) {
            return Key.get(getSpecificRouterImplementationClass());
        }

        //==========================================
        // If we use the default request context and default
        // Websocket context, we directly bind the DefaultRouterDefault that
        // implements the "DefaultRouter" interface, for
        // easy injection.
        //==========================================
        if (getRequestContextInterface().equals(DefaultRequestContext.class) &&
            getWebsocketContextInterface().equals(DefaultWebsocketContext.class)) {
            return Key.get(DefaultRouterDefault.class);
        } else {
            return parameterizeWithContextInterfaces(SpincastRouter.class);
        }
    }

    protected Key<?> getRouteKey() {
        return parameterizeWithContextInterfaces(RouteDefault.class);
    }

    protected Key<?> getWebsocketRouteKey() {
        return parameterizeWithContextInterfaces(SpincastWebsocketRoute.class);
    }

    protected Key<?> getStaticResourceKey() {
        return parameterizeWithContextInterfaces(StaticResourceDefault.class);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindRouter() {

        Key key = getRouterImplementationKey();
        try {
            key.getTypeLiteral().getSupertype(Router.class);
        } catch (Exception ex) {
            throw new RuntimeException("The router Key must implement " + Router.class.getName() + " : " + key);
        }

        //==========================================
        // Make sure we only use one instance for this object, wathever
        // interface we bind it to.
        //==========================================
        bind(key).in(Scopes.SINGLETON);

        //==========================================
        // Bind a parameterized version.
        //==========================================
        bind(parameterizeWithContextInterfaces(Router.class)).to(key).in(Scopes.SINGLETON);

        //==========================================
        // Bind a generic "Router" version.
        //==========================================
        bind(Router.class).to(key).in(Scopes.SINGLETON);

        //==========================================
        // Bind a generic "Router<?, ?>" version.
        //==========================================
        bind(new TypeLiteral<Router<?, ?>>() {}).to(key).in(Scopes.SINGLETON);

        //==========================================
        // If the default request context class is used
        // and the router extends DefaultRouter, we can bind the
        // "DefaultRouter" interface for easier access to the parameterized
        // router!
        //==========================================
        if (getRequestContextInterface().equals(DefaultRequestContext.class) &&
            DefaultRouter.class.isAssignableFrom(key.getTypeLiteral().getRawType())) {
            bind(DefaultRouter.class).to(key).in(Scopes.SINGLETON);
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindRouteFactory() {

        Key key = getRouteKey();
        try {
            key.getTypeLiteral().getSupertype(Route.class);
        } catch (Exception ex) {
            throw new RuntimeException("The route Key must implement " +
                                       Route.class.getName() + " : " + key);
        }

        Key routeKey = parameterizeWithRequestContext(Route.class);
        Key factoryKey = parameterizeWithRequestContext(RouteFactory.class);

        // Bind as assisted factory
        Annotation annotation = key.getAnnotation();
        if (annotation != null) {
            install(new FactoryModuleBuilder().implement(routeKey.getTypeLiteral(),
                                                         annotation,
                                                         key.getTypeLiteral())
                                              .build(factoryKey));
        } else {
            install(new FactoryModuleBuilder().implement(routeKey, key.getTypeLiteral())
                                              .build(factoryKey));
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindWebsocketRouteFactory() {

        Key key = getWebsocketRouteKey();
        try {
            key.getTypeLiteral().getSupertype(WebsocketRoute.class);
        } catch (Exception ex) {
            throw new RuntimeException("The websocket route Key must implement " +
                                       WebsocketRoute.class.getName() + " : " + key);
        }

        Key routeKey = parameterizeWithContextInterfaces(WebsocketRoute.class);
        Key factoryKey = parameterizeWithContextInterfaces(WebsocketRouteFactory.class);

        // Bind as assisted factory
        Annotation annotation = key.getAnnotation();
        if (annotation != null) {
            install(new FactoryModuleBuilder().implement(routeKey.getTypeLiteral(),
                                                         annotation,
                                                         key.getTypeLiteral())
                                              .build(factoryKey));
        } else {
            install(new FactoryModuleBuilder().implement(routeKey, key.getTypeLiteral())
                                              .build(factoryKey));
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindRouteBuilderFactory() {

        Key interfaceKey = parameterizeWithRequestContext(RouteBuilder.class);
        Key implementationKey = parameterizeWithContextInterfaces(getRouteBuilderImplClass());
        Key factoryKey = parameterizeWithContextInterfaces(RouteBuilderFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends RouteBuilder> getRouteBuilderImplClass() {
        return RouteBuilderDefault.class;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindRedirectRuleBuilderFactory() {

        Key interfaceKey = parameterizeWithContextInterfaces(RedirectRuleBuilder.class);
        Key implementationKey = parameterizeWithContextInterfaces(getRedirectRuleBuilderImplClass());
        Key factoryKey = parameterizeWithContextInterfaces(RedirectRuleBuilderFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends RedirectRuleBuilder> getRedirectRuleBuilderImplClass() {
        return RedirectRuleBuilderDefault.class;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindWebsocketRouteBuilderFactory() {

        Key interfaceKey = parameterizeWithContextInterfaces(WebsocketRouteBuilder.class);
        Key implementationKey = parameterizeWithContextInterfaces(getWebsocketRouteBuilderImplClass());
        Key factoryKey = parameterizeWithContextInterfaces(WebsocketRouteBuilderFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends WebsocketRouteBuilder> getWebsocketRouteBuilderImplClass() {
        return WebsocketRouteBuilderDefault.class;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindWebsocketRouteHandlerFactory() {

        Key interfaceKey = parameterizeWithRequestContext(Handler.class);
        Key implementationKey = parameterizeWithContextInterfaces(getWebsocketRouteHandlerImplClass());
        Key factoryKey = parameterizeWithContextInterfaces(WebsocketRouteHandlerFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends Handler> getWebsocketRouteHandlerImplClass() {
        return WebsocketRouteHandler.class;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindRouteHandlerMatchFactory() {
        Key interfaceKey = parameterizeWithRequestContext(RouteHandlerMatch.class);
        Key implementationKey = parameterizeWithRequestContext(getRouteHandlerMatchImplClass());
        Key factoryKey = parameterizeWithRequestContext(RouteHandlerMatchFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends RouteHandlerMatch> getRouteHandlerMatchImplClass() {
        return RouteHandlerMatchDefault.class;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindStaticResourceFactory() {

        Key key = getStaticResourceKey();
        try {
            key.getTypeLiteral().getSupertype(StaticResource.class);
        } catch (Exception ex) {
            throw new RuntimeException("The static resource Key must implement " +
                                       StaticResource.class.getName() + " : " + key);
        }

        Key staticResourceKey = parameterizeWithRequestContext(StaticResource.class);
        Key factoryKey = parameterizeWithRequestContext(StaticResourceFactory.class);

        // Bind as assisted factory
        Annotation annotation = key.getAnnotation();
        if (annotation != null) {
            install(new FactoryModuleBuilder().implement(staticResourceKey.getTypeLiteral(),
                                                         annotation,
                                                         key.getTypeLiteral())
                                              .build(factoryKey));
        } else {
            install(new FactoryModuleBuilder().implement(staticResourceKey, key.getTypeLiteral())
                                              .build(factoryKey));
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void bindStaticResourceBuilderFactory() {
        Key interfaceKey = parameterizeWithRequestContext(StaticResourceBuilder.class);
        Key implementationKey = parameterizeWithContextInterfaces(getStaticResourceBuilderImplClass());
        Key factoryKey = parameterizeWithContextInterfaces(StaticResourceBuilderFactory.class);

        install(new FactoryModuleBuilder().implement(interfaceKey, implementationKey.getTypeLiteral())
                                          .build(factoryKey));
    }

    @SuppressWarnings("rawtypes")
    protected Class<? extends StaticResourceBuilder> getStaticResourceBuilderImplClass() {
        return StaticResourceBuilderDefault.class;
    }

    protected void bindStaticResourceCorsConfigFactory() {
        install(new FactoryModuleBuilder().implement(StaticResourceCorsConfig.class,
                                                     getStaticResourceCorsConfigImplClass())
                                          .build(StaticResourceCorsConfigFactory.class));
    }

    protected Class<? extends StaticResourceCorsConfig> getStaticResourceCorsConfigImplClass() {
        return StaticResourceCorsConfigDefault.class;
    }

    protected void bindStaticResourceCacheConfigFactory() {
        install(new FactoryModuleBuilder().implement(StaticResourceCacheConfig.class,
                                                     getStaticResourceCacheConfigImplClass())
                                          .build(StaticResourceCacheConfigFactory.class));
    }

    protected Class<? extends StaticResourceCacheConfig> getStaticResourceCacheConfigImplClass() {
        return StaticResourceCacheConfigDefault.class;
    }

    protected void bindStaticResourceHotlinkingManager() {
        bind(HotlinkingManagerDefault.class).in(Scopes.SINGLETON);
        bind(HotlinkingManager.class).to(HotlinkingManagerDefault.class).in(Scopes.SINGLETON);
    }

    protected void bindRequestContextAddon() {
        bind(parameterizeWithRequestContext(RoutingRequestContextAddon.class)).to(parameterizeWithContextInterfaces(SpincastRoutingRequestContextAddon.class))
                                                                              .in(SpincastGuiceScopes.REQUEST);
    }

    protected void bindETagFactory() {
        bind(ETagFactory.class).to(getETagFactoryImplClass()).in(Scopes.SINGLETON);
    }

    protected Class<? extends ETagFactory> getETagFactoryImplClass() {
        return ETagFactoryDefault.class;
    }

    protected void bindSpincastRoutingUtils() {
        bind(SpincastRoutingUtils.class).to(getSpincastRoutingUtilsImplClass()).in(Scopes.SINGLETON);
    }

    protected Class<? extends SpincastRoutingUtils> getSpincastRoutingUtilsImplClass() {
        return SpincastRoutingUtilsDefault.class;
    }

}


text:
@implementation MOBProjectionEPSG4215
- (id)init
{
    if (self = [super initWithEPSG:4215 withDefinition:@"+proj=longlat +ellps=intl +no_defs"]) {
        ;
    }
    return self;
}

@end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe RightOn::PermissionDeniedResponse do
  let(:controller_action_options) { { controller: 'users', action: 'destroy' } }
  let(:params) { { controller: 'users' } }
  subject { RightOn::PermissionDeniedResponse.new(params, controller_action_options) }

  let(:create_user_right) { double(name: 'create_user', allowed?: true, roles: [double(title: 'Users')]) }
  let(:allowed) { double(allowed?: true) }
  let(:denied) { double(allowed?: false) }

  let(:no_right_for_page) {
    'No right is defined for this page: users. '\
    'Contact your system manager to notify this problem.'
  }
  let(:no_roles_for_page) { 'N/A (as no right is assigned for this action)' }

  before do
    stub_const 'RightOn::RightAllowed', double(new: right_allowed)
    stub_const 'RightOn::Right', double(all: [create_user_right])
  end

  context '#text_message' do
    context 'when right exists' do
      let(:right_allowed) { allowed }

      specify {
        expect(subject.text_message).to eq(
          "You are not authorised to perform the requested operation.\n"\
          "Right required: #[Double (anonymous)]\n"\
          "This right is given to the following roles: Users.\n"\
          "Contact your system manager to be given this right.\n"
        )
      }
    end

    context 'when right not allowed' do
      let(:right_allowed) { denied }
      specify { expect(subject.text_message).to eq no_right_for_page }
    end
  end

  context '#to_json' do
    context 'when right exists' do
      let(:right_allowed) { allowed }
      specify {
        expect(subject.to_json).to eq(
          error: 'Permission Denied',
          right_allowed: 'create_user',
          roles_for_right: ['Users']
        )
      }
    end

    context 'when right allowed' do
      let(:right_allowed) { denied }
      specify {
        expect(subject.to_json).to eq(
          error: 'Permission Denied',
          right_allowed: no_right_for_page,
          roles_for_right: no_roles_for_page
        )
      }
    end
  end
end


text:
"""
Middleware that will provide Dynamic Large Object (DLO) support.

---------------
Using ``swift``
---------------

The quickest way to try out this feature is use the ``swift`` Swift Tool
included with the `python-swiftclient`_ library.  You can use the ``-S``
option to specify the segment size to use when splitting a large file. For
example::

    swift upload test_container -S 1073741824 large_file

This would split the large_file into 1G segments and begin uploading those
segments in parallel. Once all the segments have been uploaded, ``swift`` will
then create the manifest file so the segments can be downloaded as one.

So now, the following ``swift`` command would download the entire large
object::

    swift download test_container large_file

``swift`` command uses a strict convention for its segmented object
support. In the above example it will upload all the segments into a
second container named test_container_segments. These segments will
have names like large_file/1290206778.25/21474836480/00000000,
large_file/1290206778.25/21474836480/00000001, etc.

The main benefit for using a separate container is that the main container
listings will not be polluted with all the segment names. The reason for using
the segment name format of <name>/<timestamp>/<size>/<segment> is so that an
upload of a new file with the same name won't overwrite the contents of the
first until the last moment when the manifest file is updated.

``swift`` will manage these segment files for you, deleting old segments on
deletes and overwrites, etc. You can override this behavior with the
``--leave-segments`` option if desired; this is useful if you want to have
multiple versions of the same large object available.

.. _`python-swiftclient`: http://github.com/openstack/python-swiftclient

----------
Direct API
----------

You can also work with the segments and manifests directly with HTTP
requests instead of having ``swift`` do that for you. You can just
upload the segments like you would any other object and the manifest
is just a zero-byte (not enforced) file with an extra
``X-Object-Manifest`` header.

All the object segments need to be in the same container, have a common object
name prefix, and sort in the order in which they should be concatenated.
Object names are sorted lexicographically as UTF-8 byte strings.
They don't have to be in the same container as the manifest file will be, which
is useful to keep container listings clean as explained above with ``swift``.

The manifest file is simply a zero-byte (not enforced) file with the extra
``X-Object-Manifest: <container>/<prefix>`` header, where ``<container>`` is
the container the object segments are in and ``<prefix>`` is the common prefix
for all the segments.

It is best to upload all the segments first and then create or update the
manifest. In this way, the full object won't be available for downloading
until the upload is complete. Also, you can upload a new set of segments to
a second location and then update the manifest to point to this new location.
During the upload of the new segments, the original manifest will still be
available to download the first set of segments.

.. note::

    The manifest file should have no content. However, this is not enforced.
    If the manifest path itself conforms to container/prefix specified in
    X-Object-Manifest, and if manifest has some content/data in it, it would
    also be considered as segment and manifest's content will be part of the
    concatenated GET response. The order of concatenation follows the usual DLO
    logic which is - the order of concatenation adheres to order returned when
    segment names are sorted.

Here's an example using ``curl`` with tiny 1-byte segments::

    # First, upload the segments
    curl -X PUT -H 'X-Auth-Token: <token>' \
        http://<storage_url>/container/myobject/00000001 --data-binary '1'
    curl -X PUT -H 'X-Auth-Token: <token>' \
        http://<storage_url>/container/myobject/00000002 --data-binary '2'
    curl -X PUT -H 'X-Auth-Token: <token>' \
        http://<storage_url>/container/myobject/00000003 --data-binary '3'

    # Next, create the manifest file
    curl -X PUT -H 'X-Auth-Token: <token>' \
        -H 'X-Object-Manifest: container/myobject/' \
        http://<storage_url>/container/myobject --data-binary ''

    # And now we can download the segments as a single object
    curl -H 'X-Auth-Token: <token>' \
        http://<storage_url>/container/myobject
"""

import json
import os

import six
from six.moves.configparser import ConfigParser, NoSectionError, NoOptionError
from six.moves.urllib.parse import unquote

from hashlib import md5
from swift.common import constraints
from swift.common.exceptions import ListingIterError, SegmentError
from swift.common.http import is_success
from swift.common.swob import Request, Response, \
    HTTPRequestedRangeNotSatisfiable, HTTPBadRequest, HTTPConflict
from swift.common.utils import get_logger, \
    RateLimitedIterator, read_conf_dir, quote, close_if_possible, \
    closing_if_possible
from swift.common.request_helpers import SegmentedIterable
from swift.common.wsgi import WSGIContext, make_subrequest

class GetContext(WSGIContext):
    def __init__(self, dlo, logger):
        super(GetContext, self).__init__(dlo.app)
        self.dlo = dlo
        self.logger = logger

    def _get_container_listing(self, req, version, account, container,
                               prefix, marker=''):
        con_req = make_subrequest(
            req.environ, path='/'.join(['', version, account, container]),
            method='GET',
            headers={'x-auth-token': req.headers.get('x-auth-token')},
            agent=('%(orig)s ' + 'DLO MultipartGET'), swift_source='DLO')
        con_req.query_string = 'format=json&prefix=%s' % quote(prefix)
        if marker:
            con_req.query_string += '&marker=%s' % quote(marker)

        con_resp = con_req.get_response(self.dlo.app)
        if not is_success(con_resp.status_int):
            return con_resp, None
        with closing_if_possible(con_resp.app_iter):
            return None, json.loads(''.join(con_resp.app_iter))

    def _segment_listing_iterator(self, req, version, account, container,
                                  prefix, segments, first_byte=None,
                                  last_byte=None):
        # It's sort of hokey that this thing takes in the first page of
        # segments as an argument, but we need to compute the etag and content
        # length from the first page, and it's better to have a hokey
        # interface than to make redundant requests.
        if first_byte is None:
            first_byte = 0
        if last_byte is None:
            last_byte = float("inf")

        marker = ''
        while True:
            for segment in segments:
                seg_length = int(segment['bytes'])

                if first_byte >= seg_length:
                    # don't need any bytes from this segment
                    first_byte = max(first_byte - seg_length, -1)
                    last_byte = max(last_byte - seg_length, -1)
                    continue
                elif last_byte < 0:
                    # no bytes are needed from this or any future segment
                    break

                seg_name = segment['name']
                if isinstance(seg_name, six.text_type):
                    seg_name = seg_name.encode("utf-8")

                # (obj path, etag, size, first byte, last byte)
                yield ("/" + "/".join((version, account, container,
                                       seg_name)),
                       # We deliberately omit the etag and size here;
                       # SegmentedIterable will check size and etag if
                       # specified, but we don't want it to. DLOs only care
                       # that the objects' names match the specified prefix.
                       None, None,
                       (None if first_byte <= 0 else first_byte),
                       (None if last_byte >= seg_length - 1 else last_byte))

                first_byte = max(first_byte - seg_length, -1)
                last_byte = max(last_byte - seg_length, -1)

            if len(segments) < constraints.CONTAINER_LISTING_LIMIT:
                # a short page means that we're done with the listing
                break
            elif last_byte < 0:
                break

            marker = segments[-1]['name']
            error_response, segments = self._get_container_listing(
                req, version, account, container, prefix, marker)
            if error_response:
                # we've already started sending the response body to the
                # client, so all we can do is raise an exception to make the
                # WSGI server close the connection early
                close_if_possible(error_response.app_iter)
                raise ListingIterError(
                    "Got status %d listing container /%s/%s" %
                    (error_response.status_int, account, container))

    def get_or_head_response(self, req, x_object_manifest,
                             response_headers=None):
        if response_headers is None:
            response_headers = self._response_headers

        container, obj_prefix = x_object_manifest.split('/', 1)
        container = unquote(container)
        obj_prefix = unquote(obj_prefix)

        # manifest might point to a different container
        req.acl = None
        version, account, _junk = req.split_path(2, 3, True)
        error_response, segments = self._get_container_listing(
            req, version, account, container, obj_prefix)
        if error_response:
            return error_response
        have_complete_listing = len(segments) < \
            constraints.CONTAINER_LISTING_LIMIT

        first_byte = last_byte = None
        actual_content_length = None
        content_length_for_swob_range = None
        if req.range and len(req.range.ranges) == 1:
            content_length_for_swob_range = sum(o['bytes'] for o in segments)

            # This is a hack to handle suffix byte ranges (e.g. "bytes=-5"),
            # which we can't honor unless we have a complete listing.
            _junk, range_end = req.range.ranges_for_length(float("inf"))[0]

            # If this is all the segments, we know whether or not this
            # range request is satisfiable.
            #
            # Alternately, we may not have all the segments, but this range
            # falls entirely within the first page's segments, so we know
            # that it is satisfiable.
            if (have_complete_listing
               or range_end < content_length_for_swob_range):
                byteranges = req.range.ranges_for_length(
                    content_length_for_swob_range)
                if not byteranges:
                    return HTTPRequestedRangeNotSatisfiable(request=req)
                first_byte, last_byte = byteranges[0]
                # For some reason, swob.Range.ranges_for_length adds 1 to the
                # last byte's position.
                last_byte -= 1
                actual_content_length = last_byte - first_byte + 1
            else:
                # The range may or may not be satisfiable, but we can't tell
                # based on just one page of listing, and we're not going to go
                # get more pages because that would use up too many resources,
                # so we ignore the Range header and return the whole object.
                actual_content_length = None
                content_length_for_swob_range = None
                req.range = None

        response_headers = [
            (h, v) for h, v in response_headers
            if h.lower() not in ("content-length", "content-range")]

        if content_length_for_swob_range is not None:
            # Here, we have to give swob a big-enough content length so that
            # it can compute the actual content length based on the Range
            # header. This value will not be visible to the client; swob will
            # substitute its own Content-Length.
            #
            # Note: if the manifest points to at least CONTAINER_LISTING_LIMIT
            # segments, this may be less than the sum of all the segments'
            # sizes. However, it'll still be greater than the last byte in the
            # Range header, so it's good enough for swob.
            response_headers.append(('Content-Length',
                                     str(content_length_for_swob_range)))
        elif have_complete_listing:
            actual_content_length = sum(o['bytes'] for o in segments)
            response_headers.append(('Content-Length',
                                     str(actual_content_length)))

        if have_complete_listing:
            response_headers = [(h, v) for h, v in response_headers
                                if h.lower() != "etag"]
            etag = md5()
            for seg_dict in segments:
                etag.update(seg_dict['hash'].strip('"'))
            response_headers.append(('Etag', '"%s"' % etag.hexdigest()))

        app_iter = None
        if req.method == 'GET':
            listing_iter = RateLimitedIterator(
                self._segment_listing_iterator(
                    req, version, account, container, obj_prefix, segments,
                    first_byte=first_byte, last_byte=last_byte),
                self.dlo.rate_limit_segments_per_sec,
                limit_after=self.dlo.rate_limit_after_segment)

            app_iter = SegmentedIterable(
                req, self.dlo.app, listing_iter, ua_suffix="DLO MultipartGET",
                swift_source="DLO", name=req.path, logger=self.logger,
                max_get_time=self.dlo.max_get_time,
                response_body_length=actual_content_length)

            try:
                app_iter.validate_first_segment()
            except (SegmentError, ListingIterError):
                return HTTPConflict(request=req)

        resp = Response(request=req, headers=response_headers,
                        conditional_response=True,
                        app_iter=app_iter)

        return resp

    def handle_request(self, req, start_response):
        """
        Take a GET or HEAD request, and if it is for a dynamic large object
        manifest, return an appropriate response.

        Otherwise, simply pass it through.
        """
        resp_iter = self._app_call(req.environ)

        # make sure this response is for a dynamic large object manifest
        for header, value in self._response_headers:
            if (header.lower() == 'x-object-manifest'):
                close_if_possible(resp_iter)
                response = self.get_or_head_response(req, value)
                return response(req.environ, start_response)
        else:
            # Not a dynamic large object manifest; just pass it through.
            start_response(self._response_status,
                           self._response_headers,
                           self._response_exc_info)
            return resp_iter

class DynamicLargeObject(object):
    def __init__(self, app, conf):
        self.app = app
        self.logger = get_logger(conf, log_route='dlo')

        # DLO functionality used to live in the proxy server, not middleware,
        # so let's try to go find config values in the proxy's config section
        # to ease cluster upgrades.
        self._populate_config_from_old_location(conf)

        self.max_get_time = int(conf.get('max_get_time', '86400'))
        self.rate_limit_after_segment = int(conf.get(
            'rate_limit_after_segment', '10'))
        self.rate_limit_segments_per_sec = int(conf.get(
            'rate_limit_segments_per_sec', '1'))

    def _populate_config_from_old_location(self, conf):
        if ('rate_limit_after_segment' in conf or
                'rate_limit_segments_per_sec' in conf or
                'max_get_time' in conf or
                '__file__' not in conf):
            return

        cp = ConfigParser()
        if os.path.isdir(conf['__file__']):
            read_conf_dir(cp, conf['__file__'])
        else:
            cp.read(conf['__file__'])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name
        for setting in ('rate_limit_after_segment',
                        'rate_limit_segments_per_sec',
                        'max_get_time'):
            try:
                conf[setting] = cp.get(proxy_section, setting)
            except (NoSectionError, NoOptionError):
                pass

    def __call__(self, env, start_response):
        """
        WSGI entry point
        """
        req = Request(env)
        try:
            vrs, account, container, obj = req.split_path(4, 4, True)
        except ValueError:
            return self.app(env, start_response)

        # install our COPY-callback hook
        env['swift.copy_hook'] = self.copy_hook(
            env.get('swift.copy_hook',
                    lambda src_req, src_resp, sink_req: src_resp))

        if ((req.method == 'GET' or req.method == 'HEAD') and
                req.params.get('multipart-manifest') != 'get'):
            return GetContext(self, self.logger).\
                handle_request(req, start_response)
        elif req.method == 'PUT':
            error_response = self._validate_x_object_manifest_header(req)
            if error_response:
                return error_response(env, start_response)
        return self.app(env, start_response)

    def _validate_x_object_manifest_header(self, req):
        """
        Make sure that X-Object-Manifest is valid if present.
        """
        if 'X-Object-Manifest' in req.headers:
            value = req.headers['X-Object-Manifest']
            container = prefix = None
            try:
                container, prefix = value.split('/', 1)
            except ValueError:
                pass
            if not container or not prefix or '?' in value or '&' in value or \
                    prefix.startswith('/'):
                return HTTPBadRequest(
                    request=req,
                    body=('X-Object-Manifest must be in the '
                          'format container/prefix'))

    def copy_hook(self, inner_hook):

        def dlo_copy_hook(source_req, source_resp, sink_req):
            x_o_m = source_resp.headers.get('X-Object-Manifest')
            if x_o_m:
                if source_req.params.get('multipart-manifest') == 'get':
                    # To copy the manifest, we let the copy proceed as normal,
                    # but ensure that X-Object-Manifest is set on the new
                    # object.
                    sink_req.headers['X-Object-Manifest'] = x_o_m
                else:
                    ctx = GetContext(self, self.logger)
                    source_resp = ctx.get_or_head_response(
                        source_req, x_o_m, source_resp.headers.items())
            return inner_hook(source_req, source_resp, sink_req)

        return dlo_copy_hook

def filter_factory(global_conf, **local_conf):
    conf = global_conf.copy()
    conf.update(local_conf)

    def dlo_filter(app):
        return DynamicLargeObject(app, conf)
    return dlo_filter


text:
* {margin: 0;}

html, body {height: 100%; margin:0 1px;}

div#container {min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -71px;}
div#classList {width: 900px; top: -90px;}

div#footer {height: 30px; clear: both; padding-top: 10px; border-top: 1px solid midnightblue;}

div#header {width: 100%; height: 250px; margin: 0; padding: 0;}
div#header-narrow {display:none;}
div#breadcrumb {width: 850px; text-align: center; margin-top: 10px; font-size: 14px; margin-left: auto; margin-right: auto; line-height: 20px; font-family: arial;}
div#breadcrumb span.crumb, div#breadcrumb span.lastcrumb {margin: 0 20px;}
xdiv#breadcrumb span.crumb {padding-right: 20px;}
div#breadcrumb span#crumb1 {font-weight: bold; color: orange; font-style: italic;}

form#pepForm, div#demographics, div#classes, div#waiver, div#contactVendor {display: none;}

div#frontpage, form#pepForm {width: 600px; margin-left: auto; margin-right: auto; position: relative; top: -90px;}
div#frontpage {width: 800px;}

span#classListInstructions {font-weight: bold; font-size: large;}

#img_logo {float: left; padding-top: 5px;}

h1, h2, h3, h4 {margin-left: auto; margin-right: auto; text-align: center; padding-top: 15px;}
h1 {font-size: 26px;}
h2 {font-size: 20px; font-weight: bold;}
h3 {width: 100%; font-size: 20px; border-bottom: 1px solid midnightblue; color: midnightblue; margin: 10px 0 20px; padding-bottom: 5px;}
h4 {font-size: 20px; margin-bottom: 15px; text-align: left;}

fieldset.data_input input {border: 1px solid #ccc; width: 250px; float: left;}
div.fld {width: 250px;}

fieldset#submit1, fieldset#submit2 {border-top: 1px solid #a6a6a6; padding: 10px 0 20px; text-align: right;}
fieldset#submit2 {width: 900px;}

div.txtbox, div.select {height: 35px; margin-bottom: 5px;}

label {width: 200px; text-align: right; float: left; margin: 0 20px 0 0;}

div.fld {float: left;}

#tblClasses {border-style: groove; border-width: 5px; border-color: lightblue; padding: 0; width: 900px;}
#tblClasses tr#classHeader {background-color: #3300cc; color: white;}
#tblClasses tr.white {background-color: white;}
#tblClasses tr.cream {background-color: #ffff99;}
#tblClasses td {border-style: solid; border-width: 0 1px 1px; text-align: center;}

label.error {width: 210px; color: red; clear: both; text-align: left;}
fieldset.data_input input.error {border-color: red; background-color: #fff2f2;}

.bold {font-weight: bold;}
a:link, a:visited, a:active {color: #000; text-decoration: none;}
a:hover {color: orange;}

#btn-back-1, #btn-back-2, #btn-back-3 {float: left;}
#btn-next-1, #btn-next-2, #btn-next-3 {float: right;}

#studentNameFirst, #studentNameLast, #parentName, #pickedupby {text-transform: capitalize;}
fieldset#submit0 {margin-top: 15px;}
fieldset#submit1 {margin-top: 15px;}
#inp_group-1 .fld {margin: 0 0 10px 220px; clear: both;}
#inp_group-1 .fld input {width: 12px; margin-top: 4px;}
#inp_group-1 .fld input.moreinfo {width: 250px; margin-left: 0px;}
#inp_group-1 .fld label {text-align: left; margin-right: 0; margin-left: 10px; width: 150px;}
#inp_group-1 label.invalid {display: none;}
div#waiver {margin-top: 10px;}
.bold {font-weight: bold;}
.red {color: red;}
.margined {margin: 15px 0;}
.pepForm {list-style-type: none; margin: 0 0 0 30px; padding-top: 10px;}
div#agreements p {margin: 15px 0;}
div#agreements a:link, div#agreements a:visited, div#agreements a:active {color: blue;}
div#agreements a:hover {text-decoration: underline;}
ol {list-style: lower-roman outside none;}
ol li {margin: 10px 0 0 20px;}

div#breadcrumb div {text-align: center; width: 150px; height: 50px; float: left;}
div#breadcrumb span.crumb, div#breadcrumb span.lastcrumb {margin: 0;}

@media screen and (max-width:480px){
	div#header{display:none;}
	br {display:none;}
	div#header-narrow{display:block;}
	div#classList {top:auto;}

	table, thead, tbody, th, tr {
		display: block;
	}

	h1,h2 {padding-top: 5px;}
	div#frontpage,form#pepForm {width: 100%; top: 0px;}
	#tblClasses {width:100%;}

	span#classListInstructions {display:none;}
	tr#classHeader { display:none;}
	tr { border: 1px solid #ccc; }

	td.fee,td.meets,td.dates,td.room,td.grades,td.classname,td.classname2,td.selectclass {
		/* Behave  like a "row" */
		display: block;
		border: none;
		border-bottom: 1px solid #eee;
		position: relative;
		width:100%;
	}
	td:before {
		position: absolute;
		top: 0px;
		left: 5px;
		padding-right: 10px;
		white-space: nowrap;
		float: left;
	}
	td.selectclass {text-align: left;}

	td.selectclass:before { content: "Enroll for this class";}
	td.grades:before { content: "Grades"; }
	td.meets:before { content: "Meets"; }
	td.fee:before { content: "Fee"; }
	td.dates:before { content: "Dates"; }
	td.room:before { content: "Room"; }

	label {font-weight:12; text-align: left; float: left; margin: 0 0 0 10px;}
	div.fld {float:none;}
	input#btn-next-3,input#btn-next-2 { float:left;}
	div#footer {margin-top: 15px;}
	fieldset.data_input input { float:none;}
	#inp_group-1 .fld { margin: 0px 0 10px 0; }
	#inp_group-1 { margin-top: 20px; }

	fieldset#submit2 {width: 100%;}
	div#classList { width: 100%; top:0px;}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace MOEWcfServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TMCExport" in both code and config file together.
    public class TMCExport : ITMCExport
    {
        public void DoWork()
        {
        }
    }
}


text:
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    ChildViewController *childViewController = [[ChildViewController alloc]
                                                initWithNibName:@"ChildViewController" bundle:nil];
    childViewController.title = @"/";
    self.naviController = [[UINavigationController alloc] initWithRootViewController:childViewController];
}

- (IBAction)open:(id)sender
{
    [self presentViewController:self.naviController animated:YES completion:nil];
}

@end


text:
module Transformer
  VERSION = "0.0.7"
end


text:
"""pyflation_newrun - Script to create and populate new Pyflation run directory.

"""
#Author: Ian Huston
#For license and copyright information see LICENSE.txt which was distributed with this file.

import os.path
import logging
import sys
import time
from optparse import OptionParser
import shutil

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext #@UnresolvedImport
import numpy

#Version information
from sys import version as python_version
from numpy import __version__ as numpy_version
from scipy import __version__ as scipy_version
from tables import __version__ as tables_version
from Cython.Compiler.Version import version as cython_version

try:
    #Local modules from pyflation package
    from pyflation import __version__ as pyflation_version
    from pyflation import configuration, helpers
except ImportError,e:
    if __name__ == "__main__":
        msg = """Pyflation module needs to be available.
Either run this script from the base directory as bin/newrun.py or add directory enclosing pyflation package to PYTHONPATH."""
        print msg, e
        sys.exit(1)
    else:
        raise

# Test whether Bazaar is available
try:
    import bzrlib.export, bzrlib.workingtree
    bzr_available = True
except ImportError:
    bzr_available = False

provenance_template = """Provenance document for this Pyflation run
------------------------------------------

Pyflation Version
-----------------
Version: %(version)s

%(bzrinfo)s

Code Directory Information
--------------------------
Original code directory: %(codedir)s
New run directory: %(newrundir)s
Date run directory was created: %(now)s

Library version information at time of run creation
-------------------------------------------
Python version: %(python_version)s
Numpy version: %(numpy_version)s
Scipy version: %(scipy_version)s
PyTables version: %(tables_version)s
Cython version: %(cython_version)s

This information added on: %(now)s.
-----------------------------------------------

"""

def copy_code_directory(codedir, newcodedir, use_bzr=False, bzr_available=False):
    """Create code directory and copy from Bazaar repository."""
    mytree = None
    if bzr_available and use_bzr:
        try:
            mytree =  bzrlib.workingtree.WorkingTree.open(codedir)
            newtree = mytree.branch.create_checkout(newcodedir, lightweight=True)
            logging.debug("Bazaar code copied successfully.")
        except bzrlib.errors.NotBranchError, e:
            mytree = None
            logging.error("Error using bazaar. Directory %s is not a branch." % codedir)
    else:
        if use_bzr:
            logging.error("Bazaar not available, copying code instead.")
        try:
            shutil.copytree(codedir, newcodedir)
            logging.debug("Copying of code successful.")
        except:
            logging.error("Error copying code. Please do so manually.")

    ext_modules = [Extension("pyflation.sourceterm.srccython", ["pyflation/sourceterm/srccython.pyx"],
               extra_compile_args=["-g"],
               extra_link_args=["-g"],
               include_dirs=[numpy.get_include()]),
               #
               Extension("pyflation.romberg", ["pyflation/romberg.pyx"],
               extra_compile_args=["-g"],
               extra_link_args=["-g"],
               include_dirs=[numpy.get_include()]),
               #
               ]

    setup_args = dict(name='Pyflation',
                  author='Ian Huston',
                  author_email='ian.huston@gmail.com',
                  url='http://www.maths.qmul.ac.uk/~ith/pyflation',
                  description='Cosmological Inflation in Python',
                  cmdclass = {'build_ext': build_ext},
                  ext_modules = ext_modules)

    #Try to run setup to create .so files
    try:
        olddir = os.getcwd()
        os.chdir(newcodedir)
        logging.info("Preparing to compile non-python files.")
        setup(script_args=["build_ext", "-i"], **setup_args)
        os.chdir(olddir)
    except:
        logging.exception("Compiling additional modules did not work. Please do so by hand!")

    return mytree

def create_run_directory(newrundir, codedir, copy_code=False,
                         use_bzr=False, overwrite=False):
    """Create the run directory using `newdir` as directory name."""
    if os.path.isdir(newrundir) and not overwrite:
        raise IOError("New run directory already exists!")

    try:
        helpers.ensurepath(newrundir)
    except OSError:
        logging.error("Cannot create parent directories for run.")
        raise

    mytree = None
    if copy_code:
        #Check for bzr
        logging.debug("bzr_available=%s", bzr_available)
        newcodedir = os.path.join(newrundir, configuration.CODEDIRNAME)
        logging.debug("Attempting to copy code directory...")
        mytree = copy_code_directory(codedir, newcodedir, use_bzr, bzr_available)
    else:
        logging.debug("No copying of code directory attempted.")

    try:
        if not os.path.isdir(newrundir):
            os.makedirs(newrundir)
    except OSError:
        logging.error("Creating new run directory failed.")
        raise

    resultsdir = os.path.join(newrundir, configuration.RESULTSDIRNAME)
    logdir = os.path.join(newrundir, configuration.LOGDIRNAME)
    qsublogsdir = os.path.join(newrundir, configuration.QSUBLOGSDIRNAME)
    qsubscriptsdir = os.path.join(newrundir, configuration.QSUBSCRIPTSDIRNAME)
    #debug info
    logging.debug("resultsdir=%s, logdir=%s, qsublogsdir=%s, qsubscriptsdir=%s",
                  resultsdir, logdir, qsublogsdir, qsubscriptsdir)

    try:
        os.makedirs(resultsdir)
        os.makedirs(logdir)
        os.makedirs(qsublogsdir)
        os.makedirs(qsubscriptsdir)
    except OSError:
        logging.error("Creating subdirectories in new run directory failed.")
        raise

    #Copy run_config template file into new run directory if not already
    #copied by bzr.
    if not os.path.isfile(os.path.join(newrundir, "run_config.py")):
        logging.debug("Need to create run_config.py from template.")
        pkgdir = os.path.dirname(os.path.abspath(configuration.__file__))
        runconfigtemplate = os.path.join(pkgdir, configuration.RUNCONFIGTEMPLATE)
        logging.debug("run_config template file is %s" % runconfigtemplate)
        if not os.path.isfile(runconfigtemplate):
            raise IOError("File run_config.template is not available to be copied!")
        else:
            try:
                shutil.copyfile(runconfigtemplate, os.path.join(newrundir, "run_config.py"))
                logging.debug("run_config file copied successfully.")
            except:
                logging.error("Error copying run_config template file.")
                raise
    else:
        logging.debug("The run_config.py file already exists in correct directory.")

    #Create provenance file detailing revision and branch used
    prov_dict = dict(version=pyflation_version,
                     python_version=python_version,
                     numpy_version=numpy_version,
                     scipy_version=scipy_version,
                     tables_version=tables_version,
                     cython_version=cython_version,
                     codedir=codedir,
                     newrundir=newrundir,
                     now=time.strftime("%Y/%m/%d %H:%M:%S %Z"))
    if mytree:
        prov_dict["bzrinfo"] = """
Bazaar Revision Control Information
-------------------------------------------------
Branch name: %(nick)s
Branch revision number: %(revno)s
Branch revision id: %(revid)s""" % {"nick": mytree.branch.nick,
                                    "revno": mytree.branch.revno(),
                                    "revid": mytree.branch.last_revision()}
    else:
        prov_dict["bzrinfo"] = ""

    provenance_file = os.path.join(newrundir, configuration.LOGDIRNAME,
                                   configuration.provenancefilename)
    with open(provenance_file, "w") as f:
        f.write(provenance_template % prov_dict)
        logging.info("Created provenance file %s." % provenance_file)

    return

def main(argv = None):
    """Check command line options and start directory creation."""
    if not argv:
        argv = sys.argv
    #Parse command line options
    parser = OptionParser()

    parser.set_defaults(loglevel=configuration.LOGLEVEL)

    parser.add_option("-d", "--dir", dest="dir", default=os.getcwd(),
                  help="create run directory in DIR, default is current directory", metavar="DIR")
    parser.add_option("-n", "--name", dest="dirname", default="pyflation_run",
                      help="new run directory name, default is pyflation_run")
    parser.add_option("-c", "--codedir", dest="codedir",
                  help="copy code from CODEDIR (where run_config.py resides)", metavar="CODEDIR")
    parser.add_option("-o", "--overwrite", action="store_true", dest="overwrite",
                      default=False, help="Overwrite into directory if it exists")
    parser.add_option("-q", "--quiet",
                  action="store_const", const=logging.FATAL, dest="loglevel",
                  help="only print fatal error messages")
    parser.add_option("-v", "--verbose",
                  action="store_const", const=logging.INFO, dest="loglevel",
                  help="print informative messages")
    parser.add_option("--debug",
                  action="store_const", const=logging.DEBUG, dest="loglevel",
                  help="print lots of debugging information")
    parser.add_option("--copy-code", action="store_true", dest="copy_code",
                      default=False, help="copy code directory into run directory (using Bazaar)")
    parser.add_option("--bzr", action="store_true", dest="use_bzr",
                      default=False, help="use Bazaar to create branch of code")

    (options, args) = parser.parse_args(args=argv[1:])

    logging.basicConfig(level=options.loglevel)

    if not os.path.isdir(options.dir):
        raise IOError("Please check that parent directory %s exists." % options.dir)

    if options.dirname:
        newdir = os.path.join(options.dir, options.dirname)
        logging.debug("Variable newdir specified with value %s.", newdir)
    else:
        newdir = os.path.join(options.dir, time.strftime("%Y%m%d%H%M%S"))
        logging.debug("Variable newdir created with value %s", newdir)

    if options.codedir and options.copy_code:
        codedir = os.path.abspath(options.codedir)
        logging.debug("Option codedir specified with value %s.", options.codedir)
    elif options.copy_code:
        try:
            from run_config import CODEDIR
        except ImportError, e:
            msg = "Configuration file run_config.py needs to be available. \
                Use --codedir command line option to specify its location."
            print msg, e
            sys.exit(1)
        codedir = os.path.abspath(CODEDIR)
        logging.debug("Variable codedir created with value %s.", codedir)
    else:
        codedir = None

    try:
        create_run_directory(newdir, codedir, options.copy_code,
                             options.use_bzr, options.overwrite)
    except Exception, e:
        logging.critical("Something went wrong! Quitting.")
        sys.exit(e)

    logging.info("New run directory created successfully.")
    return

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Corex.Threading
{
    public class LockedThreadSafe<T>
    {
        public LockedThreadSafe(T value)
        {
            Value = value;
        }

        T Value;
        object Entrance = new object();
        public void Access(Action<T> action)
        {
            lock (Entrance)
            {
                action(Value);
            }
        }
    }
}


text:
package ch.genidea.geniweb.base.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name = "genidea_documentHolder")
public class AbstractDocumentHolder {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long Id;
}


text:
def get_prime_numbers(n):
    """Gets all prime numbers below n."""
    primes, sieve = [], [True] * n

    for i in range(2, n):
        if sieve[i]:
            primes.append(i)
            for j in range(i*i, n, i):
                sieve[j] = False

    return primes

def get_prime_sum(n):
    """Calculate the sum of all prime numbers below n."""
    return sum(get_prime_numbers(n))

if __name__ == "__main__":
    print(get_prime_sum(2000000))


text:
pcaprub_helper
==============

[![Code Climate](https://codeclimate.com/github/benSlaughter/pcaprub_helper/badges/gpa.svg)](https://codeclimate.com/github/benSlaughter/pcaprub_helper)
[![Build Status](https://travis-ci.org/benSlaughter/pcaprub_helper.svg?branch=master)](https://travis-ci.org/benSlaughter/pcaprub_helper)
[![Dependency Status](https://gemnasium.com/benSlaughter/pcaprub_helper.svg)](https://gemnasium.com/benSlaughter/pcaprub_helper)
[![Test Coverage](https://codeclimate.com/github/benSlaughter/pcaprub_helper/badges/coverage.svg)](https://codeclimate.com/github/benSlaughter/pcaprub_helper)
[![Coverage Status](https://img.shields.io/coveralls/benSlaughter/pcaprub_helper.svg)](https://coveralls.io/r/benSlaughter/pcaprub_helper)

Helper methods built on top of pcaprub

## Installation

    Gem install pcaprub_helper

## Helpful docs
[Help with creating filters](http://www.tcpdump.org/manpages/pcap-filter.7.html)


text:
package com.jamonapi.utils;

import org.junit.Test;

import java.util.Arrays;

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

public class BufferListTest {

    private Object[][] getData() {
        Object[][] data={{"steven","thomas","souza"},{"mindy","darci","souza"}};
        return data;
    }

    @Test
    public void testData_WithExtraData() {
        BufferList bl=new BufferList(new String[]{"fname","mname"});
        Object[][] data = getData();
        bl.addRow(data[0]);
        bl.addRow(data[1]);

        DetailData detailData=bl.getDetailData();
        data=detailData.getData();

        // header
        assertThat(detailData.getHeader().length).isEqualTo(3);
        assertThat(Arrays.toString(detailData.getHeader())).isEqualTo("[fname, mname, col2]");

        // data
        assertThat(data.length).isEqualTo(2);
        assertThat(Arrays.toString(data[0])).isEqualTo("[steven, thomas, souza]");
        assertThat(Arrays.toString(data[1])).isEqualTo("[mindy, darci, souza]");
    }

    @Test
    public void testData_WithExtraHeader() {
        BufferList bl=new BufferList(new String[]{"fname","mname","lname","salary"});
        Object[][] data = getData();
        bl.addRow(data[0]);
        bl.addRow(data[1]);

        DetailData detailData=bl.getDetailData();
        data=detailData.getData();

        // header
        assertThat(detailData.getHeader().length).isEqualTo(4);
        assertThat(Arrays.toString(detailData.getHeader())).isEqualTo("[fname, mname, lname, salary]");

        // data
        assertThat(data.length).isEqualTo(2);
        assertThat(Arrays.toString(data[0])).isEqualTo("[steven, thomas, souza, null]");
        assertThat(Arrays.toString(data[1])).isEqualTo("[mindy, darci, souza, null]");
    }

}


text:
define(["jquery", "jasmine-jquery", "elements.atoms.example"],
function(jQ,       JasminejQuery,    Example) {
  describe("Example", function() {
    beforeEach(function() {
      jasmine.getFixtures().fixturesPath = "/base/tests";
      loadFixtures("elements/atoms/example/example-fixture.html");

      var example = Example.create({ /* ... options ... */ });
    });

    it("loadFixtures() Should load fixtures", function() {
      expect(jQ("[data-js~='example']")).toBeInDOM();
    });

    // Add more tests accordingly...
  });
});


text:
import json, block

b=block.Block('textlines')
s=json.dumps([b], default = block.object2dict)
d=json.loads(s)
a=block.dict2object(d[0])
print a


text:
<?php

/**
 * Propel_Connection_Oracle
 *
 * @package     Propel
 * @subpackage  Connection
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.propel-project.org
 * @since       1.0
 * @version     $Revision: 7490 $
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
class Propel_Connection_Oracle extends Propel_Connection_Common
{
    /**
     * @var string $driverName                  the name of this connection driver
     */
    protected $driverName = 'Oracle';

    public function __construct(Propel_Manager $manager, $adapter)
    {
        $this->supported = array(
                          'sequences'            => true,
                          'indexes'              => true,
                          'summary_functions'    => true,
                          'order_by_text'        => true,
                          'current_id'           => true,
                          'affected_rows'        => true,
                          'transactions'         => true,
                          'savepoints'           => true,
                          'limit_queries'        => true,
                          'LOBs'                 => true,
                          'replace'              => 'emulated',
                          'sub_selects'          => true,
                          'auto_increment'       => false, // implementation is broken
                          'primary_key'          => true,
                          'result_introspection' => true,
                          'prepared_statements'  => true,
                          'identifier_quoting'   => true,
                          'pattern_escaping'     => true,
                          );

        $this->properties['sql_file_delimiter']    = "\n/\n";
        $this->properties['number_max_precision']  = 38;
        $this->properties['max_identifier_length'] = 30;

        parent::__construct($manager, $adapter);

        // moving properties to params to make them changeable by user
        // VARCHAR2 allowed length is 4000 BYTE. For UTF8 strings is better to use 1000 CHAR
        $this->setParam('varchar2_max_length', 4000);
        // Oracle's default unit for char data types is BYTE. For UTF8 string it is better to use CHAR
        $this->setParam('char_unit', null);
    }

    /**
     * Sets up the date/time format
     *
     */
    public function setDateFormat($format = 'YYYY-MM-DD HH24:MI:SS')
    {
        $this->exec('ALTER SESSION SET NLS_DATE_FORMAT = "' . $format . '"');
    }

    /**
     * Adds an driver-specific LIMIT clause to the query
     *
     * @param string $query         query to modify
     * @param integer $limit        limit the number of rows
     * @param integer $offset       start reading from given offset
     * @return string               the modified query
     */
    public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false)
    {
        return $this->_createLimitSubquery($query, $limit, $offset);
    }

    private function _createLimitSubquery($query, $limit, $offset, $column = null)
    {
        $limit = (int) $limit;
        $offset = (int) $offset;
        if (preg_match('/^\s*SELECT/i', $query)) {
            if ( ! preg_match('/\sFROM\s/i', $query)) {
                $query .= " FROM dual";
            }
            if ($limit > 0) {
                $max = $offset + $limit;
                $column = $column === null ? '*' : $this->quoteIdentifier($column);
                if ($offset > 0) {
                    $min = $offset + 1;
                    $query = 'SELECT b.'.$column.' FROM ( '.
                                 'SELECT a.*, ROWNUM AS propel_rownum FROM ( '
                                   . $query . ' ) ' . $this->quoteIdentifier('a') . ' '.
                              ' ) ' . $this->quoteIdentifier('b') . ' '.
                              'WHERE propel_rownum BETWEEN ' . $min .  ' AND ' . $max;
                } else {
                    $query = 'SELECT a.'.$column.' FROM ( ' . $query .' ) a WHERE ROWNUM <= ' . $max;
                }
            }
        }
        return $query;
    }

    /**
     * Creates the SQL for Oracle that can be used in the subquery for the limit-subquery
     * algorithm.
     */
    public function modifyLimitSubquery(Propel_Table $rootTable, $query, $limit = false,
            $offset = false, $isManip = false)
    {
        // NOTE: no composite key support
        $columnNames = $rootTable->getIdentifierColumnNames();
        if (count($columnNames) > 1) {
            throw new Propel_Connection_Exception("Composite keys in LIMIT queries are "
                    . "currently not supported.");
        }
        $column = $columnNames[0];
        return $this->_createLimitSubquery($query, $limit, $offset, $column);
    }

    public function getTmpConnection($info)
    {
        return clone $this;
    }
}


text:
package dk.silverbullet.telemed.device.monica;

public class MonicaSamplesMissingException extends Exception {

    /**
     *
     */
    private static final long serialVersionUID = -2935875184529134509L;

    public MonicaSamplesMissingException(String message) {
        super(message);
    }

}


text:
package bootstrap

var Options struct {
	Zone             string
	ShowVersion      bool
	LogFile          string
	LogLevel         string
	LogRotateSize    int
	InfluxAddr       string
	InfluxDbname     string
	ListenAddr       string
	ManagerType      string
	HintedHandoffDir string
}


text:
/**
 * @file findFundamentalMat.cpp
 * @brief mex interface for cv::findFundamentalMat
 * @ingroup calib3d
 * @author Kota Yamaguchi
 * @date 2011
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

namespace {
/// Method for option processing
const ConstMap<string,int> FMMethod = ConstMap<string,int>
    ("7Point", cv::FM_7POINT)
    ("8Point", cv::FM_8POINT)
    ("Ransac", cv::FM_RANSAC)
    ("LMedS",  cv::FM_LMEDS);
}

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check the number of arguments
    nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=2);

    // Argument vector
    vector<MxArray> rhs(prhs, prhs+nrhs);

    // Option processing
    int method = cv::FM_RANSAC;
    double param1 = 3.0;
    double param2 = 0.99;
    for (int i=2; i<nrhs; i+=2) {
        string key(rhs[i].toString());
        if (key=="Method")
            method = FMMethod[rhs[i+1].toString()];
        else if (key=="Param1")
            param1 = rhs[i+1].toDouble();
        else if (key=="Param2")
            param2 = rhs[i+1].toDouble();
        else
            mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
    }

    // Process
    Mat F, mask;
    if (rhs[0].isNumeric() && rhs[1].isNumeric()) {
        Mat points1(rhs[0].toMat(CV_32F)),
            points2(rhs[1].toMat(CV_32F));
        if (points1.channels() == 1 && points1.cols == 2)
            points1 = points1.reshape(2,0);
        if (points2.channels() == 1 && points2.cols == 2)
            points2 = points2.reshape(2,0);
        F = findFundamentalMat(points1, points2, method, param1, param2,
            (nlhs>1 ? mask : noArray()));
    }
    else if (rhs[0].isCell() && rhs[1].isCell()) {
        vector<Point2f> points1(rhs[0].toVector<Point2f>()),
                        points2(rhs[1].toVector<Point2f>());
        F = findFundamentalMat(points1, points2, method, param1, param2,
            (nlhs>1 ? mask : noArray()));
    }
    else
        mexErrMsgIdAndTxt("mexopencv:error","Invalid argument");
    plhs[0] = MxArray(F);
    if (nlhs>1)
        plhs[1] = MxArray(mask);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>opentracing-agent-rules-parent</artifactId>
    <groupId>io.opentracing.contrib</groupId>
    <version>0.5.1-SNAPSHOT</version>
  </parent>

  <artifactId>opentracing-agent-rules-java-web-servlet-filter</artifactId>

  <properties>
    <opentracing-agent.lib>${project.build.directory}/lib</opentracing-agent.lib>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.opentracing.contrib</groupId>
      <artifactId>opentracing-agent</artifactId>
      <scope>test</scope>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>io.opentracing.contrib</groupId>
      <artifactId>opentracing-agent-itests</artifactId>
      <scope>test</scope>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>io.opentracing</groupId>
      <artifactId>opentracing-mock</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.opentracing.contrib</groupId>
      <artifactId>opentracing-web-servlet-filter</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-servlet</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>mockwebserver</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${version.junit}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>get-agent</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>io.opentracing.contrib</groupId>
                  <artifactId>opentracing-agent</artifactId>
                  <overWrite>true</overWrite>
                  <outputDirectory>${opentracing-agent.lib}</outputDirectory>
                  <destFileName>opentracing-agent.jar</destFileName>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>JDK6to8</id>
      <activation>
        <jdk>[1.6,1.9]</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
              <argLine>
                -javaagent:${opentracing-agent.lib}/opentracing-agent.jar
                -Dorg.jboss.byteman.verbose
              </argLine>
            </configuration>
            <executions>
              <execution>
                <id>run-integration-tests</id>
                <goals>
                  <goal>integration-test</goal>
                </goals>
                <configuration>
                  <includes>
                    <include>**/*ITest.java</include>
                  </includes>
                </configuration>
              </execution>
              <execution>
                <id>final-verify</id>
                <goals>
                  <goal>verify</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>JDK9</id>
      <activation>
        <jdk>1.9</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
              <argLine>
                -javaagent:${opentracing-agent.lib}/opentracing-agent.jar
                -Dorg.jboss.byteman.verbose
                --add-opens=java.base/java.lang=ALL-UNNAMED
                --add-opens=java.base/java.util.concurrent=ALL-UNNAMED
                --add-opens=java.base/java.util=ALL-UNNAMED
                --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
              </argLine>
            </configuration>
            <executions>
              <execution>
                <id>run-integration-tests</id>
                <goals>
                  <goal>integration-test</goal>
                </goals>
                <configuration>
                  <includes>
                    <include>**/*ITest.java</include>
                  </includes>
                </configuration>
              </execution>
              <execution>
                <id>final-verify</id>
                <goals>
                  <goal>verify</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
package mq.consumer

/**
 * Created by Bruce on 3/7/15.
 */
class IOSPushClient {

}


text:
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Marten.Linq;
using Marten.Schema;
using Marten.Services;

namespace Marten.Transforms
{
    public class TransformToJsonSelector : ISelector<string>
    {
        private readonly IQueryableDocument _document;
        private readonly string _fieldName;

        public TransformToJsonSelector(string dataLocator, TransformFunction transform, IQueryableDocument document)
        {
            _document = document;
            _fieldName = $"{transform.Function.QualifiedName}({dataLocator}) as json";
        }

        public string Resolve(DbDataReader reader, IIdentityMap map, QueryStatistics stats)
        {
            return reader.GetString(0);
        }

        public async Task<string> ResolveAsync(DbDataReader reader, IIdentityMap map, QueryStatistics stats, CancellationToken token)
        {
            return await reader.GetFieldValueAsync<string>(0, token).ConfigureAwait(false);
        }

        public string[] SelectFields()
        {
            return new[] {_fieldName};
        }

        public string ToSelectClause(IQueryableDocument mapping)
        {
            return $"select {_fieldName} from {_document.Table.QualifiedName} as d";
        }
    }
}


text:
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading;

namespace JanusSharedLib
{
    public class ObservableSet<T> : ObservableCollection<T>
    {
        private readonly SynchronizationContext _syncContext;

        public ObservableSet()
        {
            _syncContext = SynchronizationContext.Current;
        }

        private void NotifyCountChanged()
        {
            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        }

        private void NotifyCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
        {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
        }

        private void NotifyCollectionChanged(NotifyCollectionChangedAction action, object item = null)
        {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item));
        }

        private void _add(T item)
        {
            var index = IndexOf(item);
            if (index >= 0) return;

            base.Add(item);

            NotifyCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
            NotifyCountChanged();
        }

        public new void Add(T item)
        {
            if (_syncContext != null)
            {
                _syncContext.Send(x => _add(item), this);
            }
            else
            {
                _add(item);
            }
        }

        private void _remove(T item)
        {
            var index = IndexOf(item);
            if (index < 0) return;

            var changed = base.Remove(item);

            if (changed)
            {
                NotifyCollectionChanged(NotifyCollectionChangedAction.Remove, item, index);
                NotifyCountChanged();
            }
        }

        public new void Remove(T item)
        {
            if (_syncContext != null)
            {
                _syncContext.Send(x => _remove(item), this);
            }
            else
            {
                _remove(item);
            }
        }

        private void _clear()
        {
            if (Count == 0)
                return;

            base.Clear();

            NotifyCollectionChanged(NotifyCollectionChangedAction.Reset);
            NotifyCountChanged();
        }

        public new void Clear()
        {
            if (_syncContext != null)
            {
                _syncContext.Send(x => _clear(), this);
            }
            else
            {
                _clear();
            }
        }
    }
}


text:
package cbn

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// OperateCommunitySet is a nested struct in cbn response
type OperateCommunitySet struct {
	OperateCommunity []string `json:"OperateCommunity" xml:"OperateCommunity"`
}


text:
import { Record } from 'immutable';

/** OutputDefinitionのChoiceに格納するクラス */
export const ChoiceDefinitionRecord = Record({
  _id: null,           // 内部で使用するIDでitemの移動やnodeの移動があっても変わらない
  label: null,         // 表示用のラベル
  value: null,         // 対応する値
});

export default class ChoiceDefinition extends ChoiceDefinitionRecord {
  getId() {
    return this.get('_id');
  }

  getLabel() {
    return this.get('label');
  }

  getValue() {
    return this.get('value');
  }
}


text:
<?php

/**
 * Smarty Method RegisterDefaultPluginHandler
 *
 * Smarty::registerDefaultPluginHandler() method
 *
 * @package    Smarty
 * @subpackage PluginsInternal
 * @author     Uwe Tews
 */
class Smarty_Internal_Method_RegisterDefaultPluginHandler
{
    /**
     * Valid for Smarty and template object
     *
     * @var int
     */
    public $objMap = 3;

    /**
     * Registers a default plugin handler
     *
     * @api  Smarty::registerDefaultPluginHandler()
     * @link http://www.smarty.net/docs/en/api.register.default.plugin.handler.tpl
     *
     * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
     * @param  callable                                                       $callback class/method name
     *
     * @return \Smarty|\Smarty_Internal_Template
     * @throws SmartyException              if $callback is not callable
     */
    public function registerDefaultPluginHandler(Smarty_Internal_TemplateBase $obj, $callback)
    {
        $smarty = isset($obj->smarty) ? $obj->smarty : $obj;
        if (is_callable($callback)) {
            $smarty->default_plugin_handler_func = $callback;
        } else {
            throw new SmartyException("Default plugin handler '$callback' not callable");
        }
        return $obj;
    }
}