text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <utility>

#include "third_party/blink/renderer/modules/service_worker/fetch_event.h"

#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/mojom/timing/performance_mark_or_measure.mojom-blink.h"
#include "third_party/blink/public/mojom/timing/worker_timing_container.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_error.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_traits.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/fetch/response.h"
#include "third_party/blink/renderer/core/timing/performance_mark.h"
#include "third_party/blink/renderer/core/timing/performance_measure.h"
#include "third_party/blink/renderer/core/timing/worker_global_scope_performance.h"
#include "third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_error.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"

namespace blink {

FetchEvent* FetchEvent::Create(ScriptState* script_state,
                               const AtomicString& type,
                               const FetchEventInit* initializer) {
  return MakeGarbageCollected<FetchEvent>(script_state, type, initializer,
                                          nullptr, nullptr, mojo::NullRemote(),
                                          false);
}

Request* FetchEvent::request() const {
  return request_;
}

String FetchEvent::clientId() const {
  return client_id_;
}

String FetchEvent::resultingClientId() const {
  return resulting_client_id_;
}

bool FetchEvent::isReload() const {
  UseCounter::Count(GetExecutionContext(), WebFeature::kFetchEventIsReload);
  return is_reload_;
}

void FetchEvent::respondWith(ScriptState* script_state,
                             ScriptPromise script_promise,
                             ExceptionState& exception_state) {
  stopImmediatePropagation();
  if (observer_)
    observer_->RespondWith(script_state, script_promise, exception_state);
}

ScriptPromise FetchEvent::preloadResponse(ScriptState* script_state) {
  return preload_response_property_->Promise(script_state->World());
}

ScriptPromise FetchEvent::handled(ScriptState* script_state) {
  return handled_property_->Promise(script_state->World());
}

void FetchEvent::ResolveHandledPromise() {
  handled_property_->ResolveWithUndefined();
}

void FetchEvent::RejectHandledPromise(const String& error_message) {
  handled_property_->Reject(ServiceWorkerError::GetException(
      nullptr, mojom::blink::ServiceWorkerErrorType::kNetwork, error_message));
}

const AtomicString& FetchEvent::InterfaceName() const {
  return event_interface_names::kFetchEvent;
}

bool FetchEvent::HasPendingActivity() const {
  // Prevent V8 from garbage collecting the wrapper object while waiting for the
  // preload response. This is in order to keep the resolver of preloadResponse
  // Promise alive. Note that |preload_response_property_| can be nullptr as
  // GC can run while running the FetchEvent constructor, before the member is
  // set. If it isn't set we treat it as a pending state.
  return !preload_response_property_ ||
         preload_response_property_->GetState() ==
             PreloadResponseProperty::kPending;
}

FetchEvent::FetchEvent(ScriptState* script_state,
                       const AtomicString& type,
                       const FetchEventInit* initializer,
                       FetchRespondWithObserver* respond_with_observer,
                       WaitUntilObserver* wait_until_observer,
                       mojo::PendingRemote<mojom::blink::WorkerTimingContainer>
                           worker_timing_remote,
                       bool navigation_preload_sent)
    : ExtendableEvent(type, initializer, wait_until_observer),
      ExecutionContextClient(ExecutionContext::From(script_state)),
      observer_(respond_with_observer),
      preload_response_property_(MakeGarbageCollected<PreloadResponseProperty>(
          ExecutionContext::From(script_state))),
      handled_property_(
          MakeGarbageCollected<ScriptPromiseProperty<ToV8UndefinedGenerator,
                                                     Member<DOMException>>>(
              ExecutionContext::From(script_state))),
      worker_timing_remote_(ExecutionContext::From(script_state)) {
  worker_timing_remote_.Bind(std::move(worker_timing_remote),
                             ExecutionContext::From(script_state)
                                 ->GetTaskRunner(TaskType::kNetworking));
  if (!navigation_preload_sent)
    preload_response_property_->ResolveWithUndefined();

  client_id_ = initializer->clientId();
  resulting_client_id_ = initializer->resultingClientId();
  is_reload_ = initializer->isReload();
  request_ = initializer->request();
}

FetchEvent::~FetchEvent() = default;

void FetchEvent::OnNavigationPreloadResponse(
    ScriptState* script_state,
    std::unique_ptr<WebURLResponse> response,
    mojo::ScopedDataPipeConsumerHandle data_pipe) {
  if (!script_state->ContextIsValid())
    return;
  DCHECK(preload_response_property_);
  DCHECK(!preload_response_);
  ScriptState::Scope scope(script_state);
  preload_response_ = std::move(response);
  DataPipeBytesConsumer* bytes_consumer = nullptr;
  if (data_pipe.is_valid()) {
    DataPipeBytesConsumer::CompletionNotifier* completion_notifier = nullptr;
    bytes_consumer = MakeGarbageCollected<DataPipeBytesConsumer>(
        ExecutionContext::From(script_state)
            ->GetTaskRunner(TaskType::kNetworking),
        std::move(data_pipe), &completion_notifier);
    body_completion_notifier_ = completion_notifier;
  }
  // TODO(ricea): Verify that this response can't be aborted from JS.
  FetchResponseData* response_data =
      bytes_consumer
          ? FetchResponseData::CreateWithBuffer(BodyStreamBuffer::Create(
                script_state, bytes_consumer,
                MakeGarbageCollected<AbortSignal>(
                    ExecutionContext::From(script_state)),
                /*cached_metadata_handler=*/nullptr))
          : FetchResponseData::Create();
  Vector<KURL> url_list(1);
  url_list[0] = preload_response_->CurrentRequestUrl();

  auto response_type =
      network_utils::IsRedirectResponseCode(preload_response_->HttpStatusCode())
          ? network::mojom::FetchResponseType::kOpaqueRedirect
          : network::mojom::FetchResponseType::kBasic;

  response_data->InitFromResourceResponse(
      ExecutionContext::From(script_state), response_type, url_list,
      http_names::kGET, network::mojom::CredentialsMode::kInclude,
      preload_response_->ToResourceResponse());

  FetchResponseData* tainted_response =
      response_type == network::mojom::FetchResponseType::kOpaqueRedirect
          ? response_data->CreateOpaqueRedirectFilteredResponse()
          : response_data->CreateBasicFilteredResponse();
  preload_response_property_->Resolve(
      Response::Create(ExecutionContext::From(script_state), tainted_response));
}

void FetchEvent::OnNavigationPreloadError(
    ScriptState* script_state,
    std::unique_ptr<WebServiceWorkerError> error) {
  if (!script_state->ContextIsValid())
    return;
  if (body_completion_notifier_) {
    body_completion_notifier_->SignalError(BytesConsumer::Error());
    body_completion_notifier_ = nullptr;
  }
  DCHECK(preload_response_property_);
  if (preload_response_property_->GetState() !=
      PreloadResponseProperty::kPending) {
    return;
  }
  preload_response_property_->Reject(
      ServiceWorkerError::Take(nullptr, *error.get()));
}

void FetchEvent::OnNavigationPreloadComplete(
    WorkerGlobalScope* worker_global_scope,
    base::TimeTicks completion_time,
    int64_t encoded_data_length,
    int64_t encoded_body_length,
    int64_t decoded_body_length) {
  DCHECK(preload_response_);
  if (body_completion_notifier_) {
    body_completion_notifier_->SignalComplete();
    body_completion_notifier_ = nullptr;
  }
  std::unique_ptr<WebURLResponse> response = std::move(preload_response_);
  ResourceResponse resource_response = response->ToResourceResponse();
  resource_response.SetEncodedDataLength(encoded_data_length);
  resource_response.SetEncodedBodyLength(encoded_body_length);
  resource_response.SetDecodedBodyLength(decoded_body_length);

  ResourceLoadTiming* timing = resource_response.GetResourceLoadTiming();
  // |timing| can be null, see https://crbug.com/817691.
  base::TimeTicks request_time =
      timing ? timing->RequestTime() : base::TimeTicks();
  // According to the Resource Timing spec, the initiator type of
  // navigation preload request is "navigation".
  scoped_refptr<ResourceTimingInfo> info = ResourceTimingInfo::Create(
      "navigation", request_time, request_->GetRequestContextType(),
      request_->GetRequestDestination());
  info->SetNegativeAllowed(true);
  info->SetLoadResponseEnd(completion_time);
  info->SetInitialURL(request_->url());
  info->SetFinalResponse(resource_response);
  WorkerGlobalScopePerformance::performance(*worker_global_scope)
      ->GenerateAndAddResourceTiming(*info);
}

void FetchEvent::addPerformanceEntry(PerformanceMark* performance_mark) {
  if (worker_timing_remote_.is_bound()) {
    auto mojo_performance_mark =
        performance_mark->ToMojoPerformanceMarkOrMeasure();
    worker_timing_remote_->AddPerformanceEntry(
        std::move(mojo_performance_mark));
  }
}

void FetchEvent::addPerformanceEntry(PerformanceMeasure* performance_measure) {
  if (worker_timing_remote_.is_bound()) {
    auto mojo_performance_measure =
        performance_measure->ToMojoPerformanceMarkOrMeasure();
    worker_timing_remote_->AddPerformanceEntry(
        std::move(mojo_performance_measure));
  }
}

void FetchEvent::Trace(Visitor* visitor) const {
  visitor->Trace(observer_);
  visitor->Trace(request_);
  visitor->Trace(preload_response_property_);
  visitor->Trace(body_completion_notifier_);
  visitor->Trace(handled_property_);
  visitor->Trace(worker_timing_remote_);
  ExtendableEvent::Trace(visitor);
  ExecutionContextClient::Trace(visitor);
}

}  // namespace blink


text:
var _ = require('underscore');
var clone = require('clone');
var ShortId = require('shortid');
var util = require('util');

var Cassandra = require('oae-util/lib/cassandra');
var EmitterAPI = require('oae-emitter');
var Pubsub = require('oae-util/lib/pubsub');

var TenantNetwork = require('../model').TenantNetwork;

// A cache that holds all tenant networks keyed by tenantNetworkId
var _cacheTenantNetworks = null;

// An cache that holds all tenantAliases that belong to each tenant network, keyed by tenant network id
var _cacheTenantAliasesByTenantNetworkId = null;

// An cache that holds all network ids a tenant belongs to, keyed by tenant alias (inverse
// of _tenantAliasesByTenantNetworkId)
var _cacheTenantNetworkIdsByTenantAlias = null;

// Emit events when the cache was successfully invalidated
var emitter = module.exports = new EmitterAPI.EventEmitter();

/**
 * Initialize the Tenant Networks DAO.
 */
var init = module.exports.init = function() {
    // When an invalidate pubsub message comes in for tenant networks, clear
    // the local tenant networks caches
    Pubsub.on('oae-tenant-networks', function(message) {
        if (message === 'invalidate') {
            _invalidateLocalCache();
        }
    });
};

///////////////////////////////////
// OPERATIONS ON TENANT NETWORKS //
///////////////////////////////////

/**
 * Create a tenant network in the system.
 *
 * @param  {String}         displayName             The display name of the tenant network
 * @param  {Function}       callback                Standard callback function
 * @param  {Object}         callback.err            An error that occurred, if any
 * @param  {TenantNetwork}  callback.tenantNetwork  The tenant network that was created
 */
var createTenantNetwork = module.exports.createTenantNetwork = function(displayName, callback) {
    var tenantNetwork = new TenantNetwork(ShortId.generate(), displayName);

    // Create a query that can be used to create the tenant network
    var tenantNetworkQuery = Cassandra.constructUpsertCQL('TenantNetwork', 'id', tenantNetwork.id, _.omit(tenantNetwork, 'id'));
    if (!tenantNetworkQuery) {
        log().error({
            'err': new Error('Error creating a query to create a tenant network'),
            'tenantNetwork': tenantNetwork
        }, 'Error creating a tenant network');
        return callback({'code': 500, 'msg': 'An unexpected error occurred while creating the tenant network'});
    }

    // Execute the create query
    Cassandra.runQuery(tenantNetworkQuery.query, tenantNetworkQuery.parameters, function(err) {
        if (err) {
            return callback(err);
        }

        _invalidateAllCaches();
        return callback(null, tenantNetwork);
    });
};

/**
 * Fetch all tenant networks from the system.
 *
 * @param  {Function}   callback                    Standard callback function
 * @param  {Object}     callback.err                An error that occurred, if any
 * @param  {Object}     callback.tenantNetworks     All tenant networks in the system, keyed by their tenant network id
 */
var getAllTenantNetworks = module.exports.getAllTenantNetworks = function(callback) {
    // Verify the cache is populated
    _ensureCache(function(err) {
        if (err) {
            return callback(err);
        }

        return callback(null, clone(_cacheTenantNetworks));
    });
};

/**
 * Get a tenant network.
 *
 * @param  {String}         id                      The id of the tenant network to fetch
 * @param  {Function}       callback                Standard callback function
 * @param  {Object}         callback.err            An error that occurred, if any
 * @param  {TenantNetwork}  callback.tenantNetwork  The tenant network with the provided id
 */
var getTenantNetwork = module.exports.getTenantNetwork = function(id, callback) {
    _ensureCache(function(err) {
        if (err) {
            return callback(err);
        } else if (!_cacheTenantNetworks[id]) {
            return callback({'code': 404, 'msg': util.format('Attempted to access non-existing tenant network: "%s"', id)});
        }

        return callback(null, clone(_cacheTenantNetworks[id]));
    });
};

/**
 * Update a tenant network.
 *
 * @param  {String}         id                      The id of the tenant network being updated
 * @param  {String}         displayName             The updated display name of the tenant network
 * @param  {Function}       callback                Standard callback function
 * @param  {Object}         callback.err            An error that occurred, if any
 * @param  {TenantNetwork}  callback.tenantNetwork  The new tenant network, after update
 */
var updateTenantNetwork = module.exports.updateTenantNetwork = function(id, displayName, callback) {
    // Ensure the tenant network we're updating exists
    getTenantNetwork(id, function(err, tenantNetwork) {
        if (err) {
            return callback(err);
        }

        var query = Cassandra.constructUpsertCQL('TenantNetwork', 'id', id, {'displayName': displayName});
        Cassandra.runQuery(query.query, query.parameters, function(err) {
            if (err) {
                return callback(err);
            }

            _invalidateAllCaches();

            // Return the tenant network with the updates applied as a new object
            return callback(null, _.extend({}, tenantNetwork, {'displayName': displayName}));
        });
    });
};

/**
 * Delete a tenant network from the system.
 *
 * @param  {String}     id              The id of the tenant network to delete
 * @param  {Function}   callback        Standard callback function
 * @param  {Object}     callback.err    An error that occurred, if any
 */
var deleteTenantNetwork = module.exports.deleteTenantNetwork = function(id, callback) {
    // Ensure the tenant network exists
    getTenantNetwork(id, function(err, tenantNetwork) {
        if (err) {
            return callback(err);
        }

        // Delete the tenant network and the associations to the child tenants
        var deleteQueries = [
            {
                'query': 'DELETE FROM "TenantNetwork" WHERE "id" = ?',
                'parameters': [id]
            },
            {
                'query': 'DELETE FROM "TenantNetworkTenants" WHERE "tenantNetworkId" = ?',
                'parameters': [id]
            }
        ];

        Cassandra.runBatchQuery(deleteQueries, function(err) {
            if (err) {
                return callback(err);
            }

            _invalidateAllCaches();
            return callback();
        });
    });
};

//////////////////////////////////////////////////
// OPERATIONS ON TENANT NETWORK TENANTS ALIASES //
//////////////////////////////////////////////////

/**
 * Add the provided tenant aliases to the specified tenant network.
 *
 * @param  {String}     tenantNetworkId         The id of the tenant network to which to add the provided tenant aliases
 * @param  {String[]}   tenantAlises            The tenant aliases to add to the tenant network
 * @param  {Function}   callback                Standard callback function
 * @param  {Object}     callback.err            An error that occurred, if any
 */
var addTenantAliases = module.exports.addTenantAliases = function(tenantNetworkId, tenantAliases, callback) {
    // Ensure the tenant network exists
    getTenantNetwork(tenantNetworkId, function(err, tenantNetwork) {
        if (err) {
            return callback(err);
        } else if (_.isEmpty(tenantAliases)) {
            return callback();
        }

        // Map all tenant aliases into the queries necessary to insert them all into the tenant network tenants table
        var queries = _.map(tenantAliases, function(tenantAlias) {
            return Cassandra.constructUpsertCQL('TenantNetworkTenants', ['tenantNetworkId', 'tenantAlias'], [tenantNetworkId, tenantAlias], {'value': '1'});
        });

        Cassandra.runBatchQuery(queries, function(err) {
            if (err) {
                return callback(err);
            }

            _invalidateAllCaches();
            return callback();
        });
    });
};

/**
 * Get all tenant network ids along with all the tenant aliases that belong to the network.
 *
 * @param  {Function}   callback                                Standard callback function
 * @param  {Object}     callback.err                            An error that occurred, if any
 * @param  {Object}     callback.tenantNetworkTenantAliases     An object keyed by tenant network id whose value is the array of tenant aliases that belong to the tenant network
 */
var getAllTenantNetworkTenantAliases = module.exports.getAllTenantNetworkTenantAliases = function(callback) {
    _ensureCache(function(err) {
        if (err) {
            return callback(err);
        }

        return callback(null, clone(_cacheTenantAliasesByTenantNetworkId));
    });
};

/**
 * Remove the provided tenant aliases from the specified tenant network.
 *
 * @param  {String}     tenantNetworkId     The id of the tenant network from which to remove the provided tenant aliases
 * @param  {String[]}   tenantAlises        The tenant aliases to remove from the tenant network
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 */
var removeTenantAliases = module.exports.removeTenantAliases = function(tenantNetworkId, tenantAliases, callback) {
    // Ensure the tenant network exists
    getTenantNetwork(tenantNetworkId, function(err, tenantNetwork) {
        if (err) {
            return callback(err);
        } else if (_.isEmpty(tenantAliases)) {
            return callback();
        }

        // Create and execute the delete queries
        var queries = _.map(tenantAliases, function(tenantAlias) {
            return {
                'query': 'DELETE FROM "TenantNetworkTenants" WHERE "tenantNetworkId" = ? AND "tenantAlias" = ?',
                'parameters': [tenantNetworkId, tenantAlias]
            };
        });
        Cassandra.runBatchQuery(queries, function(err) {
            if (err) {
                return callback(err);
            }

            _invalidateAllCaches();
            return callback();
        });
    });
};

/**
 * Fetch all tenant networks from Cassandra, ignoring the cache.
 *
 * @param  {Function}   callback                    Standard callback function
 * @param  {Object}     callback.err                An error that occurred, if any
 * @param  {Object}     callback.tenantNetworks     All tenant networks in cassandra keyed by their id
 * @api private
 */
var _getAllTenantNetworksFromCassandra = function(callback) {
    Cassandra.runQuery('SELECT * FROM "TenantNetwork"', null, function(err, rows) {
        if (err) {
            return callback(err);
        }

        // Convert all rows into tenant networks
        var tenantNetworks = _.chain(rows).map(_rowToTenantNetwork).compact().indexBy('id').value();
        return callback(null, tenantNetworks);
    });
};

/**
 * Fetch tenant network tenant alias associations from Cassandra for all provided tenant network ids, ignoring the cache.
 *
 * @param  {String[]}   tenantNetworkIds                The ids of the tenant networks whose tenant alias associations to fetch
 * @param  {Object}     callback.err                    An error that occurred, if any
 * @param  {Object}     callback.tenantNetworkAliases   An object keyed by tenant network id whose values are the arrays of tenant aliases that belong to the network
 * @api private
 */
var _getAllTenantNetworkTenantAliasesFromCassandra = function(tenantNetworkIds, callback) {
    if (_.isEmpty(tenantNetworkIds)) {
        return callback(null, {});
    }

    // Fetch all of the tenant aliases associated to the specified tenant network from Cassandra
    Cassandra.runQuery('SELECT "tenantNetworkId", "tenantAlias" FROM "TenantNetworkTenants" WHERE "tenantNetworkId" IN (?)', [tenantNetworkIds], function(err, rows) {
        if (err) {
            return callback(err);
        }

        // Collect all tenant network aliases for each tenant network
        var tenantNetworkAliases = {};
        _.chain(rows).map(Cassandra.rowToHash).each(function(rowHash) {
            tenantNetworkAliases[rowHash.tenantNetworkId] = tenantNetworkAliases[rowHash.tenantNetworkId] || [];
            tenantNetworkAliases[rowHash.tenantNetworkId].push(rowHash.tenantAlias);
        });

        return callback(null, tenantNetworkAliases);
    });
};

/**
 * Convert a Cassandra row into a tenant network.
 *
 * @param  {Row}            row     A Cassandra row that was queried from TenantNetwork
 * @return {TenantNetwork}          The tenant network that is represented by the row of data
 * @api private
 */
var _rowToTenantNetwork = function(row) {
    row = Cassandra.rowToHash(row);
    if (!row.displayName) {
        return null;
    }

    return new TenantNetwork(row.id, row.displayName);
};

/**
 * Ensure the tenant networks caches are populated.
 *
 * @param  {Function}   callback        Standard callback function
 * @param  {Object}     callback.err    An error that occurred, if any
 * @api private
 */
var _ensureCache = function(callback) {
    if (_cacheTenantNetworks) {
        return callback();
    }

    // Load all known tenant networks from Cassandra
    _getAllTenantNetworksFromCassandra(function(err, tenantNetworks) {
        if (err) {
            return callback(err);
        }

        // Load all known tenant network tenant associations from Cassandra
        _getAllTenantNetworkTenantAliasesFromCassandra(_.keys(tenantNetworks), function(err, tenantNetworkTenantAliases) {
            if (err) {
                return callback(err);
            }

            // Reset the caches
            _cacheTenantNetworks = tenantNetworks;
            _cacheTenantAliasesByTenantNetworkId = tenantNetworkTenantAliases;
            _cacheTenantNetworkIdsByTenantAlias = {};

            // Build the inverted TenantAlias->TenantNetworkIds cache
            _.each(_cacheTenantAliasesByTenantNetworkId, function(tenantAliases, tenantNetworkId) {
                _.each(tenantAliases, function(tenantAlias) {
                    _cacheTenantNetworkIdsByTenantAlias[tenantAlias] = _cacheTenantNetworkIdsByTenantAlias[tenantAlias] || [];
                    _cacheTenantNetworkIdsByTenantAlias[tenantAlias].push(tenantNetworkId);
                });
            });

            emitter.emit('revalidate');
            return callback();
        });
    });
};

/**
 * Invalidate all tenant network caches of all nodes in the cluster. The cache of this node will be cleared
 * by the end of this invocation.
 *
 * @api private
 */
var _invalidateAllCaches = function() {
    _invalidateLocalCache();
    Pubsub.publish('oae-tenant-networks', 'invalidate');
};

/**
 * Invalidate all local tenant network caches so that they may be repopulated at the next request.
 *
 * @api private
 */
var _invalidateLocalCache = function() {
    _cacheTenantNetworks = null;
    _cacheTenantAliasesByTenantNetworkId = null;
    _cacheTenantNetworkIdsByTenantAlias = null;
    emitter.emit('invalidate');
};

redpajama_set_name: RedPajamaGithub


text:
class WordPartPolicy < ApplicationPolicy
end


text:
import java.net.InetSocketAddress

import cn.changhong.web.util.Parser.{StringToChannelBuffer, ObjectToJsonStringToChannelBuffer}
import com.twitter.finagle.{Service, SimpleFilter, Http}
import com.twitter.finagle.builder.ServerBuilder
import com.twitter.util.{Await, Future}
import org.jboss.netty.handler.codec.http._

//import java.net.InetSocketAddress
//import java.util.Date
//
//import cn.changhong.web.router.AuthAopAction
//import cn.changhong.web.util.{NoAuthException, Parser, RestRequest}
//import com.twitter.finagle.builder.ServerBuilder
//import com.twitter.finagle.http.{Request, RichHttp, Response, Http}
//import com.twitter.finagle.redis.util.{StringToChannelBuffer, RedisCluster}
//import com.twitter.finagle.{RedisClient, Service}
//import com.twitter.util.{Await, Future}
//import org.jboss.netty.handler.codec.http._
//import org.slf4j.LoggerFactory
//import redis.clients.jedis.{JedisPool, JedisPoolConfig, Jedis}
//
//
///**
// * Created by yangguo on 14-12-8.
// */
//trait RestAopAction{
//  def aopAction(request:RestRequest): HttpResponse
//}
//trait LogAopService extends RestAopAction{
//  val log=LoggerFactory.getLogger(getClass.getName)
//  abstract override def aopAction(request:RestRequest):HttpResponse={
//    println("start log....")
//    val res=super.aopAction(request)
//    request.logBean.et=new Date().getTime-request.logBean.st
//    log.info(createLog(request))
//    res
//  }
//  def createLog(request:RestRequest): String ={
//    Parser.ObjectToJsonString(request.logBean)
//  }
//}
//trait AuthRequestRouterProvider extends Service[RestRequest,HttpResponse] with RestAopAction{
//  override def apply(request: RestRequest): Future[HttpResponse] = {
//    Future.value{
//      aopAction(request)
//    }
//  }
//
//}
//
//trait AuthAopAction extends RestAopAction{
//  abstract override def aopAction(request:RestRequest):HttpResponse={
//    println("start auth....")
//    throw new NoAuthException(request.logBean.path,"No Permission")
//    null
//  }
//}
//class TestAction extends AuthRequestRouterProvider with RestAopAction{
//  override def aopAction(request: RestRequest): HttpResponse = {
//    println("start bus...")
//    val  res=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK)
//    request.logBean.et=new Date().getTime
//    println("end bus...")
//    res
//  }
//}
//object TestAction extends TestAction with AuthAopAction with LogAopService
//import com.twitter.finagle.redis.Client
//
//object Test{
//  import scala.collection.JavaConverters._
//  def main(args:Array[String]): Unit ={
//    val service=new Service[Request, Response] {
//        override def apply(request: Request): Future[Response] = {
//          request.headers().names().asScala.foreach(key =>
//            println(key + "->" + request.headers().get(key))
//          )
//          request.getParamNames().asScala.foreach{key=>
//            println(key + "->" + request.getParam(key))
//          }
//          println(request.getHeader("Remote_Addr"))
//          println(request.getHeader("HTTP_X_FORWARDED_FOR"))
//          println(request.remoteHost+","+request.remotePort)
//          Future.value(Response())
//        }
//      }
//    ServerBuilder().codec(RichHttp[Request](Http()))
//    .bindTo(new InetSocketAddress(10000))
//    .name("server")
//    .build (service)
//    (1 to 100000) foreach{p=>
//      Thread.sleep(10)
//     val client= com.twitter.finagle.Http.newService("10.9.52.99:10001")
//      client.apply(new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"/dsadsads")) onSuccess(s=>
//        println("successed"+p)) onFailure(e=>println("failed"+p))
//    }
//  }
//  def action: Unit ={
////    val testAction=new TestAction with LogAopService
////    val testAction1=new TestAction with AuthAopAction with LogAopService //需要log 需要Auth
////    TestAction(RestRequest(new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"/auth")))
//  }
//  def Jedis_Test(): Unit ={
////    val jedis=new Jedis("localhost",6379)
////    println(jedis.set("redis","myredis"))
////    println(jedis.set("redis","value","XX","PX",1000))
////    println(jedis.get("redis"))
//    val config=new JedisPoolConfig()
//    config.setMaxTotal(50)
//    config.setMaxIdle(5)
//    config.setMaxWaitMillis(1000*10)
//    val pool=new JedisPool(config,"localhost",6379)
////    pool.getResource.set()
//  }
//  def Finagle_Redis(): Unit ={
//   RedisCluster.start(1)
//   val client=Client(RedisCluster.hostAddresses())
//    client.set(StringToChannelBuffer("foo"),StringToChannelBuffer("bar"))
//    val getResult=Await.result(client.get(StringToChannelBuffer("foo")))
//    getResult match{
//      case Some(n)=>println("Got Result:"+new String(n.array))
//    }
//  }
//}
object Test {
  def main(args:Array[String]): Unit ={
    client
  }
  def client: Unit ={
    val client=Http.newService("www.chphone.cn:8081")
    val request=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"/")
    request.headers().set("Client_Id","client_id")
    val response=client(request)
    response onSuccess(re=>println(new String(re.getContent.array()))) onFailure(ex=>ex.printStackTrace())
    Thread.sleep(1000)
    Await.ready(response)
  }

  def server: Unit ={
    val service=ExceptionFilterService andThen new Service[HttpRequest,HttpResponse] {
      override def apply(request: HttpRequest): Future[HttpResponse] = {
        val response=new org.jboss.netty.handler.codec.http.DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK)
        response.setContent(StringToChannelBuffer("proxy"))
        Future.value(response)
      }
    }
    val serviceProxy = ExceptionFilterService andThen Http.newService("localhost:" + 10011)
    println("....")
    startServer(10011,service)
    startServer(10012,serviceProxy)
    Thread.sleep(100000)

  }
  def startServer(port:Int,service:Service[HttpRequest,HttpResponse]): Unit ={
    new Thread(new Runnable {
      override def run(): Unit = {
        ServerBuilder()
          .codec(com.twitter.finagle.http.Http())
          .name("proxy")
          .bindTo(new InetSocketAddress(port))
          .build(service)
      }
    }).start()
  }
}
object ExceptionFilterService extends SimpleFilter[HttpRequest,HttpResponse]{
  override def apply(request: HttpRequest, service: Service[HttpRequest, HttpResponse]): Future[HttpResponse] = service(request) handle { case ex =>
    println(ex.getLocalizedMessage+"sdsadsadsads")
    new org.jboss.netty.handler.codec.http.DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK)
  }
}


text:
    cd vendor/engines/alerts
    gem build refinerycms-alerts.gempspec
    gem install refinerycms-alerts.gem

    # Sign up for a http://rubygems.org/ account and publish the gem
    gem push refinerycms-alerts.gem


text:
package org.opencb.opencga.app.cli.main.parent;

import com.beust.jcommander.JCommander;
import org.apache.commons.lang3.StringUtils;
import org.opencb.commons.utils.CommandLineUtils;
import org.opencb.commons.utils.PrintUtils;
import org.opencb.opencga.app.cli.CliOptionsParser;
import org.opencb.opencga.app.cli.GeneralCliOptions;
import org.opencb.opencga.app.cli.admin.AdminCliOptionsParser;
import org.opencb.opencga.app.cli.main.OpencgaMain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class ParentCliOptionsParser extends CliOptionsParser {

    private static final Logger logger = LoggerFactory.getLogger(ParentCliOptionsParser.class);
    protected final GeneralCliOptions.CommonCommandOptions commonCommandOptions;

    public ParentCliOptionsParser() {
        commonCommandOptions = new GeneralCliOptions.CommonCommandOptions();
    }

    @Override
    public boolean isHelp() {
        String parsedCommand = jCommander.getParsedCommand();
        if (parsedCommand != null) {
            JCommander jCommander2 = jCommander.getCommands().get(parsedCommand);
            List<Object> objects = jCommander2.getObjects();
            if (!objects.isEmpty() && objects.get(0) instanceof AdminCliOptionsParser.AdminCommonCommandOptions) {
                return ((AdminCliOptionsParser.AdminCommonCommandOptions) objects.get(0)).commonOptions.help;
            }
        }
        return commonCommandOptions.help;
    }

    public boolean isValid(String parsedCommand) {
        if (StringUtils.isEmpty(parsedCommand)) {
            // 1. Check if a command has been provided
            logger.debug("IS EMPTY COMMAND " + parsedCommand);
            return false;
        } else {
            // 2. Check if a subcommand has been provided
            String parsedSubCommand = getSubCommand();
            logger.debug("PARSED SUBCOMMAND " + parsedCommand);
            return !StringUtils.isEmpty(parsedSubCommand);
        }
    }

    public void printUsage(String[] args) {
        parse(args);
        printUsage();
    }

    @Override
    public void printUsage() {
        String parsedCommand = getCommand();
        if (parsedCommand.isEmpty()) {
            System.err.println();
            PrintUtils.println(org.opencb.opencga.app.cli.main.utils.CommandLineUtils.getHelpVersionString());
            System.err.println();
            if (OpencgaMain.isShellMode()) {
                PrintUtils.println(PrintUtils.getKeyValueAsFormattedString("Usage:", "       " + getPrefix() + " <command> [options] [-h|--help] [--version]"));
            } else {
                PrintUtils.println(PrintUtils.getKeyValueAsFormattedString("Usage:", "       " + getPrefix() + "[-h|--help] [--shell] [--host] [--version] <command> [options]"));
            }
            System.err.println();
            printMainUsage();
            System.err.println();
        } else {
            String parsedSubCommand = getSubCommand();
            if (parsedSubCommand.isEmpty()) {
                System.err.println();
                PrintUtils.println(PrintUtils.getKeyValueAsFormattedString("Usage:", "   " + getPrefix() + parsedCommand + " <subcommand> [options]"));
                System.err.println();
                PrintUtils.println(PrintUtils.format("Subcommands:", PrintUtils.Color.GREEN));
                printCommands(jCommander.getCommands().get(parsedCommand));
                System.err.println();
            } else {
                System.err.println();
                PrintUtils.println(PrintUtils.getKeyValueAsFormattedString("Usage:", "   " + getPrefix() + parsedCommand + " " + parsedSubCommand + " [options]"));
                System.err.println();
                PrintUtils.println(PrintUtils.format("Options:", PrintUtils.Color.GREEN));
                CommandLineUtils.printCommandUsage(jCommander.getCommands().get(parsedCommand).getCommands().get(parsedSubCommand));
                System.err.println();
            }
        }
    }

    private String getPrefix() {
        if (OpencgaMain.isShellMode()) {
            return "";
        }
        return "opencga.sh ";
    }

    @Override
    protected void printMainUsage() {
        Set<String> analysisCommands = new HashSet<>(Arrays.asList("alignments", "variant", "clinical"));
        Set<String> operationsCommands = new HashSet<>(Collections.singletonList("operations"));
        Map<String, String> opencgaCommands = getOpencgaCommands();

        String[] catalog = {"users", "projects", "studies", "files", "jobs", "individuals", "families", "panels", "samples", "cohorts", "meta"};
        PrintUtils.println(PrintUtils.format("Catalog commands:", PrintUtils.Color.GREEN));
        for (int i = 0; i < catalog.length; i++) {
            for (String command : jCommander.getCommands().keySet()) {
                if (command.equals(catalog[i])) {
                    PrintUtils.printCommandHelpFormattedString(command, jCommander.getCommandDescription(command));
                }
            }
        }
        System.err.println();
        PrintUtils.println(PrintUtils.format("Analysis commands:", PrintUtils.Color.GREEN));
        String[] analysis = {"alignments", "variant", "clinical"};
        for (int i = 0; i < analysis.length; i++) {
            for (String command : jCommander.getCommands().keySet()) {
                if (command.equals(analysis[i])) {
                    PrintUtils.printCommandHelpFormattedString(command, jCommander.getCommandDescription(command));
                }
            }
        }

        System.err.println();
        PrintUtils.println(PrintUtils.format("Operation commands:", PrintUtils.Color.GREEN));
        String[] operations = {"operations"};
        for (int i = 0; i < operations.length; i++) {
            for (String command : jCommander.getCommands().keySet()) {
                if (command.equals(operations[i])) {
                    PrintUtils.printCommandHelpFormattedString(command, jCommander.getCommandDescription(command));
                }
            }
        }
        System.err.println();
        PrintUtils.println(PrintUtils.format("Administrator commands:", PrintUtils.Color.GREEN));
        String[] superuser = {"admin"};
        for (int i = 0; i < superuser.length; i++) {
            for (String command : jCommander.getCommands().keySet()) {
                if (command.equals(superuser[i])) {
                    PrintUtils.printCommandHelpFormattedString(command, jCommander.getCommandDescription(command));
                }
            }
        }

        System.err.println();
        if (!OpencgaMain.isShellMode()) {
            PrintUtils.println(PrintUtils.format("Opencga options:", PrintUtils.Color.GREEN));
        } else {
            PrintUtils.println(PrintUtils.format("Opencga commands:", PrintUtils.Color.GREEN));
        }
        for (Map.Entry entry : opencgaCommands.entrySet()) {
            PrintUtils.printCommandHelpFormattedString(entry.getKey().toString(), entry.getValue().toString());
        }
    }

    private Map<String, String> getOpencgaCommands() {
        Map<String, String> h = new HashMap<>();
        h.put("login [user]", "Authenticates new user in OpenCGA");
        h.put("logout", "Logouts the current user from OpenCGA");
        if (!OpencgaMain.isShellMode()) {
            h.put("--host", "Set the host server to query data");
            h.put("--shell", "Interactive mode opencga shell");
        } else {
            h.put("use study <name>", "Sets the study to be used in the following commands");
            h.put("list studies", "Print available studies for user");
            h.put("exit", "Closes the opencga shell");
        }
        return h;
    }
}


text:
namespace BlogSystem.Web.ViewModels.Pages
{
    using System;

    using BlogSystem.Data.Models;
    using BlogSystem.Services.Mapping;

    public class PageViewModel : IMapFrom<Page>
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        public DateTime LastModified { get; set; }
    }
}


text:
    <title></title>

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

Custom transclude demo

      scope.name = {{ name }}

this is original content ({{ name }})

this is original content ({{ name }})


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Dissnes Bot. 17: 287 (1972)

#### Original name
Aspicilia melinodes Körb.

### Remarks
null


text:
namespace RelationshipGraph
{
  enum class AgentType : unsigned char
  {
    SINGLE,
    GROUP
  };
}

#endif


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Api\V2010;

use Twilio\Options;
use Twilio\Values;

abstract class AccountOptions {
    /**
     * @param string $friendlyName A human readable description of the account
     * @return CreateAccountOptions Options builder
     */
    public static function create($friendlyName = Values::NONE) {
        return new CreateAccountOptions($friendlyName);
    }

    /**
     * @param string $friendlyName FriendlyName to filter on
     * @param string $status Status to filter on
     * @return ReadAccountOptions Options builder
     */
    public static function read($friendlyName = Values::NONE, $status = Values::NONE) {
        return new ReadAccountOptions($friendlyName, $status);
    }

    /**
     * @param string $friendlyName FriendlyName to update
     * @param string $status Status to update the Account with
     * @return UpdateAccountOptions Options builder
     */
    public static function update($friendlyName = Values::NONE, $status = Values::NONE) {
        return new UpdateAccountOptions($friendlyName, $status);
    }
}

class CreateAccountOptions extends Options {
    /**
     * @param string $friendlyName A human readable description of the account
     */
    public function __construct($friendlyName = Values::NONE) {
        $this->options['friendlyName'] = $friendlyName;
    }

    /**
     * A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}`
     *
     * @param string $friendlyName A human readable description of the account
     * @return $this Fluent Builder
     */
    public function setFriendlyName($friendlyName) {
        $this->options['friendlyName'] = $friendlyName;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Api.V2010.CreateAccountOptions ' . implode(' ', $options) . ']';
    }
}

class ReadAccountOptions extends Options {
    /**
     * @param string $friendlyName FriendlyName to filter on
     * @param string $status Status to filter on
     */
    public function __construct($friendlyName = Values::NONE, $status = Values::NONE) {
        $this->options['friendlyName'] = $friendlyName;
        $this->options['status'] = $status;
    }

    /**
     * Filter accounts where the friendly name exactly matches the desired FriendlyName
     *
     * @param string $friendlyName FriendlyName to filter on
     * @return $this Fluent Builder
     */
    public function setFriendlyName($friendlyName) {
        $this->options['friendlyName'] = $friendlyName;
        return $this;
    }

    /**
     * Only show accounts with the given Status
     *
     * @param string $status Status to filter on
     * @return $this Fluent Builder
     */
    public function setStatus($status) {
        $this->options['status'] = $status;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Api.V2010.ReadAccountOptions ' . implode(' ', $options) . ']';
    }
}

class UpdateAccountOptions extends Options {
    /**
     * @param string $friendlyName FriendlyName to update
     * @param string $status Status to update the Account with
     */
    public function __construct($friendlyName = Values::NONE, $status = Values::NONE) {
        $this->options['friendlyName'] = $friendlyName;
        $this->options['status'] = $status;
    }

    /**
     * Update the human-readable description of this Account
     *
     * @param string $friendlyName FriendlyName to update
     * @return $this Fluent Builder
     */
    public function setFriendlyName($friendlyName) {
        $this->options['friendlyName'] = $friendlyName;
        return $this;
    }

    /**
     * Alter the status of this account with a given Status
     *
     * @param string $status Status to update the Account with
     * @return $this Fluent Builder
     */
    public function setStatus($status) {
        $this->options['status'] = $status;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Api.V2010.UpdateAccountOptions ' . implode(' ', $options) . ']';
    }
}


text:
include RundeckCookbook::Helpers

property :acl_policies, Hash, default: {}
property :admin_password, String, default: 'admin', sensitive: true
property :basedir, String, default: '/var/lib/rundeck'
property :configdir, String, default: '/etc/rundeck'
property :custom_framework_config, Hash, default: {}
property :custom_jvm_properties, String
property :custom_rundeck_config, Hash, default: {}
property :datadir, String, default: '/var/rundeck'
property :default_role, String, default: 'user'
property :exec_logdir, String, default: lazy { "#{basedir}/logs" }
property :extra_wait, Integer, default: 120
property :framework_properties, Hash, default: {}
property :grails_port, Integer, default: lazy { use_ssl ? 443 : 80 }
property :grails_server_url, String, default: lazy { "#{use_inbuilt_ssl ? 'https' : 'http'}://#{node['hostname']}.#{node['domain']}" }
property :hostname, String, default: "#{node['hostname']}.#{node['domain']}"
property :jaas, String, default: 'internal'
property :jvm_mem, String, default: ' -Xmx1024m -Xms256m'
property :rundeckgroup, String,
         default: 'rundeck' # 'The user account that rundeck will operate as'
property :rundeckuser, String,
         default: 'rundeck' # 'The group that rundeck will operate as'
property :ldap_provider, String
property :ldap_binddn, String
property :ldap_bindpwd, String
property :ldap_authenticationmethod, String
property :ldap_debug, [true, false], default: false
property :ldap_forcebindinglogin, String
property :ldap_userbasedn, String
property :ldap_userrdnattribute, String
property :ldap_useridattribute, String
property :ldap_userpasswordattribute, String
property :ldap_userobjectclass, String
property :ldap_rolebasedn, String
property :ldap_rolenameattribute, String
property :ldap_rolememberattribute, String
property :ldap_roleobjectclass, String
property :ldap_roleprefix, String
property :ldap_cachedurationmillis, String
property :ldap_reportstatistics, String
property :log_level, %w(ERR WARN INFO VERBOSE DEBUG), default: 'INFO'
property :mail_email, String
property :mail_enable, [true, false], default: false
property :mail_host, String
property :mail_password, String, sensitive: true
property :mail_port, Integer, default: 25
property :mail_user, String
property :port, Integer, default: 4440
property :private_key, [nil, String], default: nil, sensitive: true
property :quartz_threadPoolCount, Integer, default: 10
property :rdbms_dbname, String
property :rdbms_dialect, String
property :rdbms_enable, [true, false], default: false
property :rdbms_location, String
property :rdbms_password, String, sensitive: true
property :rdbms_port, Integer
property :rdbms_type, %w(mysql oracle)
property :rdbms_user, String
property :restart_on_config_change, [true, false], default: false
property :retry_delay, Integer, default: 5
property :retries, Integer, default: 60
property :rss_enabled, [true, false], default: false
property :rundeckgroup, String, default: 'rundeck'
property :rundeckuser, String, default: 'rundeck'
property :rundeck_users, Hash, default: {}, sensitive: true
property :security_roles, Hash, default: {}
property :session_timeout, Integer, default: 30
property :ssl_port, Integer, default: 4443
property :setup_repo, [true, false], default: true
property :tempdir, String, default: '/tmp/rundeck'
property :tokens_file, String
property :truststore_type, String, default: 'jks'
property :use_inbuilt_ssl, [true, false], default: false
property :use_ssl, [true, false], default: false
property :uuid, String, default: lazy { generateuuid }
property :version, String, default: '3.0.8.20181029-1.201810292220'
property :webcontext, String, default: '/'

action :install do
  rundeck_dependencies 'default'

  rundeck_repository 'public' do
    only_if { new_resource.setup_repo }
  end

  package 'rundeck' do
    version new_resource.version
    action :install
  end

  case node['platform_family']
  when 'rhel'
    yum_package 'which'

    yum_package 'rundeck-config' do
      version new_resource.version
      allow_downgrade true
      action :install
    end

  else
    package 'uuid-runtime'
    package 'openssh-client'
  end

  directory new_resource.basedir do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    recursive true
  end

  directory new_resource.exec_logdir do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    recursive true
  end

  directory "#{new_resource.basedir}/projects" do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    recursive true
  end

  directory "#{new_resource.basedir}/.chef" do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    recursive true
    mode '0700'
  end

  directory "#{new_resource.basedir}/.ssh" do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    recursive true
    mode '0700'
  end

  file "#{new_resource.basedir}/.ssh/id_rsa" do
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    mode '0600'
    backup false
    content new_resource.private_key
    sensitive true
    not_if { new_resource.private_key.nil? }
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
  end

  template "#{new_resource.configdir}/profile" do
    cookbook 'rundeck'
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    source 'profile.erb'
    variables(
      basedir: new_resource.basedir,
      configdir: new_resource.configdir,
      tempdir: new_resource.tempdir,
      exec_logdir: new_resource.exec_logdir,
      jvm_mem: new_resource.jvm_mem,
      truststore_type: new_resource.truststore_type,
      port: new_resource.port,
      ssl_port: new_resource.ssl_port,
      jaas: new_resource.jaas,
      webcontext: new_resource.webcontext,
      custom_jvm_properties: new_resource.custom_jvm_properties,
      use_inbuilt_ssl: new_resource.use_inbuilt_ssl
    )
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
  end

  template "#{new_resource.configdir}/rundeck-config.properties" do
    cookbook 'rundeck'
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    source 'rundeck-config.properties.erb'
    sensitive true
    variables(
      configdir: new_resource.configdir,
      custom_rundeck_config: new_resource.custom_rundeck_config,
      grails_port: new_resource.grails_port,
      grails_server_url: new_resource.grails_server_url,
      log_level: new_resource.log_level,
      mail_enable: new_resource.mail_enable,
      mail_email: new_resource.mail_email,
      mail_host: new_resource.mail_host,
      mail_password: new_resource.mail_password,
      mail_port: new_resource.mail_port,
      mail_user: new_resource.mail_user,
      quartz_threadPoolCount: new_resource.quartz_threadPoolCount,
      rdbms_dbname: new_resource.rdbms_dbname,
      rdbms_dialect: new_resource.rdbms_dialect,
      rdbms_enable: new_resource.rdbms_enable,
      rdbms_location: new_resource.rdbms_location,
      rdbms_password: new_resource.rdbms_password,
      rdbms_port: new_resource.rdbms_port,
      rdbms_type: new_resource.rdbms_type,
      rdbms_user: new_resource.rdbms_user,
      rss_enabled: new_resource.rss_enabled
    )
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
  end

  template '/etc/init/rundeckd.conf' do
    cookbook 'rundeck'
    owner 'root'
    group 'root'
    source 'rundeck-upstart.conf.erb'
    variables(
      configdir: new_resource.configdir
    )
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
    only_if { node['platform_family'] == 'debian' }
  end

  template "#{new_resource.configdir}/framework.properties" do
    cookbook 'rundeck'
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    source 'framework.properties.erb'
    sensitive true
    variables(
      admin_password: new_resource.admin_password,
      basedir: new_resource.basedir,
      configdir: new_resource.configdir,
      custom_framework_config: new_resource.custom_framework_config,
      datadir: new_resource.datadir,
      exec_logdir: new_resource.exec_logdir,
      framework_properties: new_resource.framework_properties.to_java_properties_hash,
      hostname: new_resource.hostname,
      mail_email: new_resource.mail_email,
      mail_host: new_resource.mail_host,
      mail_password: new_resource.mail_password,
      mail_port: new_resource.mail_port,
      mail_user: new_resource.mail_user,
      port: new_resource.port,
      ssl_port: new_resource.ssl_port,
      tokens_file: new_resource.tokens_file,
      use_inbuilt_ssl: new_resource.use_inbuilt_ssl,
      user: new_resource.rundeckuser,
      uuid: new_resource.uuid
    )
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
  end

  template "#{new_resource.configdir}/realm.properties" do
    cookbook 'rundeck'
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    sensitive true
    source 'realm.properties.erb'
    variables(
      admin_password: new_resource.admin_password,
      rundeck_users: new_resource.rundeck_users
    )
  end

  template "#{new_resource.configdir}/jaas-activedirectory.conf" do
    cookbook 'rundeck'
    owner new_resource.rundeckuser
    group new_resource.rundeckgroup
    source 'jaas-activedirectory.conf.erb'
    variables(
      configdir: new_resource.configdir,
      ldap_debug: new_resource.ldap_debug,
      ldap_provider: new_resource.ldap_provider,
      ldap_binddn: new_resource.ldap_binddn,
      ldap_bindpwd: new_resource.ldap_bindpwd,
      ldap_authenticationmethod: new_resource.ldap_authenticationmethod,
      ldap_forcebindinglogin: new_resource.ldap_forcebindinglogin,
      ldap_userbasedn: new_resource.ldap_userbasedn,
      ldap_userrdnattribute: new_resource.ldap_userrdnattribute,
      ldap_useridattribute: new_resource.ldap_useridattribute,
      ldap_userpasswordattribute: new_resource.ldap_userpasswordattribute,
      ldap_userobjectclass: new_resource.ldap_userobjectclass,
      ldap_rolebasedn: new_resource.ldap_rolebasedn,
      ldap_rolenameattribute: new_resource.ldap_rolenameattribute,
      ldap_rolememberattribute: new_resource.ldap_rolememberattribute,
      ldap_roleobjectclass: new_resource.ldap_roleobjectclass,
      ldap_roleprefix: new_resource.ldap_roleprefix,
      ldap_cachedurationmillis: new_resource.ldap_cachedurationmillis,
      ldap_reportstatistics: new_resource.ldap_reportstatistics,
      rundeck_version: new_resource.version
    )
    notifies (new_resource.restart_on_config_change ? :restart : :nothing), 'service[rundeckd]', :delayed
  end

  if new_resource.acl_policies
    new_resource.acl_policies.each do |name, policy|
      policy_content = ''

      policy.each do |policysection|
        policy_content += "\n" + YAML.dump(policysection.to_hash).tr('"', "'")
      end

      file "#{new_resource.configdir}/#{name}.aclpolicy" do
        content policy_content
        owner new_resource.rundeckuser
        group new_resource.rundeckgroup
        action :create
      end
    end
  end

  service 'rundeckd' do
    case node['platform']
    when 'ubuntu'
      if node['platform_version'].to_f >= 16.04
        provider Chef::Provider::Service::Systemd
      else
        provider Chef::Provider::Service::Upstart
      end
    end
    action [:start, :enable]
    notifies :run, 'ruby_block[wait for rundeckd startup]', :immediately
  end

  ruby_block 'wait for rundeckd startup' do
    action :nothing
    block do
      # test connection to the authentication endpoint
      require 'uri'
      require 'net/http'
      uri = URI("#{new_resource.grails_server_url}:#{new_resource.grails_port}")
      uri.path = ::File.join(new_resource.webcontext, '/j_security_check')
      res = Net::HTTP.get_response(uri)
      unless (200..399).cover?(res.code.to_i)
        Chef::Log.warn { "#{res.uri} not responding healthy. #{res.code}" }
        Chef::Log.debug { res.body }
        raise
      end
      Chef::Log.info { 'wait a little longer for Rundeck startup' }
      sleep new_resource.extra_wait
    end
    retries new_resource.retries
    retry_delay new_resource.retry_delay
  end

  rundeck_cli 'cli' do
    basedir new_resource.basedir
    rundeckuser new_resource.rundeckuser
    rundeckgroup new_resource.rundeckgroup
    admin_password new_resource.admin_password
  end
end

action_class do
  include RundeckCookbook::Helpers
end


text:
jQuery.fn.extend({
    setCursorPosition: function(position){
        if(this.length == 0) return this;
        return $(this).setSelection(position, position);
    },

    setSelection: function(selectionStart, selectionEnd) {
        if(this.length == 0) return this;
        input = this[0];

        if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        } else if (input.setSelectionRange) {
			input.focus();
			input.setSelectionRange(selectionStart, selectionEnd);
		}

		return this;
	},

	focusEnd: function(){
		this.setCursorPosition(this.val().length);
		return this;
	},

	getCurrentLine: function() {
		var $ta = $(this[0]),
			pos = $ta.getCursorPosition(),
			taval = $ta.val(),
			start = taval.lastIndexOf('\n', pos - 1) + 1,
			end = taval.indexOf('\n', pos);

		if (end == -1) {
			end = taval.length;
		}

		return taval.substr(start, end - start);
	},

	getCursorPosition: function() {
		var el = $(this).get(0);
		var pos = 0;
		if('selectionStart' in el) {
			pos = el.selectionStart;
		} else if('selection' in document) {
			el.focus();
			var Sel = document.selection.createRange();
			var SelLength = document.selection.createRange().text.length;
			Sel.moveStart('character', -el.value.length);
			pos = Sel.text.length - SelLength;
		}
		return pos;
	},

	insertAtCursor: function(myValue) {
		return this.each(function(i) {
			if (document.selection) {
			  //For browsers like Internet Explorer
			  this.focus();
			  sel = document.selection.createRange();
			  sel.text = myValue;
			  this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
			  //For browsers like Firefox and Webkit based
			  var startPos = this.selectionStart;
			  var endPos = this.selectionEnd;
			  var scrollTop = this.scrollTop;
			  this.value = this.value.substring(0, startPos) + myValue +
							this.value.substring(endPos,this.value.length);
			  this.focus();
			  this.selectionStart = startPos + myValue.length;
			  this.selectionEnd = startPos + myValue.length;
			  this.scrollTop = scrollTop;
			} else {
			  this.value += myValue;
			  this.focus();
			}
	  	})
	}
});


text:
declare module '@storybook/addon-links' {
    import * as React from 'react';

    function linkTo<T>(book: string, kind?: string): React.MouseEventHandler<T>;
}


text:
package denominator.designate;

import com.squareup.okhttp.mockwebserver.MockResponse;

import org.junit.Rule;
import org.junit.Test;

import denominator.ZoneApi;
import denominator.model.Zone;

import static denominator.assertj.ModelAssertions.assertThat;
import static denominator.designate.DesignateTest.domainId;
import static denominator.designate.DesignateTest.domainResponse;
import static denominator.designate.DesignateTest.domainsResponse;
import static java.lang.String.format;

public class DesignateZoneApiMockTest {

  @Rule
  public MockDesignateServer server = new MockDesignateServer();

  @Test
  public void iteratorWhenPresent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody(domainsResponse));

    ZoneApi api = server.connect().api().zones();

    assertThat(api.iterator()).containsExactly(
        Zone.create(domainId, "denominator.io.", 3601, "nil@denominator.io")
    );

    server.assertAuthRequest();
    server.assertRequest().hasPath("/v1/domains");
  }

  @Test
  public void iteratorWhenAbsent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody("{ \"domains\": [] }"));

    ZoneApi api = server.connect().api().zones();
    assertThat(api.iterator()).isEmpty();

    server.assertAuthRequest();
    server.assertRequest().hasPath("/v1/domains");
  }

  @Test
  public void iteratorByNameWhenPresent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody(domainsResponse));

    ZoneApi api = server.connect().api().zones();

    assertThat(api.iterateByName("denominator.io.")).containsExactly(
        Zone.create(domainId, "denominator.io.", 3601, "nil@denominator.io")
    );

    server.assertAuthRequest();
    server.assertRequest().hasPath("/v1/domains");
  }

  /**
   * Client-side filter is used as there's no server-side command.
   */
  @Test
  public void iteratorByNameWhenIrrelevant() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody(domainsResponse));

    ZoneApi api = server.connect().api().zones();

    assertThat(api.iterateByName("denominator.com.")).isEmpty();

    server.assertAuthRequest();
    server.assertRequest().hasPath("/v1/domains");
  }

  @Test
  public void iteratorByNameWhenAbsent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody("{ \"domains\": [] }"));

    ZoneApi api = server.connect().api().zones();
    assertThat(api.iterateByName("denominator.io.")).isEmpty();

    server.assertAuthRequest();
    server.assertRequest().hasPath("/v1/domains");
  }

  @Test
  public void putWhenAbsent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody(domainResponse));

    ZoneApi api = server.connect().api().zones();

    Zone zone = Zone.create(null, "denominator.io.", 3601, "nil@denominator.io");
    assertThat(api.put(zone)).isEqualTo(domainId);

    server.assertAuthRequest();
    server.assertRequest()
        .hasMethod("POST")
        .hasPath("/v1/domains")
        .hasBody(
            "{\"name\":\"denominator.io.\",\"ttl\":3601,\"email\":\"nil@denominator.io\"}");
  }

  @Test
  public void putWhenPresent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setResponseCode(409).setBody(
        "{\"code\": 409, \"type\": \"duplicate_domain\", \"request_id\": \"req-6b86464d-15bb-467f-aa9e-7c90b10555f3\"}"));
    server.enqueue(new MockResponse().setBody(domainsResponse));
    server.enqueue(new MockResponse().setBody(domainResponse));

    ZoneApi api = server.connect().api().zones();

    Zone zone = Zone.create(null, "denominator.io.", 3601, "nil@denominator.io");
    assertThat(api.put(zone)).isEqualTo(domainId);

    server.assertAuthRequest();
    server.assertRequest()
        .hasMethod("POST")
        .hasPath("/v1/domains")
        .hasBody(
            "{\"name\":\"denominator.io.\",\"ttl\":3601,\"email\":\"nil@denominator.io\"}");
    server.assertRequest().hasPath("/v1/domains");
    server.assertRequest()
        .hasMethod("PUT")
        .hasPath("/v1/domains/" + domainId)
        .hasBody(format(
            "{\"id\":\"%s\",\"name\":\"denominator.io.\",\"ttl\":3601,\"email\":\"nil@denominator.io\"}",
            domainId));
  }

  @Test
  public void putWhenPresent_withId() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setBody(domainResponse));

    ZoneApi api = server.connect().api().zones();

    Zone zone = Zone.create(domainId, "denominator.io.", 3601, "nil@denominator.io");
    assertThat(api.put(zone)).isEqualTo(domainId);

    server.assertAuthRequest();
    server.assertRequest()
        .hasMethod("PUT")
        .hasPath("/v1/domains/" + domainId)
        .hasBody(format(
            "{\"id\":\"%s\",\"name\":\"denominator.io.\",\"ttl\":3601,\"email\":\"nil@denominator.io\"}",
            domainId));
  }

  @Test
  public void deleteWhenPresent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse());

    ZoneApi api = server.connect().api().zones();
    api.delete(domainId);

    server.assertAuthRequest();
    server.assertRequest().hasMethod("DELETE").hasPath("/v1/domains/" + domainId);
  }

  @Test
  public void deleteWhenAbsent() throws Exception {
    server.enqueueAuthResponse();
    server.enqueue(new MockResponse().setResponseCode(404).setBody(
        "{\"code\": 404, \"type\": \"domain_not_found\", \"request_id\": \"req-809e7455-0e56-42ec-8674-a1aa24e18600\"}"));

    ZoneApi api = server.connect().api().zones();
    api.delete(domainId);

    server.assertAuthRequest();
    server.assertRequest().hasMethod("DELETE").hasPath("/v1/domains/" + domainId);
  }
}


text:
package com.amazonaws.services.s3control.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.s3control.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * AccountLevel StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AccountLevelStaxUnmarshaller implements Unmarshaller<AccountLevel, StaxUnmarshallerContext> {

    public AccountLevel unmarshall(StaxUnmarshallerContext context) throws Exception {
        AccountLevel accountLevel = new AccountLevel();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return accountLevel;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("ActivityMetrics", targetDepth)) {
                    accountLevel.setActivityMetrics(ActivityMetricsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("BucketLevel", targetDepth)) {
                    accountLevel.setBucketLevel(BucketLevelStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("AdvancedCostOptimizationMetrics", targetDepth)) {
                    accountLevel.setAdvancedCostOptimizationMetrics(AdvancedCostOptimizationMetricsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("AdvancedDataProtectionMetrics", targetDepth)) {
                    accountLevel.setAdvancedDataProtectionMetrics(AdvancedDataProtectionMetricsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DetailedStatusCodesMetrics", targetDepth)) {
                    accountLevel.setDetailedStatusCodesMetrics(DetailedStatusCodesMetricsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return accountLevel;
                }
            }
        }
    }

    private static AccountLevelStaxUnmarshaller instance;

    public static AccountLevelStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new AccountLevelStaxUnmarshaller();
        return instance;
    }
}


text:
package io.cos.cas.authentication;

import io.cos.cas.adaptors.postgres.types.DelegationProtocol;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.jasig.cas.authentication.RememberMeUsernamePasswordCredential;

import java.util.HashMap;
import java.util.Map;

/**
 * Open Science Framework Credential.
 *
 * @author Michael Haselton
 * @author Longze Chen
 * @since 4.1.5
 */
public class OpenScienceFrameworkCredential extends RememberMeUsernamePasswordCredential {

    /** Authentication attribute name for Institution ID. */
    public static final String INSTITUTION_ID = "institutionId";

    /** Authentication attribute name for Remote Principal. */
    public static final String REMOTE_PRINCIPAL = "remotePrincipal";

    /** Unique ID for serialization. */
    private static final long serialVersionUID = -3006234230814410939L;

    /** Remote Principal appended to username in string representation. */
    private static final String REMOTE_PRINCIPAL_SUFFIX = "+rp";

    /** Verification Key appended to username in string representation. */
    private static final String VERIFICATION_KEY_SUFFIX = "+vk";

    /** Time-based One Time Password suffix appended to username in string representation. */
    private static final String ONE_TIME_PASSWORD_SUFFIX = "+otp";

    /** The Verification Key. */
    private String verificationKey;

    /** The One Time Password. */
    private String oneTimePassword;

    /** Indicates a Remote Principal. */
    private Boolean remotePrincipal = Boolean.FALSE;

    /** The Institution Id. */
    private String institutionId;

    /** The Authentication Delegation Protocol. */
    private DelegationProtocol delegationProtocol;

    /** The Attributes Released from Authentication Delegation. */
    private Map<String, String> delegationAttributes = new HashMap<>();

    /** Default constructor. */
    public OpenScienceFrameworkCredential() {}

    /**
     * Creates a new instance with the given username and password.
     *
     * @param username Non-null user name.
     * @param password Non-null password.
     * @param rememberMe remember me.
     * @param verificationKey verification key.
     */
    public OpenScienceFrameworkCredential(final String username, final String password, final Boolean rememberMe,
                                          final String verificationKey) {
        this(username, password, rememberMe, verificationKey, null);
    }

    /**
     * Creates a new instance with the given username and password.
     *
     * @param username Non-null user name.
     * @param password Non-null password.
     * @param rememberMe remember me.
     * @param verificationKey verification key.
     * @param oneTimePassword one time password.
     */
    public OpenScienceFrameworkCredential(final String username, final String password, final Boolean rememberMe,
                                          final String verificationKey, final String oneTimePassword) {
        this.setUsername(username);
        this.setPassword(password);
        this.setRememberMe(rememberMe);
        this.setVerificationKey(verificationKey);
        this.setOneTimePassword(oneTimePassword);
    }

    /**
     * @return Returns the Verification Key.
     */
    public String getVerificationKey() {
        return this.verificationKey;
    }

    /**
     * @param verificationKey The Verification Key to set.
     */
    public void setVerificationKey(final String verificationKey) {
        this.verificationKey = verificationKey;
    }

    /**
     * @return Returns the One Time Password.
     */
    public String getOneTimePassword() {
        return this.oneTimePassword;
    }

    /**
     * @param oneTimePassword the One Time Password to set.
     */
    public void setOneTimePassword(final String oneTimePassword) {
        this.oneTimePassword = oneTimePassword;
    }

    /**
     * @return Returns the Remote Principal.
     */
    public final Boolean isRemotePrincipal() {
        return this.remotePrincipal;
    }

    /**
     * @param remotePrincipal the Remote Principal.
     */
    public final void setRemotePrincipal(final Boolean remotePrincipal) {
        this.remotePrincipal = remotePrincipal;
    }

    /**
     * @return Returns the Institution Id.
     */
    public final String getInstitutionId() {
        return this.institutionId;
    }

    /**
     * @param institutionId the Institution Id.
     */
    public final void setInstitutionId(final String institutionId) {
        this.institutionId = institutionId;
    }

    /**
     * @return Returns the Delegation Protocol.
     */
    public final DelegationProtocol getDelegationProtocol() {
        return delegationProtocol;
    }

    /**
     * @param delegationProtocol the Delegation Protocol.
     */
    public void setDelegationProtocol(final DelegationProtocol delegationProtocol) {
        this.delegationProtocol = delegationProtocol;
    }

    /**
     * @return Returns the Released Attributes from Authentication Delegation.
     */
    public final Map<String, String> getDelegationAttributes() {
        return delegationAttributes;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getId() {
        return this.getUsername();
    }

    @Override
    public String toString() {
        String representation = super.toString();

        if (this.remotePrincipal) {
            representation += REMOTE_PRINCIPAL_SUFFIX;
        }
        if (this.verificationKey != null) {
            representation += VERIFICATION_KEY_SUFFIX;
        }
        if (this.oneTimePassword != null) {
            representation += ONE_TIME_PASSWORD_SUFFIX;
        }
        return representation;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (!super.equals(obj)) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }

        final OpenScienceFrameworkCredential other = (OpenScienceFrameworkCredential) obj;

        if (!this.verificationKey.equals(other.verificationKey)) {
            return false;
        }
        if (!this.oneTimePassword.equals(other.oneTimePassword)) {
            return false;
        }
        if (!this.remotePrincipal.equals(other.remotePrincipal)) {
            return false;
        }
        if (!this.institutionId.equals(other.institutionId)) {
            return false;
        }
        if (!this.delegationProtocol.equals(other.delegationProtocol)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .appendSuper(super.hashCode())
                .append(verificationKey)
                .append(oneTimePassword)
                .append(remotePrincipal)
                .append(institutionId)
                .append(delegationProtocol)
                .toHashCode();
    }
}


text:
namespace rocksdb {

DBOptions BuildDBOptions(const ImmutableDBOptions& immutable_db_options,
                         const MutableDBOptions& mutable_db_options);

ColumnFamilyOptions BuildColumnFamilyOptions(
    const ColumnFamilyOptions& ioptions,
    const MutableCFOptions& mutable_cf_options);

#ifndef ROCKSDB_LITE

Status GetMutableOptionsFromStrings(
    const MutableCFOptions& base_options,
    const std::unordered_map<std::string, std::string>& options_map,
    MutableCFOptions* new_options);

Status GetMutableDBOptionsFromStrings(
    const MutableDBOptions& base_options,
    const std::unordered_map<std::string, std::string>& options_map,
    MutableDBOptions* new_options);

Status GetTableFactoryFromMap(
    const std::string& factory_name,
    const std::unordered_map<std::string, std::string>& opt_map,
    std::shared_ptr<TableFactory>* table_factory,
    bool ignore_unknown_options = false);

enum class OptionType {
  kBoolean,
  kInt,
  kVectorInt,
  kUInt,
  kUInt32T,
  kUInt64T,
  kSizeT,
  kString,
  kDouble,
  kCompactionStyle,
  kCompactionPri,
  kSliceTransform,
  kCompressionType,
  kVectorCompressionType,
  kTableFactory,
  kComparator,
  kCompactionFilter,
  kCompactionFilterFactory,
  kCompactionOptionsFIFO,
  kCompactionOptionsUniversal,
  kCompactionStopStyle,
  kMergeOperator,
  kMemTableRepFactory,
  kBlockBasedTableIndexType,
  kFilterPolicy,
  kFlushBlockPolicyFactory,
  kChecksumType,
  kEncodingType,
  kWALRecoveryMode,
  kAccessHint,
  kInfoLogLevel,
  kLRUCacheOptions,
  kUnknown
};

enum class OptionVerificationType {
  kNormal,
  kByName,               // The option is pointer typed so we can only verify
                         // based on it's name.
  kByNameAllowNull,      // Same as kByName, but it also allows the case
                         // where one of them is a nullptr.
  kByNameAllowFromNull,  // Same as kByName, but it also allows the case
                         // where the old option is nullptr.
  kDeprecated            // The option is no longer used in rocksdb. The RocksDB
                         // OptionsParser will still accept this option if it
                         // happen to exists in some Options file.  However,
                         // the parser will not include it in serialization
                         // and verification processes.
};

// A struct for storing constant option information such as option name,
// option type, and offset.
struct OptionTypeInfo {
  int offset;
  OptionType type;
  OptionVerificationType verification;
  bool is_mutable;
  int mutable_offset;
};

// A helper function that converts "opt_address" to a std::string
// based on the specified OptionType.
bool SerializeSingleOptionHelper(const char* opt_address,
                                 const OptionType opt_type, std::string* value);

// In addition to its public version defined in rocksdb/convenience.h,
// this further takes an optional output vector "unsupported_options_names",
// which stores the name of all the unsupported options specified in "opts_map".
Status GetDBOptionsFromMapInternal(
    const DBOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
    DBOptions* new_options, bool input_strings_escaped,
    std::vector<std::string>* unsupported_options_names = nullptr,
    bool ignore_unknown_options = false);

// In addition to its public version defined in rocksdb/convenience.h,
// this further takes an optional output vector "unsupported_options_names",
// which stores the name of all the unsupported options specified in "opts_map".
Status GetColumnFamilyOptionsFromMapInternal(
    const ColumnFamilyOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
    ColumnFamilyOptions* new_options, bool input_strings_escaped,
    std::vector<std::string>* unsupported_options_names = nullptr,
    bool ignore_unknown_options = false);

extern Status StringToMap(
    const std::string& opts_str,
    std::unordered_map<std::string, std::string>* opts_map);

extern bool ParseOptionHelper(char* opt_address, const OptionType& opt_type,
                              const std::string& value);
#endif  // !ROCKSDB_LITE

struct OptionsHelper {
  static std::map<CompactionStyle, std::string> compaction_style_to_string;
  static std::map<CompactionPri, std::string> compaction_pri_to_string;
  static std::map<CompactionStopStyle, std::string>
      compaction_stop_style_to_string;
  static std::unordered_map<std::string, ChecksumType> checksum_type_string_map;
#ifndef ROCKSDB_LITE
  static std::unordered_map<std::string, OptionTypeInfo> cf_options_type_info;
  static std::unordered_map<std::string, OptionTypeInfo>
      fifo_compaction_options_type_info;
  static std::unordered_map<std::string, OptionTypeInfo>
      universal_compaction_options_type_info;
  static std::unordered_map<std::string, CompactionStopStyle>
      compaction_stop_style_string_map;
  static std::unordered_map<std::string, OptionTypeInfo> db_options_type_info;
  static std::unordered_map<std::string, OptionTypeInfo>
      lru_cache_options_type_info;
  static std::unordered_map<std::string, CompressionType>
      compression_type_string_map;
  static std::unordered_map<std::string, BlockBasedTableOptions::IndexType>
      block_base_table_index_type_string_map;
  static std::unordered_map<std::string, EncodingType> encoding_type_string_map;
  static std::unordered_map<std::string, CompactionStyle>
      compaction_style_string_map;
  static std::unordered_map<std::string, CompactionPri>
      compaction_pri_string_map;
  static std::unordered_map<std::string, WALRecoveryMode>
      wal_recovery_mode_string_map;
  static std::unordered_map<std::string, DBOptions::AccessHint>
      access_hint_string_map;
  static std::unordered_map<std::string, InfoLogLevel>
      info_log_level_string_map;
  static ColumnFamilyOptions dummy_cf_options;
  static CompactionOptionsFIFO dummy_comp_options;
  static LRUCacheOptions dummy_lru_cache_options;
  static CompactionOptionsUniversal dummy_comp_options_universal;
#endif  // !ROCKSDB_LITE
};

// Some aliasing
static auto& compaction_style_to_string =
    OptionsHelper::compaction_style_to_string;
static auto& compaction_pri_to_string = OptionsHelper::compaction_pri_to_string;
static auto& compaction_stop_style_to_string =
    OptionsHelper::compaction_stop_style_to_string;
static auto& checksum_type_string_map = OptionsHelper::checksum_type_string_map;
#ifndef ROCKSDB_LITE
static auto& cf_options_type_info = OptionsHelper::cf_options_type_info;
static auto& fifo_compaction_options_type_info =
    OptionsHelper::fifo_compaction_options_type_info;
static auto& universal_compaction_options_type_info =
    OptionsHelper::universal_compaction_options_type_info;
static auto& compaction_stop_style_string_map =
    OptionsHelper::compaction_stop_style_string_map;
static auto& db_options_type_info = OptionsHelper::db_options_type_info;
static auto& lru_cache_options_type_info =
    OptionsHelper::lru_cache_options_type_info;
static auto& compression_type_string_map =
    OptionsHelper::compression_type_string_map;
static auto& block_base_table_index_type_string_map =
    OptionsHelper::block_base_table_index_type_string_map;
static auto& encoding_type_string_map = OptionsHelper::encoding_type_string_map;
static auto& compaction_style_string_map =
    OptionsHelper::compaction_style_string_map;
static auto& compaction_pri_string_map =
    OptionsHelper::compaction_pri_string_map;
static auto& wal_recovery_mode_string_map =
    OptionsHelper::wal_recovery_mode_string_map;
static auto& access_hint_string_map = OptionsHelper::access_hint_string_map;
static auto& info_log_level_string_map =
    OptionsHelper::info_log_level_string_map;
#endif  // !ROCKSDB_LITE

}  // namespace rocksdb


text:
#pragma once

#include "api_core.h"
#include "coreservices/itap.h"
#include "coreservices/icommand.h"
#include "debug/dsumap.h"

namespace debugger {

class CmdDsuBusUtil : public ICommand  {
 public:
    explicit CmdDsuBusUtil(uint64_t dmibar, ITap *tap);

    /** ICommand */
    virtual int isValid(AttributeType *args);
    virtual void exec(AttributeType *args, AttributeType *res);

 private:
    uint64_t clock_cnt_z_;
    DsuMapType::local_regs_type::local_region_type::mst_bus_util_type
    bus_util_z_[32];
    uint32_t mst_total_;
};

}  // namespace debugger


text:
#import "WXMetaModule.h"
#import "WXConvert.h"
#import "WXUtility.h"
#import "WXSDKInstance_private.h"

@implementation WXMetaModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(setViewport:))

- (void)setViewport:(NSDictionary *)viewportArguments
{
    CGFloat viewportWidthFloat;
    id viewportWidth = viewportArguments[@"width"];
    if ([viewportWidth isKindOfClass:[NSString class]]) {
        if ([viewportWidth isEqualToString:@"device-width"]) {
            viewportWidthFloat = [WXUtility portraitScreenSize].width * WXScreenScale();
        } else if ([viewportWidth isEqualToString:@"device-height"]) {
            viewportWidthFloat = [WXUtility portraitScreenSize].height * WXScreenScale();
        } else {
            viewportWidthFloat = [WXConvert CGFloat:viewportWidth];
        }
    } else {
        viewportWidthFloat = [WXConvert CGFloat:viewportWidth];
    }

    if (viewportWidthFloat > 0) {
        self.weexInstance.viewportWidth = viewportWidthFloat;
    }
}

@end


text:
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.235
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TemplateSample
{

    [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "1.2.0.0")]
    public partial class MailTemplate : RazorGenerator.Templating.RazorTemplateBase
    {
#line hidden

        public override void Execute()
        {

            WriteLiteral("\r\n\r\nSome mail\r\n");

        }
    }
}
#pragma warning restore 1591


text:
import http.server
import re
import os
import json
from .replay import  ReplayFile

VERSION = '1.82.98'
REPLAYS_DIR = 'replays'
class ReplayServer(http.server.HTTPServer):
    def __init__(self):
        http.server.HTTPServer.__init__(self, ('', 8080), RequestHandler)

    def run(self):
        self.serve_forever()

class RequestHandler(http.server.BaseHTTPRequestHandler):
    def write_200(self, content_type, data):
        self.send_response(200, 'OK')
        self.send_header('Content-type', content_type)
        self.end_headers()

        if type(data) is str:
            data = bytes(data, 'UTF-8')
        self.wfile.write(data)

    def do_POST(self):
        r = re.compile('^/observer-mode/rest/consumer'
                + '/(?P<method>[a-zA-Z]+)'
                + '/(?P<region>[A-Z1-9]+)'
                + '/(?P<gameid>[0-9]+)'
                + '/(?:null|(?P<id>-?[0-9]+)/token)'
                + '$')

        m = r.match(self.path)
        if m is None:
            self.send_error(404)
            return

        args = m.groupdict()
        if args['method'] == 'end':
            # Riot pls
            self.send_error(405)
            return

        self.send_error(404)

    def do_GET(self):
        if self.path == '/':
            return self.do_index()
        if self.path == '/observer-mode/rest/consumer/version':
            self.write_200('text/plain', VERSION)
        elif self.path == '/observer-mode/rest/featured':
            self.write_200('application/json', '{"gameList":[], "clientRefreshInterval":300}')
        else:
            r = re.compile('^/observer-mode/rest/consumer'
                + '/(?P<method>[a-zA-Z]+)'
                + '/(?P<region>[A-Z1-9]+)'
                + '/(?P<gameid>[0-9]+)'
                + '/(?:null|(?P<id>-?[0-9]+)/token)'
                + '$')

            m = r.match(self.path)
            if m is None:
                self.send_error(404)
                return

            args = m.groupdict()
            rf = ReplayFile(args['gameid'], ReplayFile.read, REPLAYS_DIR)

            if args['method'] == 'getGameMetaData':
                try:
                    self.write_200('application/octet-stream', rf.read_metadata())
                except FileNotFoundError:
                    self.send_error(404)
                return
            elif args['method'] == 'getLastChunkInfo':
                try:
                    self.write_200('application/octet-stream', rf.read_last_chunk_info())
                except FileNotFoundError:
                    self.send_error(404)
                return
            elif args['method'] == 'getKeyFrame':
                try:
                    self.write_200('application/octet-stream', rf.read_keyframe(args['id']))
                except FileNotFoundError:
                    self.send_error(404)
                return
            elif args['method'] == 'getGameDataChunk':
                try:
                    self.write_200('application/octet-stream', rf.read_chunk(args['id']))
                except FileNotFoundError:
                    self.send_error(404)
                return
            elif args['method'] == 'endOfGameStats':
                try:
                    self.write_200('application/octet-stream', rf.read_end_of_game_stats())
                except FileNotFoundError:
                    self.send_error(404)
                return
            else:
                self.send_error(404)
                return

    def do_index(self):
        self.send_response(200, 'OK')
        self.send_header('Content-type', 'text/plain')
        self.end_headers()

        for game in os.listdir(REPLAYS_DIR):
            if game.endswith(".tar"):
                game = game[:-4]
            try:
                game_id = int(game)
            except ValueError:
                continue

            rf = ReplayFile(game_id, ReplayFile.read, REPLAYS_DIR)
            game_json = json.loads(rf.read_game().decode('utf-8'))
            key = game_json['observers']['encryptionKey']
            platform = game_json['platformId']

            r = 'replay' if rf.is_finished() and not rf.is_partial() else 'spectator'
            h = 'localhost:8080'
            self.wfile.write("{} {} {} {} {}\n".format(r, h, key, game_id, platform).encode("utf-8"))


text:
class SessionServiceFactory : public BrowserContextKeyedServiceFactory {
 public:
  // Returns the session service for |profile|. This may return NULL. If this
  // profile supports a session service (it isn't incognito), and the session
  // service hasn't yet been created, this forces creation of the session
  // service. This returns NULL if ShutdownForProfile has been called for
  // |profile|.
  //
  // This returns NULL if the profile is incognito. Callers should always check
  // the return value for NULL.
  static SessionService* GetForProfile(Profile* profile);

  // Returns the session service for |profile|, but do not create it if it
  // doesn't exist. This returns NULL if the profile is incognito or if session
  // service has been explicitly shutdown (browser is exiting). Callers should
  // always check the return value for NULL.
  static SessionService* GetForProfileIfExisting(Profile* profile);

  // Returns the session service for |profile|. This is the same as
  // GetForProfile, but will force creation of the session service even if
  // ShutdownForProfile has been called for |profile|.
  static SessionService* GetForProfileForSessionRestore(Profile* profile);

  // If |profile| has a session service, it is shut down. To properly record the
  // current state this forces creation of the session service, then shuts it
  // down.
  static void ShutdownForProfile(Profile* profile);

#if defined(UNIT_TEST)
  // For test use: force setting of the session service for a given profile.
  // This will delete a previous session service for this profile if it exists.
  static void SetForTestProfile(Profile* profile,
                                std::unique_ptr<SessionService> service) {
    GetInstance()->BrowserContextShutdown(profile);
    GetInstance()->BrowserContextDestroyed(profile);
    GetInstance()->Associate(profile, std::move(service));
  }
#endif

  static SessionServiceFactory* GetInstance();

 private:
  friend struct base::DefaultSingletonTraits<SessionServiceFactory>;
  FRIEND_TEST_ALL_PREFIXES(SessionCrashedInfoBarDelegateUnitTest,
                           DetachingTabWithCrashedInfoBar);

  SessionServiceFactory();
  ~SessionServiceFactory() override;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* profile) const override;
  bool ServiceIsCreatedWithBrowserContext() const override;
  bool ServiceIsNULLWhileTesting() const override;
};

#endif  // CHROME_BROWSER_SESSIONS_SESSION_SERVICE_FACTORY_H_


text:
import { Component, Input } from '@angular/core';

import { Grid } from '../../../lib/grid';
import { DataSource } from '../../../lib/data-source/data-source';

@Component({
  selector: '[ng2-st-checkbox-select-all]',
  template: `
    <input type="checkbox" [ngModel]="isAllSelected">
  `,
})
export class CheckboxSelectAllComponent {

  @Input() grid: Grid;
  @Input() source: DataSource;
  @Input() isAllSelected: boolean;
}