text:
package dao

import (
	"context"
	"time"

	"go-common/app/service/main/coin/conf"
	"go-common/app/service/main/coin/model"
	"go-common/library/cache/memcache"
	"go-common/library/cache/redis"
	"go-common/library/database/elastic"
	"go-common/library/database/sql"
	bm "go-common/library/net/http/blademaster"
	"go-common/library/queue/databus"
	"go-common/library/stat/prom"
	"go-common/library/sync/pipeline/fanout"
)

// Dao dao config.
type Dao struct {
	c *conf.Config
	// databus stat
	stat *databus.Databus
	// coin
	coin *sql.DB
	//http
	httpClient *bm.Client
	// databus
	dbBigData *databus.Databus
	// databus for coin-job
	dbCoinJob *databus.Databus
	// redis
	redis       *redis.Pool
	expireAdded int32
	expireExp   int32
	// tag url
	tagURI        string
	mc            *memcache.Pool
	mcExpire      int32
	cache         *fanout.Fanout
	Businesses    map[int64]*model.Business
	BusinessNames map[string]*model.Business
	es            *elastic.Elastic
}

// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		c:             c,
		coin:          sql.NewMySQL(c.DB.Coin),
		httpClient:    bm.NewClient(c.HTTPClient),
		tagURI:        c.TagURL,
		redis:         redis.NewPool(c.Redis.Config),
		mc:            memcache.NewPool(c.Memcache.Config),
		mcExpire:      int32(time.Duration(c.Memcache.Expire) / time.Second),
		expireExp:     int32(time.Duration(c.Memcache.ExpExpire) / time.Second),
		dbBigData:     databus.New(c.DbBigData),
		dbCoinJob:     databus.New(c.DbCoinJob),
		stat:          databus.New(c.Stat.Databus),
		expireAdded:   int32(time.Duration(c.Redis.Expire) / time.Second),
		cache:         fanout.New("cache", fanout.Buffer(10240)),
		Businesses:    make(map[int64]*model.Business),
		BusinessNames: make(map[string]*model.Business),
		es:            elastic.NewElastic(nil),
	}
	if len(c.Businesses) > 0 {
		for _, b := range c.Businesses {
			d.Businesses[b.ID] = b
			d.BusinessNames[b.Name] = b
		}
	}
	return
}

// PromError .
func PromError(name string) {
	prom.BusinessErrCount.Incr(name)
}

// Ping check service health.
func (dao *Dao) Ping(c context.Context) (err error) {
	return dao.coin.Ping(c)
}


text:
@implementation DTCoreTextParagraphStyle

+ (DTCoreTextParagraphStyle *)defaultParagraphStyle
{
    return [[[DTCoreTextParagraphStyle alloc] init] autorelease];
}

+ (DTCoreTextParagraphStyle *)paragraphStyleWithCTParagraphStyle:(CTParagraphStyleRef)ctParagraphStyle
{
	return [[[DTCoreTextParagraphStyle alloc] init] autorelease];
}

- (id)init
{
    self = [super init];

    if (self)
    {
        // defaults
        firstLineIndent = 0.0;
        defaultTabInterval = 36.0;
        writingDirection = kCTWritingDirectionNatural;
        textAlignment = kCTNaturalTextAlignment;
        lineHeightMultiple = 0.0;
        lineHeight = 0.0;
    }

    return self;
}

- (id)initWithCTParagraphStyle:(CTParagraphStyleRef)ctParagraphStyle
{
	self = [super init];

	if (self)
	{
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierAlignment,sizeof(textAlignment), &textAlignment);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(firstLineIndent), &firstLineIndent);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierDefaultTabInterval, sizeof(defaultTabInterval), &defaultTabInterval);

		NSArray *tabStops;
		if (CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierTabStops, sizeof(tabStops), &tabStops))
		{
			self.tabStops = tabStops;
		}
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierParagraphSpacing, sizeof(paragraphSpacing), &paragraphSpacing);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierParagraphSpacingBefore,sizeof(paragraphSpacingBefore), &paragraphSpacingBefore);

		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierHeadIndent, sizeof(headIndent), &headIndent);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(writingDirection), &writingDirection);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierLineHeightMultiple, sizeof(lineHeightMultiple), &lineHeightMultiple);

		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(lineHeight), &lineHeight);
		CTParagraphStyleGetValueForSpecifier(ctParagraphStyle, kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(lineHeight), &lineHeight);
	}

	return self;
}

- (void)dealloc
{
    [_tabStops release];

    [super dealloc];
}

- (CTParagraphStyleRef)createCTParagraphStyle
{
	CTParagraphStyleSetting settings[] =
    {
		{kCTParagraphStyleSpecifierAlignment, sizeof(textAlignment), &textAlignment},
		{kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(firstLineIndent), &firstLineIndent},
		{kCTParagraphStyleSpecifierDefaultTabInterval, sizeof(defaultTabInterval), &defaultTabInterval},

		{kCTParagraphStyleSpecifierTabStops, sizeof(_tabStops), &_tabStops},
		{kCTParagraphStyleSpecifierParagraphSpacing, sizeof(paragraphSpacing), &paragraphSpacing},
		{kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(paragraphSpacingBefore), &paragraphSpacingBefore},

		{kCTParagraphStyleSpecifierHeadIndent, sizeof(headIndent), &headIndent},
		{kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(writingDirection), &writingDirection},
        {kCTParagraphStyleSpecifierLineHeightMultiple, sizeof(lineHeightMultiple), &lineHeightMultiple},

		{kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(lineHeight), &lineHeight},
        {kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(lineHeight), &lineHeight}
	};

	return CTParagraphStyleCreate(settings, 11);
}

- (void)addTabStopAtPosition:(CGFloat)position alignment:(CTTextAlignment)alignment
{
    if (!_tabStops)
    {
        _tabStops = [[NSMutableArray alloc] init];
    }

    CTTextTabRef tab = CTTextTabCreate(alignment, position, NULL);
    [_tabStops addObject:(id)tab];
    CFRelease(tab);
}

#pragma mark Copying

- (id)copyWithZone:(NSZone *)zone
{
    DTCoreTextParagraphStyle *newObject = [[DTCoreTextParagraphStyle allocWithZone:zone] init];

    newObject.firstLineIndent = self.firstLineIndent;
    newObject.defaultTabInterval = self.defaultTabInterval;
    newObject.paragraphSpacing = self.paragraphSpacing;
    newObject.paragraphSpacingBefore = self.paragraphSpacingBefore;
    newObject.lineHeightMultiple = self.lineHeightMultiple;
    newObject.headIndent = self.headIndent;
    newObject.textAlignment = self.textAlignment;
    newObject.writingDirection = self.writingDirection;
    newObject.tabStops = self.tabStops; // copy

    return newObject;
}

#pragma mark Properties

- (void)setTabStops:(NSArray *)tabStops
{
	if (tabStops != _tabStops)
	{
		[_tabStops release];
		_tabStops = [tabStops mutableCopy]; // keep mutability
	}
}

@synthesize firstLineIndent;
@synthesize defaultTabInterval;
@synthesize paragraphSpacingBefore;
@synthesize paragraphSpacing;
@synthesize lineHeightMultiple;
@synthesize lineHeight;
@synthesize headIndent;
@synthesize textAlignment;
@synthesize writingDirection;
@synthesize tabStops = _tabStops;

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file sinais.h
 * @brief Estruturas e funções para manipulação de sinais de entrada e saída.
 */

#ifndef SINAIS_H

#define SINAIS_H

#define MAX_NOME_SINAL 50

/** @brief Valor lógico de um pulso. Aqui, nulo serve para indicar o fim de uma "string" de pulsos.
 */
typedef enum en_valor {
    zero = 0,
    um = 1,
    xis,
    nulo
} ValorLogico;

/** @brief Unidades de tempo disponíveis para a duração de um pulso.
        Na ordem, segundo, milisegundo, microsegundo, nanosegundo e picosegundo.
        O valor numérico é equivalente ao valor absoluto do módulo do expoente.
*/
typedef enum en_un_tempo {
    UN_S = 0,
    UN_MS = 3,
    UN_US = 6,
    UN_NS = 9,
    UN_PS = 12
} UnidTempo;

/** @brief O tipo das variáveis usadas na representação do tempo.
 */
typedef unsigned int Tempo;

/** @brief Um pulso de valor fixo e duração definida.
 */
typedef struct st_pulso {
    ValorLogico valor;
    Tempo tempo;
    UnidTempo unidade;
} Pulso;

/** @brief Um sinal contém um array de pulsos com o último pulso nulo. Semelhantemente a uma string.
 */
typedef struct st_sinal {
    char nome[MAX_NOME_SINAL];
    Pulso* pulsos;
    Tempo duracaoTotal;
} Sinal;

/** @brief Um conjunto de um ou mais sinais. Podem ser todos de entrada ou todos de saída.
 */
typedef struct st_sinais {
    int quantidade;
    Sinal* lista;
} Sinais;

/** @brief Inicializa um sinal vazio com um respectivo nome.
 */
Sinal* novoSinal(char *nome);

/** @brief Muda a string contendo o nome do sinal para a indicada.
 */
int setSinalNome(Sinal* s, char* nome);

/** @brief Define o pulso indicado com sendo nulo. Isto é, seu valor conterá nulo.
 */
int setPulsoNulo(Pulso* p);

/** @brief Adiciona ao sinal, mais especificamente ao vetor de pulsos do obj. Sinal,
            mais um pulso de valor e duração indicados.
            É como se fosse um append, aqui fazemos uso de realloc.
 */
int addPulso(Sinal* s, ValorLogico valor, Tempo duracao);

/** @brief Inicializa um nova estrutura Sinas vazia e devolve sua pos. de memória.
            Vazia significa: primeiro e ultimo apontam a NULL e num. de elem. é zero.
 */
Sinais* novaSinais();

/** @brief Insere um sinal em branco na estrutura Sinais.
 */
int addSinal(Sinais* s, char* nome);

/** @brief Copia um sinal para a estrutura Sinais.
 */
int addSinalPronto(Sinais *ls, Sinal *sinal);

#endif // SINAIS_H


text:
import random as rnd

import algorithms as algs
import knapsack.hyper.single.problem as ksp

def simple_state_generator_ksp(dimension):
    state = []
    for i in range(0, dimension):
        random_boolean = False if rnd.randint(0, 1) == 0 else True
        state.append(random_boolean)
    return state

def initial_population_generator_ksp(amount, dimension, validator=ksp.validate,
                                     state_generator=simple_state_generator_ksp,
                                     **kwargs):
    population = []
    while len(population) < amount:
        population_candidate = state_generator(dimension)
        if validator(population_candidate, **kwargs):
            population.append(population_candidate)
    return population

def compare_state_ksp(state1, state2):
    for i in range(0, len(state1)):
        if state1 != state2:
            return True
    return False

def crossover_func_ksp(first_parent, second_parent, **kwargs):
    iteration = 0
    while iteration < len(first_parent) ** 2:
        # TODO: try other genetic operators (different types of crossover, for example)
        # nor first allel nor last allel
        crossover_index = rnd.randint(1, len(first_parent) - 1)
        child_candidate = first_parent[:crossover_index + 1] + second_parent[crossover_index + 1:]
        if ksp.validate(child_candidate, **kwargs):
            return child_candidate
    return None

def minimize(dimension, **kwargs):
    return algs.genetic.minimize(dimension, initial_population_generator_ksp, crossover_func_ksp, ksp.solve, **kwargs)


text:
<?php
require 'globals.php';
require 'oauth_helper.php';

// Fill in the next 3 variables.
$guid='UOM4UNZYNI3E2QK6PCGXJWOKMY';
$access_token='A=XTULSMrbiT47BY.oipJD04TrZFy.es8i3CyPcE5z7udjN5gCcAVmpbapbQfoqZh_3g.dmALgm.crVvZi.96NPKROcthNtbISPz6kRIqaLutzvl6qux3Yvn4O3TF0VqaTWcH3zHHB0DJwdTOSZXd3ngxFjWup18DdS7GMjOO4kNsAae8QGjuIPCMqCgns6Frn7nPE8qBUJRZ3nzpb3hwRA9KNKewSJ.C3tm81V9xAM9cvo3WI6C_D42b0LU0M66QhegbWrXb5yASsBOXWT3tnj5f8MHpDlSn0eaOIG4OuHBzifnRzj0sv1BoimjJWMdhAPE8.gY2qQufn1_9Nhpw8St7j9fcVGKjC2O7AyJme_psFQ1F8HQ5pnrwRazkqQSxPtIVDcNqYckBNEJ6E578qqmgmjZhoG0fonSMeekmzOMzbHtI0fW57Faa1Al5C6q5eRH7PBKY_DRqFm7U_yAS4DyK.KPtLmy5e3M.GiOz_kocuRh6K8S4nJelSZIIuLxmDLBteBhpFmddXHGVzmU2w4GpVhd5GSq4UsoYN6_dXsK4GAdC2jXJfeoGm1pFhw_Wm2K2sarnEtlDgEIWMVwE9gr5xVfOkIhG7A_noVjiJ1srPBnS5NWGXx79XUZsR5K.IOcA2M4femi29RZt59FnfSpJEQqRMX7.Mr1SIPnN1rfE94KOVSOSY7kYWg0NV2jYfCSNJLjmu7e1_Q0w3WbtoNa5iisL_78kSvaf1alL3i5.G._85W0dkqwrE9kkW0yZY4uq0jgx1ROy6sA927X_fjsdh4wYLZF3If0BzxuADzcgkoE0oM2q5VZp0vCQ-';
$access_token_secret='edefc7236c654690a2c1482ca471be815096306f';

// Call Contact API
$retarr = postcontact(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
                      $guid, $access_token, $access_token_secret,
                      true, true);

exit(0);

/**
 * Call the Yahoo Contact API
 * @param string $consumer_key obtained when you registered your app
 * @param string $consumer_secret obtained when you registered your app
 * @param string $guid obtained from getacctok
 * @param string $access_token obtained from getacctok
 * @param string $access_token_secret obtained from getacctok
 * @param bool $usePost use HTTP POST instead of GET
 * @param bool $passOAuthInHeader pass the OAuth credentials in HTTP header
 * @return response string with token or empty array on error
 */
function postcontact($consumer_key, $consumer_secret, $guid, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true)
{
  $retarr = array();  // return value
  $response = array();

  $post_body='{"contact":{"fields":[{"type":"name","value":{"givenName":"John","middleName":"","familyName":"Doe","prefix":"","suffix":"","givenNameSound":"","familyNameSound":""}},{"type":"email","value":"johndoe@example.com"}]}}';
  $url = 'https://social.yahooapis.com/v1/user/' . $guid . '/contacts';
  $params['oauth_version'] = '1.0';
  $params['oauth_nonce'] = mt_rand();
  $params['oauth_timestamp'] = time();
  $params['oauth_consumer_key'] = $consumer_key;
  $params['oauth_token'] = $access_token;

  // compute hmac-sha1 signature and add it to the params list
  $params['oauth_signature_method'] = 'HMAC-SHA1';
  $params['oauth_signature'] =
      oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
                             $consumer_secret, $access_token_secret);

  // Pass OAuth credentials in a separate header or in the query string
  if ($passOAuthInHeader) {
    $query_parameter_string = oauth_http_build_query($params, true);
    $header = build_oauth_header($params, "yahooapis.com");
    $headers[] = $header;
    $request_url = $url;
  } else {
    $query_parameter_string = oauth_http_build_query($params);
    $request_url = $url . '?' . $query_parameter_string;
  }

  // POST or GET the request
  if ($usePost) {
    logit("postcontact:INFO:request_url:$request_url");
    logit("postcontact:INFO:post_body:$post_body");
    $headers[] = 'Content-Type: application/json';
    $response = do_post($request_url, $post_body, 80, $headers);
  } else {
    logit("postcontact:INFO:request_url:$request_url");
    $response = do_get($request_url, 80, $headers);
  }

  // extract successful response
  if (! empty($response)) {
    list($info, $header, $body) = $response;
    if ($body) {
      logit("postcontact:INFO:response:");
      print(json_pretty_print($body));
    }
    $retarr = $response;
  }

  return $retarr;
}
?>


text:
namespace chromecast {
namespace media {

namespace {

class DummyDemuxerStream : public ::media::DemuxerStream {
 public:
  // Creates a demuxer stream which provides frames either with a delay
  // or instantly. The scheduling pattern is the following:
  // - provides |delayed_frame_count| frames with a delay,
  // - then provides the following |cycle_count| - |delayed_frame_count|
  //   instantly,
  // - then provides |delayed_frame_count| frames with a delay,
  // - ... and so on.
  // Special cases:
  // - all frames are delayed: |delayed_frame_count| = |cycle_count|
  // - all frames are provided instantly: |delayed_frame_count| = 0
  // |config_idx| is a list of frame index before which there is
  // a change of decoder configuration.
  DummyDemuxerStream(int cycle_count,
                     int delayed_frame_count,
                     const std::list<int>& config_idx);
  virtual ~DummyDemuxerStream();

  // ::media::DemuxerStream implementation.
  virtual void Read(const ReadCB& read_cb) OVERRIDE;
  virtual ::media::AudioDecoderConfig audio_decoder_config() OVERRIDE;
  virtual ::media::VideoDecoderConfig video_decoder_config() OVERRIDE;
  virtual Type type() OVERRIDE;
  virtual bool SupportsConfigChanges() OVERRIDE;
  virtual ::media::VideoRotation video_rotation() OVERRIDE;

  bool has_pending_read() const {
    return has_pending_read_;
  }

 private:
  void DoRead(const ReadCB& read_cb);

  // Demuxer configuration.
  const int cycle_count_;
  const int delayed_frame_count_;
  std::list<int> config_idx_;

  // Number of frames sent so far.
  int frame_count_;

  bool has_pending_read_;

  DISALLOW_COPY_AND_ASSIGN(DummyDemuxerStream);
};

DummyDemuxerStream::DummyDemuxerStream(
    int cycle_count,
    int delayed_frame_count,
    const std::list<int>& config_idx)
  : cycle_count_(cycle_count),
    delayed_frame_count_(delayed_frame_count),
    config_idx_(config_idx),
    frame_count_(0),
    has_pending_read_(false) {
  DCHECK_LE(delayed_frame_count, cycle_count);
}

DummyDemuxerStream::~DummyDemuxerStream() {
}

void DummyDemuxerStream::Read(const ReadCB& read_cb) {
  has_pending_read_ = true;
  if (!config_idx_.empty() && config_idx_.front() == frame_count_) {
    config_idx_.pop_front();
    has_pending_read_ = false;
    read_cb.Run(kConfigChanged,
                scoped_refptr< ::media::DecoderBuffer>());
    return;
  }

  if ((frame_count_ % cycle_count_) < delayed_frame_count_) {
    base::MessageLoopProxy::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&DummyDemuxerStream::DoRead, base::Unretained(this),
                   read_cb),
        base::TimeDelta::FromMilliseconds(20));
    return;
  }
  DoRead(read_cb);
}

::media::AudioDecoderConfig DummyDemuxerStream::audio_decoder_config() {
  LOG(FATAL) << "DummyDemuxerStream is a video DemuxerStream";
  return ::media::AudioDecoderConfig();
}

::media::VideoDecoderConfig DummyDemuxerStream::video_decoder_config() {
  gfx::Size coded_size(640, 480);
  gfx::Rect visible_rect(640, 480);
  gfx::Size natural_size(640, 480);
  return ::media::VideoDecoderConfig(
      ::media::kCodecH264,
      ::media::VIDEO_CODEC_PROFILE_UNKNOWN,
      ::media::VideoFrame::YV12,
      coded_size,
      visible_rect,
      natural_size,
      NULL, 0,
      false);
}

::media::DemuxerStream::Type DummyDemuxerStream::type() {
  return VIDEO;
}

bool DummyDemuxerStream::SupportsConfigChanges() {
  return true;
}

::media::VideoRotation DummyDemuxerStream::video_rotation() {
  return ::media::VIDEO_ROTATION_0;
}

void DummyDemuxerStream::DoRead(const ReadCB& read_cb) {
  has_pending_read_ = false;
  scoped_refptr< ::media::DecoderBuffer> buffer(
      new ::media::DecoderBuffer(16));
  buffer->set_timestamp(frame_count_ * base::TimeDelta::FromMilliseconds(40));
  frame_count_++;
  read_cb.Run(kOk, buffer);
}

}  // namespace

class DemuxerStreamAdapterTest : public testing::Test {
 public:
  DemuxerStreamAdapterTest();
  virtual ~DemuxerStreamAdapterTest();

  void Initialize(::media::DemuxerStream* demuxer_stream);
  void Start();

 protected:
  void OnTestTimeout();
  void OnNewFrame(const scoped_refptr<DecoderBufferBase>& buffer,
                  const ::media::AudioDecoderConfig& audio_config,
                  const ::media::VideoDecoderConfig& video_config);
  void OnFlushCompleted();

  // Total number of frames to request.
  int total_frames_;

  // Number of demuxer read before issuing an early flush.
  int early_flush_idx_;
  bool use_post_task_for_flush_;

  // Number of expected read frames.
  int total_expected_frames_;

  // Number of frames actually read so far.
  int frame_received_count_;

  // List of expected frame indices with decoder config changes.
  std::list<int> config_idx_;

  scoped_ptr<DummyDemuxerStream> demuxer_stream_;

  scoped_ptr<CodedFrameProvider> coded_frame_provider_;

  DISALLOW_COPY_AND_ASSIGN(DemuxerStreamAdapterTest);
};

DemuxerStreamAdapterTest::DemuxerStreamAdapterTest()
    : use_post_task_for_flush_(false) {
}

DemuxerStreamAdapterTest::~DemuxerStreamAdapterTest() {
}

void DemuxerStreamAdapterTest::Initialize(
    ::media::DemuxerStream* demuxer_stream) {
  coded_frame_provider_.reset(
      new DemuxerStreamAdapter(
          base::MessageLoopProxy::current(),
          scoped_refptr<BalancedMediaTaskRunnerFactory>(),
          demuxer_stream));
}

void DemuxerStreamAdapterTest::Start() {
  frame_received_count_ = 0;

  // TODO(damienv): currently, test assertions which fail do not trigger the
  // exit of the unit test, the message loop is still running. Find a different
  // way to exit the unit test.
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&DemuxerStreamAdapterTest::OnTestTimeout,
                 base::Unretained(this)),
      base::TimeDelta::FromSeconds(5));

  coded_frame_provider_->Read(
      base::Bind(&DemuxerStreamAdapterTest::OnNewFrame,
                 base::Unretained(this)));
}

void DemuxerStreamAdapterTest::OnTestTimeout() {
  ADD_FAILURE() << "Test timed out";
  if (base::MessageLoop::current())
    base::MessageLoop::current()->QuitWhenIdle();
}

void DemuxerStreamAdapterTest::OnNewFrame(
    const scoped_refptr<DecoderBufferBase>& buffer,
    const ::media::AudioDecoderConfig& audio_config,
    const ::media::VideoDecoderConfig& video_config) {
  if (video_config.IsValidConfig()) {
    ASSERT_GT(config_idx_.size(), 0);
    ASSERT_EQ(frame_received_count_, config_idx_.front());
    config_idx_.pop_front();
  }

  ASSERT_TRUE(buffer.get() != NULL);
  ASSERT_EQ(buffer->timestamp(),
            frame_received_count_ * base::TimeDelta::FromMilliseconds(40));
  frame_received_count_++;

  if (frame_received_count_ >= total_frames_) {
    coded_frame_provider_->Flush(
        base::Bind(&DemuxerStreamAdapterTest::OnFlushCompleted,
                   base::Unretained(this)));
    return;
  }

  coded_frame_provider_->Read(
      base::Bind(&DemuxerStreamAdapterTest::OnNewFrame,
                 base::Unretained(this)));

  ASSERT_LE(frame_received_count_, early_flush_idx_);
  if (frame_received_count_ == early_flush_idx_) {
    base::Closure flush_cb =
        base::Bind(&DemuxerStreamAdapterTest::OnFlushCompleted,
                   base::Unretained(this));
    if (use_post_task_for_flush_) {
      base::MessageLoop::current()->PostTask(
          FROM_HERE,
          base::Bind(&CodedFrameProvider::Flush,
                     base::Unretained(coded_frame_provider_.get()),
                     flush_cb));
    } else {
      coded_frame_provider_->Flush(flush_cb);
    }
    return;
  }
}

void DemuxerStreamAdapterTest::OnFlushCompleted() {
  ASSERT_EQ(frame_received_count_, total_expected_frames_);
  ASSERT_FALSE(demuxer_stream_->has_pending_read());
  base::MessageLoop::current()->QuitWhenIdle();
}

TEST_F(DemuxerStreamAdapterTest, NoDelay) {
  total_frames_ = 10;
  early_flush_idx_ = total_frames_;   // No early flush.
  total_expected_frames_ = 10;
  config_idx_.push_back(0);
  config_idx_.push_back(5);

  int cycle_count = 1;
  int delayed_frame_count = 0;
  demuxer_stream_.reset(
      new DummyDemuxerStream(
          cycle_count, delayed_frame_count, config_idx_));

  scoped_ptr<base::MessageLoop> message_loop(new base::MessageLoop());
  Initialize(demuxer_stream_.get());
  message_loop->PostTask(
      FROM_HERE,
      base::Bind(&DemuxerStreamAdapterTest::Start, base::Unretained(this)));
  message_loop->Run();
}

TEST_F(DemuxerStreamAdapterTest, AllDelayed) {
  total_frames_ = 10;
  early_flush_idx_ = total_frames_;   // No early flush.
  total_expected_frames_ = 10;
  config_idx_.push_back(0);
  config_idx_.push_back(5);

  int cycle_count = 1;
  int delayed_frame_count = 1;
  demuxer_stream_.reset(
      new DummyDemuxerStream(
          cycle_count, delayed_frame_count, config_idx_));

  scoped_ptr<base::MessageLoop> message_loop(new base::MessageLoop());
  Initialize(demuxer_stream_.get());
  message_loop->PostTask(
      FROM_HERE,
      base::Bind(&DemuxerStreamAdapterTest::Start, base::Unretained(this)));
  message_loop->Run();
}

TEST_F(DemuxerStreamAdapterTest, AllDelayedEarlyFlush) {
  total_frames_ = 10;
  early_flush_idx_ = 5;
  use_post_task_for_flush_ = true;
  total_expected_frames_ = 5;
  config_idx_.push_back(0);
  config_idx_.push_back(3);

  int cycle_count = 1;
  int delayed_frame_count = 1;
  demuxer_stream_.reset(
      new DummyDemuxerStream(
          cycle_count, delayed_frame_count, config_idx_));

  scoped_ptr<base::MessageLoop> message_loop(new base::MessageLoop());
  Initialize(demuxer_stream_.get());
  message_loop->PostTask(
      FROM_HERE,
      base::Bind(&DemuxerStreamAdapterTest::Start, base::Unretained(this)));
  message_loop->Run();
}

}  // namespace media
}  // namespace chromecast


text:
using EasyNetQ.Scheduler.Mongo.Core;
using Topshelf;
using log4net.Config;

namespace EasyNetQ.Scheduler.Mongo
{
    public class Program
    {
        private static void Main()
        {
            XmlConfigurator.Configure();

            HostFactory.Run(hostConfiguration =>
                {
                    hostConfiguration.EnableServiceRecovery( serviceRecoveryConfiguration =>
                    {
                        serviceRecoveryConfiguration.RestartService( delayInMinutes: 1 ); // On the first service failure, reset service after a minute
                        serviceRecoveryConfiguration.SetResetPeriod( days: 0 ); // Reset failure count after every failure
                    } );
                    hostConfiguration.RunAsLocalSystem();
                    hostConfiguration.SetDescription("EasyNetQ.Scheduler");
                    hostConfiguration.SetDisplayName("EasyNetQ.Scheduler");
                    hostConfiguration.SetServiceName("EasyNetQ.Scheduler");

                    hostConfiguration.Service<ISchedulerService>(serviceConfiguration =>
                        {
                            serviceConfiguration.ConstructUsing(_ => SchedulerServiceFactory.CreateScheduler());

                            serviceConfiguration.WhenStarted((service, _) =>
                                {
                                    service.Start();
                                    return true;
                                });
                            serviceConfiguration.WhenStopped((service, _) =>
                                {
                                    service.Stop();
                                    return true;
                                });
                        });
                });
        }
    }
}


text:
<?php
namespace marionnewlevant\twigperversion\twigextensions;

class Continue_Node extends \Twig\Node\Node
{
	/**
	 * Compiles a Continue_Node into PHP.
	 */
	public function compile(\Twig\Compiler $compiler)
	{
		$compiler
			->addDebugInfo($this)
			->write("if (array_key_exists('loop', \$context)) {\n")
			->indent()
				->write("++\$context['loop']['index0'];\n")
				->write("++\$context['loop']['index'];\n")
				->write("\$context['loop']['first'] = false;\n")
				->write("if (isset(\$context['loop']['length'])) {\n")
				->indent()
					->write("--\$context['loop']['revindex0'];\n")
					->write("--\$context['loop']['revindex'];\n")
					->write("\$context['loop']['last'] = 0 === \$context['loop']['revindex0'];\n")
				->outdent()
				->write("}\n")
			->outdent()
			->write("}\n")
			->write("continue;\n");
	}
}


text:
package mysh.cluster;

import java.util.Arrays;
import java.util.List;

/**
 * @author Mysh
 * @since 2014/12/17 23:18
 */
public class Cu2 extends IClusterUser<String, String, String, String> {

    @Override
    public SubTasksPack<String> fork(String task, String masterNode, List<String> workerNodes) {
        return pack(Arrays.asList(task.split(" ")), null);
    }

    @Override
    public String procSubTask(String subTask, int timeout) throws InterruptedException {
        try {
            System.out.println(Thread.currentThread().getContextClassLoader());
            final Object cu2x = Class.forName("mysh.cluster.Cu2X").getConstructor().newInstance();
            System.out.println(cu2x.getClass().getClassLoader());
            return subTask + cu2x;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String join(String masterNode, List<String> assignedNodeIds, List<String> subResults) {
        return String.join(",", subResults);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>FunctionDeclaration</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.thoughtworks.selenium.webdriven

Class FunctionDeclaration

java.lang.Object

com.thoughtworks.selenium.webdriven.FunctionDeclaration

All Implemented Interfaces:

ScriptMutator

public class FunctionDeclaration
extends java.lang.Object
implements ScriptMutator

Models a function declaration. That is, it provides an implementation of a particular Javascript
 function.

Constructor Summary

Constructors

Constructor and Description

FunctionDeclaration(java.lang.String raw,
                   java.lang.String result)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
mutate(java.lang.String script,
      java.lang.StringBuilder outputTo)

Mutate a script.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FunctionDeclaration

public FunctionDeclaration(java.lang.String raw,
                           java.lang.String result)

Parameters:

raw - The original function (eg: "selenium.isElementPresent")

result - The body of the function implementation.

Method Detail

mutate

public void mutate(java.lang.String script,
                   java.lang.StringBuilder outputTo)

Description copied from interface: ScriptMutator

Mutate a script. The original, unmodified script is used to generate a script on the
 StringBuilder, the "toString" method of which should be used to get the result. We make use of
 a StringBuilder rather than a normal String so that we can efficiently chain mutators.

Specified by:

mutate in interface ScriptMutator

Parameters:

script - The original script.

outputTo - The mutated script.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import {keyValueArraySet} from '../../util/array_utils';
import {getLView} from '../state';
import {interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV} from './interpolation';
import {checkStylingMap, classStringParser} from './styling';

/**
 *
 * Update an interpolated class on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div class="prefix{{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate1(prefix: string, v0: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate2(
    prefix: string, v0: any, i0: string, v1: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate3(
 * 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate3(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate4(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate4(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any,
    suffix: string): void {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate5(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate5(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any,
    i3: string, v4: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue =
      interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate6(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate6(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any,
    i3: string, v4: any, i4: string, v5: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue =
      interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate7(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate7(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any,
    i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string): void {
  const lView = getLView();
  const interpolatedValue =
      interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 *
 * Update an interpolated class on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate8(
 *  'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
export function ɵɵclassMapInterpolate8(
    prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any,
    i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any,
    suffix: string): void {
  const lView = getLView();
  const interpolatedValue = interpolation8(
      lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/**
 * Update an interpolated class on an element with 9 or more bound values surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolateV(
 *  ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *.
 * @param values The collection of values and the strings in-between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 * @codeGenApi
 */
export function ɵɵclassMapInterpolateV(values: any[]): void {
  const lView = getLView();
  const interpolatedValue = interpolationV(lView, values);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}


text:
<?php

require('config.php');

define('USE_EXT', 'GMP');
require('vendor/autoload.php');

// -----------------------------------------------

function raiseError($log) {
    require('core_error.php');
    die($log);
}

// -----------------------------------------------

$token = preg_replace("/[^A-Za-z0-9]/", '', $_GET['token']);
if (empty($token)) {
    raiseError('no token');
}

// -----------------------------------------------

require('../../../inc/PassHash.class.php');
$ph = new PassHash();
$cookie = $ph->gen_salt(32);
if (!headers_sent()) {
    setcookie($cfg_cookie_name, $cookie, time() + $cfg_expire_session, '/', null, $cfg_cookie_https_only, true);
}

// -----------------------------------------------

try {
    $api = new Brave\API($cfg_core_endpoint, $cfg_core_application_id, $cfg_core_private_key, $cfg_core_public_key);
    $result = $api->core->info(array('token' => $token));
} catch(\Exception $e) {
    raiseError('core failed');
}

$charid = $result->character->id;
$charname = $result->character->name;
$username = preg_replace("/[^A-Za-z0-9]/", '_', strtolower($charname));
$corpid = $result->corporation->id;
$corpname = $result->corporation->name;
$allianceid = $result->alliance->id;
$alliancename = $result->alliance->name;
$tags = $result->tags;
$perms = $result->perms;

// -----------------------------------------------

try {
    $db = new PDO($cfg_sql_url, $cfg_sql_user, $cfg_sql_pass);
} catch (PDOException $e) {
    raiseError('auth database init failed');
}

// -----------------------------------------------

function addGroup($db, $groups, $criteria) {
    $stm = $db->prepare('SELECT grp FROM grp WHERE criteria = :criteria;');
    $stm->bindValue(':criteria', $criteria);
    if (!$stm->execute()) { raiseError('group query failed'); };
    while($res = $stm->fetch()){
	$groups[] = $res['grp'];
    }
    return $groups;
}

$groups = array('user');
$groups = addGroup($db, $groups, 'charid_' . $charid);
$groups = addGroup($db, $groups, 'corpid_' . $corpid);
$groups = addGroup($db, $groups, 'allianceid_' . $allianceid);
foreach ($tags as $tkey => $tvalue) {
    $groups = addGroup($db, $groups, 'tag_' . $tvalue);
}
foreach ($perms as $pkey => $pvalue) {
    $groups = addGroup($db, $groups, 'perm_' . $pvalue);
}
$groups = array_unique($groups);

// -----------------------------------------------

function addBan($db, $banned, $criteria) {
    $stm = $db->prepare('SELECT id FROM ban WHERE criteria = :criteria;');
    $stm->bindValue(':criteria', $criteria);
    if (!$stm->execute()) { raiseError('ban query failed'); };
    if ($stm->fetch()) {
	return true;
    }
    return $banned;
}

$banned = false;
$banned = addBan($db, $banned, 'charid_' . $charid);
$banned = addBan($db, $banned, 'corpid_' . $corpid);
$banned = addBan($db, $banned, 'allianceid_' . $allianceid);
foreach ($tags as $tkey => $tvalue) {
    $banned = addBan($db, $banned, 'tag_' . $tvalue);
}

if ($banned) {
    $groups = array('user');
}

// -----------------------------------------------

$stm = $db->prepare('SELECT charid FROM user where charid = :charid;');
$stm->bindValue(':charid', $charid);
if (!$stm->execute()) { raiseError('user query failed'); };

if ($stm->fetch()) {
    $stm = $db->prepare('UPDATE user SET username = :username, groups = :groups, charname = :charname, corpid = :corpid, corpname = :corpname, allianceid = :allianceid, alliancename = :alliancename, authtoken = :authtoken, authlast = :now WHERE charid = :charid;');
} else {
    $stm = $db->prepare('INSERT INTO user (username, groups, charid, charname, corpid, corpname, allianceid, alliancename, authtoken, authcreated, authlast) VALUES (:username, :groups, :charid, :charname, :corpid, :corpname, :allianceid, :alliancename, :authtoken, :now, :now);');
}
$stm->bindValue(':username', $username, PDO::PARAM_STR);
$stm->bindValue(':groups', implode(',', $groups), PDO::PARAM_STR);
$stm->bindValue(':charid', $charid, PDO::PARAM_INT);
$stm->bindValue(':charname', $charname, PDO::PARAM_STR);
$stm->bindValue(':corpid', $corpid, PDO::PARAM_INT);
$stm->bindValue(':corpname', $corpname, PDO::PARAM_STR);
$stm->bindValue(':allianceid', $allianceid, PDO::PARAM_INT);
$stm->bindValue(':alliancename', $alliancename, PDO::PARAM_STR);
$stm->bindValue(':authtoken', $token, PDO::PARAM_STR);
$stm->bindValue(':now', time(), PDO::PARAM_INT);
if (!$stm->execute()) { raiseError('user insert or update failed'); };

$stm = $db->prepare('DELETE from session where sessionid = :sessionid;');
$stm->bindValue(':sessionid', $cookie);
if (!$stm->execute()) { raiseError('session cleanup failed'); };

$stm = $db->prepare('INSERT INTO session (sessionid, charid, created) VALUES (:sessionid, :charid, :created)');
$stm->bindValue(':sessionid', $cookie);
$stm->bindValue(':charid', $charid);
$stm->bindValue(':created', time());
if (!$stm->execute()) { raiseError('session insert failed'); };

// -----------------------------------------------

header("Location: " . $cfg_url_base . '/' . $_GET['cb']);

?>


text:
using key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
using vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
using LSL_List = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list;
using LSL_Key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_String = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_Integer = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger;
using LSL_Float = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat;

namespace Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces
{
    public interface IAA_Api
    {
        void aaSetCloudDensity(LSL_Float density);

        void aaUpdateDatabase(LSL_String key, LSL_String value, LSL_String token);

        LSL_List aaQueryDatabase(LSL_String key, LSL_String token);

        LSL_List aaDeserializeXMLValues(key xmlFile);

        LSL_List aaDeserializeXMLKeys(key xmlFile);

        void aaSetConeOfSilence(LSL_Float radius);

        key aaSerializeXML(LSL_List keys, LSL_List values);

        LSL_String aaGetTeam(LSL_Key id);

        LSL_Float aaGetHealth(LSL_Key id);

        void aaJoinCombat(LSL_Key id);

        void aaLeaveCombat(LSL_Key id);

        void aaJoinCombatTeam(LSL_Key id, LSL_String team);

        void aaRequestCombatPermission(string ID);

        void aaThawAvatar(string ID);

        void aaFreezeAvatar(string ID);

        LSL_List aaGetTeamMembers(LSL_String team);

        LSL_String aaGetLastOwner();

        LSL_String aaGetLastOwner(LSL_String PrimID);

        void aaSayDistance(int channelID, LSL_Float Distance, string text);

        void aaSayTo(string userID, string text);

        LSL_Integer aaGetWalkDisabled(string userID);

        void aaSetWalkDisabled(string userID, bool Value);

        LSL_Integer aaGetFlyDisabled(string userID);

        void aaSetFlyDisabled(string userID, bool Value);

        key aaAvatarFullName2Key(string username);

        void aaRaiseError(string message);

        key aaGetText();

        rotation aaGetTextColor();

        void aaSetEnv(LSL_String name, LSL_List value);

        LSL_Integer aaGetIsInfiniteRegion();

        void aaAllRegionInstanceSay(LSL_Integer channelID, string text);

        LSL_Integer aaWindlightGetSceneIsStatic();

        LSL_Integer aaWindlightGetSceneDayCycleKeyFrameCount();
        LSL_List aaWindlightGetDayCycle();
        LSL_Integer aaWindlightAddDayCycleFrame(LSL_Float dayCyclePosition, int dayCycleFrameToCopy);
        LSL_Integer aaWindlightRemoveDayCycleFrame(int dayCycleFrame);

        LSL_List aaWindlightGetScene(LSL_List rules);
        LSL_List aaWindlightGetScene(int dayCycleKeyFrame, LSL_List rules);

        LSL_Integer aaWindlightSetScene(LSL_List list);
        LSL_Integer aaWindlightSetScene(int dayCycleIndex, LSL_List list);
    }
}


text:
[ $# -eq 0 ] && bash ${Script_Cat_Path}/bin/utils/usage.sh $Script_Cat_Name && exit 0
COMMAND="$1"; shift

function utils_path(){
	echo "  Path"
}

case $COMMAND in
utils_path)
    utils_path $@
    ;;
*)
	if [ -f ${Script_Cat_Path}/bin/utils/$COMMAND ] ; then
		bash ${Script_Cat_Debug} ${Script_Cat_Path}/bin/utils/$COMMAND $@
	elif [ -f ${Script_Cat_Path}/bin/utils/$COMMAND.sh ] ; then
		bash ${Script_Cat_Debug} ${Script_Cat_Path}/bin/utils/$COMMAND.sh $@
	elif [ -d ${Script_Cat_Path}/bin/utils/$COMMAND ] ; then
		SUBCOMMAND="$1"; shift
		bash ${Script_Cat_Debug} ${Script_Cat_Path}/bin/utils/$COMMAND/main.sh $SUBCOMMAND $@
	else
		bash ${Script_Cat_Debug} ${Script_Cat_Path}/bin/utils/usage.sh $Script_Cat_Name
	fi
    ;;
esac


text:
package iso20022

// Provides further details on the reference and status on the original transactions, included in the original instruction, to which the reversal message applies.
type PaymentTransaction45 struct {

	// Unique identification, as assigned by an instructing party for an instructed party, to unambiguously identify the reversed transaction.
	// Usage: The instructing party is the party sending the reversal message and not the party that sent the original instruction that is being reversed.
	ReversalIdentification *Max35Text `xml:"RvslId,omitempty"`

	// Unique identification, as assigned by the original instructing party for the original instructed party, to unambiguously identify the original instruction.
	OriginalInstructionIdentification *Max35Text `xml:"OrgnlInstrId,omitempty"`

	// Unique identification, as assigned by the original initiating party, to unambiguously identify the original transaction.
	OriginalEndToEndIdentification *Max35Text `xml:"OrgnlEndToEndId,omitempty"`

	// Unique identification, as assigned by the original first instructing agent, to unambiguously identify the transaction.
	OriginalTransactionIdentification *Max35Text `xml:"OrgnlTxId,omitempty"`

	// Unique reference, as assigned by the original clearing system, to unambiguously identify the original instruction.
	OriginalClearingSystemReference *Max35Text `xml:"OrgnlClrSysRef,omitempty"`

	// Amount of money, as provided in the original transaction, to be moved between the instructing agent and the instructed agent.
	OriginalInterbankSettlementAmount *ActiveOrHistoricCurrencyAndAmount `xml:"OrgnlIntrBkSttlmAmt,omitempty"`

	// Amount of money moved between the instructing agent and the instructed agent in the reversed transaction.
	ReversedInterbankSettlementAmount *ActiveCurrencyAndAmount `xml:"RvsdIntrBkSttlmAmt"`

	// Date on which the amount of money ceases to be available to the agent that owes it and when the amount of money becomes available to the agent to which it is due.
	//
	// Usage: The InterbankSettlementDate is the interbank settlement date of the reversal message, and not of the original instruction.
	InterbankSettlementDate *ISODate `xml:"IntrBkSttlmDt,omitempty"`

	// Amount of money to be moved between the debtor and the creditor, before deduction of charges, in the reversed transaction.
	ReversedInstructedAmount *ActiveOrHistoricCurrencyAndAmount `xml:"RvsdInstdAmt,omitempty"`

	// Factor used to convert an amount from one currency into another. This reflects the price at which one currency was bought with another currency.
	ExchangeRate *BaseOneRate `xml:"XchgRate,omitempty"`

	// Amount of money asked or paid as compensation for the processing of the instruction.
	CompensationAmount *ActiveOrHistoricCurrencyAndAmount `xml:"CompstnAmt,omitempty"`

	// Specifies if the creditor and/or debtor will bear the charges associated with the processing of the payment transaction.
	//
	// Usage: The ChargeBearer applies to the reversal message, not to the original instruction.
	ChargeBearer *ChargeBearerType1Code `xml:"ChrgBr,omitempty"`

	// Provides information on the charges to be paid by the charge bearer(s) related to the processing of the reversal transaction.
	ChargesInformation []*Charges2 `xml:"ChrgsInf,omitempty"`

	// Agent that instructs the next party in the chain to carry out the (set of) instruction(s).
	//
	// Usage: The instructing agent is the party sending the reversal message and not the party that sent the original instruction that is being reversed.
	InstructingAgent *BranchAndFinancialInstitutionIdentification5 `xml:"InstgAgt,omitempty"`

	// Agent that is instructed by the previous party in the chain to carry out the (set of) instruction(s).
	//
	// Usage: The instructed agent is the party receiving the reversal message and not the party that received the original instruction that is being reversed.
	InstructedAgent *BranchAndFinancialInstitutionIdentification5 `xml:"InstdAgt,omitempty"`

	// Provides detailed information on the reversal reason.
	ReversalReasonInformation []*PaymentReversalReason7 `xml:"RvslRsnInf,omitempty"`

	// Key elements used to identify the original transaction that is being referred to.
	OriginalTransactionReference *OriginalTransactionReference16 `xml:"OrgnlTxRef,omitempty"`

	// Additional information that cannot be captured in the structured elements and/or any other specific block.
	SupplementaryData []*SupplementaryData1 `xml:"SplmtryData,omitempty"`
}

func (p *PaymentTransaction45) SetReversalIdentification(value string) {
	p.ReversalIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction45) SetOriginalInstructionIdentification(value string) {
	p.OriginalInstructionIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction45) SetOriginalEndToEndIdentification(value string) {
	p.OriginalEndToEndIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction45) SetOriginalTransactionIdentification(value string) {
	p.OriginalTransactionIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction45) SetOriginalClearingSystemReference(value string) {
	p.OriginalClearingSystemReference = (*Max35Text)(&value)
}

func (p *PaymentTransaction45) SetOriginalInterbankSettlementAmount(value, currency string) {
	p.OriginalInterbankSettlementAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (p *PaymentTransaction45) SetReversedInterbankSettlementAmount(value, currency string) {
	p.ReversedInterbankSettlementAmount = NewActiveCurrencyAndAmount(value, currency)
}

func (p *PaymentTransaction45) SetInterbankSettlementDate(value string) {
	p.InterbankSettlementDate = (*ISODate)(&value)
}

func (p *PaymentTransaction45) SetReversedInstructedAmount(value, currency string) {
	p.ReversedInstructedAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (p *PaymentTransaction45) SetExchangeRate(value string) {
	p.ExchangeRate = (*BaseOneRate)(&value)
}

func (p *PaymentTransaction45) SetCompensationAmount(value, currency string) {
	p.CompensationAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (p *PaymentTransaction45) SetChargeBearer(value string) {
	p.ChargeBearer = (*ChargeBearerType1Code)(&value)
}

func (p *PaymentTransaction45) AddChargesInformation() *Charges2 {
	newValue := new(Charges2)
	p.ChargesInformation = append(p.ChargesInformation, newValue)
	return newValue
}

func (p *PaymentTransaction45) AddInstructingAgent() *BranchAndFinancialInstitutionIdentification5 {
	p.InstructingAgent = new(BranchAndFinancialInstitutionIdentification5)
	return p.InstructingAgent
}

func (p *PaymentTransaction45) AddInstructedAgent() *BranchAndFinancialInstitutionIdentification5 {
	p.InstructedAgent = new(BranchAndFinancialInstitutionIdentification5)
	return p.InstructedAgent
}

func (p *PaymentTransaction45) AddReversalReasonInformation() *PaymentReversalReason7 {
	newValue := new(PaymentReversalReason7)
	p.ReversalReasonInformation = append(p.ReversalReasonInformation, newValue)
	return newValue
}

func (p *PaymentTransaction45) AddOriginalTransactionReference() *OriginalTransactionReference16 {
	p.OriginalTransactionReference = new(OriginalTransactionReference16)
	return p.OriginalTransactionReference
}

func (p *PaymentTransaction45) AddSupplementaryData() *SupplementaryData1 {
	newValue := new(SupplementaryData1)
	p.SupplementaryData = append(p.SupplementaryData, newValue)
	return newValue
}


text:
/**
 * Created by Cami on 2017-04-21.
 */
/**
 * @author Elena Hardon
 * @date 11/04/2017
 */
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Population } from '../model/population.model';
@Injectable()
export class PopulationService {

  private backendUrl: String;

  constructor(private http: Http) {
    this.backendUrl = "http://localhost:8666/neda"
  }

  getAllPopulation() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/all',
      {headers: headers})
      .map(res => res.json());
  }

  addPopulation(population: Population) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let populationString = JSON.stringify(population);

    return this.http.post(
      this.backendUrl + '/population',
      populationString,
      {headers: headers})
      .map(res => res.json());
  }

  getFemaleNumber(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/female/' + district,
      {headers: headers})
      .map(res => res.json());

  }

  getMaleNumber(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/male/' + district,
      {headers: headers})
      .map(res => res.json());

  }

  getAge15(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/age/15/' + district,
      {headers: headers})
      .map(res => res.json());

  }

  getAge25(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/age/25/' + district,
      {headers: headers})
      .map(res => res.json());

  }

  getAge40(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/age/40/' + district,
      {headers: headers})
      .map(res => res.json());

  }

  getAge55(district: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.get(
      this.backendUrl + '/population/age/55/' + district,
      {headers: headers})
      .map(res => res.json());

  }
}


text:
import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import colors from "shared/colors";

const styles = {
  base: {
    width: "100%",
    height: "42px",
    lineHeight: "41px",
    borderTop: `1px solid ${colors.argile}`
  },
  title: {
    fontWeight: "600",
    fontSize: "11px",
    textTransform: "uppercase"
  },
  value: {
    fontSize: "13px",
    float: "right",
    textAlign: "right"
  }
};
class LineRow extends Component<{
  label: string,
  children: React$Node | string,
  classes: Object
}> {
  render() {
    const { label, children, classes } = this.props;
    return (

        {label}
        {children}

    );
  }
}

export default withStyles(styles)(LineRow);


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="320dp"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="org.c99.wear_imessage.QuickReplyActivity"
    android:orientation="vertical"
    android:weightSum="1">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:id="@+id/contact"
        android:layout_weight="0">

        <ImageView
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:id="@+id/photo"
            android:src="@drawable/ic_profile" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:id="@+id/name"
                android:textStyle="bold"
                android:textColor="#000">
                <requestFocus/>
            </TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:id="@+id/protocol"
                android:textColor="#ccc" />
        </LinearLayout>

    </LinearLayout>

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_weight="0" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/conversation"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:divider="#00000000"
        android:dividerHeight="0dp"
        android:stackFromBottom="true"
        android:transcriptMode="normal"
        android:visibility="gone"
        android:layout_marginTop="6dp" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/thumbnail"
        android:scaleType="fitCenter"
        android:layout_margin="6dp"
        android:maxHeight="100dp"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:visibility="gone" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_marginTop="6dp"
        android:layout_weight="0">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/message"
            android:inputType="textShortMessage|textMultiLine|textCapSentences|textAutoCorrect"
            android:minWidth="240dp"
            android:editable="true"
            android:gravity="bottom"
            android:layout_weight="1"
            android:hint="Message" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/send"
            android:layout_weight="0"
            android:src="@drawable/ic_action_send"
            style="@style/Widget.Styled.ImageButton"
            android:layout_marginLeft="@dimen/activity_horizontal_margin" />
    </LinearLayout>

</LinearLayout>


text:
alias d='sudo docker'
# If user is root no need for sudo
if [[ "$(id -u)" == "0" ]]; then
  alias d='docker'
fi

# If running on Mac (Darwin) no need for sudo
if [[ "$(uname)" == "Darwin" ]]; then
  alias d='docker'
fi

alias di='d images'
alias dps='d ps'
alias dpsa='dps -a'

function dex
{
    d exec -it "$1" /bin/bash
}

# Prune all unused local volumes
function dvp
{
    d volume prune -f
}


text:
package org.apache.commons.jcs.access.exception;

/** Thrown if there is some severe configuration problem that makes the cache nonfunctional. */
public class ConfigurationException
    extends CacheException
{
    /** Don't change. */
    private static final long serialVersionUID = 6881044536186097055L;

    /** Constructor for the ConfigurationException object */
    public ConfigurationException()
    {
        super();
    }

    /**
     * Constructor for the ConfigurationException object.
     * <p>
     * @param message
     */
    public ConfigurationException( String message )
    {
        super( message );
    }
}


text:
@interface FTFoldItem : NSObject

@property(nonatomic, assign)BOOL foldOpened;
@property(nonatomic, copy)NSString *foldIdentifier;
@property(nonatomic, strong)NSMutableArray *subFoldItems;
@property(nonatomic, copy)NSString *foldName;

- (instancetype)initWithFoldIdentifier:(NSString *)identifier foldName:(NSString *)foldName foldOpened:(BOOL)foldOpened subFoldItems:(NSArray *)foldItems;

- (instancetype)initWithFoldIdentifier:(NSString *)identifier foldName:(NSString *)foldName;

- (NSInteger)foldLevel;

@end


text:
Hello from Detail

            Child Detail »

<router-outlet></router-outlet>


text:
package libvirt

/*
#cgo pkg-config: libvirt
#include <libvirt/libvirt.h>
#include <assert.h>
#include "connect_compat.h"

int virNodeGetFreePagesCompat(virConnectPtr conn,
			      unsigned int npages,
			      unsigned int *pages,
			      int startcell,
			      unsigned int cellcount,
			      unsigned long long *counts,
			      unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002006
    assert(0); // Caller should have checked version
#else
    return virNodeGetFreePages(conn, npages, pages, startcell, cellcount, counts, flags);
#endif
}

char * virConnectGetDomainCapabilitiesCompat(virConnectPtr conn,
					     const char *emulatorbin,
					     const char *arch,
					     const char *machine,
					     const char *virttype,
					     unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002007
    assert(0); // Caller should have checked version
#else
    return virConnectGetDomainCapabilities(conn, emulatorbin, arch, machine, virttype, flags);
#endif
}

int virConnectGetAllDomainStatsCompat(virConnectPtr conn,
				      unsigned int stats,
				      virDomainStatsRecordPtr **retStats,
				      unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002008
    assert(0); // Caller should have checked version
#else
    return virConnectGetAllDomainStats(conn, stats, retStats, flags);
#endif
}

int virDomainListGetStatsCompat(virDomainPtr *doms,
				unsigned int stats,
				virDomainStatsRecordPtr **retStats,
				unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002008
    assert(0); // Caller should have checked version
#else
    return virDomainListGetStats(doms, stats, retStats, flags);
#endif
}

void virDomainStatsRecordListFreeCompat(virDomainStatsRecordPtr *stats)
{
}

int virNodeAllocPagesCompat(virConnectPtr conn,
			    unsigned int npages,
			    unsigned int *pageSizes,
			    unsigned long long *pageCounts,
			    int startCell,
			    unsigned int cellCount,
			    unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002009
    assert(0); // Caller should have checked version
#else
    return virNodeAllocPages(conn, npages, pageSizes, pageCounts, startCell, cellCount, flags);
#endif
}

virDomainPtr virDomainDefineXMLFlagsCompat(virConnectPtr conn,
					   const char *xml,
					   unsigned int flags)
{
#if LIBVIR_VERSION_NUMBER < 1002012
    assert(0); // Caller should have checked version
#else
    return virDomainDefineXMLFlags(conn, xml, flags);
#endif
}

virStoragePoolPtr virStoragePoolLookupByTargetPathCompat(virConnectPtr conn,
							 const char *path)
{
#if LIBVIR_VERSION_NUMBER < 4001000
    assert(0); // Caller should have checked version
#else
    return virStoragePoolLookupByTargetPath(conn, path);
#endif
}

*/
import "C"


text:
    <form>
        Username:
        <input type="text" name="username" ng-model="user.username"/>

        Password:
        <input type="password" name="password" ng-model="user.password"/>

        <button ng-click="onSignIn()">Sign in</button>
    </form>


text:
Unit Tests
==========

## Testing custom operators

RxSwift uses `RxTest` for all operator tests, located in the AllTests-* target inside the project `Rx.xcworkspace`.

This is an example of a typical `RxSwift` operator unit test:

```swift
func testMap_Range() {
    // Initializes test scheduler.
    // Test scheduler implements virtual time that is
    // detached from local machine clock.
    // This enables running the simulation as fast as possible
    // and proving that all events have been handled.
    let scheduler = TestScheduler(initialClock: 0)

    // Creates a mock hot observable sequence.
    // The sequence will emit events at designated
    // times, no matter if there are observers subscribed or not.
    // (that's what hot means).
    // This observable sequence will also record all subscriptions
    // made during its lifetime (`subscriptions` property).
    let xs = scheduler.createHotObservable([
        .next(150, 1),  // first argument is virtual time, second argument is element value
        .next(210, 0),
        .next(220, 1),
        .next(230, 2),
        .next(240, 4),
        .completed(300) // virtual time when completed is sent
    ])

    // `start` method will by default:
    // * Run the simulation and record all events
    //   using observer referenced by `res`.
    // * Subscribe at virtual time 200
    // * Dispose subscription at virtual time 1000
    let res = scheduler.start { xs.map { $0 * 2 } }

    let correctMessages = Recorded.events(
        .next(210, 0 * 2),
        .next(220, 1 * 2),
        .next(230, 2 * 2),
        .next(240, 4 * 2),
        .completed(300)
    )

    let correctSubscriptions = [
        Subscription(200, 300)
    ]

    XCTAssertEqual(res.events, correctMessages)
    XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
```

In the case of non-terminating sequences where you don't necessarily care about the event times, You may also use `RxTest`'s `XCTAssertRecordedElements` to assert specific elements have been emitted.
A terminating stop event (e.g. `completed` or `error`) will cause the test to fail.

```swift
func testElementsEmitted() {
    let scheduler = TestScheduler(initialClock: 0)

    let xs = scheduler.createHotObservable([
        .next(210, "RxSwift"),
        .next(220, "is"),
        .next(230, "pretty"),
        .next(240, "awesome")
    ])

    let res = scheduler.start { xs.asObservable() }

    XCTAssertRecordedElements(res.events, ["RxSwift", "is", "pretty", "awesome"])
}
```

## Testing operator compositions (view models, components)

Examples of how to test operator compositions are contained inside `Rx.xcworkspace` > `RxExample-iOSTests` target.

It's easy to define `RxTest` extensions so you can write your tests in a readable way. Provided examples inside `RxExample-iOSTests` are just suggestions on how you can write those extensions, but there are a lot of possibilities on how to write those tests.

```swift
    // expected events and test data
    let (
        usernameEvents,
        passwordEvents,
        repeatedPasswordEvents,
        loginTapEvents,

        expectedValidatedUsernameEvents,
        expectedSignupEnabledEvents
    ) = (
        scheduler.parseEventsAndTimes("e---u1----u2-----u3-----------------", values: stringValues).first!,
        scheduler.parseEventsAndTimes("e----------------------p1-----------", values: stringValues).first!,
        scheduler.parseEventsAndTimes("e---------------------------p2---p1-", values: stringValues).first!,
        scheduler.parseEventsAndTimes("------------------------------------", values: events).first!,

        scheduler.parseEventsAndTimes("e---v--f--v--f---v--o----------------", values: validations).first!,
        scheduler.parseEventsAndTimes("f--------------------------------t---", values: booleans).first!
    )
```

## Integration tests

It is also possible to write integration tests by using `RxBlocking` operators.

Using `RxBlocking`'s `toBlocking()` method, you can block the current thread and wait for the sequence to complete, allowing you to synchronously access its result.

A simple way to test the result of your sequence is using the `toArray` method. It will return an array of all elements emitted once a sequence has completed successfully, or `throw` if an error caused the sequence to terminate.

```swift
let result = try fetchResource(location)
        .toBlocking()
        .toArray()

XCTAssertEqual(result, expectedResult)
```

Another option would be to use the `materialize` operator which lets you more granularly examine your sequence. It will return a `MaterializedSequenceResult` enumeration that could be either `.completed` along with the emitted elements if the sequence completed successfully, or `failed` if the sequence terminated with an error, along with the emitted error.

```swift
let result = try fetchResource(location)
        .toBlocking()
        .materialize()

// For testing the results or error in the case of terminating with error
switch result {
        case .completed:
            XCTFail("Expected result to complete with error, but result was successful.")
        case .failed(let elements, let error):
            XCTAssertEqual(elements, expectedResult)
            XCTAssertErrorEqual(error, expectedError)
        }

// For testing the results in the case of termination with completion
switch result {
        case .completed(let elements):
            XCTAssertEqual(elements, expectedResult)
        case .failed(_, let error):
            XCTFail("Expected result to complete without error, but received \(error).")
        }
```


text:
titel: Beratung studentische Workshops
kuerzel: s-workshop
verantwortlich: cn, jk
typ: feedback
pflicht: false
termine: 2017-10-26 13:00|3.241|http://bit.ly/2lbBsIq
empfohlene-voraussetzungen:
published: true
dauer: 60
info:
---

## Material
- [Programm WBA1 2015](http://th-koeln.github.io/wba1-2015/)
- [Programm WBA1 2014](http://th-koeln.github.io/wba1-2014/)
- [Programm WBA1 2013 - siehe Sidebar](https://github.com/th-koeln/wba1-2013/wiki)
- [Programm WBA1 2012 - siehe Sidebar](https://github.com/th-koeln/wba1-2012/wiki)


text:
// Filename: IBFEMethod.h
// Created on 5 Oct 2011 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of New York University nor the names of its
//      contributors may be used to endorse or promote products derived from
//      this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef included_IBFEMethod
#define included_IBFEMethod

/////////////////////////////// INCLUDES /////////////////////////////////////

#define LIBMESH_REQUIRE_SEPARATE_NAMESPACE

#include "ibamr/IBStrategy.h"
#include "ibtk/FEDataManager.h"
#include "libmesh/mesh.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/point.h"
#include "libmesh/system.h"
#include "libmesh/vector_value.h"
#include "petscsys.h"

/////////////////////////////// CLASS DEFINITION /////////////////////////////

namespace IBAMR
{
/*!
 * \brief Class IBFEMethod is an implementation of the abstract base class
 * IBStrategy that provides functionality required by the IB method with finite
 * element elasticity.
 */
class IBFEMethod
    : public IBStrategy
{
public:
    static const std::string        COORDS_SYSTEM_NAME;
    static const std::string COORD_MAPPING_SYSTEM_NAME;
    static const std::string         FORCE_SYSTEM_NAME;
    static const std::string      VELOCITY_SYSTEM_NAME;
    static const std::string BODY_VELOCITY_SYSTEM_NAME;

    /*!
     * \brief Constructor.
     */
    IBFEMethod(
        const std::string& object_name,
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db,
        libMesh::Mesh* mesh,
        int max_level_number,
        bool register_for_restart=true);

    /*!
     * \brief Constructor.
     */
    IBFEMethod(
        const std::string& object_name,
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db,
        const std::vector<libMesh::Mesh*>& meshes,
        int max_level_number,
        bool register_for_restart=true);

    /*!
     * \brief Destructor.
     */
    ~IBFEMethod();

    /*!
     * Return a pointer to the finite element data manager object for the
     * specified part.
     */
    IBTK::FEDataManager*
    getFEDataManager(
        unsigned int part=0) const;

    /*!
     * Indicate that a part is constrained.
     */
    void
    registerConstrainedPart(
        unsigned int part=0);

    /*!
     * Typedef specifying interface for specifying constrained body velocities.
     */
    typedef
    void
    (*ConstrainedPartVelocityFcnPtr)(
        libMesh::NumericVector<double>& U_b,
        libMesh::NumericVector<double>& U,
        libMesh::NumericVector<double>& X,
        libMesh::MeshBase& mesh,
        double data_time,
        void* ctx);

    /*!
     * Register a constrained body velocity function.
     */
    void
    registerConstrainedPartVelocityFunction(
        ConstrainedPartVelocityFcnPtr constrained_part_velocity_fcn,
        void* constrained_part_velocity_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Typedef specifying interface for coordinate mapping function.
     */
    typedef
    void
    (*CoordinateMappingFcnPtr)(
        libMesh::Point& X,
        const libMesh::Point& s,
        void* ctx);

    /*!
     * Register the (optional) function used to initialize the physical
     * coordinates from the Lagrangian coordinates.
     *
     * \note If no function is provided, the initial physical coordinates are
     * taken to be the same as the Lagrangian coordinate system, i.e., the
     * initial coordinate mapping is assumed to be the identity mapping.
     */
    void
    registerInitialCoordinateMappingFunction(
        CoordinateMappingFcnPtr coordinate_mapping_fcn,
        void* coordinate_mapping_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Typedef specifying interface for PK1 stress tensor function.
     */
    typedef
    void
    (*PK1StressFcnPtr)(
        libMesh::TensorValue<double>& PP,
        const libMesh::TensorValue<double>& FF,
        const libMesh::Point& X,
        const libMesh::Point& s,
        libMesh::Elem* elem,
        libMesh::NumericVector<double>& X_vec,
        const std::vector<libMesh::NumericVector<double>*>& system_data,
        double data_time,
        void* ctx);

    /*!
     * Register the (optional) function to compute the first Piola-Kirchhoff
     * stress tensor, used to compute the forces on the Lagrangian finite
     * element mesh.
     */
    void
    registerPK1StressTensorFunction(
        PK1StressFcnPtr PK1_stress_fcn,
        std::vector<unsigned int> PK1_stress_fcn_systems=std::vector<unsigned int>(),
        void* PK1_stress_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Typedef specifying interface for Lagrangian body force distribution
     * function.
     */
    typedef
    void
    (*LagBodyForceFcnPtr)(
        libMesh::VectorValue<double>& F,
        const libMesh::TensorValue<double>& FF,
        const libMesh::Point& X,
        const libMesh::Point& s,
        libMesh::Elem* elem,
        libMesh::NumericVector<double>& X_vec,
        const std::vector<libMesh::NumericVector<double>*>& system_data,
        double data_time,
        void* ctx);

    /*!
     * Register the (optional) function to compute body force distributions on
     * the Lagrangian finite element mesh.
     */
    void
    registerLagBodyForceFunction(
        LagBodyForceFcnPtr lag_body_force_fcn,
        std::vector<unsigned int> lag_body_force_fcn_systems=std::vector<unsigned int>(),
        void* lag_body_force_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Typedef specifying interface for Lagrangian pressure force distribution
     * function.
     */
    typedef
    void
    (*LagPressureFcnPtr)(
        double& P,
        const libMesh::TensorValue<double>& FF,
        const libMesh::Point& X,
        const libMesh::Point& s,
        libMesh::Elem* elem,
        unsigned short int side,
        libMesh::NumericVector<double>& X_vec,
        const std::vector<libMesh::NumericVector<double>*>& system_data,
        double data_time,
        void* ctx);

    /*!
     * Register the (optional) function to compute surface pressure
     * distributions on the Lagrangian finite element mesh.
     */
    void
    registerLagPressureFunction(
        LagPressureFcnPtr lag_pressure_fcn,
        std::vector<unsigned int> lag_pressure_fcn_systems=std::vector<unsigned int>(),
        void* lag_pressure_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Typedef specifying interface for Lagrangian surface force distribution
     * function.
     */
    typedef
    void
    (*LagSurfaceForceFcnPtr)(
        libMesh::VectorValue<double>& F,
        const libMesh::TensorValue<double>& FF,
        const libMesh::Point& X,
        const libMesh::Point& s,
        libMesh::Elem* elem,
        unsigned short int side,
        libMesh::NumericVector<double>& X_vec,
        const std::vector<libMesh::NumericVector<double>*>& system_data,
        double data_time,
        void* ctx);

    /*!
     * Register the (optional) function to compute surface force distributions
     * on the Lagrangian finite element mesh.
     */
    void
    registerLagSurfaceForceFunction(
        LagSurfaceForceFcnPtr lag_surface_force_fcn,
        std::vector<unsigned int> lag_surface_force_fcn_systems=std::vector<unsigned int>(),
        void* lag_surface_force_fcn_ctx=NULL,
        unsigned int part=0);

    /*!
     * Return the number of ghost cells required by the Lagrangian-Eulerian
     * interaction routines.
     */
    const SAMRAI::hier::IntVector<NDIM>&
    getMinimumGhostCellWidth() const;

    /*!
     * Setup the tag buffer.
     */
    void
    setupTagBuffer(
        SAMRAI::tbox::Array<int>& tag_buffer,
        SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > gridding_alg) const;

    /*!
     * Method to prepare to advance data from current_time to new_time.
     */
    void
    preprocessIntegrateData(
        double current_time,
        double new_time,
        int num_cycles);

    /*!
     * Method to clean up data following call(s) to integrateHierarchy().
     */
    void
    postprocessIntegrateData(
        double current_time,
        double new_time,
        int num_cycles);

    /*!
     * Interpolate the Eulerian velocity to the curvilinear mesh at the
     * specified time within the current time interval.
     */
    void
    interpolateVelocity(
        int u_data_idx,
        const std::vector<SAMRAI::tbox::Pointer<SAMRAI::xfer::CoarsenSchedule<NDIM> > >& u_synch_scheds,
        const std::vector<SAMRAI::tbox::Pointer<SAMRAI::xfer::RefineSchedule<NDIM> > >& u_ghost_fill_scheds,
        double data_time);

    /*!
     * Advance the positions of the Lagrangian structure using the forward Euler
     * method.
     */
    void
    eulerStep(
        double current_time,
        double new_time);

    /*!
     * Advance the positions of the Lagrangian structure using the (explicit)
     * midpoint rule.
     */
    void
    midpointStep(
        double current_time,
        double new_time);

    /*!
     * Advance the positions of the Lagrangian structure using the (explicit)
     * trapezoidal rule.
     */
    void
    trapezoidalStep(
        double current_time,
        double new_time);

    /*!
     * Compute the Lagrangian force at the specified time within the current
     * time interval.
     */
    void
    computeLagrangianForce(
        double data_time);

    /*!
     * Spread the Lagrangian force to the Cartesian grid at the specified time
     * within the current time interval.
     */
    void
    spreadForce(
        int f_data_idx,
        const std::vector<SAMRAI::tbox::Pointer<SAMRAI::xfer::RefineSchedule<NDIM> > >& f_prolongation_scheds,
        double data_time);

    /*!
     * Initialize FE data.  This method must be called prior to calling
     * IBHierarchyIntegrator::initializePatchHierarchy().
     */
    void
    initializeFEData();

    /*!
     * Initialize Lagrangian data corresponding to the given AMR patch hierarchy
     * at the start of a computation.  If the computation is begun from a
     * restart file, data may be read from the restart databases.
     *
     * A patch data descriptor is provided for the Eulerian velocity in case
     * initialization requires interpolating Eulerian data.  Ghost cells for
     * Eulerian data will be filled upon entry to this function.
     */
    void
    initializePatchHierarchy(
        SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy,
        SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > gridding_alg,
        int u_data_idx,
        const std::vector<SAMRAI::tbox::Pointer<SAMRAI::xfer::CoarsenSchedule<NDIM> > >& u_synch_scheds,
        const std::vector<SAMRAI::tbox::Pointer<SAMRAI::xfer::RefineSchedule<NDIM> > >& u_ghost_fill_scheds,
        int integrator_step,
        double init_data_time,
        bool initial_time);

    /*!
     * Register a load balancer and work load patch data index with the IB
     * strategy object.
     */
    void
    registerLoadBalancer(
        SAMRAI::tbox::Pointer<SAMRAI::mesh::LoadBalancer<NDIM> > load_balancer,
        int workload_data_idx);

    /*!
     * Update work load estimates on each level of the patch hierarchy.
     */
    void
    updateWorkloadEstimates(
        SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy,
        int workload_data_idx);

    /*!
     * Begin redistributing Lagrangian data prior to regridding the patch
     * hierarchy.
     */
    void
    beginDataRedistribution(
        SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy,
        SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > gridding_alg);

    /*!
     * Complete redistributing Lagrangian data following regridding the patch
     * hierarchy.
     */
    void
    endDataRedistribution(
        SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy,
        SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > gridding_alg);

    /*!
     * Initialize data on a new level after it is inserted into an AMR patch
     * hierarchy by the gridding algorithm.
     *
     * \see SAMRAI::mesh::StandardTagAndInitStrategy::initializeLevelData
     */
    void
    initializeLevelData(
        SAMRAI::tbox::Pointer<SAMRAI::hier::BasePatchHierarchy<NDIM> > hierarchy,
        int level_number,
        double init_data_time,
        bool can_be_refined,
        bool initial_time,
        SAMRAI::tbox::Pointer<SAMRAI::hier::BasePatchLevel<NDIM> > old_level,
        bool allocate_data);

    /*!
     * Reset cached hierarchy dependent data.
     *
     * \see SAMRAI::mesh::StandardTagAndInitStrategy::resetHierarchyConfiguration
     */
    void
    resetHierarchyConfiguration(
        SAMRAI::tbox::Pointer<SAMRAI::hier::BasePatchHierarchy<NDIM> > hierarchy,
        int coarsest_level,
        int finest_level);

    /*!
     * Set integer tags to "one" in cells where refinement of the given level
     * should occur according to user-supplied feature detection criteria.
     *
     * \see SAMRAI::mesh::StandardTagAndInitStrategy::applyGradientDetector
     */
    void
    applyGradientDetector(
        SAMRAI::tbox::Pointer<SAMRAI::hier::BasePatchHierarchy<NDIM> > hierarchy,
        int level_number,
        double error_data_time,
        int tag_index,
        bool initial_time,
        bool uses_richardson_extrapolation_too);

    /*!
     * Write out object state to the given database.
     */
    void
    putToDatabase(
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> db);

protected:
    /*
     * \brief Compute the constraint force density.
     */
    void
    computeConstraintForceDensity(
        libMesh::PetscVector<double>& F_vec,
        libMesh::PetscVector<double>& X_vec,
        libMesh::PetscVector<double>& U_vec,
        libMesh::PetscVector<double>& U_b_vec,
        double data_time,
        unsigned int part);

    /*
     * \brief Compute the interior elastic density, possibly splitting off the
     * normal component of the transmission force along the physical boundary of
     * the Lagrangian structure.
     */
    void
    computeInteriorForceDensity(
        libMesh::PetscVector<double>& G_vec,
        libMesh::PetscVector<double>& X_vec,
        double data_time,
        unsigned int part);

    /*!
     * \brief Spread the transmission force density along the physical boundary
     * of the Lagrangian structure.
     */
    void
    spreadTransmissionForceDensity(
        int f_data_idx,
        libMesh::PetscVector<double>& X_ghost_vec,
        double data_time,
        unsigned int part);

    /*!
     * \brief Impose jump conditions determined from the interior and
     * transmission force densities along the physical boundary of the
     * Lagrangian structure.
     */
    void
    imposeJumpConditions(
        int f_data_idx,
        libMesh::PetscVector<double>& F_ghost_vec,
        libMesh::PetscVector<double>& X_ghost_vec,
        double data_time,
        unsigned int part);

    /*!
     * \brief Initialize the physical coordinates using the supplied coordinate
     * mapping function.  If no function is provided, the initial coordinates
     * are taken to be the Lagrangian coordinates.
     */
    void
    initializeCoordinates(
        unsigned int part);

    /*!
     * \brief Compute dX = X - s, useful mainly for visualization purposes.
     */
    void
    updateCoordinateMapping(
        unsigned int part);

    /*
     * Indicates whether the integrator should output logging messages.
     */
    bool d_do_log;

    /*
     * Pointers to the patch hierarchy and gridding algorithm objects associated
     * with this object.
     */
    SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > d_hierarchy;
    SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > d_gridding_alg;
    bool d_is_initialized;

    /*
     * The current time step interval.
     */
    double d_current_time, d_new_time, d_half_time;

    /*
     * FE data associated with this object.
     */
    std::vector<libMesh::Mesh*> d_meshes;
    std::vector<libMesh::EquationSystems*> d_equation_systems;

    const unsigned int d_num_parts;
    std::vector<IBTK::FEDataManager*> d_fe_data_managers;
    SAMRAI::hier::IntVector<NDIM> d_ghosts;
    std::vector<libMesh::System*> d_X_systems, d_U_systems, d_F_systems, d_U_b_systems;
    std::vector<libMesh::PetscVector<double>*> d_X_current_vecs, d_X_new_vecs, d_X_half_vecs, d_X_IB_ghost_vecs;
    std::vector<libMesh::PetscVector<double>*> d_U_current_vecs, d_U_new_vecs, d_U_half_vecs;
    std::vector<libMesh::PetscVector<double>*> d_F_half_vecs, d_F_IB_ghost_vecs;
    std::vector<libMesh::PetscVector<double>*> d_U_b_vecs;

    /*
     * Method paramters.
     */
    bool d_use_IB_spread_operator;
    std::string d_spread_delta_fcn;
    bool d_use_IB_interp_operator;
    std::string d_interp_delta_fcn;
    bool d_split_forces;
    bool d_use_jump_conditions;
    bool d_use_consistent_mass_matrix;
    libMeshEnums::FEFamily d_fe_family;
    libMeshEnums::Order d_fe_order;
    libMeshEnums::QuadratureType d_quad_type;
    libMeshEnums::Order d_quad_order;

    /*
     * Data related to handling constrained body constraints.
     */
    bool d_has_constrained_parts;
    std::vector<bool> d_constrained_part;
    std::vector<ConstrainedPartVelocityFcnPtr> d_constrained_part_velocity_fcns;
    std::vector<void*> d_constrained_part_velocity_fcn_ctxs;
    double d_constraint_omega;

    /*
     * Functions used to compute the initial coordinates of the Lagrangian mesh.
     */
    std::vector<CoordinateMappingFcnPtr> d_coordinate_mapping_fcns;
    std::vector<void*> d_coordinate_mapping_fcn_ctxs;

    /*
     * Functions used to compute the first Piola-Kirchhoff stress tensor.
     */
    std::vector<PK1StressFcnPtr> d_PK1_stress_fcns;
    std::vector<std::vector<unsigned int> > d_PK1_stress_fcn_systems;
    std::vector<void*> d_PK1_stress_fcn_ctxs;

    /*
     * Functions used to compute additional body and surface forces on the
     * Lagrangian mesh.
     */
    std::vector<LagBodyForceFcnPtr> d_lag_body_force_fcns;
    std::vector<std::vector<unsigned int> > d_lag_body_force_fcn_systems;
    std::vector<void*> d_lag_body_force_fcn_ctxs;

    std::vector<LagPressureFcnPtr> d_lag_pressure_fcns;
    std::vector<std::vector<unsigned int> > d_lag_pressure_fcn_systems;
    std::vector<void*> d_lag_pressure_fcn_ctxs;

    std::vector<LagSurfaceForceFcnPtr> d_lag_surface_force_fcns;
    std::vector<std::vector<unsigned int> > d_lag_surface_force_fcn_systems;
    std::vector<void*> d_lag_surface_force_fcn_ctxs;

    /*
     * Nonuniform load balancing data structures.
     */
    SAMRAI::tbox::Pointer<SAMRAI::mesh::LoadBalancer<NDIM> > d_load_balancer;
    int d_workload_idx;

    /*
     * The object name is used as a handle to databases stored in restart files
     * and for error reporting purposes.
     */
    std::string d_object_name;

    /*
     * A boolean value indicating whether the class is registered with the
     * restart database.
     */
    bool d_registered_for_restart;

private:
    /*!
     * \brief Default constructor.
     *
     * \note This constructor is not implemented and should not be used.
     */
    IBFEMethod();

    /*!
     * \brief Copy constructor.
     *
     * \note This constructor is not implemented and should not be used.
     *
     * \param from The value to copy to this object.
     */
    IBFEMethod(
        const IBFEMethod& from);

    /*!
     * \brief Assignment operator.
     *
     * \note This operator is not implemented and should not be used.
     *
     * \param that The value to assign to this object.
     *
     * \return A reference to this object.
     */
    IBFEMethod&
    operator=(
        const IBFEMethod& that);

    /*!
     * Implementation of class constructor.
     */
    void
    commonConstructor(
        const std::string& object_name,
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db,
        const std::vector<libMesh::Mesh*>& meshes,
        int max_level_number,
        bool register_for_restart);

    /*!
     * Read input values from a given database.
     */
    void
    getFromInput(
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> db,
        bool is_from_restart);

    /*!
     * Read object state from the restart file and initialize class data
     * members.
     */
    void
    getFromRestart();
};
}// namespace IBAMR

//////////////////////////////////////////////////////////////////////////////

#endif //#ifndef included_IBFEMethod