text:
class DependencyManager;
class KeyedService;

// Base class for Factories that take an opaque pointer and return some service
// on a one-to-one mapping. Each concrete factory that derives from this class
// *must* be a Singleton (only unit tests don't do that).
//
// We do this because services depend on each other and we need to control
// shutdown/destruction order. In each derived classes' constructors, the
// implementors must explicitly state which services are depended on.
class KEYED_SERVICE_EXPORT KeyedServiceFactory
    : public KeyedServiceBaseFactory {
 public:
  KeyedServiceFactory(const KeyedServiceFactory&) = delete;
  KeyedServiceFactory& operator=(const KeyedServiceFactory&) = delete;

 protected:
  KeyedServiceFactory(const char* name, DependencyManager* manager, Type type);
  ~KeyedServiceFactory() override;

  // A callback that supplies the instance of a KeyedService for a given
  // |context|. This is used primarily for testing, where we want to feed
  // a specific test double into the KeyedServiceFactory system.
  using TestingFactory =
      base::RepeatingCallback<std::unique_ptr<KeyedService>(void* context)>;

  // Associates |testing_factory| with |context| so that |testing_factory| is
  // used to create the KeyedService when requested.  |testing_factory| can be
  // empty to signal that KeyedService should be null.  Multiple calls to
  // SetTestingFactory() are allowed; previous services will be shut down.
  void SetTestingFactory(void* context, TestingFactory testing_factory);

  // Associates |testing_factory| with |context| and immediately returns the
  // created KeyedService. Since the factory will be used immediately, it may
  // not be empty.
  KeyedService* SetTestingFactoryAndUse(void* context,
                                        TestingFactory testing_factory);

  // Common implementation that maps |context| to some service object. Deals
  // with incognito contexts per subclass instructions with GetContextToUse()
  // method on the base.  If |create| is true, the service will be created
  // using BuildServiceInstanceFor() if it doesn't already exist.
  KeyedService* GetServiceForContext(void* context,
                                     bool create);

  // Maps |context| to |service| with debug checks to prevent duplication and
  // returns a raw pointer to |service|.
  KeyedService* Associate(void* context, std::unique_ptr<KeyedService> service);

  // Removes the mapping from |context| to a service.
  void Disassociate(void* context);

  // Returns a new KeyedService that will be associated with |context|. The
  // |side_parameter| could be nullptr or some object required to create a
  // service instance.
  virtual std::unique_ptr<KeyedService> BuildServiceInstanceFor(
      void* context) const = 0;

  // Returns whether the |context| is off-the-record or not.
  virtual bool IsOffTheRecord(void* context) const = 0;

  // KeyedServiceBaseFactory:
  void ContextShutdown(void* context) override;
  void ContextDestroyed(void* context) override;

  void SetEmptyTestingFactory(void* context) override;
  bool HasTestingFactory(void* context) override;

 private:
  friend class DependencyManager;
  friend class DependencyManagerUnittests;

  // The mapping between a context and its service.
  std::map<void*, std::unique_ptr<KeyedService>> mapping_;

  // The mapping between a context and its overridden TestingFactory.
  std::map<void*, TestingFactory> testing_factories_;
};

#endif  // COMPONENTS_KEYED_SERVICE_CORE_KEYED_SERVICE_FACTORY_H_


text:
Application Ruby on Rails avec base de données PostgreSQL, assets compilés avec asset pipeline **et** webpack.

Des fichiers de définition Docker docker-compose sont présents pour faciliter la mise en place de l'environnements de développement.

Build des images Docker :

```sh
docker-compose build
```

Installation des gems :

```sh
docker-compose run web bundle install
```

Cette commande doit être lancée dès qu'une nouvelle gem apparait.

Installation des packages Javascript :

```sh
docker-compose run web yarn install
```

Un fichier `.env` à la racine du projet local au développeur derait contenir les valeurs suivantes :

```sh
CLOUDINARY_URL=cloudinary://blablah
```

Créer la base de données :

```sh
docker-compose run web rails db:drop db:create db:schema:load db:seed
```

Lancement d'une migration de base :

```sh
docker-compose run web rails db:migrate
```

Démarrage des images :

```sh
docker-compose down && docker-compose up
```

## Workflow de développement

Le workflow de développement est basé sur le [GitHub flow](https://guides.github.com/introduction/flow/) :

* chaque changement de code (nouvelle fonctionnialité, bug fix, etc) devrait résulter d'un ticket (une *issue* GitHub)
* chaque changement de code devrait passer une *review* de code via une Pull Request

La bonne manière de créer une Pull Request est de :

* créer localement une nouvelle branche correspondant au ticket/issue qu'on veut traiter via ```git checkout master && git pull && git checkout -b fix/13```
* modifier le code et accumuler les commits dans cette nouvelle branch. Les commits devraient mentionner le ticket correspondant (utiliser les mot-clés *fix* or *see*)
* pousser le code vers GitHub ```git push origin fix/13```
* ouvrir une PUll Request
* attendre la review de code et éventuellement modifier son code en fonction des commentaires

## Déploiement en production

Actuellement, la branche master est autodéployée sur Scalingo.

redpajama_set_name: RedPajamaGithub


text:
function [assoc]=tfanalysis_compute(resp)

%  TFANALYSIS_COMPUTE  Analyze reponses to temporal frequencies
% %  [ASSOC]=TFANALYSIS_COMPUTE(RESP)
%
%  Analyzes temporal frequency responses.
%
%  RESP is a structure list of response properties with fields:
%  curve    |    4xnumber of temporal frequencies tested,
%           |      curve(1,:) is temporal frequencies tested
%           |      curve(2,:) is mean responses
%           |      curve(3,:) is standard deviation
%           |      curve(4,:) is standard error
%  ind      |    cell list of individual trial responses for each TF
%  spont    |    spontaneous responses [mean stddev stderr]
%  spontind |    individual spontaneous responses
%  Optionally:
%  blank    |    response to a blank trial: [mean stddev stderr]
%  blankind |    individual responses to blank
%
%
%  If the function is called with no arguments, then the of associate
%  names that are computed by the function is returned.
%
%  Returns data in the form of 'associates' that can be added
%  to a measured data object:
%  'TF Response curve'        |   Response curve (tfs;mean;stddev;stderr)
%  'TF Pref'                  |   TF w/ max response
%  'TF Low'                   |   low TF with half of max response
%  'TF High'                  |   high TF with half of max response
%
%        Same as above with 'blank' or 'spont' rate subtracted
%  'TF Low TF'                |   low TF with half of max response
%  'TF High TF'               |   high TF with half of max response
%
%  'TF sig resp p'            |   p value of ANOVA across conditions
%  'TF sig resp'              |   (0/1) Is above < 0.05?
%  'TF visual response p'     |   p value of ANOVA across conditions +
%                             |     blank, if available
%  'TF visual response'       |   (0/1) Is above < 0.05?
%
%  Difference of gaussians fit:
%  'TF DOG params'            |   'r0 re se ri si'
%  'TF DOG Fit'               |   1st row has TF values, 2nd has responses
%  'TF DOG R2'                |   R^2 error
%  'TF DOG Low'               |   Low cut-off, as measured with DOG
%  'TF DOG High'              |   High cut-off, as measured with DOG
%  'TF DOG Pref'              |   TF Pref, as measured with DOG
%
%  Cubic spline "Fit":
%  'TF spline Fit'            |   1st row has TF values, 2nd has responses
%  'TF spline Pref'           |   TF Pref, as measured with spline
%  'TF spline Low'            |   Low cut-off, as measured with spline
%  'TF spline High'           |   High cut-off, as measured with spline
%

assoclist = { 'TF Low TF','TF High TF',...
	'TF Response curve','TF Pref','TF Low','TF High',...
	'TF sig resp p','TF sig resp','TF visual response p','TF visual response','TF Blank Response',...
	'TF DOG params','TF DOG Fit','TF DOG R2','TF DOG Low','TF DOG High','TF DOG Pref',...
	'TF spline Fit','TF spline Pref','TF spline Low','TF spline High'};

assoc=struct('type','t','owner','t','data',0,'desc',0); assoc=assoc([]);

if nargin==0, assoc = assoclist; return; end;

r0=resp.spont(1);
if isfield(resp,'blankresp'),
	r0 = resp.blankresp(1);
end;

% from the raw curve
[mf,preftf]=max(resp.curve(2,:));
preftf = resp.curve(1,preftf(1));
[lowv, maxv, highv] = compute_halfwidth(resp.curve(1,:),resp.curve(2,:));
[lowvsp, maxvsp, highvsp] = compute_halfwidth(resp.curve(1,:),resp.curve(2,:)-r0);

 % significance

[tfsigp,tfvp] = neural_response_significance(resp);

 % DOG fit
re = mf; ri = mf; se = maxv; si = 5+5*randn;
rcurve = resp.curve;

search_options=optimset('fminsearch');
search_options.TolFun=1e-3;
search_options.TolX=1e-3;
%search_options.MaxFunEvals='300*numberOfVariables';
search_options.Display='off';

norm_error_overall = Inf;
dog_par_overall = [];

for jj=1:10,
	re = mf; ri = mf; se = maxv; si = 5+5*randn;
	dog_par=fminsearch('dog_error',[r0 re se ri si],search_options,...
		[rcurve(1,:) 60 70],[rcurve(2,:) r0 r0], ...
		[rcurve(4,:) mean(rcurve(4,:)) mean(rcurve(4,:))] 	    )';

	norm_error=dog_error(dog_par, [rcurve(1,:) 60 70],[rcurve(2,:) r0 r0]);

	if norm_error<norm_error_overall,
		dog_par_overall = dog_par;
	end;
end;

norm_error = norm_error_overall;
dog_par = dog_par_overall;

tfrange_interp=logspace( log10(min( min(rcurve(1,:)),0.01)),log10(50),50);
if isempty(dog_par),
	norm_error = Inf;
	r2 = -Inf;
	response=NaN*tfrange_interp;
else,
	norm_error=dog_error(dog_par, [rcurve(1,:) ],[rcurve(2,:)]);
	r2 = norm_error - ((rcurve(2,:)-mean(rcurve(2,:)))*(rcurve(2,:)'-mean(rcurve(2,:))));
	response=dog(dog_par',tfrange_interp);
end;

[lowdog, prefdog, highdog] =   compute_halfwidth(tfrange_interp,response);

fitx = min(rcurve(1,:)):1:max(rcurve(1,:));
if fitx(end)~=max(rcurve(1,:)), fitx(end+1) = max(rcurve(1,:)); end;
fity = interp1([rcurve(1,:)],[rcurve(2,:)], fitx,'spline');
[lowspline, prefspline, highspline] = compute_halfwidth(fitx,fity);

assoc(end+1) = tfassoc('TF Response curve',rcurve,'TF Response curve');
if isfield(resp,'blankresp'),
        assoc(end+1)=tfassoc('TF Blank Response',resp.blankresp,'TF blank resp');
end;
assoc(end+1) = tfassoc('TF Pref',preftf,'TF Pref');
assoc(end+1) = tfassoc('TF Low',lowv,'TF Low cut-off (half-max)');
assoc(end+1) = tfassoc('TF High',highv,'TF High cut-off (half-max)');

assoc(end+1) = tfassoc('TF Low TF',lowvsp,'TF Low cut-off (half-max) TF');
assoc(end+1) = tfassoc('TF High TF',highvsp,'TF High cut-off (half-max) TF');

assoc(end+1) = tfassoc('TF sig resp p',tfsigp,'TF response p value');
assoc(end+1) = tfassoc('TF sig resp',tfsigp<=0.05,'Is TF response significant?');
assoc(end+1) = tfassoc('TF visual response p',tfvp,'TF visual response (including blank) p value');
assoc(end+1) = tfassoc('TF visual response',tfvp<=0.05,'Is TF response across stims and blank significant?');

assoc(end+1) = tfassoc('TF DOG Pref',prefdog,'TF Pref difference of gaussians');
assoc(end+1) = tfassoc('TF DOG Low',lowdog,'TF Low cut-off (half-max from DOG)');
assoc(end+1) = tfassoc('TF DOG High',highdog,'TF High cut-off (half-max from DOG)');
assoc(end+1) = tfassoc('TF DOG R2',r2,'TF DOG r^2 of fit');
assoc(end+1) = tfassoc('TF DOG Fit',[tfrange_interp; response],'TF DOG Fit, 1st row is TF, 2nd row is response');

assoc(end+1) = tfassoc('TF spline Pref',prefspline,'TF Pref spline');
assoc(end+1) = tfassoc('TF spline Low',lowspline,'TF Low cut-off (half-max from spline)');
assoc(end+1) = tfassoc('TF spline High',highspline,'TF High cut-off (half-max from spline)');
assoc(end+1) = tfassoc('TF spline Fit',[fitx; fity],'TF spline Fit, 1st row is TF, 2nd row is response');

function myassoc = tfassoc(type,data,desc)
myassoc  = struct('type',type,'owner','tf','data',data,'desc',desc);


text:
package ca.uhn.fhir.jpa.batch.config;

import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.PostConstruct;

@Component
@Configuration
public class InMemoryJobRepositoryBatchConfig implements BatchConfigurer {

	private PlatformTransactionManager myPlatformTransactionManager;
	private JobLauncher myJobLauncher;
	private JobRepository myJobRepository;
	private JobExplorer myJobExplorer;

	@Override
	public PlatformTransactionManager getTransactionManager() {
		return myPlatformTransactionManager;
	}

	@Override
	public JobRepository getJobRepository() {
		return myJobRepository;
	}

	@Override
	public JobLauncher getJobLauncher() {
		return myJobLauncher;
	}

	@Override
	public JobExplorer getJobExplorer() {
		return myJobExplorer;
	}

	@PostConstruct
	public void setup() throws Exception{
		if (myPlatformTransactionManager == null) {
			myPlatformTransactionManager = new ResourcelessTransactionManager();
		}
		MapJobRepositoryFactoryBean jobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(myPlatformTransactionManager);
		jobRepositoryFactoryBean.afterPropertiesSet();
		myJobRepository = jobRepositoryFactoryBean.getObject();

		MapJobExplorerFactoryBean jobExplorerFactoryBean = new MapJobExplorerFactoryBean(jobRepositoryFactoryBean);
		jobExplorerFactoryBean.afterPropertiesSet();
		myJobExplorer = jobExplorerFactoryBean.getObject();

		SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
		jobLauncher.setJobRepository(myJobRepository);
		jobLauncher.afterPropertiesSet();
		myJobLauncher = jobLauncher;
	}
}


text:
<?php

namespace sourcetoad\bbii2\components;

Yii::import('zii.widgets.CPortlet');

class SimpleSearchForm extends CPortlet {
    protected function renderContent() {
        $form = $this->beginWidget('ActiveForm', array(
            'id' => 'simple-search-form',
            'action' => array('search/index'),
            'enableAjaxValidation' => false,
        ));
            echo Html::textField('search','', array('size' => 20,'maxlength' => 50,'class' => 'small-search-field'));
            echo Html::hiddenField('choice','0');
            echo Html::hiddenField('type','0');
            echo Html::submitButton('',array('class' => 'small-search-button'));
        $this->endWidget();
    }
}


text:
import cherrypy
import hashlib
import mock
import mongomock
import os
import pytest
import shutil

from .utils import uploadFile, MockSmtpReceiver, request as restRequest
from .plugin_registry import PluginRegistry

def _uid(node):
    """
    Generate a unique name from a pytest request node object.
    """
    return '_'.join((node.module.__name__, node.cls.__name__ if node.cls else '', node.name))

@pytest.fixture(autouse=True)
def bcrypt():
    """
    Mock out bcrypt password hashing to avoid unnecessary testing bottlenecks.
    """
    with mock.patch('bcrypt.hashpw') as hashpw:
        hashpw.side_effect = lambda x, y: x
        yield hashpw

@pytest.fixture
def db(request):
    """
    Require a Mongo test database.

    Provides a Mongo test database named after the requesting test function. Mongo databases are
    created/destroyed based on the URI provided with the --mongo-uri option and tear-down
    behavior is modified by the --keep-db option.
    """
    from girder.models import _dbClients, getDbConnection, pymongo
    from girder.models import model_base
    from girder.external import mongodb_proxy

    mockDb = request.config.getoption('--mock-db')
    dbUri = request.config.getoption('--mongo-uri')
    dbName = 'girder_test_%s' % hashlib.md5(_uid(request.node).encode('utf8')).hexdigest()
    keepDb = request.config.getoption('--keep-db')
    executable_methods = mongodb_proxy.EXECUTABLE_MONGO_METHODS
    realMongoClient = pymongo.MongoClient

    if mockDb:
        mongodb_proxy.EXECUTABLE_MONGO_METHODS = set()
        pymongo.MongoClient = mongomock.MongoClient

    connection = getDbConnection(uri='%s/%s' % (dbUri, dbName), quiet=False)

    # Force getDbConnection from models to return our connection
    _dbClients[(None, None)] = connection

    connection.drop_database(dbName)

    # Since models store a local reference to the current database, we need to force them all to
    # reconnect
    for model in model_base._modelSingletons:
        model.reconnect()

    yield connection

    if not keepDb:
        connection.drop_database(dbName)

    connection.close()

    if mockDb:
        mongodb_proxy.EXECUTABLE_MONGO_METHODS = executable_methods
        pymongo.MongoClient = realMongoClient

@pytest.fixture
def server(db, request):
    """
    Require a CherryPy embedded server.

    Provides a started CherryPy embedded server with a request method for performing
    local requests against it. Note: this fixture requires the db fixture.
    """
    # The event daemon cannot be restarted since it is a threading.Thread object, however
    # all references to girder.events.daemon are a singular global daemon due to its side
    # effect on import. We have to hack around this by creating a unique event daemon
    # each time we startup the server and assigning it to the global.
    import girder.events
    from girder.api import docs
    from girder.constants import SettingKey
    from girder.models.setting import Setting
    from girder.utility.server import setup as setupServer

    girder.events.daemon = girder.events.AsyncEventsThread()

    enabledPlugins = []
    hasPluginMarkers = request.node.get_marker('plugin') is not None
    pluginRegistry = PluginRegistry()

    with pluginRegistry():
        if hasPluginMarkers:
            for pluginMarker in request.node.iter_markers('plugin'):
                pluginName = pluginMarker.args[0]
                shouldEnable = pluginMarker.kwargs.pop('enabled', True)
                if len(pluginMarker.args) > 1:
                    pluginRegistry.registerTestPlugin(
                        *pluginMarker.args, **pluginMarker.kwargs
                    )
                if shouldEnable:
                    enabledPlugins.append(pluginName)

        Setting().set(SettingKey.PLUGINS_ENABLED, enabledPlugins)

        server = setupServer(test=True, plugins=enabledPlugins)
        server.request = restRequest
        server.uploadFile = uploadFile

        cherrypy.server.unsubscribe()
        cherrypy.config.update({'environment': 'embedded',
                                'log.screen': False,
                                'request.throw_errors': True})
        cherrypy.engine.start()

        yield server

        cherrypy.engine.unsubscribe('start', girder.events.daemon.start)
        cherrypy.engine.unsubscribe('stop', girder.events.daemon.stop)
        cherrypy.engine.stop()
        cherrypy.engine.exit()
        cherrypy.tree.apps = {}
        docs.routes.clear()

@pytest.fixture
def smtp(db, server):
    """
    Provides a mock SMTP server for testing.
    """
    # TODO strictly speaking, this does not depend on the server itself, but does
    # depend on the events daemon, which is currently managed by the server fixture.
    # We should sort this out so that the daemon is its own fixture rather than being
    # started/stopped via the cherrypy server lifecycle.
    from girder.constants import SettingKey
    from girder.models.setting import Setting

    receiver = MockSmtpReceiver()
    receiver.start()

    host, port = receiver.address
    Setting().set(SettingKey.SMTP_HOST, host)
    Setting().set(SettingKey.SMTP_PORT, port)

    yield receiver

    receiver.stop()

@pytest.fixture
def admin(db):
    """
    Require an admin user.

    Provides a user with the admin flag set to True.
    """
    from girder.models.user import User
    u = User().createUser(email='admin@email.com', login='admin', firstName='Admin',
                          lastName='Admin', password='password', admin=True)

    yield u

@pytest.fixture
def user(db, admin):
    """
    Require a user.

    Provides a regular user with no additional privileges. Note this fixture requires
    the admin fixture since an administrative user must exist before a regular user can.
    """
    from girder.models.user import User
    u = User().createUser(email='user@email.com', login='user', firstName='user',
                          lastName='user', password='password', admin=False)

    yield u

@pytest.fixture
def fsAssetstore(db, request):
    """
    Require a filesystem assetstore. Its location will be derived from the test function name.
    """
    from girder.constants import ROOT_DIR
    from girder.models.assetstore import Assetstore

    name = _uid(request.node)
    path = os.path.join(ROOT_DIR, 'tests', 'assetstore', name)

    if os.path.isdir(path):
        shutil.rmtree(path)

    yield Assetstore().createFilesystemAssetstore(name=name, root=path)

    if os.path.isdir(path):
        shutil.rmtree(path)

__all__ = ('admin', 'bcrypt', 'db', 'fsAssetstore', 'server', 'user', 'smtp')


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use common\modules\users\models\User;
use common\helpers\ThumbHelper;

$role = current(Yii::$app->getAuthManager()->getRolesByUser($model->id));
if($role) {
    $model->role = $role->name;
}
?>

        <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

                <?= $form->field($model, 'first_name')->textInput() ?>
                <?= $form->field($model, 'last_name')->textInput() ?>

                <?= $form->field($model, 'username')->textInput() ?>
                <?= $form->field($model, 'email')->textInput() ?>

                <?= $form->field($model, 'role')->widget(Select2::classname(), [
                    'data' => User::getRolesList(),
                    'language' => 'en',
                    'options' => ['placeholder' => 'Select a role ...'],
                    'pluginOptions' => [
                        'allowClear' => true
                    ],
                ]); ?>

                <?= $form->field($model, 'password')->passwordInput() ?>

                        <?= $form->field($model, 'photoFile')->fileInput() ?>

                        <?= ThumbHelper::getImg($model->avatar, 100, 100, ['class' => 'pull-right'])?>

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

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


text:
mvn clean install docker:build
docker push $DOCKER_REGISTRY/quickstart/java-camel-spring:2.0-SNAPSHOT
mvn fabric8:run


text:
var _ = require('lodash');
var utils = require('./utils');

var VALUE = 'v';
var UPDATE_TIME = 't';

var DEFAULT_OPTIONS = {
  ttl: 5 * 60 * 1000, // In millisecond
};

/**
 *
 * @param options
 * @param {Number}   options.ttl    缓存时间
 * @param {Function} options.logger (Optional)
 * @constructor
 */
function PTStore(options) {
  this.options = _.merge(DEFAULT_OPTIONS, options);
}

PTStore.prototype.set = function(req, key, value, callback) {
  var logger = utils.getLogger(req, this.options);
  if (!req.session.ptStorage) req.session.ptStorage = {};

  // If this key exist, overwrite directly
  req.session.ptStorage[key] = {};
  req.session.ptStorage[key][VALUE] = value;
  req.session.ptStorage[key][UPDATE_TIME] = Date.now();

  req.session.save(function(err) {
    if (err) {
      logger.error('Error when trying to cache pt in session.');
      logger.error(err);
      return callback(err);
    }

    logger.info('Store pt for cache succeed, service: ' + key + ', pt: ' + value);

    callback();
  });
};

PTStore.prototype.get = function(req, key, callback) {
  var logger = utils.getLogger(req, this.options);
  if (!req.session.ptStorage) req.session.ptStorage = {};

  var ptData = req.session.ptStorage[key];
  if (ptData) {
    var updateTime = ptData[UPDATE_TIME];
    var value = ptData[VALUE];

    logger.info('Find PT from cache', ptData);
    logger.info('Current ttl is ' + this.options.ttl + ', start checking validation.');

    if (Date.now() - updateTime > this.options.ttl) {
      logger.info('Find PT from cache, but it is expired!');

      return this.remove(req, key, callback);
    }

    logger.info('Find PT from cache for service: ' + key + ', pt: ' + value);

    // PT still valid
    callback(null, value);
  } else {
    callback(null);
  }
};

PTStore.prototype.remove = function(req, key, callback) {
  var logger = utils.getLogger(req, this.options);
  if (!req.session.ptStorage) req.session.ptStorage = {};
  if (!req.session.ptStorage[key]) {
    logger.info('Trying to remove PT for service: ' + key + ', but it don\' exist!');
    return callback(null);
  }

  delete req.session.ptStorage[key];
  req.session.save(function(err) {
    if (err) {
      logger.error('Error when deleting pt');
      logger.error(err);
      return callback(err);
    }

    logger.info('Delete PT from cache succeed!');
    callback(null);
  });
};

PTStore.prototype.clear = function(req, callback) {
  if (!req.session.ptStorage) return callback(null);

  req.session.ptStorage = {};
  req.session.save(function(err) {
    if (err) return callback(err);
    callback(null);
  });
};

module.exports = PTStore;


text:
{%- comment -%}
This file can be used to fix the HTML produced by Jekyll for highlighted
code with line numbers.

It works with `{% highlight some_language linenos %}...{% endhighlight %}`
and with the Kramdown option to add line numbers to fenced code.

The implementation was derived from the workaround provided by
Dmitry Hrabrov (DeXP) at
https://github.com/penibelst/jekyll-compress-html/issues/71#issuecomment-188144901

EXPLANATION

The HTML produced by Rouge highlighting with lie numbers is of the form
`code table`. Jekyll (<= 4.1.1) always wraps the highlighted HTML
with `pre`. This wrapping is not only unnecessary, but also transforms
the conforming HTML produced by Rouge to non-conforming HTML, which
results in HTML validation error reports.

The fix removes the outer `pre` tags whenever they contain the pattern
`<table class="rouge-table">`.

Apart from avoiding HTML validation errors, the fix allows the use of
the [Jekyll layout for compressing HTML](http://jch.penibelst.de),
which relies on `pre` tags not being nested, according to
https://github.com/penibelst/jekyll-compress-html/issues/71#issuecomment-172069842

USAGE

(Any names can be used for `some_var` and `some_language`.)

{% capture some_var %}
{% highlight some_language linenos %}
Some code
{% endhighlight %}
{% endcapture %}
{% include fix_linenos.html code=some_var %}

For code fences:

{% capture some_var %}
```some_language
Some code
```
{% endcapture %}
{% assign some_var = some_var | markdownify %}
{% include fix_linenos.html code=some_var %}

CAVEATS

The above does not work when `Some code` happens to contain the matched string
`<table class="rouge-table">`.

The use of this file overwrites the variable `fix_linenos_code` with `nil`.

{%- endcomment -%}

{% assign fix_linenos_code = include.code %}
{% if fix_linenos_code contains '
' %}
  {% assign fix_linenos_code = fix_linenos_code | replace: '
', '
' %}
  {% assign fix_linenos_code = fix_linenos_code | replace: "
<code", "<code" %}
  {% assign fix_linenos_code = fix_linenos_code | replace: "
", "" %}
{% endif %}
{{ fix_linenos_code }}
{% assign fix_linenos_code = nil %}


text:
/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/utility.h"
#include "magick/version-private.h"

/*
  Forward declarations.
*/
static MagickBooleanType
  WriteMPCImage(const ImageInfo *,Image *);

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I s M P C                                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  IsMPC() returns MagickTrue if the image format type, identified by the
%  magick string, is an Magick Persistent Cache image.
%
%  The format of the IsMPC method is:
%
%      MagickBooleanType IsMPC(const unsigned char *magick,const size_t length)
%
%  A description of each parameter follows:
%
%    o magick: compare image format pattern against these bytes.
%
%    o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsMPC(const unsigned char *magick,const size_t length)
{
  if (length < 14)
    return(MagickFalse);
  if (LocaleNCompare((const char *) magick,"id=MagickCache",14) == 0)
    return(MagickTrue);
  return(MagickFalse);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d C A C H E I m a g e                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadMPCImage() reads an Magick Persistent Cache image file and returns
%  it.  It allocates the memory necessary for the new Image structure and
%  returns a pointer to the new image.
%
%  The format of the ReadMPCImage method is:
%
%      Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  Decompression code contributed by Kyle Shorter.
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    cache_filename[MaxTextExtent],
    id[MaxTextExtent],
    keyword[MaxTextExtent],
    *options;

  const unsigned char
    *p;

  GeometryInfo
    geometry_info;

  Image
    *image;

  int
    c;

  LinkedListInfo
    *profiles;

  MagickBooleanType
    status;

  MagickOffsetType
    offset;

  MagickStatusType
    flags;

  register ssize_t
    i;

  size_t
    depth,
    length;

  ssize_t
    count;

  StringInfo
    *profile;

  unsigned int
    signature;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
  AppendImageFormat("cache",cache_filename);
  c=ReadBlobByte(image);
  if (c == EOF)
    {
      image=DestroyImage(image);
      return((Image *) NULL);
    }
  *id='\0';
  (void) ResetMagickMemory(keyword,0,sizeof(keyword));
  offset=0;
  do
  {
    /*
      Decode image header;  header terminates one character beyond a ':'.
    */
    profiles=(LinkedListInfo *) NULL;
    length=MaxTextExtent;
    options=AcquireString((char *) NULL);
    signature=GetMagickSignature((const StringInfo *) NULL);
    image->depth=8;
    image->compression=NoCompression;
    while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
    {
      register char
        *p;

      if (c == (int) '{')
        {
          char
            *comment;

          /*
            Read comment-- any text between { }.
          */
          length=MaxTextExtent;
          comment=AcquireString((char *) NULL);
          for (p=comment; comment != (char *) NULL; p++)
          {
            c=ReadBlobByte(image);
            if (c == (int) '\\')
              c=ReadBlobByte(image);
            else
              if ((c == EOF) || (c == (int) '}'))
                break;
            if ((size_t) (p-comment+1) >= length)
              {
                *p='\0';
                length<<=1;
                comment=(char *) ResizeQuantumMemory(comment,length+
                  MaxTextExtent,sizeof(*comment));
                if (comment == (char *) NULL)
                  break;
                p=comment+strlen(comment);
              }
            *p=(char) c;
          }
          if (comment == (char *) NULL)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          *p='\0';
          (void) SetImageProperty(image,"comment",comment);
          comment=DestroyString(comment);
          c=ReadBlobByte(image);
        }
      else
        if (isalnum(c) != MagickFalse)
          {
            /*
              Get the keyword.
            */
            length=MaxTextExtent;
            p=keyword;
            do
            {
              if (c == (int) '=')
                break;
              if ((size_t) (p-keyword) < (MaxTextExtent-1))
                *p++=(char) c;
              c=ReadBlobByte(image);
            } while (c != EOF);
            *p='\0';
            p=options;
            while (isspace((int) ((unsigned char) c)) != 0)
              c=ReadBlobByte(image);
            if (c == (int) '=')
              {
                /*
                  Get the keyword value.
                */
                c=ReadBlobByte(image);
                while ((c != (int) '}') && (c != EOF))
                {
                  if ((size_t) (p-options+1) >= length)
                    {
                      *p='\0';
                      length<<=1;
                      options=(char *) ResizeQuantumMemory(options,length+
                        MaxTextExtent,sizeof(*options));
                      if (options == (char *) NULL)
                        break;
                      p=options+strlen(options);
                    }
                  *p++=(char) c;
                  c=ReadBlobByte(image);
                  if (c == '\\')
                    {
                      c=ReadBlobByte(image);
                      if (c == (int) '}')
                        {
                          *p++=(char) c;
                          c=ReadBlobByte(image);
                        }
                    }
                  if (*options != '{')
                    if (isspace((int) ((unsigned char) c)) != 0)
                      break;
                }
                if (options == (char *) NULL)
                  ThrowReaderException(ResourceLimitError,
                    "MemoryAllocationFailed");
              }
            *p='\0';
            if (*options == '{')
              (void) CopyMagickString(options,options+1,strlen(options));
            /*
              Assign a value to the specified keyword.
            */
            switch (*keyword)
            {
              case 'b':
              case 'B':
              {
                if (LocaleCompare(keyword,"background-color") == 0)
                  {
                    (void) QueryColorDatabase(options,&image->background_color,
                      exception);
                    break;
                  }
                if (LocaleCompare(keyword,"blue-primary") == 0)
                  {
                    flags=ParseGeometry(options,&geometry_info);
                    image->chromaticity.blue_primary.x=geometry_info.rho;
                    image->chromaticity.blue_primary.y=geometry_info.sigma;
                    if ((flags & SigmaValue) == 0)
                      image->chromaticity.blue_primary.y=
                        image->chromaticity.blue_primary.x;
                    break;
                  }
                if (LocaleCompare(keyword,"border-color") == 0)
                  {
                    (void) QueryColorDatabase(options,&image->border_color,
                      exception);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'c':
              case 'C':
              {
                if (LocaleCompare(keyword,"class") == 0)
                  {
                    ssize_t
                      storage_class;

                    storage_class=ParseCommandOption(MagickClassOptions,
                      MagickFalse,options);
                    if (storage_class < 0)
                      break;
                    image->storage_class=(ClassType) storage_class;
                    break;
                  }
                if (LocaleCompare(keyword,"colors") == 0)
                  {
                    image->colors=StringToUnsignedLong(options);
                    break;
                  }
                if (LocaleCompare(keyword,"colorspace") == 0)
                  {
                    ssize_t
                      colorspace;

                    colorspace=ParseCommandOption(MagickColorspaceOptions,
                      MagickFalse,options);
                    if (colorspace < 0)
                      break;
                    image->colorspace=(ColorspaceType) colorspace;
                    break;
                  }
                if (LocaleCompare(keyword,"compression") == 0)
                  {
                    ssize_t
                      compression;

                    compression=ParseCommandOption(MagickCompressOptions,
                      MagickFalse,options);
                    if (compression < 0)
                      break;
                    image->compression=(CompressionType) compression;
                    break;
                  }
                if (LocaleCompare(keyword,"columns") == 0)
                  {
                    image->columns=StringToUnsignedLong(options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'd':
              case 'D':
              {
                if (LocaleCompare(keyword,"delay") == 0)
                  {
                    image->delay=StringToUnsignedLong(options);
                    break;
                  }
                if (LocaleCompare(keyword,"depth") == 0)
                  {
                    image->depth=StringToUnsignedLong(options);
                    break;
                  }
                if (LocaleCompare(keyword,"dispose") == 0)
                  {
                    ssize_t
                      dispose;

                    dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
                      options);
                    if (dispose < 0)
                      break;
                    image->dispose=(DisposeType) dispose;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'e':
              case 'E':
              {
                if (LocaleCompare(keyword,"endian") == 0)
                  {
                    ssize_t
                      endian;

                    endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
                      options);
                    if (endian < 0)
                      break;
                    image->endian=(EndianType) endian;
                    break;
                  }
                if (LocaleCompare(keyword,"error") == 0)
                  {
                    image->error.mean_error_per_pixel=StringToDouble(options,
                      (char **) NULL);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'g':
              case 'G':
              {
                if (LocaleCompare(keyword,"gamma") == 0)
                  {
                    image->gamma=StringToDouble(options,(char **) NULL);
                    break;
                  }
                if (LocaleCompare(keyword,"green-primary") == 0)
                  {
                    flags=ParseGeometry(options,&geometry_info);
                    image->chromaticity.green_primary.x=geometry_info.rho;
                    image->chromaticity.green_primary.y=geometry_info.sigma;
                    if ((flags & SigmaValue) == 0)
                      image->chromaticity.green_primary.y=
                        image->chromaticity.green_primary.x;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'i':
              case 'I':
              {
                if (LocaleCompare(keyword,"id") == 0)
                  {
                    (void) CopyMagickString(id,options,MaxTextExtent);
                    break;
                  }
                if (LocaleCompare(keyword,"iterations") == 0)
                  {
                    image->iterations=StringToUnsignedLong(options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'm':
              case 'M':
              {
                if (LocaleCompare(keyword,"magick-signature") == 0)
                  {
                    signature=(unsigned int) StringToUnsignedLong(options);
                    break;
                  }
                if (LocaleCompare(keyword,"matte") == 0)
                  {
                    ssize_t
                      matte;

                    matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
                      options);
                    if (matte < 0)
                      break;
                    image->matte=(MagickBooleanType) matte;
                    break;
                  }
                if (LocaleCompare(keyword,"matte-color") == 0)
                  {
                    (void) QueryColorDatabase(options,&image->matte_color,
                      exception);
                    break;
                  }
                if (LocaleCompare(keyword,"maximum-error") == 0)
                  {
                    image->error.normalized_maximum_error=StringToDouble(
                      options,(char **) NULL);
                    break;
                  }
                if (LocaleCompare(keyword,"mean-error") == 0)
                  {
                    image->error.normalized_mean_error=StringToDouble(options,
                      (char **) NULL);
                    break;
                  }
                if (LocaleCompare(keyword,"montage") == 0)
                  {
                    (void) CloneString(&image->montage,options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'o':
              case 'O':
              {
                if (LocaleCompare(keyword,"opaque") == 0)
                  {
                    ssize_t
                      matte;

                    matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
                      options);
                    if (matte < 0)
                      break;
                    image->matte=(MagickBooleanType) matte;
                    break;
                  }
                if (LocaleCompare(keyword,"orientation") == 0)
                  {
                    ssize_t
                      orientation;

                    orientation=ParseCommandOption(MagickOrientationOptions,
                      MagickFalse,options);
                    if (orientation < 0)
                      break;
                    image->orientation=(OrientationType) orientation;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'p':
              case 'P':
              {
                if (LocaleCompare(keyword,"page") == 0)
                  {
                    char
                      *geometry;

                    geometry=GetPageGeometry(options);
                    (void) ParseAbsoluteGeometry(geometry,&image->page);
                    geometry=DestroyString(geometry);
                    break;
                  }
                if (LocaleCompare(keyword,"pixel-intensity") == 0)
                  {
                    ssize_t
                      intensity;

                    intensity=ParseCommandOption(MagickPixelIntensityOptions,
                      MagickFalse,options);
                    if (intensity < 0)
                      break;
                    image->intensity=(PixelIntensityMethod) intensity;
                    break;
                  }
                if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
                    (LocaleNCompare(keyword,"profile-",8) == 0))
                  {
                    if (profiles == (LinkedListInfo *) NULL)
                      profiles=NewLinkedList(0);
                    (void) AppendValueToLinkedList(profiles,
                      AcquireString(keyword+8));
                    profile=BlobToStringInfo((const void *) NULL,(size_t)
                      StringToLong(options));
                    if (profile == (StringInfo *) NULL)
                      ThrowReaderException(ResourceLimitError,
                        "MemoryAllocationFailed");
                    (void) SetImageProfile(image,keyword+8,profile);
                    profile=DestroyStringInfo(profile);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'q':
              case 'Q':
              {
                if (LocaleCompare(keyword,"quality") == 0)
                  {
                    image->quality=StringToUnsignedLong(options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'r':
              case 'R':
              {
                if (LocaleCompare(keyword,"red-primary") == 0)
                  {
                    flags=ParseGeometry(options,&geometry_info);
                    image->chromaticity.red_primary.x=geometry_info.rho;
                    if ((flags & SigmaValue) != 0)
                      image->chromaticity.red_primary.y=geometry_info.sigma;
                    break;
                  }
                if (LocaleCompare(keyword,"rendering-intent") == 0)
                  {
                    ssize_t
                      rendering_intent;

                    rendering_intent=ParseCommandOption(MagickIntentOptions,
                      MagickFalse,options);
                    if (rendering_intent < 0)
                      break;
                    image->rendering_intent=(RenderingIntent) rendering_intent;
                    break;
                  }
                if (LocaleCompare(keyword,"resolution") == 0)
                  {
                    flags=ParseGeometry(options,&geometry_info);
                    image->x_resolution=geometry_info.rho;
                    image->y_resolution=geometry_info.sigma;
                    if ((flags & SigmaValue) == 0)
                      image->y_resolution=image->x_resolution;
                    break;
                  }
                if (LocaleCompare(keyword,"rows") == 0)
                  {
                    image->rows=StringToUnsignedLong(options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 's':
              case 'S':
              {
                if (LocaleCompare(keyword,"scene") == 0)
                  {
                    image->scene=StringToUnsignedLong(options);
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 't':
              case 'T':
              {
                if (LocaleCompare(keyword,"ticks-per-second") == 0)
                  {
                    image->ticks_per_second=(ssize_t) StringToLong(options);
                    break;
                  }
                if (LocaleCompare(keyword,"tile-offset") == 0)
                  {
                    char
                      *geometry;

                    geometry=GetPageGeometry(options);
                    (void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
                    geometry=DestroyString(geometry);
                  }
                if (LocaleCompare(keyword,"type") == 0)
                  {
                    ssize_t
                      type;

                    type=ParseCommandOption(MagickTypeOptions,MagickFalse,
                      options);
                    if (type < 0)
                      break;
                    image->type=(ImageType) type;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'u':
              case 'U':
              {
                if (LocaleCompare(keyword,"units") == 0)
                  {
                    ssize_t
                      units;

                    units=ParseCommandOption(MagickResolutionOptions,MagickFalse,
                      options);
                    if (units < 0)
                      break;
                    image->units=(ResolutionType) units;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              case 'w':
              case 'W':
              {
                if (LocaleCompare(keyword,"white-point") == 0)
                  {
                    flags=ParseGeometry(options,&geometry_info);
                    image->chromaticity.white_point.x=geometry_info.rho;
                    image->chromaticity.white_point.y=geometry_info.sigma;
                    if ((flags & SigmaValue) == 0)
                      image->chromaticity.white_point.y=
                        image->chromaticity.white_point.x;
                    break;
                  }
                (void) SetImageProperty(image,keyword,options);
                break;
              }
              default:
              {
                (void) SetImageProperty(image,keyword,options);
                break;
              }
            }
          }
        else
          c=ReadBlobByte(image);
      while (isspace((int) ((unsigned char) c)) != 0)
        c=ReadBlobByte(image);
    }
    options=DestroyString(options);
    (void) ReadBlobByte(image);
    /*
      Verify that required image information is defined.
    */
    if ((LocaleCompare(id,"MagickCache") != 0) ||
        (image->storage_class == UndefinedClass) ||
        (image->compression == UndefinedCompression) || (image->columns == 0) ||
        (image->rows == 0))
      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
    if (signature != GetMagickSignature((const StringInfo *) NULL))
      ThrowReaderException(CacheError,"IncompatibleAPI");
    if (image->montage != (char *) NULL)
      {
        register char
          *p;

        /*
          Image directory.
        */
        length=MaxTextExtent;
        image->directory=AcquireString((char *) NULL);
        p=image->directory;
        do
        {
          *p='\0';
          if ((strlen(image->directory)+MaxTextExtent) >= length)
            {
              /*
                Allocate more memory for the image directory.
              */
              length<<=1;
              image->directory=(char *) ResizeQuantumMemory(image->directory,
                length+MaxTextExtent,sizeof(*image->directory));
              if (image->directory == (char *) NULL)
                ThrowReaderException(CorruptImageError,"UnableToReadImageData");
              p=image->directory+strlen(image->directory);
            }
          c=ReadBlobByte(image);
          *p++=(char) c;
        } while (c != (int) '\0');
      }
    if (profiles != (LinkedListInfo *) NULL)
      {
        const char
          *name;

        const StringInfo
          *profile;

        register unsigned char
          *p;

        /*
          Read image profiles.
        */
        ResetLinkedListIterator(profiles);
        name=(const char *) GetNextValueInLinkedList(profiles);
        while (name != (const char *) NULL)
        {
          profile=GetImageProfile(image,name);
          if (profile != (StringInfo *) NULL)
            {
              p=GetStringInfoDatum(profile);
              count=ReadBlob(image,GetStringInfoLength(profile),p);
            }
          name=(const char *) GetNextValueInLinkedList(profiles);
        }
        profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
      }
    depth=GetImageQuantumDepth(image,MagickFalse);
    if (image->storage_class == PseudoClass)
      {
        /*
          Create image colormap.
        */
        if (AcquireImageColormap(image,image->colors) == MagickFalse)
          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
        if (image->colors != 0)
          {
            size_t
              packet_size;

            unsigned char
              *colormap;

            /*
              Read image colormap from file.
            */
            packet_size=(size_t) (3UL*depth/8UL);
            colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
              packet_size*sizeof(*colormap));
            if (colormap == (unsigned char *) NULL)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            count=ReadBlob(image,packet_size*image->colors,colormap);
            if (count != (ssize_t) (packet_size*image->colors))
              ThrowReaderException(CorruptImageError,
                "InsufficientImageDataInFile");
            p=colormap;
            switch (depth)
            {
              default:
                ThrowReaderException(CorruptImageError,
                  "ImageDepthNotSupported");
              case 8:
              {
                unsigned char
                  pixel;

                for (i=0; i < (ssize_t) image->colors; i++)
                {
                  p=PushCharPixel(p,&pixel);
                  image->colormap[i].red=ScaleCharToQuantum(pixel);
                  p=PushCharPixel(p,&pixel);
                  image->colormap[i].green=ScaleCharToQuantum(pixel);
                  p=PushCharPixel(p,&pixel);
                  image->colormap[i].blue=ScaleCharToQuantum(pixel);
                }
                break;
              }
              case 16:
              {
                unsigned short
                  pixel;

                for (i=0; i < (ssize_t) image->colors; i++)
                {
                  p=PushShortPixel(MSBEndian,p,&pixel);
                  image->colormap[i].red=ScaleShortToQuantum(pixel);
                  p=PushShortPixel(MSBEndian,p,&pixel);
                  image->colormap[i].green=ScaleShortToQuantum(pixel);
                  p=PushShortPixel(MSBEndian,p,&pixel);
                  image->colormap[i].blue=ScaleShortToQuantum(pixel);
                }
                break;
              }
              case 32:
              {
                unsigned int
                  pixel;

                for (i=0; i < (ssize_t) image->colors; i++)
                {
                  p=PushLongPixel(MSBEndian,p,&pixel);
                  image->colormap[i].red=ScaleLongToQuantum(pixel);
                  p=PushLongPixel(MSBEndian,p,&pixel);
                  image->colormap[i].green=ScaleLongToQuantum(pixel);
                  p=PushLongPixel(MSBEndian,p,&pixel);
                  image->colormap[i].blue=ScaleLongToQuantum(pixel);
                }
                break;
              }
            }
            colormap=(unsigned char *) RelinquishMagickMemory(colormap);
          }
      }
    if (EOFBlob(image) != MagickFalse)
      {
        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
          image->filename);
        break;
      }
    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageExtent(image,image->columns,image->rows);
    if (status == MagickFalse)
      {
        InheritException(exception,&image->exception);
        return(DestroyImageList(image));
      }
    /*
      Attach persistent pixel cache.
    */
    status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
    if (status == MagickFalse)
      ThrowReaderException(CacheError,"UnableToPersistPixelCache");
    /*
      Proceed to next image.
    */
    do
    {
      c=ReadBlobByte(image);
    } while ((isgraph(c) == MagickFalse) && (c != EOF));
    if (c != EOF)
      {
        /*
          Allocate next image structure.
        */
        AcquireNextImage(image_info,image);
        if (GetNextImageInList(image) == (Image *) NULL)
          {
            image=DestroyImageList(image);
            return((Image *) NULL);
          }
        image=SyncNextImageInList(image);
        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
          GetBlobSize(image));
        if (status == MagickFalse)
          break;
      }
  } while (c != EOF);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r M P C I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterMPCImage() adds properties for the Cache image format to
%  the list of supported formats.  The properties include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterMPCImage method is:
%
%      size_t RegisterMPCImage(void)
%
*/
ModuleExport size_t RegisterMPCImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("CACHE");
  entry->description=ConstantString("Magick Persistent Cache image format");
  entry->module=ConstantString("CACHE");
  entry->stealth=MagickTrue;
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("MPC");
  entry->decoder=(DecodeImageHandler *) ReadMPCImage;
  entry->encoder=(EncodeImageHandler *) WriteMPCImage;
  entry->magick=(IsImageFormatHandler *) IsMPC;
  entry->description=ConstantString("Magick Persistent Cache image format");
  entry->module=ConstantString("MPC");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r M P C I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterMPCImage() removes format registrations made by the
%  MPC module from the list of supported formats.
%
%  The format of the UnregisterMPCImage method is:
%
%      UnregisterMPCImage(void)
%
*/
ModuleExport void UnregisterMPCImage(void)
{
  (void) UnregisterMagickInfo("CACHE");
  (void) UnregisterMagickInfo("MPC");
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e M P C I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WriteMPCImage() writes an Magick Persistent Cache image to a file.
%
%  The format of the WriteMPCImage method is:
%
%      MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o image: the image.
%
*/
static MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image)
{
  char
    buffer[MaxTextExtent],
    cache_filename[MaxTextExtent];

  const char
    *property,
    *value;

  MagickBooleanType
    status;

  MagickOffsetType
    offset,
    scene;

  register ssize_t
    i;

  size_t
    depth,
    one;

  /*
    Open persistent cache.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFalse)
    return(status);
  (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
  AppendImageFormat("cache",cache_filename);
  scene=0;
  offset=0;
  one=1;
  do
  {
    /*
      Write persistent cache meta-information.
    */
    depth=GetImageQuantumDepth(image,MagickTrue);
    if ((image->storage_class == PseudoClass) &&
        (image->colors > (one << depth)))
      image->storage_class=DirectClass;
    (void) WriteBlobString(image,"id=MagickCache\n");
    (void) FormatLocaleString(buffer,MaxTextExtent,"magick-signature=%u\n",
      GetMagickSignature((const StringInfo *) NULL));
    (void) WriteBlobString(image,buffer);
    (void) FormatLocaleString(buffer,MaxTextExtent,
      "class=%s  colors=%.20g  matte=%s\n",CommandOptionToMnemonic(
      MagickClassOptions,image->storage_class),(double) image->colors,
      CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));
    (void) WriteBlobString(image,buffer);
    (void) FormatLocaleString(buffer,MaxTextExtent,
      "columns=%.20g  rows=%.20g depth=%.20g\n",(double) image->columns,
      (double) image->rows,(double) image->depth);
    (void) WriteBlobString(image,buffer);
    if (image->type != UndefinedType)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n",
          CommandOptionToMnemonic(MagickTypeOptions,image->type));
        (void) WriteBlobString(image,buffer);
      }
    if (image->colorspace != UndefinedColorspace)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n",
          CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace));
        (void) WriteBlobString(image,buffer);
      }
    if (image->intensity != UndefinedPixelIntensityMethod)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n",
          CommandOptionToMnemonic(MagickPixelIntensityOptions,
          image->intensity));
        (void) WriteBlobString(image,buffer);
      }
    if (image->endian != UndefinedEndian)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n",
          CommandOptionToMnemonic(MagickEndianOptions,image->endian));
        (void) WriteBlobString(image,buffer);
      }
    if (image->compression != UndefinedCompression)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "compression=%s  quality=%.20g\n",CommandOptionToMnemonic(
          MagickCompressOptions,image->compression),(double) image->quality);
        (void) WriteBlobString(image,buffer);
      }
    if (image->units != UndefinedResolution)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n",
          CommandOptionToMnemonic(MagickResolutionOptions,image->units));
        (void) WriteBlobString(image,buffer);
      }
    if ((image->x_resolution != 0) || (image->y_resolution != 0))
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "resolution=%gx%g\n",image->x_resolution,image->y_resolution);
        (void) WriteBlobString(image,buffer);
      }
    if ((image->page.width != 0) || (image->page.height != 0))
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double)
          image->page.height,(double) image->page.x,(double) image->page.y);
        (void) WriteBlobString(image,buffer);
      }
    else
      if ((image->page.x != 0) || (image->page.y != 0))
        {
          (void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n",
            (long) image->page.x,(long) image->page.y);
          (void) WriteBlobString(image,buffer);
        }
    if ((image->page.x != 0) || (image->page.y != 0))
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n",
          (long) image->tile_offset.x,(long) image->tile_offset.y);
        (void) WriteBlobString(image,buffer);
      }
    if ((GetNextImageInList(image) != (Image *) NULL) ||
        (GetPreviousImageInList(image) != (Image *) NULL))
      {
        if (image->scene == 0)
          (void) FormatLocaleString(buffer,MaxTextExtent,
            "iterations=%.20g  delay=%.20g  ticks-per-second=%.20g\n",(double)
            image->iterations,(double) image->delay,(double)
            image->ticks_per_second);
        else
          (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g  "
            "iterations=%.20g  delay=%.20g  ticks-per-second=%.20g\n",
            (double) image->scene,(double) image->iterations,(double)
            image->delay,(double) image->ticks_per_second);
        (void) WriteBlobString(image,buffer);
      }
    else
      {
        if (image->scene != 0)
          {
            (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n",
              (double) image->scene);
            (void) WriteBlobString(image,buffer);
          }
        if (image->iterations != 0)
          {
            (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n",
              (double) image->iterations);
            (void) WriteBlobString(image,buffer);
          }
        if (image->delay != 0)
          {
            (void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n",
              (double) image->delay);
            (void) WriteBlobString(image,buffer);
          }
        if (image->ticks_per_second != UndefinedTicksPerSecond)
          {
            (void) FormatLocaleString(buffer,MaxTextExtent,
              "ticks-per-second=%.20g\n",(double) image->ticks_per_second);
            (void) WriteBlobString(image,buffer);
          }
      }
    if (image->gravity != UndefinedGravity)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n",
          CommandOptionToMnemonic(MagickGravityOptions,image->gravity));
        (void) WriteBlobString(image,buffer);
      }
    if (image->dispose != UndefinedDispose)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n",
          CommandOptionToMnemonic(MagickDisposeOptions,image->dispose));
        (void) WriteBlobString(image,buffer);
      }
    if (image->rendering_intent != UndefinedIntent)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "rendering-intent=%s\n",CommandOptionToMnemonic(MagickIntentOptions,
          image->rendering_intent));
        (void) WriteBlobString(image,buffer);
      }
    if (image->gamma != 0.0)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n",
          image->gamma);
        (void) WriteBlobString(image,buffer);
      }
    if (image->chromaticity.white_point.x != 0.0)
      {
        /*
          Note chomaticity points.
        */
        (void) FormatLocaleString(buffer,MaxTextExtent,"red-primary="
          "%g,%g  green-primary=%g,%g  blue-primary=%g,%g\n",
          image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
          image->chromaticity.green_primary.x,
          image->chromaticity.green_primary.y,
          image->chromaticity.blue_primary.x,
          image->chromaticity.blue_primary.y);
        (void) WriteBlobString(image,buffer);
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "white-point=%g,%g\n",image->chromaticity.white_point.x,
          image->chromaticity.white_point.y);
        (void) WriteBlobString(image,buffer);
      }
    if (image->orientation != UndefinedOrientation)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,
          "orientation=%s\n",CommandOptionToMnemonic(MagickOrientationOptions,
          image->orientation));
        (void) WriteBlobString(image,buffer);
      }
    if (image->profiles != (void *) NULL)
      {
        const char
          *name;

        const StringInfo
          *profile;

        /*
          Generic profile.
        */
        ResetImageProfileIterator(image);
        for (name=GetNextImageProfile(image); name != (const char *) NULL; )
        {
          profile=GetImageProfile(image,name);
          if (profile != (StringInfo *) NULL)
            {
              (void) FormatLocaleString(buffer,MaxTextExtent,
                "profile:%s=%.20g\n",name,(double)
                GetStringInfoLength(profile));
              (void) WriteBlobString(image,buffer);
            }
          name=GetNextImageProfile(image);
        }
      }
    if (image->montage != (char *) NULL)
      {
        (void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n",
          image->montage);
        (void) WriteBlobString(image,buffer);
      }
    ResetImagePropertyIterator(image);
    property=GetNextImageProperty(image);
    while (property != (const char *) NULL)
    {
      (void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property);
      (void) WriteBlobString(image,buffer);
      value=GetImageProperty(image,property);
      if (value != (const char *) NULL)
        {
          size_t
            length;

          length=strlen(value);
          for (i=0; i < (ssize_t) length; i++)
            if (isspace((int) ((unsigned char) value[i])) != 0)
              break;
          if ((i == (ssize_t) length) && (i != 0))
            (void) WriteBlob(image,length,(const unsigned char *) value);
          else
            {
              (void) WriteBlobByte(image,'{');
              if (strchr(value,'}') == (char *) NULL)
                (void) WriteBlob(image,length,(const unsigned char *) value);
              else
                for (i=0; i < (ssize_t) length; i++)
                {
                  if (value[i] == (int) '}')
                    (void) WriteBlobByte(image,'\\');
                  (void) WriteBlobByte(image,value[i]);
                }
              (void) WriteBlobByte(image,'}');
            }
        }
      (void) WriteBlobByte(image,'\n');
      property=GetNextImageProperty(image);
    }
    (void) WriteBlobString(image,"\f\n:\032");
    if (image->montage != (char *) NULL)
      {
        /*
          Write montage tile directory.
        */
        if (image->directory != (char *) NULL)
          (void) WriteBlobString(image,image->directory);
        (void) WriteBlobByte(image,'\0');
      }
    if (image->profiles != 0)
      {
        const char
          *name;

        const StringInfo
          *profile;

        /*
          Write image profiles.
        */
        ResetImageProfileIterator(image);
        name=GetNextImageProfile(image);
        while (name != (const char *) NULL)
        {
          profile=GetImageProfile(image,name);
          (void) WriteBlob(image,GetStringInfoLength(profile),
            GetStringInfoDatum(profile));
          name=GetNextImageProfile(image);
        }
      }
    if (image->storage_class == PseudoClass)
      {
        size_t
          packet_size;

        unsigned char
          *colormap,
          *q;

        /*
          Allocate colormap.
        */
        packet_size=(size_t) (3UL*depth/8UL);
        colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
          packet_size*sizeof(*colormap));
        if (colormap == (unsigned char *) NULL)
          return(MagickFalse);
        /*
          Write colormap to file.
        */
        q=colormap;
        for (i=0; i < (ssize_t) image->colors; i++)
        {
          switch (depth)
          {
            default:
              ThrowWriterException(CorruptImageError,"ImageDepthNotSupported");
            case 32:
            {
              unsigned int
                pixel;

              pixel=ScaleQuantumToLong(image->colormap[i].red);
              q=PopLongPixel(MSBEndian,pixel,q);
              pixel=ScaleQuantumToLong(image->colormap[i].green);
              q=PopLongPixel(MSBEndian,pixel,q);
              pixel=ScaleQuantumToLong(image->colormap[i].blue);
              q=PopLongPixel(MSBEndian,pixel,q);
              break;
            }
            case 16:
            {
              unsigned short
                pixel;

              pixel=ScaleQuantumToShort(image->colormap[i].red);
              q=PopShortPixel(MSBEndian,pixel,q);
              pixel=ScaleQuantumToShort(image->colormap[i].green);
              q=PopShortPixel(MSBEndian,pixel,q);
              pixel=ScaleQuantumToShort(image->colormap[i].blue);
              q=PopShortPixel(MSBEndian,pixel,q);
              break;
            }
            case 8:
            {
              unsigned char
                pixel;

              pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
              q=PopCharPixel(pixel,q);
              pixel=(unsigned char) ScaleQuantumToChar(
                image->colormap[i].green);
              q=PopCharPixel(pixel,q);
              pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
              q=PopCharPixel(pixel,q);
              break;
            }
          }
        }
        (void) WriteBlob(image,packet_size*image->colors,colormap);
        colormap=(unsigned char *) RelinquishMagickMemory(colormap);
      }
    /*
      Initialize persistent pixel cache.
    */
    status=PersistPixelCache(image,cache_filename,MagickFalse,&offset,
      &image->exception);
    if (status == MagickFalse)
      ThrowWriterException(CacheError,"UnableToPersistPixelCache");
    if (GetNextImageInList(image) == (Image *) NULL)
      break;
    image=SyncNextImageInList(image);
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        status=image->progress_monitor(SaveImagesTag,scene,
          GetImageListLength(image),image->client_data);
        if (status == MagickFalse)
          break;
      }
    scene++;
  } while (image_info->adjoin != MagickFalse);
  (void) CloseBlob(image);
  return(status);
}


text:
MyUnity
=======

My Unity Project


text:
using System;
using System.ServiceModel;
using System.Xml.Serialization;

namespace WcfService
{
    public class WcfSoapService : IWcfSoapService
    {
        public string CombineStringXmlSerializerFormatSoap(string message1, string message2)
        {
            return message1 + message2;
        }

        public SoapComplexType EchoComositeTypeXmlSerializerFormatSoap(SoapComplexType complexObject)
        {
            return complexObject;
        }

        [return: MessageParameter(Name = "ProcessCustomerDataReturn"), SoapElement(DataType = "string")]
        public string ProcessCustomerData([MessageParameter(Name = "CustomerData")] CustomerObject customerData)
        {
            return customerData.Name + ((AdditionalData)customerData.Data).Field;
        }

        public PingEncodedResponse Ping(PingEncodedRequest request)
        {
            int requestIntValue;
            return new PingEncodedResponse() { @Return = Int32.TryParse(request.Pinginfo, out requestIntValue) ? requestIntValue : -1 };
        }
    }
}


text:
using System;
using System.Threading.Tasks;
using Consul.RsetApi.Client;
using FCP.Util;
using System.Linq;
using System.Net;

namespace FCP.Web.Cluster
{
    public class ConsulClusterProvider : IClusterProvider
    {
        private Uri _apiBaseUri;
        private int _checkInterval;

        #region 构造函数
        public ConsulClusterProvider()
            : this(ConsulConstants.DefaultApiBaseUri)
        { }

        public ConsulClusterProvider(Uri apiBaseUri)
            : this(apiBaseUri, ClusterConstants.DefaultCheckInterval)
        { }

        public ConsulClusterProvider(Uri apiBaseUri, int checkInterval)
        {
            _apiBaseUri = apiBaseUri ?? ConsulConstants.DefaultApiBaseUri;
            _checkInterval = checkInterval < 1 ? ClusterConstants.DefaultCheckInterval : checkInterval;
        }
        #endregion

        /// <summary>
        /// 根据名称获取服务Id
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns></returns>
        protected string getServiceIdByName(string serviceName)
        {
            if (string.IsNullOrEmpty(serviceName))
                return string.Empty;

            return string.Format("{0}_{1}", serviceName, Guid.NewGuid().ToString("N"));
        }

        /// <summary>
        /// 查询服务实例
        /// </summary>
        /// <param name="name">服务名称</param>
        /// <returns></returns>
        public async Task<ServiceInfo[]> findHealthServicesAsync(string name)
        {
            if (name.isNullOrEmpty())
                return null;

            using (var client = new ConsulRsetApiClient(_apiBaseUri))
            {
                var response = await client.healthServiceAsync(name, string.Empty, true).ConfigureAwait(false);

                if (response.ResponseData.isEmpty())
                    return null;

                return response.ResponseData.Select(m => new ServiceInfo
                    {
                        id = m.Service.ID,
                        name = m.Service.Service,
                        address = m.Service.Address,
                        port = m.Service.Port
                    }).ToArray();
            }
        }

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="address">地址</param>
        /// <param name="statusUrl">状态Url地址</param>
        /// <returns></returns>
        public async Task<string> registerServiceAsync(string name, Uri address, string statusUrl)
        {
            if (name.isNullOrEmpty() || address == null || statusUrl.isNullOrEmpty())
                return string.Empty;

            var registerInfo = new ConsulAgentServiceRegistration
            {
                ID = getServiceIdByName(name),
                Name = name,
                Tags = new[] { name },
                Address = address.Host,
                Port = address.Port,
                Check = new ConsulAgentServiceCheck
                {
                    HTTP = string.Format("{0}{1}", address, statusUrl),
                    Interval = string.Format("{0}s", _checkInterval)
                }
            };

            using (var client = new ConsulRsetApiClient(_apiBaseUri))
            {
                var response = await client.agentServiceRegisterAsync(registerInfo).ConfigureAwait(false);

                return response.StatusCode == HttpStatusCode.OK ? registerInfo.ID : string.Empty;
            }
        }

        /// <summary>
        /// 注销服务
        /// </summary>
        /// <param name="serviceId">服务Id</param>
        /// <returns></returns>
        public async Task<bool> deregisterServiceAsync(string serviceId)
        {
            if (serviceId.isNullOrEmpty())
                return false;

            using (var client = new ConsulRsetApiClient(_apiBaseUri))
            {
                var response = await client.agentServiceDeregisterAsync(serviceId).ConfigureAwait(false);

                return response.StatusCode == HttpStatusCode.OK;
            }
        }
    }
}


text:
This document describes the behaviour and syntax of free standing methods in eJass language.

# Table of contents

1. [Free Standing Method](#1-free-standing-method)
	1. [Syntax](#11-syntax)
		1. [White spaces](#111-white-spaces)

## 1. Free Standing Method
Free standing method provides a way for the script to extend [build-in types](../Type) with [struct](../Struct)-like syntax.

### 1.1 Syntax
```Jass
opt:(deprecated) opt:(inline) opt:(Visibility-Qualifier) opt:(Comp-Qualifier)
opt:(Const-Qualifier) method Type.method_name takes opt:(arguments)
returns opt:(Comp-Qualifier) opt:(Const-Qualifier) return_type
    Free-Standing_Method-Body
endmethod
```

Example:
```Jass
private method integer.increment takes nothing returns nothing
    set this++
endmethod
```

this variable always stores the object for running instance. Free standing methods may not be declared inside structs.
Rules other than mentioned above as well as white spacing of Free standing methods are the same as member [methods](../Struct).
If Free standing method is declared as private, it will only be usable inside that Scope.
Free standing method can not be declared as static, cannot be declared as stub or override and cannot be operator.

### 1.1.1 White spaces
```Jass
opt:(deprecated) opt:(inline) opt:(Visibility-Qualifier) opt:(Comp-Qualifier)
opt:(Const-Qualifier) method Type.method_name takes opt:(arguments)
returns opt:(Comp-Qualifier) opt:(Const-Qualifier) return_type
    Free-Standing_Method-Body
endmethod
```

1. Free-standing methods follow the exact same rules of white spacing as normal methods do, but Type, "." and method_name are all bound to each other tightly.


text:
var Route = require('routes-js').Route;
var IfBinder = require('fragments-built-ins/binders/if');

module.exports = function() {
  var routeBinder = IfBinder();
  var attached = routeBinder.attached;
  var unbound = routeBinder.unbound;
  var detached = routeBinder.detached;
  routeBinder.priority = 10,

  routeBinder.compiled = function() {
    var noRoute;
    this.app = this.fragments.app;
    this.routes = [];
    this.templates = [];
    this.expression = '';

    // each child with a [path] attribute will display only when its path matches the URL
    while (this.element.firstChild) {
      var child = this.element.firstChild;
      this.element.removeChild(child);

      if (child.nodeType !== Node.ELEMENT_NODE) {
        continue;
      }

      if (child.hasAttribute('[path]')) {
        var path = child.getAttribute('[path]');
        child.removeAttribute('[path]');
        this.routes.push(new Route(path));
        this.templates.push(this.fragments.createTemplate(child));
      } else if (child.hasAttribute('[noroute]')) {
        child.removeAttribute('[noroute]');
        noRoute = this.fragments.createTemplate(child);
      }
    }

    if (noRoute) {
      this.templates.push(noRoute);
    }
  };

  routeBinder.add = function(view) {
    view.bind(this.context);
    this.element.appendChild(view);
    this.attached();
  };

  routeBinder.created = function() {
    this.onUrlChange = this.onUrlChange.bind(this);
  };

  routeBinder.attached = function() {
    attached.call(this);

    var node = this.element.parentNode;
    while (node && !node.matchedRoutePath) {
      node = node.parentNode;
    }
    this.baseURI = node && node.matchedRoutePath || '';

    this.app.on('urlChange', this.onUrlChange);
    if (this.app.listening) {
      this.onUrlChange();
    }
  };

  routeBinder.detached = function() {
    detached.call(this);
    this.currentIndex = undefined;
    this.app.off('urlChange', this.onUrlChange);
  };

  routeBinder.unbound = function() {
    unbound.call(this);
    delete this.context.params;
  };

  routeBinder.onUrlChange = function() {
    if (!this.context) {
      return;
    }

    if (this.element.baseURI === null) {
      // element.baseURI is null if it isn't in the DOM yet
      // If this is just getting inserted into the DOM wait for this.baseURI to be set
      setTimeout(function() {
        if (!this.context) return;
        this.checkForChange();
      }.bind(this));
    } else {
      this.checkForChange();
    }
  };

  routeBinder.checkForChange = function() {
    var fullUrl = this.app.path;
    var localUrl = null;
    var newIndex = this.routes.length;
    var matched;
    delete this.context.params;

    if (fullUrl && fullUrl.indexOf(this.baseURI) === 0) {
      localUrl = fullUrl.replace(this.baseURI, '');
    }

    if (localUrl !== null) {

      matched = this.routes.some(function(route, index) {
        if (route.match(localUrl)) {
          if (route.params.hasOwnProperty('*') && route.params['*']) {
            var afterLength = route.params['*'].length;
            this.element.matchedRoutePath = this.baseURI + localUrl.slice(0, -afterLength);
          } else {
            this.element.matchedRoutePath = fullUrl;
          }
          var params = this.context.params = Object.create(route.params);
          var query = this.app.query;
          Object.keys(query).forEach(function(key) {
            if (!params.hasOwnProperty(key)) {
              params[key] = query[key];
            }
          });

          newIndex = index;
          return true;
        }
      }, this);
    }

    if (matched || newIndex !== this.currentIndex) {
      this.element.dispatchEvent(new Event('routed'));
    }

    if (newIndex !== this.currentIndex) {
      this.currentIndex = newIndex;
      this.updated(this.currentIndex);
    }
  };

  return routeBinder;
};


text:
/**
 *
 */
package com.gemstone.gemfire.internal.cache.tier.sockets.command;

import com.gemstone.gemfire.internal.cache.tier.Command;
import com.gemstone.gemfire.internal.cache.tier.MessageType;
import com.gemstone.gemfire.internal.cache.tier.sockets.*;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;

import java.io.IOException;

public class Invalid extends BaseCommand {

  private final static Invalid singleton = new Invalid();

  public static Command getCommand() {
    return singleton;
  }

  private Invalid() {
  }

  @Override
  public void cmdExecute(Message msg, ServerConnection servConn, long start)
      throws IOException {
    logger.error(LocalizedMessage.create(LocalizedStrings.Invalid_0_INVALID_MESSAGE_TYPE_WITH_TX_1_FROM_2, new Object[] {servConn.getName(), Integer.valueOf(msg.getTransactionId()), servConn.getSocketString()}));
    writeErrorResponse(msg, MessageType.INVALID, servConn);

  }

}


text:
layout: "journal_by_tag"
tag: "sourdough camp"
permalink: "/journal/tag/sourdough-camp/"
header-img: "img/misc-bg.jpg"
---


text:
import React from 'react';

/* usage
 import Msg from './ReactDialogBoxes';

 <Msg ref={msg => {this.msg = msg;}}/>

 this.msg.alert('header', 'text' [,'buttonText']).then(() => {
     // code
 });

 this.msg.confirm('header', 'text' [, 'okButtonText', 'cancelButtonText']).then(result => {
     // code
 });

 this.msg.prompt(
     text: '',
     [promptPlaceholder: '',]
     [okButtonText: '',]
     [cancelButtonText: '']
 ).then(result => {
        // code
 });

 this.msg.showLoader(['Text to show']); // default is "Loading..."
 this.msg.hideLoader();

 */

export default class ReactDialogBoxes extends React.Component {
    constructor (props) {
        super(props);

        this._defaultOkButtonText = 'Ok';
        this._defaultCancelButtonText = 'Cancel';
        this._defaultLoaderText = 'Loading...';

        this.state = {
            type: 'alert',  // other types: confirm, prompt, loader
            isVisible: false,
            messageText: 'Hello!',
            sendData: null,
            okButtonText: this._defaultOkButtonText,
            cancelButtonText: this._defaultCancelButtonText,
            promptValue: ''
        };

        this.alert = this.alert.bind(this);
        this.confirm = this.confirm.bind(this);
        this.prompt = this.prompt.bind(this);
        this._okHandler = this._okHandler.bind(this);
        this._cancelHandler = this._cancelHandler.bind(this);
        this._promptHandler = this._promptHandler.bind(this);
        this.showLoader = this.showLoader.bind(this);
        this.hideLoader = this.hideLoader.bind(this);
    }

    alert (text, okButtonText) {
        this.setState({
            type: 'alert',
            isVisible: true,
            messageText: text,
            okButtonText: okButtonText || this._defaultOkButtonText
        });

        return new Promise((res, rej) => {
                this.setState({
                sendData: res
            });
    });
    }

    confirm (text, okButtonText, cancelButtonText) {
        this.setState({
            type: 'confirm',
            isVisible: true,
            messageText: text,
            okButtonText: okButtonText || this._defaultOkButtonText,
            cancelButtonText: cancelButtonText || this._defaultCancelButtonText
        });

        return new Promise((res, rej) => {
                this.setState({
                sendData: res
            });
    });
    }

    prompt (
        text,
        okButtonText,
        cancelButtonText,
        promptPlaceholder
    ) {
        this.setState({
            type: 'prompt',
            isVisible: true,
            messageText: text,
            okButtonText: okButtonText || this._defaultOkButtonText,
            cancelButtonText: cancelButtonText || this._defaultCancelButtonText,
            promptPlaceholder: promptPlaceholder || ''
        });

        return new Promise((res, rej) => {
                this.setState({
                sendData: res
            });
    });
    }

    _okHandler () {
        this.setState({
            isVisible: false,
            okButtonText: this._defaultOkButtonText
        });
        if (this.state.type === 'prompt') {
            this.state.sendData(this.state.promptValue);
        } else {
            this.state.sendData(true);
        }
    }

    _cancelHandler () {
        this.setState({
            isVisible: false,
            okButtonText: this._defaultOkButtonText,
            cancelButtonText: this._defaultCancelButtonText
        });
        this.state.sendData(false);
    }

    _promptHandler (ev) {
        this.setState({
            promptValue: ev.target.value
        });
    }

    showLoader (loaderText) {
        this.setState({
            type: 'loader',
            isVisible: true,
            messageText: loaderText || this._defaultLoaderText
        });
    }

    hideLoader () {
        this.setState({
            type: 'loader',
            isVisible: false,
            messageText: ''
        });
    }

    _renderAlertButtons () {
        return (<button className="_okButton"
        onClick={this._okHandler}
    >
        {this.state.okButtonText}
    </button>);
    }

    _renderConfirmButtons () {
        return (

            <button className="_okButton"
        onClick={this._okHandler}
    >
        {this.state.okButtonText}
    </button>
        <button className="_cancelButton"
        onClick={this._cancelHandler}
    >
        {this.state.cancelButtonText}
    </button>

);
    }

    _renderPrompt () {
        return (

            <input type="text"
        className="_promptInput"
        placeholder={this.state.promptPlaceholder}
        onChange={this._promptHandler}
        value={this.promptValue}
    />

        <button className="_okButton"
        onClick={this._okHandler}
    >
        {this.state.okButtonText}
    </button>
        <button className="_cancelButton"
        onClick={this._cancelHandler}
    >
        {this.state.cancelButtonText}
    </button>

);
    }

    render () {
        return (

            {this.state.isVisible &&

                        {this.state.messageText &&

                                    {this.state.messageText}

                        }
                        {this.state.type === 'alert' &&
                            this._renderAlertButtons()
                        }

                        {this.state.type === 'confirm' &&
                            this._renderConfirmButtons()
                        }

                        {this.state.type === 'prompt' &&
                            this._renderPrompt()
                        }

            }

);
    }
}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.iluwatar</groupId>
    <artifactId>java-design-patterns</artifactId>
    <version>1.8.0-SNAPSHOT</version>
  </parent>
  <artifactId>caching</artifactId>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver</artifactId>
      <version>3.0.4</version>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-core</artifactId>
      <version>3.0.4</version>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>bson</artifactId>
      <version>3.0.4</version>
    </dependency>
  </dependencies>
  <!--
    Due to the use of MongoDB in the test of this pattern, TRAVIS and/or MAVEN might fail if the DB connection is
    not open for the JUnit test. To avoid disrupting the compilation process, the surefire plug-in was used
    to SKIP the running of the JUnit tests for this pattern. To ACTIVATE the running of the tests, change the
    skipTests (below) flag to 'false' and vice-versa.
  -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
          <skipTests>false</skipTests>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
using System;

namespace OrchardCore.Localization
{
    /// <summary>
    /// Represents an exception that is thrown when a pluralization form is not found.
    /// </summary>
    public class PluralFormNotFoundException : Exception
    {
        /// <summary>
        /// Creates new instance of <see cref="PluralFormNotFoundException"/>.
        /// </summary>
        public PluralFormNotFoundException()
        {

        }

        /// <summary>
        /// Creates new instance of <see cref="PluralFormNotFoundException"/> with a message.
        /// </summary>
        /// <param name="message">The exception message.</param>
        public PluralFormNotFoundException(string message) : base(message)
        {

        }

        /// <summary>
        /// Creates new instance of <see cref="PluralFormNotFoundException"/> with a message.
        /// </summary>
        /// <param name="message">The exception message.</param>
        /// <param name="key">The localized string that doesn't have plural form.</param>
        /// <param name="pluralForm">The <see cref="PluralForm"/> that causes the exception.</param>
        public PluralFormNotFoundException(string message, PluralForm form) : base(message)
        {
            Form = form;
        }

        /// <summary>
        /// Creates new instance of <see cref="PluralFormNotFoundException"/> with a message and inner exception.
        /// </summary>
        /// <param name="message">The exception message.</param>
        /// <param name="innerException">The inner <see cref="Exception"/>.</param>
        public PluralFormNotFoundException(string message, Exception innerException) : base(message, innerException)
        {

        }

        /// <summary>
        /// Gets the pluralization form.
        /// </summary>
        public PluralForm Form { get; }
    }
}