text:
"""
Starting point for routing EC2 requests.

"""

import urlparse

from eventlet.green import httplib
from oslo.config import cfg
import six
import webob
import webob.dec
import webob.exc

from nova.api.ec2 import apirequest
from nova.api.ec2 import ec2utils
from nova.api.ec2 import faults
from nova.api import validator
from nova import context
from nova import exception
from nova.openstack.common.gettextutils import _
from nova.openstack.common import importutils
from nova.openstack.common import jsonutils
from nova.openstack.common import log as logging
from nova.openstack.common import memorycache
from nova.openstack.common import timeutils
from nova import utils
from nova import wsgi

LOG = logging.getLogger(__name__)

ec2_opts = [
    cfg.IntOpt('lockout_attempts',
               default=5,
               help='Number of failed auths before lockout.'),
    cfg.IntOpt('lockout_minutes',
               default=15,
               help='Number of minutes to lockout if triggered.'),
    cfg.IntOpt('lockout_window',
               default=15,
               help='Number of minutes for lockout window.'),
    cfg.StrOpt('keystone_ec2_url',
               default='http://localhost:5000/v2.0/ec2tokens',
               help='URL to get token from ec2 request.'),
    cfg.BoolOpt('ec2_private_dns_show_ip',
                default=False,
                help='Return the IP address as private dns hostname in '
                     'describe instances'),
    cfg.BoolOpt('ec2_strict_validation',
                default=True,
                help='Validate security group names'
                     ' according to EC2 specification'),
    cfg.IntOpt('ec2_timestamp_expiry',
               default=300,
               help='Time in seconds before ec2 timestamp expires'),
    ]

CONF = cfg.CONF
CONF.register_opts(ec2_opts)
CONF.import_opt('use_forwarded_for', 'nova.api.auth')

## Fault Wrapper around all EC2 requests ##
class FaultWrapper(wsgi.Middleware):
    """Calls the middleware stack, captures any exceptions into faults."""

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        try:
            return req.get_response(self.application)
        except Exception as ex:
            LOG.exception(_("FaultWrapper: %s"), unicode(ex))
            return faults.Fault(webob.exc.HTTPInternalServerError())

class RequestLogging(wsgi.Middleware):
    """Access-Log akin logging for all EC2 API requests."""

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        start = timeutils.utcnow()
        rv = req.get_response(self.application)
        self.log_request_completion(rv, req, start)
        return rv

    def log_request_completion(self, response, request, start):
        apireq = request.environ.get('ec2.request', None)
        if apireq:
            controller = apireq.controller
            action = apireq.action
        else:
            controller = None
            action = None
        ctxt = request.environ.get('nova.context', None)
        delta = timeutils.utcnow() - start
        seconds = delta.seconds
        microseconds = delta.microseconds
        LOG.info(
            "%s.%ss %s %s %s %s:%s %s [%s] %s %s",
            seconds,
            microseconds,
            request.remote_addr,
            request.method,
            "%s%s" % (request.script_name, request.path_info),
            controller,
            action,
            response.status_int,
            request.user_agent,
            request.content_type,
            response.content_type,
            context=ctxt)

class Lockout(wsgi.Middleware):
    """Lockout for x minutes on y failed auths in a z minute period.

    x = lockout_timeout flag
    y = lockout_window flag
    z = lockout_attempts flag

    Uses memcached if lockout_memcached_servers flag is set, otherwise it
    uses a very simple in-process cache. Due to the simplicity of
    the implementation, the timeout window is started with the first
    failed request, so it will block if there are x failed logins within
    that period.

    There is a possible race condition where simultaneous requests could
    sneak in before the lockout hits, but this is extremely rare and would
    only result in a couple of extra failed attempts.
    """

    def __init__(self, application):
        """middleware can use fake for testing."""
        self.mc = memorycache.get_client()
        super(Lockout, self).__init__(application)

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        access_key = str(req.params['AWSAccessKeyId'])
        failures_key = "authfailures-%s" % access_key
        failures = int(self.mc.get(failures_key) or 0)
        if failures >= CONF.lockout_attempts:
            detail = _("Too many failed authentications.")
            raise webob.exc.HTTPForbidden(detail=detail)
        res = req.get_response(self.application)
        if res.status_int == 403:
            failures = self.mc.incr(failures_key)
            if failures is None:
                # NOTE(vish): To use incr, failures has to be a string.
                self.mc.set(failures_key, '1', time=CONF.lockout_window * 60)
            elif failures >= CONF.lockout_attempts:
                LOG.warn(_('Access key %(access_key)s has had %(failures)d '
                           'failed authentications and will be locked out '
                           'for %(lock_mins)d minutes.'),
                         {'access_key': access_key,
                          'failures': failures,
                          'lock_mins': CONF.lockout_minutes})
                self.mc.set(failures_key, str(failures),
                            time=CONF.lockout_minutes * 60)
        return res

class EC2KeystoneAuth(wsgi.Middleware):
    """Authenticate an EC2 request with keystone and convert to context."""

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        request_id = context.generate_request_id()
        signature = req.params.get('Signature')
        if not signature:
            msg = _("Signature not provided")
            return faults.ec2_error_response(request_id, "AuthFailure", msg,
                                             status=400)
        access = req.params.get('AWSAccessKeyId')
        if not access:
            msg = _("Access key not provided")
            return faults.ec2_error_response(request_id, "AuthFailure", msg,
                                             status=400)

        # Make a copy of args for authentication and signature verification.
        auth_params = dict(req.params)
        # Not part of authentication args
        auth_params.pop('Signature')

        cred_dict = {
            'access': access,
            'signature': signature,
            'host': req.host,
            'verb': req.method,
            'path': req.path,
            'params': auth_params,
        }
        if "ec2" in CONF.keystone_ec2_url:
            creds = {'ec2Credentials': cred_dict}
        else:
            creds = {'auth': {'OS-KSEC2:ec2Credentials': cred_dict}}
        creds_json = jsonutils.dumps(creds)
        headers = {'Content-Type': 'application/json'}

        o = urlparse.urlparse(CONF.keystone_ec2_url)
        if o.scheme == "http":
            conn = httplib.HTTPConnection(o.netloc)
        else:
            conn = httplib.HTTPSConnection(o.netloc)
        conn.request('POST', o.path, body=creds_json, headers=headers)
        response = conn.getresponse()
        data = response.read()
        if response.status != 200:
            if response.status == 401:
                msg = response.reason
            else:
                msg = _("Failure communicating with keystone")
            return faults.ec2_error_response(request_id, "AuthFailure", msg,
                                             status=response.status)
        result = jsonutils.loads(data)
        conn.close()

        try:
            token_id = result['access']['token']['id']
            user_id = result['access']['user']['id']
            project_id = result['access']['token']['tenant']['id']
            user_name = result['access']['user'].get('name')
            project_name = result['access']['token']['tenant'].get('name')
            roles = [role['name'] for role
                     in result['access']['user']['roles']]
        except (AttributeError, KeyError) as e:
            LOG.exception(_("Keystone failure: %s") % e)
            msg = _("Failure communicating with keystone")
            return faults.ec2_error_response(request_id, "AuthFailure", msg,
                                             status=400)

        remote_address = req.remote_addr
        if CONF.use_forwarded_for:
            remote_address = req.headers.get('X-Forwarded-For',
                                             remote_address)

        catalog = result['access']['serviceCatalog']
        ctxt = context.RequestContext(user_id,
                                      project_id,
                                      user_name=user_name,
                                      project_name=project_name,
                                      roles=roles,
                                      auth_token=token_id,
                                      remote_address=remote_address,
                                      service_catalog=catalog)

        req.environ['nova.context'] = ctxt

        return self.application

class NoAuth(wsgi.Middleware):
    """Add user:project as 'nova.context' to WSGI environ."""

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        if 'AWSAccessKeyId' not in req.params:
            raise webob.exc.HTTPBadRequest()
        user_id, _sep, project_id = req.params['AWSAccessKeyId'].partition(':')
        project_id = project_id or user_id
        remote_address = req.remote_addr
        if CONF.use_forwarded_for:
            remote_address = req.headers.get('X-Forwarded-For', remote_address)
        ctx = context.RequestContext(user_id,
                                     project_id,
                                     is_admin=True,
                                     remote_address=remote_address)

        req.environ['nova.context'] = ctx
        return self.application

class Requestify(wsgi.Middleware):

    def __init__(self, app, controller):
        super(Requestify, self).__init__(app)
        self.controller = importutils.import_object(controller)

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        non_args = ['Action', 'Signature', 'AWSAccessKeyId', 'SignatureMethod',
                    'SignatureVersion', 'Version', 'Timestamp']
        args = dict(req.params)
        try:
            expired = ec2utils.is_ec2_timestamp_expired(req.params,
                            expires=CONF.ec2_timestamp_expiry)
            if expired:
                msg = _("Timestamp failed validation.")
                LOG.exception(msg)
                raise webob.exc.HTTPForbidden(detail=msg)

            # Raise KeyError if omitted
            action = req.params['Action']
            # Fix bug lp:720157 for older (version 1) clients
            version = req.params['SignatureVersion']
            if int(version) == 1:
                non_args.remove('SignatureMethod')
                if 'SignatureMethod' in args:
                    args.pop('SignatureMethod')
            for non_arg in non_args:
                # Remove, but raise KeyError if omitted
                args.pop(non_arg)
        except KeyError:
            raise webob.exc.HTTPBadRequest()
        except exception.InvalidRequest as err:
            raise webob.exc.HTTPBadRequest(explanation=unicode(err))

        LOG.debug(_('action: %s'), action)
        for key, value in args.items():
            LOG.debug(_('arg: %(key)s\t\tval: %(value)s'),
                      {'key': key, 'value': value})

        # Success!
        api_request = apirequest.APIRequest(self.controller, action,
                                            req.params['Version'], args)
        req.environ['ec2.request'] = api_request
        return self.application

class Authorizer(wsgi.Middleware):

    """Authorize an EC2 API request.

    Return a 401 if ec2.controller and ec2.action in WSGI environ may not be
    executed in nova.context.
    """

    def __init__(self, application):
        super(Authorizer, self).__init__(application)
        self.action_roles = {
            'CloudController': {
                'DescribeAvailabilityZones': ['all'],
                'DescribeRegions': ['all'],
                'DescribeSnapshots': ['all'],
                'DescribeKeyPairs': ['all'],
                'CreateKeyPair': ['all'],
                'DeleteKeyPair': ['all'],
                'DescribeSecurityGroups': ['all'],
                'ImportKeyPair': ['all'],
                'AuthorizeSecurityGroupIngress': ['netadmin'],
                'RevokeSecurityGroupIngress': ['netadmin'],
                'CreateSecurityGroup': ['netadmin'],
                'DeleteSecurityGroup': ['netadmin'],
                'GetConsoleOutput': ['projectmanager', 'sysadmin'],
                'DescribeVolumes': ['projectmanager', 'sysadmin'],
                'CreateVolume': ['projectmanager', 'sysadmin'],
                'AttachVolume': ['projectmanager', 'sysadmin'],
                'DetachVolume': ['projectmanager', 'sysadmin'],
                'DescribeInstances': ['all'],
                'DescribeAddresses': ['all'],
                'AllocateAddress': ['netadmin'],
                'ReleaseAddress': ['netadmin'],
                'AssociateAddress': ['netadmin'],
                'DisassociateAddress': ['netadmin'],
                'RunInstances': ['projectmanager', 'sysadmin'],
                'TerminateInstances': ['projectmanager', 'sysadmin'],
                'RebootInstances': ['projectmanager', 'sysadmin'],
                'UpdateInstance': ['projectmanager', 'sysadmin'],
                'StartInstances': ['projectmanager', 'sysadmin'],
                'StopInstances': ['projectmanager', 'sysadmin'],
                'DeleteVolume': ['projectmanager', 'sysadmin'],
                'DescribeImages': ['all'],
                'DeregisterImage': ['projectmanager', 'sysadmin'],
                'RegisterImage': ['projectmanager', 'sysadmin'],
                'DescribeImageAttribute': ['all'],
                'ModifyImageAttribute': ['projectmanager', 'sysadmin'],
                'UpdateImage': ['projectmanager', 'sysadmin'],
                'CreateImage': ['projectmanager', 'sysadmin'],
            },
            'AdminController': {
                # All actions have the same permission: ['none'] (the default)
                # superusers will be allowed to run them
                # all others will get HTTPUnauthorized.
            },
        }

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        context = req.environ['nova.context']
        controller = req.environ['ec2.request'].controller.__class__.__name__
        action = req.environ['ec2.request'].action
        allowed_roles = self.action_roles[controller].get(action, ['none'])
        if self._matches_any_role(context, allowed_roles):
            return self.application
        else:
            LOG.audit(_('Unauthorized request for controller=%(controller)s '
                        'and action=%(action)s'),
                      {'controller': controller, 'action': action},
                      context=context)
            raise webob.exc.HTTPUnauthorized()

    def _matches_any_role(self, context, roles):
        """Return True if any role in roles is allowed in context."""
        if context.is_admin:
            return True
        if 'all' in roles:
            return True
        if 'none' in roles:
            return False
        return any(role in context.roles for role in roles)

class Validator(wsgi.Middleware):

    def validate_ec2_id(val):
        if not validator.validate_str()(val):
            return False
        try:
            ec2utils.ec2_id_to_id(val)
        except exception.InvalidEc2Id:
            return False
        return True

    validator.validate_ec2_id = validate_ec2_id

    validator.DEFAULT_VALIDATOR = {
        'instance_id': validator.validate_ec2_id,
        'volume_id': validator.validate_ec2_id,
        'image_id': validator.validate_ec2_id,
        'attribute': validator.validate_str(),
        'image_location': validator.validate_image_path,
        'public_ip': utils.is_valid_ipv4,
        'region_name': validator.validate_str(),
        'group_name': validator.validate_str(max_length=255),
        'group_description': validator.validate_str(max_length=255),
        'size': validator.validate_int(),
        'user_data': validator.validate_user_data
    }

    def __init__(self, application):
        super(Validator, self).__init__(application)

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        if validator.validate(req.environ['ec2.request'].args,
                              validator.DEFAULT_VALIDATOR):
            return self.application
        else:
            raise webob.exc.HTTPBadRequest()

def exception_to_ec2code(ex):
    """Helper to extract EC2 error code from exception.

    For other than EC2 exceptions (those without ec2_code attribute),
    use exception name.
    """
    if hasattr(ex, 'ec2_code'):
        code = ex.ec2_code
    else:
        code = type(ex).__name__
    return code

def ec2_error_ex(ex, req, code=None, message=None, unexpected=False):
    """
    Return an EC2 error response based on passed exception and log
    the exception on an appropriate log level:

        * DEBUG: expected errors
        * ERROR: unexpected errors

    All expected errors are treated as client errors and 4xx HTTP
    status codes are always returned for them.

    Unexpected 5xx errors may contain sensitive information,
    suppress their messages for security.
    """
    if not code:
        code = exception_to_ec2code(ex)
    status = getattr(ex, 'code', None)
    if not status:
        status = 500

    if unexpected:
        log_fun = LOG.error
        if ex.args and status < 500:
            log_msg = _("Unexpected %(ex_name)s raised: %(ex_str)s")
        else:
            log_msg = _("Unexpected %(ex_name)s raised")
    else:
        log_fun = LOG.debug
        if ex.args:
            log_msg = _("%(ex_name)s raised: %(ex_str)s")
        else:
            log_msg = _("%(ex_name)s raised")
        # NOTE(jruzicka): For compatibility with EC2 API, treat expected
        # exceptions as client (4xx) errors. The exception error code is 500
        # by default and most exceptions inherit this from NovaException even
        # though they are actually client errors in most cases.
        if status >= 500:
            status = 400
    context = req.environ['nova.context']
    request_id = context.request_id
    log_msg_args = {
        'ex_name': type(ex).__name__,
        'ex_str': unicode(ex)
    }
    log_fun(log_msg % log_msg_args, context=context)

    if ex.args and not message and (not unexpected or status < 500):
        message = unicode(ex.args[0])
    if unexpected:
        # Log filtered environment for unexpected errors.
        env = req.environ.copy()
        for k in env.keys():
            if not isinstance(env[k], six.string_types):
                env.pop(k)
        log_fun(_('Environment: %s') % jsonutils.dumps(env))
    if not message:
        message = _('Unknown error occurred.')
    return faults.ec2_error_response(request_id, code, message, status=status)

class Executor(wsgi.Application):

    """Execute an EC2 API request.

    Executes 'ec2.action' upon 'ec2.controller', passing 'nova.context' and
    'ec2.action_args' (all variables in WSGI environ.)  Returns an XML
    response, or a 400 upon failure.
    """

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        context = req.environ['nova.context']
        api_request = req.environ['ec2.request']
        try:
            result = api_request.invoke(context)
        except exception.InstanceNotFound as ex:
            ec2_id = ec2utils.id_to_ec2_inst_id(ex.kwargs['instance_id'])
            message = ex.msg_fmt % {'instance_id': ec2_id}
            return ec2_error_ex(ex, req, message=message)
        except exception.VolumeNotFound as ex:
            ec2_id = ec2utils.id_to_ec2_vol_id(ex.kwargs['volume_id'])
            message = ex.msg_fmt % {'volume_id': ec2_id}
            return ec2_error_ex(ex, req, message=message)
        except exception.SnapshotNotFound as ex:
            ec2_id = ec2utils.id_to_ec2_snap_id(ex.kwargs['snapshot_id'])
            message = ex.msg_fmt % {'snapshot_id': ec2_id}
            return ec2_error_ex(ex, req, message=message)
        except (exception.CannotDisassociateAutoAssignedFloatingIP,
                exception.FloatingIpAssociated,
                exception.FloatingIpNotFound,
                exception.ImageNotActive,
                exception.InvalidInstanceIDMalformed,
                exception.InvalidKeypair,
                exception.InvalidParameterValue,
                exception.InvalidPortRange,
                exception.InvalidVolume,
                exception.KeyPairExists,
                exception.KeypairNotFound,
                exception.MissingParameter,
                exception.NoFloatingIpInterface,
                exception.NoMoreFixedIps,
                exception.NotAuthorized,
                exception.QuotaError,
                exception.SecurityGroupExists,
                exception.SecurityGroupLimitExceeded,
                exception.SecurityGroupRuleExists,
                exception.VolumeUnattached,
                # Following aren't translated to valid EC2 errors.
                exception.ImageNotFound,
                exception.ImageNotFoundEC2,
                exception.InvalidAttribute,
                exception.InvalidRequest,
                exception.NotFound) as ex:
            return ec2_error_ex(ex, req)
        except Exception as ex:
            return ec2_error_ex(ex, req, unexpected=True)
        else:
            resp = webob.Response()
            resp.status = 200
            resp.headers['Content-Type'] = 'text/xml'
            resp.body = str(result)
            return resp


text:
/*
 * This file is subject to the license found in LICENCE.TXT in the root directory of the project.
 *
 * #SNAPSHOT#
 */
package fr.jayasoft.ivy.ant;

import java.util.Map;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import junit.framework.TestCase;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Delete;

import fr.jayasoft.ivy.DependencyDescriptor;
import fr.jayasoft.ivy.Ivy;
import fr.jayasoft.ivy.ModuleDescriptor;
import fr.jayasoft.ivy.ModuleRevisionId;
import fr.jayasoft.ivy.util.FileUtil;
import fr.jayasoft.ivy.xml.XmlModuleDescriptorParser;

public class IvyDeliverTest extends TestCase {
    private File _cache;
    private IvyDeliver _deliver;
    private Project _project;

    protected void setUp() throws Exception {
        cleanTestDir();
        cleanRep();
        createCache();
        _project = new Project();
        _project.setProperty("ivy.conf.file", "test/repositories/ivyconf.xml");
        _project.setProperty("build", "build/test/deliver");

        _deliver = new IvyDeliver();
        _deliver.setProject(_project);
        _deliver.setCache(_cache);
    }

    private void createCache() {
        _cache = new File("build/cache");
        _cache.mkdirs();
    }

    protected void tearDown() throws Exception {
        cleanCache();
        cleanTestDir();
        cleanRep();
    }

    private void cleanCache() {
        Delete del = new Delete();
        del.setProject(new Project());
        del.setDir(_cache);
        del.execute();
    }

    private void cleanTestDir() {
        Delete del = new Delete();
        del.setProject(new Project());
        del.setDir(new File("build/test/deliver"));
        del.execute();
    }

    private void cleanRep() {
        Delete del = new Delete();
        del.setProject(new Project());
        del.setDir(new File("test/repositories/1/jayasoft"));
        del.execute();
    }

    public void testSimple() throws Exception {
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-latest.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(new Ivy(), deliveredIvyFile.toURL(), true);
        assertEquals(ModuleRevisionId.newInstance("jayasoft", "resolve-latest", "1.2"), md.getModuleRevisionId());
        DependencyDescriptor[] dds = md.getDependencies();
        assertEquals(1, dds.length);
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "2.2"), dds[0].getDependencyRevisionId());
    }

    public void testWithBranch() throws Exception {
    	// test case for IVY-404
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-latest-branch.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(new Ivy(), deliveredIvyFile.toURL(), true);
        assertEquals(ModuleRevisionId.newInstance("apache", "resolve-latest", "1.2"), md.getModuleRevisionId());
        DependencyDescriptor[] dds = md.getDependencies();
        assertEquals(1, dds.length);
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "TRUNK", "2.2"), dds[0].getDependencyRevisionId());
    }

    public void testWithExtraAttributes() throws Exception {
    	// test case for IVY-415
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-latest-extra.xml");
        IvyResolve res = new IvyResolve();
        res.setValidate(false);
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.setValidate(false);
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(new Ivy(), deliveredIvyFile.toURL(), false);
        assertEquals(ModuleRevisionId.newInstance("apache", "resolve-latest", "1.2"), md.getModuleRevisionId());
        DependencyDescriptor[] dds = md.getDependencies();
        assertEquals(1, dds.length);
        Map extraAtt = new HashMap();
        extraAtt.put("myExtraAtt", "myValue");
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "2.2", extraAtt), dds[0].getDependencyRevisionId());
    }

    public void testReplaceImportedConfigurations() throws Exception {
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-import-confs.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        String deliveredFileContent = FileUtil.readEntirely(new BufferedReader(new FileReader(deliveredIvyFile)));
        assertTrue("import not replaced: import can still be found in file", deliveredFileContent.indexOf("import") == -1);
        assertTrue("import not replaced: conf1 cannot be found in file", deliveredFileContent.indexOf("conf1") != -1);
    }

    public void testReplaceVariables() throws Exception {
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-with-variables.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        res.getIvyInstance().setVariable("myvar", "myvalue");

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        String deliveredFileContent = FileUtil.readEntirely(new BufferedReader(new FileReader(deliveredIvyFile)));
        assertTrue("variable not replaced: myvar can still be found in file", deliveredFileContent.indexOf("myvar") == -1);
        assertTrue("variable not replaced: myvalue cannot be found in file", deliveredFileContent.indexOf("myvalue") != -1);
    }

    public void testNoReplaceDynamicRev() throws Exception {
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-latest.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.setReplacedynamicrev(false);
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(new Ivy(), deliveredIvyFile.toURL(), true);
        assertEquals(ModuleRevisionId.newInstance("jayasoft", "resolve-latest", "1.2"), md.getModuleRevisionId());
        DependencyDescriptor[] dds = md.getDependencies();
        assertEquals(1, dds.length);
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "latest.integration"), dds[0].getDependencyRevisionId());
    }

    public void testDifferentRevisionsForSameModule() throws Exception {
        _project.setProperty("ivy.dep.file", "test/java/fr/jayasoft/ivy/ant/ivy-different-revisions.xml");
        IvyResolve res = new IvyResolve();
        res.setProject(_project);
        res.execute();

        _deliver.setPubrevision("1.2");
        _deliver.setDeliverpattern("build/test/deliver/ivy-[revision].xml");
        _deliver.execute();

        // should have done the ivy delivering
        File deliveredIvyFile = new File("build/test/deliver/ivy-1.2.xml");
        assertTrue(deliveredIvyFile.exists());
        ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(new Ivy(), deliveredIvyFile.toURL(), true);
        assertEquals(ModuleRevisionId.newInstance("jayasoft", "different-revs", "1.2"), md.getModuleRevisionId());
        DependencyDescriptor[] dds = md.getDependencies();
        assertEquals(3, dds.length);
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "2.0"), dds[0].getDependencyRevisionId());
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.1", "1.0"), dds[1].getDependencyRevisionId());
        assertEquals(ModuleRevisionId.newInstance("org1", "mod1.2", "1.1"), dds[2].getDependencyRevisionId());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jackrabbit.oak.security.authentication.ldap;

import java.util.Map;
import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalLoginModule;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser;

public final class LdapLoginModule extends ExternalLoginModule {

    private Credentials credentials;
    private LdapUser ldapUser;
    private boolean success;

    private LdapSearch search;

    //--------------------------------------------------------< LoginModule >---
    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
        super.initialize(subject, callbackHandler, sharedState, options);
        //TODO
        search = new JndiLdapSearch(new LdapSettings(options));
    }

    @Override
    public boolean login() throws LoginException {
        getExternalUser();
        if (ldapUser != null && search.findUser(ldapUser)) {
            search.authenticate(ldapUser);
            success = true;
        }
        return success;
    }

    //------------------------------------------------< AbstractLoginModule >---
    @Override
    protected Credentials getCredentials() {
        if (credentials == null) {
            credentials = super.getCredentials();
        }
        return credentials;
    }

    @Override
    protected void clearState() {
        super.clearState();
        success = false;
        credentials = null;
        ldapUser = null;
        search = null;
    }

    //------------------------------------------------< ExternalLoginModule >---
    @Override
    protected boolean loginSucceeded() {
        return success;
    }

    @Override
    protected ExternalUser getExternalUser() {
        if (ldapUser == null) {
            Credentials creds = getCredentials();
            if (creds instanceof SimpleCredentials) {
                String uid = ((SimpleCredentials) creds).getUserID();
                char[] pwd = ((SimpleCredentials) creds).getPassword();
                ldapUser = new LdapUser(uid, new String(pwd), search);
            }
        }
        return ldapUser;
    }
}


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Assimp: Assimp::IOSystem Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Assimp
    v3.1.1 (June 2014)

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

Assimp

IOSystem

Public Member Functions |
List of all members

Assimp::IOSystem Class Referenceabstract

CPP-API: Interface to the file system.
 More...

Inherits AllocateFromAssimpHeap.

Public Member Functions

virtual void 	Close (IOStream *pFile)=0

 	Closes the given file and releases all resources associated with it.  More...

virtual bool 	ComparePaths (const char *one, const char *second) const

 	Compares two paths and check whether the point to identical files.  More...

bool 	ComparePaths (const std::string &one, const std::string &second) const

 	For backward compatibility.  More...

AI_FORCE_INLINE bool 	Exists (const std::string &pFile) const

 	For backward compatibility.  More...

virtual bool 	Exists (const char *pFile) const =0

 	Tests for the existence of a file at the given path.  More...

virtual char 	getOsSeparator () const =0

 	Returns the system specific directory separator.  More...

 	IOSystem ()

 	Default constructor.  More...

virtual IOStream * 	Open (const char *pFile, const char *pMode="rb")=0

 	Open a new file with a given path.  More...

IOStream * 	Open (const std::string &pFile, const std::string &pMode=std::string("rb"))

 	For backward compatibility.  More...

virtual 	~IOSystem ()

 	Virtual destructor.  More...

Detailed Description

CPP-API: Interface to the file system.

Derive an own implementation from this interface to supply custom file handling to the importer library. If you implement this interface, you also want to supply a custom implementation for IOStream.

See also

Importer::SetIOHandler()

Constructor & Destructor Documentation

          AI_FORCE_INLINE Assimp::IOSystem::IOSystem
          (
          	)

Default constructor.

Create an instance of your derived class and assign it to an Assimp::Importer instance by calling Importer::SetIOHandler().

          AI_FORCE_INLINE Assimp::IOSystem::~IOSystem
          (
          	)

virtual

Virtual destructor.

It is safe to be called from within DLL Assimp, we're constructed on Assimp's heap.

Member Function Documentation

          virtual void Assimp::IOSystem::Close
          (
          IOStream *
          pFile	)

pure virtual

Closes the given file and releases all resources associated with it.

Parameters

pFile	The file instance previously created by Open().

          virtual bool Assimp::IOSystem::ComparePaths
          (
          const char *
          one,

          const char *
          second

          )
          	 const

virtual

Compares two paths and check whether the point to identical files.

The dummy implementation of this virtual member performs a case-insensitive comparison of the given strings. The default IO system implementation uses OS mechanisms to convert relative into absolute paths, so the result can be trusted.

Parameters

one	First file

second	Second file

Returns

true if the paths point to the same file. The file needn't be existing, however.

          bool Assimp::IOSystem::ComparePaths
          (
          const std::string &
          one,

          const std::string &
          second

          )
          	 const

inline

For backward compatibility.

See also

ComparePaths(const char*, const char*)

          AI_FORCE_INLINE bool Assimp::IOSystem::Exists
          (
          const std::string &
          pFile	)
           const

For backward compatibility.

See also

Exists(const char*)

          virtual bool Assimp::IOSystem::Exists
          (
          const char *
          pFile	)
           const

pure virtual

Tests for the existence of a file at the given path.

Parameters

pFile	Path to the file

Returns

true if there is a file with this path, else false.

          virtual char Assimp::IOSystem::getOsSeparator
          (
          	)
           const

pure virtual

Returns the system specific directory separator.

Returns

System specific directory separator

          virtual IOStream* Assimp::IOSystem::Open
          (
          const char *
          pFile,

          const char *
          pMode = "rb"

          )

pure virtual

Open a new file with a given path.

When the access to the file is finished, call Close() to release all associated resources (or the virtual dtor of the IOStream).

Parameters

pFile	Path to the file

pMode	Desired file I/O mode. Required are: "wb", "w", "wt", "rb", "r", "rt".

Returns

New IOStream interface allowing the lib to access the underlying file.

Note

When implementing this class to provide custom IO handling, you probably have to supply an own implementation of IOStream as well.

          AI_FORCE_INLINE IOStream * Assimp::IOSystem::Open
          (
          const std::string &
          pFile,

          const std::string &
          pMode = std::string("rb")

          )

inline

For backward compatibility.

See also

Open(const char*, const char*)

The documentation for this class was generated from the following file:

IOSystem.hpp

<address class="footer">
Generated on Wed Feb 18 2015 13:46:03 for Assimp by

 1.8.8
</address>


text:
package tintor.sokoban;

import static tintor.common.Util.print;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;

import lombok.Cleanup;
import lombok.val;
import tintor.common.AutoTimer;
import tintor.common.Flags;
import tintor.common.Ticker;
import tintor.common.Util;
import tintor.common.WallTimer;

public final class AStarSolver {
	public static class ExpiredError extends Error {
		private static final long serialVersionUID = 1L;
	};

	static final AutoTimer timer_solve = new AutoTimer("solve");

	final Level level;
	public final OpenSet open;
	public final ClosedSet closed;
	final Heuristic heuristic;
	final Deadlock deadlock;

	public long max_cpu_time = AutoTimer.Second * 60 * 60 * 24 * 365;
	public int trace; // 0 to turn off any tracing

	private CellVisitor visitor;
	private int[] moves;

	private int cutoff = Integer.MAX_VALUE;
	int cutoffs = 0;

	private static final Flags.Bool optimal_solution = new Flags.Bool("optimal_solution", false);
	private static final Flags.Int report_time = new Flags.Int("report_time", 20); // in seconds
	private static final Flags.Int unstuck_period = new Flags.Int("unstuck_period", 16);

	public AStarSolver(Level level, boolean enable_logging) {
		this.level = level;
		open = new OpenSet(level.alive.length, level.cells.length);
		closed = new ClosedSet(level);
		heuristic = new Heuristic(level, optimal_solution.value);
		deadlock = new Deadlock(level, enable_logging);

		visitor = new CellVisitor(level.cells.length);
		moves = new int[level.cells.length];
		deadlock.closed = closed;
		deadlock.open = open;

		agent_reachable = new boolean[level.cells.length];
		common = new boolean[level.cells.length];
		corrals = new ArrayList<byte[]>();
	}

	static boolean divisibleByPowerOf2(int a, int p) {
		return (a >> p) << p == a;
	}

	private long start_cpu_time;
	private long end_cpu_time;
	private long start_wall_time;

	public State solve() {
		prev_cpu_time = start_cpu_time = Util.threadCpuTime();
		end_cpu_time = start_cpu_time + max_cpu_time;
		start_wall_time = System.nanoTime();

		int h = heuristic.evaluate(level.start);
		if (h == Integer.MAX_VALUE)
			return null;
		level.start.set_heuristic(h);
		if (level.is_solved_fast(level.start.box))
			return level.start;

		final Ticker ticker = new Ticker(report_time.value * 1000, trace > 1);
		int explored = 0;
		explore(level.start);
		State a = null;
		StateKey recent = null;
		while (true) {
			if (ticker.tick) {
				ticker.tick = false;
				report(a);
			}

			@Cleanup val t = timer_solve.open();
			a = open.remove_min();
			if (a == null || level.is_solved_fast(a.box))
				break;
			if (!a.is_initial() && deadlock.checkFull(a))
				continue;

			explore(a);
			explored += 1;
			// TODO auto-adjust frequency here so that deadlock.unstuck is just below 35% of time
			// (or run deadlock.unstuck in a separate thread 100% of time)
			if (divisibleByPowerOf2(explored, unstuck_period.value)) {
				if (recent != null)
					deadlock.unstuck(recent, a);
				recent = a;
			}
		}
		if (trace > 1)
			report(null);
		else if (trace > 0)
			AutoTimer.report();
		return a;
	}

	final boolean[] agent_reachable;
	final boolean[] common;
	final ArrayList<byte[]> corrals;

	void explore(State a) {
		closed.add(a);

		// Find agent reachable cells
		Arrays.fill(agent_reachable, false);
		for (Cell v : visitor.init(level.cells[a.agent])) {
			agent_reachable[v.id] = true;
			for (Move m : v.moves)
				if (!visitor.visited(m.cell))
					if (!a.box(m.cell))
						visitor.add(m.cell);
		}

		// TODO optimize if there is only one box to push we can skip corral search
		byte[] pi_corral = LevelUtil.find_pi_corral(a, level, agent_reachable, corrals, common);
		if (pi_corral != null) {
			// Only push boxes on the corral boundary
			for (Cell box : level.alive)
				if (pi_corral[box.id] == 0)
					for (Move m : box.moves)
						if (m.alive && m.dist == 1 && pi_corral[m.cell.id] > 0) {
							Move n = box.rmove(m.dir);
							if (n != null && (!n.alive || !a.box(n.cell)) && agent_reachable[n.cell.id]) {
								State b = a.push(box, m.dir, n.dist, level, optimal_solution.value, /*TODO moves*/0,
										a.agent);
								process_push(b);
							}
						}
			return;
		}

		moves[a.agent] = 0; // TODO merge moves to visitor (into set)
		// TODO stop the loop early after we reach all sides of all boxes
		// TODO prioritize cells closer to untouched sides of boxes
		for (Cell agent : visitor.init(level.cells[a.agent]))
			for (Move p : agent.moves) {
				if (!a.box(p.cell.id)) {
					if (visitor.try_add(p.cell))
						moves[p.cell.id] = moves[agent.id] + p.dist;
					continue;
				}

				State b = a.push(p.cell, p.exit_dir, p.dist, level, optimal_solution.value, moves[agent.id], a.agent);
				process_push(b);
			}
	}

	private void process_push(State b) {
		if (b == null || closed.contains(b))
			return;

		int v_total_dist = open.get_total_dist(b);
		if (v_total_dist == 0 && deadlock.checkIncremental(b))
			return;

		int h = heuristic.evaluate(b);
		if (h >= cutoff) {
			cutoffs += 1;
			return;
		}
		b.set_heuristic(h);

		if (v_total_dist == 0) {
			if (level.is_solved_fast(b.box)) {
				open.remove_all_ge(optimal_solution.value ? b.total_dist : 0);
				cutoff = b.total_dist;
			}
			open.add(b);
			return;
		}
		if (b.total_dist < v_total_dist)
			open.update(v_total_dist, b);
	}

	public State[] extractPath(State end) {
		ArrayDeque<State> path = new ArrayDeque<State>();
		State start = level.transforms.normalize(level.start);
		while (true) {
			path.addFirst(end);
			StateKey p = end.prev(level);
			if (level.transforms.normalize(p).equals(start))
				break;
			end = closed.get(end.prev(level));
		}
		return path.toArray(new State[path.size()]);
	}

	private long prev_cpu_time = 0;
	private int prev_open = 0;
	private int prev_closed = 0;
	private double speed = 0;

	private void report(State a) {
		long now = System.nanoTime();
		long now_cpu = Util.threadCpuTime();
		if (now_cpu >= end_cpu_time)
			throw new ExpiredError();

		long delta_time = now_cpu - prev_cpu_time;
		int delta_closed = closed.size() - prev_closed;
		int delta_open = open.size() - prev_open;
		prev_cpu_time = now_cpu;

		speed = 1e9 * delta_closed / delta_time;

		print("%s ", level.name);
		print("cutoff:%s dead:%s live:%s ", cutoffs, heuristic.deadlocks, heuristic.non_deadlocks);
		print("time:%s ", WallTimer.format(now - start_wall_time));
		print("cpu_time:%s ", WallTimer.format(now_cpu - start_cpu_time));
		print("speed:%s ", (int) speed);
		print("branch:%.2f\n", 1 + (double) delta_open / delta_closed);
		closed.report();
		open.report();
		deadlock.report();

		prev_closed = closed.size();
		prev_open = open.size();

		AutoTimer.report();
		if (a == null)
			return;
		level.print(a);

		// Find agent reachable cells
		Arrays.fill(agent_reachable, false);
		for (Cell v : visitor.init(level.cells[a.agent])) {
			agent_reachable[v.id] = true;
			for (Move m : v.moves)
				if (!visitor.visited(m.cell))
					if (!a.box(m.cell))
						visitor.add(m.cell);
		}
		byte[] pi_corral = LevelUtil.find_pi_corral(a, level, agent_reachable, corrals, common);
		if (pi_corral != null)
			LevelUtil.print_corral(level, pi_corral, a);
	}
}


text:
import { useDebouncedValue, useMediaQuery, useMutableCallback } from '@rocket.chat/fuselage-hooks';
import React, { useMemo, useCallback, useState } from 'react';
import { Box, Table, Icon, Button } from '@rocket.chat/fuselage';

import { Th } from '../../components/GenericTable';
import { useTranslation } from '../../contexts/TranslationContext';
import { useEndpointDataExperimental } from '../../hooks/useEndpointDataExperimental';
import { useEndpointAction } from '../../hooks/useEndpointAction';
import { usePermission } from '../../contexts/AuthorizationContext';
import NotAuthorizedPage from '../../components/NotAuthorizedPage';
import AgentsPage from './AgentsPage';
import AgentEdit from './AgentEdit';
import AgentInfo from './AgentInfo';
import UserAvatar from '../../components/basic/avatar/UserAvatar';
import { useRouteParameter, useRoute } from '../../contexts/RouterContext';
import VerticalBar from '../../components/basic/VerticalBar';
import DeleteWarningModal from '../../components/DeleteWarningModal';
import { useSetModal } from '../../contexts/ModalContext';
import { useToastMessageDispatch } from '../../contexts/ToastMessagesContext';

export function RemoveAgentButton({ _id, reload }) {
	const deleteAction = useEndpointAction('DELETE', `livechat/users/agent/${ _id }`);
	const setModal = useSetModal();
	const dispatchToastMessage = useToastMessageDispatch();
	const t = useTranslation();

	const handleRemoveClick = useMutableCallback(async () => {
		const result = await deleteAction();
		if (result.success === true) {
			reload();
		}
	});

	const handleDelete = useMutableCallback((e) => {
		e.stopPropagation();
		const onDeleteAgent = async () => {
			try {
				await handleRemoveClick();
				dispatchToastMessage({ type: 'success', message: t('Agent_removed') });
			} catch (error) {
				dispatchToastMessage({ type: 'error', message: error });
			}
			setModal();
		};

		setModal(<DeleteWarningModal onDelete={onDeleteAgent} onCancel={() => setModal()}/>);
	});

	return

		<Button small ghost title={t('Remove')} onClick={handleDelete}>
			<Icon name='trash' size='x16'/>
		</Button>

;
}

export function AgentInfoActions({ reload }) {
	const t = useTranslation();
	const _id = useRouteParameter('id');
	const agentsRoute = useRoute('omnichannel-agents');
	const deleteAction = useEndpointAction('DELETE', `livechat/users/agent/${ _id }`);
	const setModal = useSetModal();
	const dispatchToastMessage = useToastMessageDispatch();

	const handleRemoveClick = useMutableCallback(async () => {
		const result = await deleteAction();
		if (result.success === true) {
			agentsRoute.push({});
			reload();
		}
	});

	const handleDelete = useMutableCallback((e) => {
		e.stopPropagation();
		const onDeleteAgent = async () => {
			try {
				await handleRemoveClick();
				dispatchToastMessage({ type: 'success', message: t('Agent_removed') });
			} catch (error) {
				dispatchToastMessage({ type: 'error', message: error });
			}
			setModal();
		};

		setModal(<DeleteWarningModal onDelete={onDeleteAgent} onCancel={() => setModal()}/>);
	});

	const handleEditClick = useMutableCallback(() => agentsRoute.push({
		context: 'edit',
		id: _id,
	}));

	return [
		<AgentInfo.Action key={t('Remove')} title={t('Remove')} label={t('Remove')} onClick={handleDelete} icon={'trash'} />,
		<AgentInfo.Action key={t('Edit')} title={t('Edit')} label={t('Edit')} onClick={handleEditClick} icon={'edit'} />,
	];
}

const sortDir = (sortDir) => (sortDir === 'asc' ? 1 : -1);

const useQuery = ({ text, itemsPerPage, current }, [column, direction]) => useMemo(() => ({
	fields: JSON.stringify({ name: 1, username: 1, emails: 1, avatarETag: 1 }),
	text,
	sort: JSON.stringify({ [column]: sortDir(direction), usernames: column === 'name' ? sortDir(direction) : undefined }),
	...itemsPerPage && { count: itemsPerPage },
	...current && { offset: current },
}), [text, itemsPerPage, current, column, direction]);

function AgentsRoute() {
	const t = useTranslation();
	const canViewAgents = usePermission('manage-livechat-agents');

	const [params, setParams] = useState({ text: '', current: 0, itemsPerPage: 25 });
	const [sort, setSort] = useState(['name', 'asc']);

	const mediaQuery = useMediaQuery('(min-width: 1024px)');

	const debouncedParams = useDebouncedValue(params, 500);
	const debouncedSort = useDebouncedValue(sort, 500);
	const query = useQuery(debouncedParams, debouncedSort);
	const agentsRoute = useRoute('omnichannel-agents');
	const context = useRouteParameter('context');
	const id = useRouteParameter('id');

	const onHeaderClick = useMutableCallback((id) => {
		const [sortBy, sortDirection] = sort;

		if (sortBy === id) {
			setSort([id, sortDirection === 'asc' ? 'desc' : 'asc']);
			return;
		}
		setSort([id, 'asc']);
	});

	const onRowClick = useMutableCallback((id) => () => agentsRoute.push({
		context: 'info',
		id,
	}));

	const { data, reload } = useEndpointDataExperimental('livechat/users/agent', query) || {};

	const header = useMemo(() => [
		{t('Name')}	,
		mediaQuery && {t('Username')}	,
		{t('Email')}	,
		{t('Livechat_status')}	,
		{t('Remove')}	,
	].filter(Boolean), [sort, onHeaderClick, t, mediaQuery]);

	const renderRow = useCallback(({ emails, _id, username, name, avatarETag, statusLivechat }) =>

			<Box display='flex' alignItems='center'>
				<UserAvatar size={mediaQuery ? 'x28' : 'x40'} title={username} username={username} etag={avatarETag}/>
				<Box display='flex' withTruncatedText mi='x8'>
					<Box display='flex' flexDirection='column' alignSelf='center' withTruncatedText>
						<Box fontScale='p2' withTruncatedText color='default'>{name || username}</Box>
						{!mediaQuery && name && <Box fontScale='p1' color='hint' withTruncatedText> {`@${ username }`} </Box>}
					</Box>
				</Box>
			</Box>

		{mediaQuery &&

			<Box fontScale='p2' withTruncatedText color='hint'>{ username }</Box> <Box mi='x4'/>

}

{emails && emails.length && emails[0].address}

{statusLivechat === 'available' ? t('Available') : t('Not_Available')}

		<RemoveAgentButton _id={_id} reload={reload}/>

, [mediaQuery, reload, onRowClick, t]);

	const EditAgentsTab = useCallback(() => {
		if (!context) {
			return '';
		}
		const handleVerticalBarCloseButtonClick = () => {
			agentsRoute.push({});
		};

		return <VerticalBar className={'contextual-bar'}>
			<VerticalBar.Header>
				{context === 'edit' && t('Edit_User')}
				{context === 'info' && t('User_Info')}
				<VerticalBar.Close onClick={handleVerticalBarCloseButtonClick} />
			</VerticalBar.Header>

			{context === 'edit' && <AgentEdit uid={id} reload={reload}/>}
			{context === 'info' && <AgentInfo uid={id}><AgentInfoActions id={id} reload={reload} /></AgentInfo>}

		</VerticalBar>;
	}, [t, context, id, agentsRoute, reload]);

	if (!canViewAgents) {
		return <NotAuthorizedPage />;
	}

	return <AgentsPage
		setParams={setParams}
		params={params}
		onHeaderClick={onHeaderClick}
		data={data} useQuery={useQuery}
		reload={reload}
		header={header}
		renderRow={renderRow}
		title={'Agents'}>
		<EditAgentsTab />
	</AgentsPage>;
}

export default AgentsRoute;


text:
menu:
  main:
    name: "5.93 (Early December 2021)"
    identifier: "5.93"
    parent: "releases599"
    weight: -593
---

> This version **does not require a new index build**

# Version 5.93.4

*Released on 20.12.2021*

In addition to the changes in 5.93.2 the class `JndiLookup.class` has been removed from Elasticsearch image to cope with the recent security vulnerabilities.

# Version 5.93.3

*Released on 16.12.2021*

## Server

### Enhancements

* writing of database transaction is avoided for read-only requests. This speeds up said requests.
* optimized search for non-existence of date fields. Search for messages is sped up by this change, for example.
* avoid adding unneeded languages in pool links to Elasticsearch mapping. This change is only done the next time the index has to be rebuilt, it is not enforced in patch release.

# Version 5.93.2

*Released on 13.12.2021*

This patch release contains an additional mitigation for the security flaw in `log4j` known as `CVE-2021-44228` (https://logging.apache.org/log4j/2.x/security.html). According to the Elasticsearch team this flaw is not exploitable anyways ( https://discuss.elastic.co/t/apache-log4j2-remote-code-execution-rce-vulnerability-cve-2021-44228-esa-2021-31/291476#elasticsearch-8 ).

# Version 5.93.1

*Released on 03.12.2021*

## Web frontend

### Fixed

* **Image Upload**:
  * fix for missing session token for EAS requests

# Version 5.93.0

*Released on 01.12.2021*

## Web frontend

### New

* **Search**:
  * `without` search for nested fields
  * sorting by *date, datetime, daterange* for nested fields
* Added deeplink for `#detail/<id>`
* New size for standard in result view: `huge`
* Upload objects modal dialog: new `RPUT` option
* **Rights Management**:
  * added optional hint for `list` parameters

### Improved

* **Search**:
  * Hide the finder when the collection manager has no content
* Do not show *'Share'* button when deeplink is disabled in the info versions of the asset

### Fixed

* **CSV Importer**:
  * fix for linked objects column id & system object id
* Show only objecttypes with file-fields in the collection hotfolder config
* Linked object filter feature bugfixes
* Small fix in the workflows confirm message

## Server

### New
* **Search**:
  * sorting by *date, datetime, daterange* for nested fields

### Improved

* **Performance**:
  * **XML Export**: Improved performance of merging of linked objects
  * Improved performance of `api/v1/objecttype`

### Fixed

* **Search**:
  * sorting by complete paths of hierarchical linked objects
  * improved handling of standard in search results: use fallbacks for languages that are not included in the search result
* **Group Editor**:
  * Update mirrored pool id of reverse-nested objects
* **Deeplink**:
  * fixed and simplified asset selection from standard (`api/v1/objects/.../file/standard/...`)
* **Datamodel Editor**:
  * Fixed corner case when a datatype of a field inside a nested tables is changed

# Checksums

Here are the checksums of our Docker images (latest version):

```ini
docker.easydb.de/pf/chrome               sha256:94e5539d1e2ca44c798f6f84227ec06d513029e2e4e2912020827fd9e37848f6
docker.easydb.de/pf/eas                  sha256:2e3ed5ac9e6d2813260679eec3dda2b4a1ce1b48bec489a9cf06f4d45d620353
docker.easydb.de/pf/elasticsearch        sha256:3e036c545e8e5c87a64d5e673bf9e1e455eb218006f3c53d518efc8867299111
docker.easydb.de/pf/fylr                 sha256:8d14e6ae1d0dd3d49756221bac0f7f3ea6bd7f810a62ffaa81a5d75faa5ef0c9
docker.easydb.de/pf/postgresql-11        sha256:6452d22df1f49980a84dd246a6683bcc5e42bba0351f80fea2f8571223349dd4
docker.easydb.de/pf/server-base          sha256:c686164eba710465b70954db1398cf997fa656a08e1264925d7d83ded4d4909e
docker.easydb.de/pf/webfrontend          sha256:82b2c93daae750e6bf4344497aa61b8bb1bbc82364bf433f804f6de2afc2cfc7
```


text:
module Azure
  class Version
    MAJOR = 0 unless defined? MAJOR
    MINOR = 7 unless defined? MINOR
    UPDATE = 0 unless defined? UPDATE
    PRE = 'pre2' unless defined? PRE

    class << self

      # @return [String]
      def to_s
        [MAJOR, MINOR, UPDATE, PRE].compact.join('.')
      end
    end
  end
end


text:
<?php
// Copyright (c) 2017  Sacarlson  sacarlson_2000@yahoo.com -->
// challenge uses dzham's method to create a challenge that
// will have to be returned to the callback signed
//{
//	"stellar": {
//		"challenge": {
//			"id":		ACCOUNT_ID,
//			"message":	MESSAGE,
//			"url":		WEBHOOK_URL
//		}
//	}
//}
// example get: https://www.funtracker.site/fed2/challenge.php?id=GCYZRAUECYEFRZS77F3P6Q57DXJCP6N2XNGXD7RMQN6XO6QFMVLW2XQ3&new_id=GAMFVORH4HI7C7SMSGTQH23EI43OQQLX3PYGP3WHFE3Y74AUTPPVEDLQ
// example returned: {"stellar":{"challenge":{"id":"GCYZRAUECYEFRZS77F3P6Q57DXJCP6N2XNGXD7RMQN6XO6QFMVLW2XQ3","message":"JLSGAIVTHP,"url":"https://www.funtracker.site/fed2/webhook.php"}}}
// then to webhook.php: webhook.php??id=GDSA...&sig=abdc&message=JLSGAIVTHP
 header('Content-type: application/json');
  //header('Vary: Origin');
  //header('Access-Control-Allow-Origin: *');
  //header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');

 include('config.php');

 // Create connection
 $conn = new mysqli($servername, $mysql_username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
    echo "bad mysql connect error: " . $conn->connect_error;
    die("Connection failed: " . $conn->connect_error);
 }

 if (isset($_GET["id"])){
    $id = mysqli_real_escape_string($conn, $_GET["id"]);
 }else{
   echo "no id provided";
   return;
 }
 if (isset($_GET["new_id"])){
    $new_id = $_GET["new_id"];
    $new_id = mysqli_real_escape_string($conn, $_GET["new_id"]);
 }else{
   //echo "no new_id provided";
   //return;
   $new_id = "";
 }

 if (isset($_GET["new_email"])){
    $new_email = $_GET["new_email"];
    $new_email = mysqli_real_escape_string($conn, $_GET["new_email"]);
 }else{
   if (isset($_GET["new_id"]) != true){
     echo ("no new_id and no new_mail error");
     die("no new_id and no new_mail error");
     return;
   }else{
     $new_email = "";
   }
 }

 $rand_string = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -10);
 $send_l1 = '{"stellar":{"challenge":{"id":"'. $id . '","message":"';
 $send_l2 = $rand_string . '","url":"' . $webhook_url .'"}}}';
 $send = $send_l1 . $send_l2;
 insert_challenge($id,$new_id,$new_email,$rand_string,"awaiting_sig");
 echo $send;

  function insert_challenge($id,$new_id,$new_email,$message,$status){
    global $conn;
    $sql = "INSERT INTO challenge (id,new_id,new_email,message,status) VALUES ('$id','$new_id','$new_email','$message','$status');";
    //echo "sql: " . $sql;
    //wrt_log("sql: " . $sql . "\n");
    $result = $conn->query($sql);

    if ($result === TRUE) {
       return true;
    } else {
       return false;
    }
  }


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Some twitter bootstrap framework examples">
        <meta name="author" content="Arthur Alvim">
        <link rel="shortcut icon" href="ico/favicon.ico">

        <title>Template for Bootstrap</title>

        <link href="css/poll-checkbox-buttons.css" rel="stylesheet">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        Toggle navigation

                    </button>
                Project name

Link

Link

Link

                            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Pool checkbox

Let's pretend this is a nice question for this poll?

                            <form role="form">

                                        <input type="checkbox" id="poll-opt-1" name="poll-option" data-size="large" value="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, dicta, minima iusto eos sunt et veniam dolore maiores veritatis magnam? Obcaecati, praesentium, veritatis voluptate ipsam vel rem sint dignissimos eligendi.

                                        <input type="checkbox" id="poll-opt-2" name="poll-option" data-size="large" value="" checked>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, dicta, minima iusto eos sunt et veniam dolore maiores veritatis magnam? Obcaecati, praesentium, veritatis voluptate ipsam vel rem sint dignissimos eligendi.

                                        <input type="checkbox" id="poll-opt-3" name="poll-option" data-size="large" value="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, dicta, minima iusto eos sunt et veniam dolore maiores veritatis magnam? Obcaecati, praesentium, veritatis voluptate ipsam vel rem sint dignissimos eligendi.

                                        <input type="checkbox" id="poll-opt-4" name="poll-option" data-size="large" value="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, dicta, minima iusto eos sunt et veniam dolore maiores veritatis magnam? Obcaecati, praesentium, veritatis voluptate ipsam vel rem sint dignissimos eligendi.

                                        <input type="checkbox" id="poll-opt-5" name="poll-option" data-size="large" value="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, dicta, minima iusto eos sunt et veniam dolore maiores veritatis magnam? Obcaecati, praesentium, veritatis voluptate ipsam vel rem sint dignissimos eligendi.

                                                <button type="submit" class="btn btn-default">See results</button>
                                                <button type="submit" class="btn btn-default">Vote</button>

                            </form>


text:
@class TSCLink;

@protocol TSCTableRowDataSource <NSObject>

@required
- (NSString *)rowTitle;
@optional
- (NSString *)rowSubtitle;
- (UIImage *)rowImage;
- (NSURL *)rowImageURL;
- (UIImage *)rowImagePlaceholder;
- (Class)tableViewCellClass;
- (UITableViewCell *)tableViewCell:(UITableViewCell *)cell;
- (CGFloat)tableViewCellHeightConstrainedToSize:(CGSize)contrainedSize;
- (CGFloat)tableViewCellHeightConstrainedToContentViewSize:(CGSize)contentViewSize tableViewSize:(CGSize)tableViewSize;
- (CGFloat)tableViewCellEstimatedHeight;
- (BOOL)canEditRow;
- (id)rowSelectionTarget;
- (SEL)rowSelectionSelector;
- (TSCLink *)rowLink;
- (NSInteger)indentationLevel;
- (UITableViewCellAccessoryType)rowAccessoryType;
- (float)rowPadding;

//The following 2 are only respected if row selection target and row selector are both not nil. Otherwise neither are displayed.
- (BOOL)shouldDisplaySelectionIndicator;
- (BOOL)shouldDisplaySelectionCell;
- (BOOL)shouldRemainSelected;
- (BOOL)shouldDisplaySeperator;

@end


text:
<!-- include footable plugin -->
<script src="<?= base_url() . 'assets/js/footable.js'; ?>" type="text/javascript"></script>
<script src="<?= base_url() . 'assets/js/footable.sortable.js'; ?>" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        $('.footable').footable();
    });
</script>

</body>
</html>


text:
from reporter.uhl_reports.i2b2.patient_mapping_tests import (
    PatientMappingDuplicatesReport,
    PatientMappingMultiplesIdsReport,
)
from reporter.uhl_reports.i2b2.patient_summary_tests import (
    PatientSummaryDuplicatesReport,
    PatientSummaryMissingData,
    PatientSummaryMissingParticipants,
)
from reporter.uhl_reports.i2b2.valid_enrolment_tests import (
    ValidEnrolmentsStudyIdDuplicates,
    ValidEnrolmentsContactMultipleRecruitments,
    RecruitedWithoutFullConsent,
    PatientSummaryMissingRecruited,
)
from reporter.emailing import (
    RECIPIENT_CARDIOMET_ADMIN as RECIPIENT_ADMIN,
)

I2B2_DB = "i2b2_app03_cardiomet_Data"

class CardiometPatientMappingDuplicatesReport(
        PatientMappingDuplicatesReport):
    def __init__(self):
        super().__init__(I2B2_DB)

class CardiometPatientMappingMultiplesIdsReport(
        PatientMappingMultiplesIdsReport):
    def __init__(self):
        super().__init__(I2B2_DB)

class CardiometPatientSummaryDuplicatesReport(
        PatientSummaryDuplicatesReport):
    def __init__(self):
        super().__init__(I2B2_DB)

class CardiometPatientSummaryMissingData(
        PatientSummaryMissingData):
    def __init__(self):
        super().__init__(
            I2B2_DB,
            [
                'CiviCrmId',
                'CiviCrmCaseId',
                'NhsNumber',
                'UhlSystemNumber',
                'StudyNumber',
                'consent_date',
                'Gender',
                'DateOfBirth',
                'Ethnicity',
            ]
        )

class CardiometPatientSummaryMissingParticipants(
        PatientSummaryMissingParticipants):
    def __init__(self):
        super().__init__(I2B2_DB)

class CardiometValidEnrolmentsStudyIdDuplicates(
        ValidEnrolmentsStudyIdDuplicates):
    def __init__(self):
        super().__init__(
            I2B2_DB,
            [RECIPIENT_ADMIN]
        )

class CardiometValidEnrolmentsContactMultipleRecruitments(
        ValidEnrolmentsContactMultipleRecruitments):
    def __init__(self):
        super().__init__(
            I2B2_DB,
            [RECIPIENT_ADMIN]
        )

class CardiometRecruitedWithoutFullConsent(
        RecruitedWithoutFullConsent):
    def __init__(self):
        super().__init__(
            I2B2_DB,
            [RECIPIENT_ADMIN]
        )

class CardiometPatientSummaryMissingRecruited(
        PatientSummaryMissingRecruited):
    def __init__(self):
        super().__init__(
            I2B2_DB,
            [RECIPIENT_ADMIN]
        )


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Template10.BootStrap;
using Template10.Navigation;
using Template10.Services.Container;
using Template10.Services.Messenger;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Template10.Core
{
    public interface IBootStrapperDependecyInjection
    {
        IContainerService CreateDependecyContainer();
        void RegisterCustomDependencies(IContainerBuilder container);
    }

    public interface IBootStrapperStartup
    {
        Task OnInitializeAsync();
        UIElement CreateRootElement(IStartArgsEx e);
        Task OnStartAsync(IStartArgsEx e, INavigationService navService, ISessionState sessionState);
    }

    public interface IBootStrapperPopup
    {
        IEnumerable<Popups.IPopupItem> Popups { get; }
    }
}


text:
<!DOCTYPE html>

        <title>test playbackRate and defaultPlaybackRate</title>

        <video controls > </video>

'playbackRate' should not change when play() is called.

'playbackRate' and 'defaultPlaybackRate' should always return the last value set.


text:
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;

namespace OpenSim.Region.CoreModules.World.Terrain.FloodBrushes
{
    public class NoiseArea : ITerrainFloodEffect
    {
        #region ITerrainFloodEffect Members

        public void FloodEffect(ITerrainChannel map, bool[,] fillArea, double strength)
        {
            int x;
            for (x = 0; x < map.Width; x++)
            {
                int y;
                for (y = 0; y < map.Height; y++)
                {
                    if (fillArea[x, y])
                    {
                        double noise = TerrainUtil.PerlinNoise2D((double) x / Constants.RegionSize, (double) y / Constants.RegionSize, 8, 1.0);

                        map[x, y] += noise * strength;
                    }
                }
            }
        }

        #endregion
    }
}


text:
@interface FDContactsViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIPanGestureRecognizer *panGesture;
@property (strong, nonatomic) IBOutlet UITapGestureRecognizer *tapGesture;

@end


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  The MIT License (MIT)
//
//  Copyright (c) 2017-present, cyder.org
//  All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in the
//  Software without restriction, including without limitation the rights to use, copy,
//  modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
//  and to permit persons to whom the Software is furnished to do so, subject to the
//  following conditions:
//
//      The above copyright notice and this permission notice shall be included in all
//      copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////////////

#include "DebugAgent.h"
#include <locale>
#include <codecvt>
#include <fstream>
#include "platform/Log.h"

namespace cyder {

    static inline int VSNPrintF(char* buffer, int size, const char* format, va_list args) {
        int n = vsnprintf(buffer, static_cast<size_t>(size), format, args);
        if (n < 0 || n >= size) {
            // If the length is zero, the assignment fails.
            if (size > 0)
                buffer[size - 1] = '\0';
            return -1;
        } else {
            return n;
        }
    }

    static inline int SNPrintF(char* buffer, int size, const char* format, ...) {
        va_list args;
        va_start(args, format);
        int result = VSNPrintF(buffer, size, format, args);
        va_end(args);
        return result;
    }

    static const char* ContentLength = "Content-Length";

    // Receive the full buffer before returning unless an error occours.
    static int ReceiveAll(Socket* conn, char* data, int len) {
        int total_received = 0;
        while (total_received < len) {
            int received = conn->receive(data + total_received, len - total_received);
            if (received == 0) {
                return total_received;
            }
            total_received += received;
        }
        return total_received;
    }

    static std::string ReceiveMessage(Socket* conn) {
        int received;

        // Read header.
        int content_length = 0;
        while (true) {
            const int kHeaderBufferSize = 80;
            char header_buffer[kHeaderBufferSize];
            int header_buffer_position = 0;
            char c = '\0';  // One character receive buffer.
            char prev_c = '\0';  // Previous character.

            // Read until CRLF.
            while (!(c == '\n' && prev_c == '\r')) {
                prev_c = c;
                received = conn->receive(&c, 1);
                if (received == 0) {
                    return "";
                }

                // Add character to header buffer.
                if (header_buffer_position < kHeaderBufferSize) {
                    header_buffer[header_buffer_position++] = c;
                }
            }

            // Check for end of header (empty header line).
            if (header_buffer_position == 2) {  // Receive buffer contains CRLF.
                break;
            }

            // Terminate header.
            ASSERT(header_buffer_position > 1);  // At least CRLF is received.
            ASSERT(header_buffer_position <= kHeaderBufferSize);
            header_buffer[header_buffer_position - 2] = '\0';

            // Split header.
            char* key = header_buffer;
            char* value = nullptr;
            for (int i = 0; header_buffer[i] != '\0'; i++) {
                if (header_buffer[i] == ':') {
                    header_buffer[i] = '\0';
                    value = header_buffer + i + 1;
                    while (*value == ' ') {
                        value++;
                    }
                    break;
                }
            }

            // Check that key is Content-Length.
            if (strcmp(key, ContentLength) == 0) {
                // Get the content length value if present and within a sensible range.
                if (value == nullptr || strlen(value) > 7) {
                    return std::string();
                }
                for (int i = 0; value[i] != '\0'; i++) {
                    // Bail out if illegal data.
                    if (value[i] < '0' || value[i] > '9') {
                        return std::string();
                    }
                    content_length = 10 * content_length + (value[i] - '0');
                }
            } else {
                // For now just print all other headers than Content-Length.
                LOG("%s: %s\n", key, value != nullptr ? value : "(no value)");
            }
        }

        // Return now if no body.
        if (content_length == 0) {
            return std::string();
        }

        // Read body.
        char buffer[content_length + 1];
        received = ReceiveAll(conn, buffer, content_length);
        if (received < content_length) {
            return std::string();
        }
        buffer[content_length] = '\0';

        return std::string(buffer);
    }

    static bool SendConnectMessage(Socket* conn,
                                   const char* embedding_host) {
        static const int BUFFER_SIZE = 80;
        char buffer[BUFFER_SIZE];  // Sending buffer.
        int ok;
        int len;

        // Send the header.
        len = SNPrintF(buffer, BUFFER_SIZE,
                       "Type: connect\r\n");
        ok = conn->send(buffer, len);
        if (!ok) return false;

        len = SNPrintF(buffer, BUFFER_SIZE,
                       "V8-Version: %s\r\n", v8::V8::GetVersion());
        ok = conn->send(buffer, len);
        if (!ok) return false;

        len = SNPrintF(buffer, BUFFER_SIZE,
                       "Protocol-Version: 1\r\n");
        ok = conn->send(buffer, len);
        if (!ok) return false;

        if (embedding_host != nullptr) {
            len = SNPrintF(buffer, BUFFER_SIZE,
                           "Embedding-Host: %s\r\n", embedding_host);
            ok = conn->send(buffer, len);
            if (!ok) return false;
        }

        len = SNPrintF(buffer, BUFFER_SIZE,
                       "%s: 0\r\n", ContentLength);
        ok = conn->send(buffer, len);
        if (!ok) return false;

        // Terminate header with empty line.
        len = SNPrintF(buffer, BUFFER_SIZE, "\r\n");
        ok = conn->send(buffer, len);
        return static_cast<bool>(ok);
    }

    DebugAgent* DebugAgent::debugAgent = nullptr;

    void DebugAgent::Enable(const std::string& hostName, int port, bool waitForConnection) {
        ASSERT(debugAgent == nullptr);
        if (debugAgent) {
            return;
        }
        auto isolate = v8::Isolate::GetCurrent();
        ASSERT(isolate != nullptr);
        debugAgent = new DebugAgent(isolate, hostName, port, waitForConnection);
    }

    void DebugAgent::Disable() {
        if (debugAgent) {
            delete debugAgent;
            debugAgent = nullptr;
        }
    }

    /**
     * Public V8 debugger API message handler function. This function just delegates to the debugger agent through it's
     * data parameter.
     */
    void DebugAgentMessageHandler(const v8::Debug::Message& message) {
        DebugAgent::debugAgent->onDebugMessage(message);
    }

    DebugAgent::DebugAgent(v8::Isolate* isolate, const std::string& hostName, int port, bool waitForConnection)
            : isolate(isolate), hostName(hostName), port(port), server(new Socket),
              client(nullptr), terminate(false) {

        // Allow this socket to reuse port even if still in TIME_WAIT.
        server->setReuseAddress(true);

        // First bind the socket to the requested port.
        bool bound = server->bind(port);
        if (!bound) {
            LOG("Failed to open socket on port %d, ", port);
            return;
        }
        v8::Debug::SetMessageHandler(isolate, DebugAgentMessageHandler);
        if (waitForConnection) {

            if (server->listen(1)) {
                // Accept the new connection.
                client = server->accept();
                if (client) {
                    v8::Debug::DebugBreak(isolate);
                    // Create and start a new session.
                    thread = std::thread(std::bind(&DebugAgent::runClientLoop, this));
                }
            }
        }
        else {
            thread = std::thread(std::bind(&DebugAgent::runClientLoop, this));
        }

    }

    DebugAgent::~DebugAgent() {
        v8::Debug::SetMessageHandler(isolate, nullptr);
        v8::Debug::CancelDebugBreak(isolate);
        terminate = true;
        delete server;
        server = nullptr;
        delete client;
        client = nullptr;
        thread.join();
    }

    void DebugAgent::runClientLoop() {
        while (true) {
            if (!client) {
                // Wait for connection
                if (server->listen(1)) {
                    // Accept the new connection.
                    client = server->accept();
                    if (!client) {
                        return;
                    }
                }
            }
            // Send the hello message.
            bool ok = SendConnectMessage(client, hostName.c_str());
            if (!ok) {
                return;
            }

            // Read data from the debugger front end.
            std::string message =
                    ReceiveMessage(client);
            if (terminate) {
                return;
            }
            const char* msg = message.c_str();
            bool closed = (message.length() == 0);

            if (closed) {
                // If we lost the connection, then simulate a disconnect msg:
                msg = "{\"seq\":1,\"type\":\"request\",\"command\":\"disconnect\"}";

            } else {
                // Check if we're getting a disconnect request:
                const char* disconnectRequestStr =
                        "\"type\":\"request\",\"command\":\"disconnect\"}";
                const char* result = strstr(msg, disconnectRequestStr);
                if (result != nullptr) {
                    closed = true;
                }
            }

            std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
            std::u16string dest = convert.from_bytes(msg);
            v8::Debug::SendCommand(isolate, reinterpret_cast<const uint16_t*>(dest.c_str()),
                                   static_cast<int>(dest.length()));
            if (closed) {
                v8::Debug::CancelDebugBreak(isolate);
                delete client;
                client = nullptr;
            }
        }
    }

    void DebugAgent::onDebugMessage(const v8::Debug::Message& message) {
        if (client == nullptr) {
            return;
        }
        v8::HandleScope scope(message.GetIsolate());
        static const int kBufferSize = 80;
        char buffer[kBufferSize];  // Sending buffer both for header and body.

        // Convert the request to UTF-8 encoding.
        v8::String::Utf8Value utf8_request(message.GetJSON());

        // Send the header.
        int len = SNPrintF(buffer, kBufferSize,
                           "Content-Length: %d\r\n", utf8_request.length());
        if (client->send(buffer, len) < len) {
            return;
        }

        // Terminate header with empty line.
        len = SNPrintF(buffer, kBufferSize, "\r\n");
        if (client->send(buffer, len) < len) {
            return;
        }

        // Send message body as UTF-8.
        len = utf8_request.length();
        client->send(*utf8_request, len);
    }

}  // namespace cyder


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Reflection;
using LightRiver.Net;

namespace LightRiver.ServiceModel
{
    public class BaseHttpService<TResult, TParameter, TParser>
        where TParameter : HttpServiceParameter
        where TParser : BaseParser<TResult, string>, new()
    {
        private string _apiUrl = null;

        public BaseHttpService(string apiUrl)
        {
            _apiUrl = apiUrl;
        }

        public virtual async Task<ParseResult<TResult>> InvokeAsync(TParameter parameter, int timeout = 60000)
        {
            // 1. 取得request字串
            var requestParameterString = PackParameterToSend(parameter);

            // 2. 發送request
            HttpClient httpClient = new HttpClient();
            string responseString = null;
            var method = (parameter == null ? HttpMethod.Get : parameter.Method);
            ParseError error = null;

            try {
                if (method == HttpMethod.Get) {
                    responseString = await GetAsync(httpClient, requestParameterString);
                }
                else if (method == HttpMethod.Post) {
                    responseString = await PostAsync(httpClient, requestParameterString);
                }
            }
            catch (HttpRequestException ex) {
                error = new ParseError(ex.GetHashCode(), ex.Message);
                return new ParseResult<TResult>(error);
            }
            catch (TaskCanceledException ex) {
                error = new ParseError(ex.GetHashCode(), ex.Message);
                return new ParseResult<TResult>(error);
            }
            catch (WebException ex) {
                error = new ParseError(ex.GetHashCode(), ex.Message);
                return new ParseResult<TResult>(error);
            }
            finally {
                httpClient.Dispose();
            }

            // 3. 解析結果
            var response = Parse(responseString);
            return response;
        }

        protected virtual string PackParameterToSend(TParameter parameter)
        {
            if (parameter == null)
                return null;
#if !NET45
            var propertyArray = parameter.GetType().GetProperties();
#else
            var propertyArray = parameter.GetType().GetRuntimeProperties();
#endif
            string parameterString = string.Empty;

            foreach (var property in propertyArray) {
                var ignoreAttribute = property.GetCustomAttribute<ServiceParameterIgnoreAttribute>();
                if (ignoreAttribute != null)
                    continue;

                var attribute = property.GetCustomAttribute<ServicePrameterPropertyAttribute>();
                string propertyName;
                string propertyValue;
                if (attribute == null) {
                    propertyName = property.Name;
                    propertyValue = string.Format("{0}", property.GetValue(parameter, null));
                }
                else {
                    propertyName = attribute.Name;

                    if (attribute.ConveterType == null) {
                        propertyValue = string.Format("{0}", property.GetValue(parameter, null));
                    }
                    else {
                        var converter = Activator.CreateInstance(attribute.ConveterType) as IServiceParameterConveter;
                        Debug.Assert(converter != null);
                        propertyValue = converter.Convert(property.GetValue(parameter, null));
                    }
                }

                parameterString += string.Format("{0}={1}&", propertyName, Uri.EscapeDataString(propertyValue));
            }

            // remove last & char
            parameterString = parameterString.Remove(parameterString.Length - 1);

            return parameterString;
        }

        protected virtual async Task<string> GetAsync(HttpClient httpClient, string requestParameterString)
        {
            string requestUrl = (string.IsNullOrEmpty(requestParameterString) ? _apiUrl : string.Format("{0}?{1}", _apiUrl, requestParameterString));
            var responseString = await httpClient.GetStringAsync(requestUrl);
            return responseString;
        }

        protected virtual async Task<string> PostAsync(HttpClient httpClient, string requestParameterString)
        {
            var requestParameterBytes = Encoding.UTF8.GetBytes(requestParameterString);
            var streamContent = new StreamContent(new MemoryStream(requestParameterBytes));
            var responseMessage = await httpClient.PostAsync(_apiUrl, streamContent);
            var responseString = await responseMessage.Content.ReadAsStringAsync();
            streamContent.Dispose();
            responseMessage.Dispose();
            return responseString;
        }

        protected virtual ParseResult<TResult> Parse(string source)
        {
            var parser = new TParser();
            return parser.Parse(source);
        }
    }
}


text:
import cgi
import QBO
import backend

backend.deleteAllBags()

from test5 import printApp
printApp()


text:
package com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * PATCH Body schema to represent list of Metadata to be updated.
 */
public class UpdateMetadataDTO {
    /**
     * List of Metadata associated with answer to be deleted.
     */
    @JsonProperty(value = "delete")
    private List<MetadataDTO> delete;

    /**
     * List of metadata associated with answer to be added.
     */
    @JsonProperty(value = "add")
    private List<MetadataDTO> add;

    /**
     * Get the delete value.
     *
     * @return the delete value
     */
    public List<MetadataDTO> delete() {
        return this.delete;
    }

    /**
     * Set the delete value.
     *
     * @param delete the delete value to set
     * @return the UpdateMetadataDTO object itself.
     */
    public UpdateMetadataDTO withDelete(List<MetadataDTO> delete) {
        this.delete = delete;
        return this;
    }

    /**
     * Get the add value.
     *
     * @return the add value
     */
    public List<MetadataDTO> add() {
        return this.add;
    }

    /**
     * Set the add value.
     *
     * @param add the add value to set
     * @return the UpdateMetadataDTO object itself.
     */
    public UpdateMetadataDTO withAdd(List<MetadataDTO> add) {
        this.add = add;
        return this;
    }

}


text:
import os, sys
from contextlib import contextmanager
import inspect, functools
from datetime import datetime
import time
import collections
import numpy as np
import six

__all__ = ['change_env',
        'map_arg',
        'get_rng', 'memoized',
        'get_dataset_path',
        'get_tqdm_kwargs',
        'execute_only_once'
        ]

@contextmanager
def change_env(name, val):
    oldval = os.environ.get(name, None)
    os.environ[name] = val
    yield
    if oldval is None:
        del os.environ[name]
    else:
        os.environ[name] = oldval

class memoized(object):
    '''Decorator. Caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned
    (not reevaluated).
    '''
    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            return self.func(*args)
        if args in self.cache:
           return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value

    def __repr__(self):
        '''Return the function's docstring.'''
        return self.func.__doc__

    def __get__(self, obj, objtype):
        '''Support instance methods.'''
        return functools.partial(self.__call__, obj)

#_GLOBAL_MEMOIZED_CACHE = dict()
#def global_memoized(func):
    #""" Make sure that the same `memoized` object is returned on different
        #calls to global_memoized(func)
    #"""
    #ret = _GLOBAL_MEMOIZED_CACHE.get(func, None)
    #if ret is None:
        #ret = _GLOBAL_MEMOIZED_CACHE[func] = memoized(func)
    #return ret

def map_arg(**maps):
    """
    Apply a mapping on certains argument before calling original function.
    maps: {key: map_func}
    """
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            argmap = inspect.getcallargs(func, *args, **kwargs)
            for k, map_func in six.iteritems(maps):
                if k in argmap:
                    argmap[k] = map_func(argmap[k])
            return func(**argmap)
        return wrapper
    return deco

def get_rng(obj=None):
    """ obj: some object to use to generate random seed"""
    seed = (id(obj) + os.getpid() +
            int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295
    return np.random.RandomState(seed)

_EXECUTE_HISTORY = set()
def execute_only_once():
    f = inspect.currentframe().f_back
    ident =  (f.f_code.co_filename, f.f_lineno)
    if ident in _EXECUTE_HISTORY:
        return False
    _EXECUTE_HISTORY.add(ident)
    return True

def get_dataset_path(*args):
    d = os.environ.get('TENSORPACK_DATASET', None)
    if d is None:
        d = os.path.abspath(os.path.join(
                    os.path.dirname(__file__), '..', 'dataflow', 'dataset'))
        if execute_only_once():
            from . import logger
            logger.info("TENSORPACK_DATASET not set, using {} for dataset.".format(d))
    assert os.path.isdir(d), d
    return os.path.join(d, *args)

def get_tqdm_kwargs(**kwargs):
    default = dict(
            smoothing=0.5,
            dynamic_ncols=True,
            ascii=True,
            bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'
            )
    f = kwargs.get('file', sys.stderr)
    if f.isatty():
        default['mininterval'] = 0.5
    else:
        default['mininterval'] = 60
    default.update(kwargs)
    return default


text:
<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activity.MergeIncludeViewActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include layout="@layout/include_view"/>

            <TextView
                android:visibility="gone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="6dp"
                android:text="include A Horizontal LinearLayout"
                android:textColor="@color/cpb_red"/>

            <include layout="@layout/include_view_1"/>

            <TextView
                android:visibility="gone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="6dp"
                android:text="include A Vertical LinearLayout"
                android:textColor="@color/cpb_red"/>

            <include layout="@layout/include_view_2"/>

        </LinearLayout>

</merge>