text:
[![Build Status](https://travis-ci.org/timdonnelly/Advance.svg?branch=master)](https://travis-ci.org/timdonnelly/Advance)
![Swift 5.0](https://img.shields.io/badge/Swift-5.0-orange.svg)
![GitHub release](https://img.shields.io/github/release/timdonnelly/Advance.svg)
[![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-orange.svg)](#swift-package-manager)
[![CocoaPods compatible](https://img.shields.io/cocoapods/v/Advance.svg)](#cocoapods)

# Advance

An animation library for iOS, tvOS, and macOS that uses physics-based animations (including springs) to power interactions that move and respond realistically.

```swift
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

// Springs animate changes to a value
let spring = Spring(initialValue: view.center)

// The `onChange` closure will be called every time the spring updates
spring.onChange = { [view] newCenter in
    view.center = newCenter
}

/// The view's center will realistically animate to the new target value.
spring.target = CGPoint(x: 300, y: 200)
```

## Installation

There are several ways to integrate Advance into your project.

* **Manually:** add  `Advance.xcodeproj` to your project, then add `Advance-{iOS|macOS|tvOS}.framework` as an "Embedded Binary" to your application target (under General in target settings). From there, add `import Advance` to your code and you're good to go.

* **Carthage:** add `github "timdonnelly/Advance"` to your `Cartfile`.

* **CocoaPods:** add `pod 'Advance'` to your `Podfile`.

* **Swift Package Manager:** add a dependency to your `Project.swift`: `.package(url: "http://github.com/timdonnelly/Advance", from: "3.0.0")`

##### Requirements
* iOS 10+, tvOS 10+, or macOS 10.12+
* Swift 5.0 (Xcode 10.2 or higher)

## Usage

**API documentation is [available here](http://timdonnelly.github.io/Advance/).**

Advance animations are applied on every frame (using `CADisplayLink` on iOS/tvOS, and `CVDisplayLink` on macOS), allowing for fine-grained control at any time.

### `Spring`

`Spring` instances animate changes to a value over time, using spring physics.

```swift
let spring = Spring(initialValue: 0.0)
spring.onChange = { [view] newAlpha in
    view.alpha = newAlpha
}

// Off it goes!
spring.target = 0.5
```

#### Configuring a spring

```swift

/// Spring values can be adjusted at any time.
spring.tension = 30.0 /// The strength of the spring
spring.damping = 2.0 /// The resistance (drag) that the spring encounters
spring.threshold = 0.1 /// The maximum delta between the current value and the spring's target (for each component) for which the simulation can enter a converged state.

/// Update the simulation state at any time.
spring.velocity = 6.5
spring.value = 0.2

/// Sets the spring's target and the current simulation value, and removes all velocity. This causes the spring to converge at the given value.
spring.reset(to: 0.5)

```

### `Animator`

`Animator` allows for more flexibility in the types of animation that can be performed, but gives up some convenience
in order to do so. Specifically, animators allow for *any* type of animation or simulation to be performed for a single
value.

```swift
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

/// Animators coordinate animations to drive changes to a value.
let sizeAnimator = Animator(initialValue: view.bounds.size)

sizeAnimator.onChange = { [view] newSize in
    view.bounds.size = newSize
}

/// A simple timed animation
sizeAnimator.animate(to: CGSize(width: 123, height: 456), duration: 0.25, timingFunction: .easeInOut)

/// Some time in the future (before the previous timed animation was complete)...

/// Spring physics will move the view's size to the new value, maintaining the velocity from the timed animation.
sizeAnimator.simulate(using: SpringFunction(target: CGSize(width: 300, height: 300)))

/// Some time in the future (before the previous spring animation was complete)...

/// The value will keep the same velocity that it had from the preceeding spring
/// animation, and a decay function will slowly bring movement to a stop.
sizeAnimator.simulate(using: DecayFunction(drag: 2.0))

```

Animators support two fundamentally different types of animations: timed and simulated.

#### Timed animations

Timed animations are, well, timed: they have a fixed duration, and they animate to a final value in a predictable manner.

```swift
animator.animate(to: CGSize(width: 123, height: 456), duration: 0.25, timingFunction: .easeInOut)
```

`TimingFunction` described the pacing of a timed animation.

`TimingFunction` comes with a standard set of functions:

```swift
TimingFunction.linear // No easing
TimingFunction.easeIn
TimingFunction.easeOut
TimingFunction.easeInOut
TimingFunction.swiftOut // Similar to Material Design's default curve
```

Custom timing functions can be expressed as unit beziers ([described here](https://www.w3.org/TR/css-easing-1/#cubic-bzier-timing-function)).

```swift
let customTimingFunction = TimingFunction(x1: 0.1, y1: 0.2, x2: 0.6, y2: 0.0)
```

#### Simulated animations

Simulated animations use a *simulation function* to power a physics-based transition. Simulation functions are types conforming to the `SimulationFunction` protocol.

Simulated animations may be started using two different methods:

```swift
// Begins animating with the custom simulation function, maintaining the previous velocity of the animator.
animator.simulate(using: MyCustomFunction())

// or...

// Begins animating with the custom simulation function, imparting the specified velocity into the simulation.
animator.simulate(using: DecayFunction(), initialVelocity: dragGestureRecognizer.velocity(in: view))
```

### Animating Custom Types

Values conforming to the `VectorConvertible` protocol can be animated by Advance. Conforming types can be converted to and from a `Vector` implementation.
```swift
public protocol VectorConvertible: Equatable, Interpolatable {
    associatedtype VectorType: SIMD where VectorType.Scalar == Double
    init(vector: VectorType)
    var vector: VectorType { get }
}
```

The library adds conformance for many common types through extensions.

## Contributing

If you encounter any issues or surprises, please open an issue.

For suggestions or new features, please consider opening a PR with a functional implementation. Issues may be used if you aren't sure how to implement the change, but working code is typically easier to evaluate.

## License
This project is released under the [BSD 2-clause license](https://github.com/timdonnelly/Advance/blob/master/LICENSE).


text:
title:  Hope Beyond Pandemics
date:  29/10/2022
---

#### inTro

**Read This Week's Passage: John 11**

**Hope Beyond Pandemics**

The coronavirus pandemic has turned many people's lives upside down. Hundreds of thousands have died in some nations and in the millions worldwide. Family members were unable to attend the funerals of their loved ones, and some of the dead did not even have family members or friends to claim them—they died alone. Losing grandmothers and grandfathers, fathers and mothers, siblings, children and friends was a painful ordeal. Furthermore, many of those who did not contract the virus panicked at the thought of being infected. In these times when people face the reality of their mortality, the Bible offers the reality of God's hope and assurance.

According to the gospel record, Jesus resurrected three people during His earthly ministry. He resurrected the son of the widow of Nain (Luke 7:11–15) and the daughter of Jairus (Luke 8:40–42, 49–56) shortly after their death. Because they had just died, the unbelieving religious leaders claimed they were not really dead, that Jesus faked their resurrection. However, the third person Jesus resurrected, Lazarus, proved they were dead wrong. Lazarus had been dead, wrapped in linen and buried in the tomb, for four days. When Jesus commanded the stone of the sepulcher to be removed, Martha complained, " 'Lord, by this time there is a stench, for he has been dead four days' " (John 11:39). There was no way to explain this miracle away!

The story of the resurrection of Lazarus contains precious gems of truth which prove that Jesus is God in the flesh, the Life Giver, truly the Resurrection and the Life. And the same Jesus who resurrected Lazarus lives today and offers the assurance of life eternal to those who trust in Him!

#### inScribe

Read John 11 from the translation of your choice. Write out John 11:21–27. You may also re-write the passage in your own words, or outline or mind-map the chapter.

` `

redpajama_set_name: RedPajamaGithub


text:
function dirList = lscell(arg, removePathBool, recursiveBool)
%% lscell
% Author: Erik Roberts
%
% Purpose: returns cell matrix of strings with results from call to ls/dir
%
% Usage: dirList = lscell()
%        dirList = lscell(arg)
%        dirList = lscell(arg, removePathBool)
%
% Inputs (optional):
%   arg: argument to ls
%   removePathBool: logical of whether to remove the path before the files/dirs

% args
if nargin < 2 || isempty(removePathBool)
  removePathBool = true; %defaults to true
end
if nargin < 3 || isempty(recursiveBool)
  recursiveBool = false; %defaults to false
end
if ~nargin || isempty(arg)
  if ~recursiveBool
    arg = {};
  else
    arg = {'.'};
  end
else
  arg = {arg};
end

if ~recursiveBool
  try
    dirList = ls(arg{:});
  catch % no arg files found
    dirList = {};
    return
  end
else % recursiveBool
  if (ismac || isunix)
    [~, dirList] = system(['find ' arg{:}]);
  elseif ispc
  end
end

if (ismac || isunix)
  dirList = strsplit(dirList);
  if isempty(dirList{end})
    dirList(end) = [];
  end
elseif ispc
  dirList = cellstr(dirList);
  if strcmp(dirList{1},'.')
    dirList(1:2) = []; %remove leading . and ..
  end
end

if isempty(dirList) || isempty(dirList{1})
  dirList = {};
end

if exist('removePathBool','var') && removePathBool
  dirList = removePath(dirList);
end

  % sub functions
  function dirList = removePath(dirList)
    for k = 1:length(dirList)
      thisDir = dirList{k};
      [~,name,ext] = fileparts(thisDir);
      dirList{k} = [name,ext];
    end
  end
end


text:
layout: dark-post
title: Dokku SSL Configuration
modified:
categories: [Dokku]
description:
tags: [Dokku,Wordpress,Deploy,Docker]
comments:
share:
date: 2017-07-05T22:40:21-04:00
image:
    feature: ssl.png
    credit:
    creditlink:
---

SSL Sertifikası eklemek için çeşitli yöntem olmakla beraber https://github.com/dokku/dokku-letsencrypt adresindeki plugini de kulanabilirsiniz.

Dokku sunucusuna plugini aşağıdaki şekilde kurabilirsiniz.

{% highlight yaml %}
  sudo dokku plugin:install https://github.com/dokku/dokku-letsencrypt.git
{% endhighlight %}

Bu plugin içerisinde dokku letsencrypt:help yazdığınız kullanabileceğiniz komutları göstermektedir. Biz sertifika eklemek için
{% highlight yaml %}
  dokku config:set --no-restart myapp DOKKU_LETSENCRYPT_EMAIL=your@email.tld
  dokku letsencrypt app-name
{% endhighlight %}

bu komutu kullanacağız. EMAİL adresini önem taşımaktadır ve zorunludur. SSL sertifikasını sorgulamak için
{% highlight yaml %}
  dokku certs:report
{% endhighlight %}

 komudunu kullanabilirsiniz.


text:
//
//  MessageGetScheduledResponse.h
//  SmsVoice
//
//  Created by Nirwan Nursabda on 7/9/15.
//

#import <Foundation/Foundation.h>
#import "ModelResponse.h"

@interface MessageGetScheduledResponse : ModelResponse
@property NSString *TotalTextMessages;
@property NSString *Page;
@property NSMutableArray *MessagesData;

- (instancetype) initWithJSONString:(NSDictionary*)jsonResp;
- (NSString*) toString;
@end


text:
-- AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")

ENT.Unit = true
ENT.Attackable = true

function ENT:Initialize()
	self:SetModel("models/roller.mdl")

	local Size = self.Size * 0.5
	local Mins = Vector( -Size, -Size, -Size )
	local Maxs = Vector( Size, Size, Size )

	self:SetMoveType(MOVETYPE_VPHYSICS)
	self:SetSolid(SOLID_VPHYSICS)
	self:PhysicsInitSphere( Size )
	self:SetCollisionBounds( Mins, Maxs )

	self:DrawShadow(false)
	self:SetNoDraw(true) -- The rollermine model is visible when doing gravitate :: FIX? // Chewgum

	self.SpeedSqr = self.Speed ^ 2
	self.SizeSqr = self.Size * self.Size

	self:SetCollisionGroup( COLLISION_GROUP_WEAPON )

	self.Phys = self:GetPhysicsObject()

	if (IsValid(self.Phys)) then
		self.Phys:EnableDrag(true)
		self.Phys:EnableMotion(true)
		self.Phys:EnableCollisions(true)
		self.Phys:EnableGravity(true)
		self.Phys:SetDamping( 0, 90 )
		self.Phys:SetDragCoefficient( 10 )
		self.Phys:SetMaterial("ice") -- gmod_silent
		--self.Phys:SetInertia( Vector(100,100,100) )
		self.Phys:SetMass( 50 )
		self.Phys:SetBuoyancyRatio( 0.025 )
		--self.Phys:Wake()
	end

	self:SetMoving( false )
end

function ENT:GetEmpire()
	if (Unit:ValidUnit(self.Unit)) then
		return self.Unit:GetEmpire()
	end
end

function ENT:PhysicsCollide( data, physobj )
	if (IsValid(data.HitEntity) and data.HitEntity.GetEmpire and data.HitEntity:GetEmpire() == self:GetEmpire()) then return end

	if (data.Speed > 100 && data.DeltaTime > 0.2 ) then
		self.nextFallDamage = self.nextFallDamage or CurTime()

		if( CurTime() < self.nextFallDamage ) then return end

		self.nextFallDamage = CurTime() + 0.1
		self:EmitSound( "Rubber.BulletImpact" )

		if( Unit:ValidUnit( self.Unit ) ) then
			local dmginfo = {}
			dmginfo.damage = data.Speed * 0.025
			dmginfo.dmgtype = DMG_FALL
			self.Unit:Damage( dmginfo )
		end
	end
end

function ENT:UpdateTransmitState()
	return TRANSMIT_NEVER
end

function ENT:PerformMiracle(ID)
	MsgN("PerformMiracle", ID)
end

function ENT:Select( Empire, Bool )

	if(self.Killed) then
		return
	end

	Empire:SelectUnit( self, Bool )

end

function ENT:Think()
	if( not Unit:ValidUnit( self.Unit ) ) then return end

	local phys = self:GetPhysicsObject()
	if( phys:IsValid() ) then
		self.Unit:HullPhysicsSimulate( self, phys )
	else
		return
	end

	self.Unit.v_Pos = self:GetPos()
	self.Unit:SetVelocity( self:GetVelocity() )

	-- self.Unit:Think()

	if( self:WaterLevel() > 2 ) then

		local dmginfo = {}
			dmginfo.damage = 1
			dmginfo.type = DMG_DROWN
		self.Unit:Damage( dmginfo )

	end

	self:NextThink(CurTime() + 0.1)

	return true

end

--[[
hook.Add( "ShouldCollide", "unit_hull.ShouldCollide", function( ent1, ent2 )

	if( not ent1 or not ent2 ) then return end

	if( Unit:ValidUnit( ent1.Unit ) and Unit:ValidUnit( ent2.Unit ) ) then

		return false

	end

end )
]]

function ENT:StartTouch(Ent)
	--MsgN("StartTouch", Ent)
end

function ENT:Touch(Ent)
	--MsgN("Touch", Ent)
end

function ENT:EndTouch(Ent)
	--MsgN("EndTouch", Ent)
end

function ENT:OnTakeDamage(DmgInfo)
end

function ENT:OnRemove()
end


text:
import os, sys
import Image
import glob
import argparse
from FilesCrawler import DiscoverPaths
from ImageManipulation import ResizeImage

def ResizeImages(allImages, size, overwrite):
	for image in allImages:
		ResizeImage(image, size, overwrite, verbose)

def GetArgumentOrDefault(argumentName, defaultValue = None):
	return args[argumentName] if args[argumentName] != None else defaultValue

# Some predefined values
recursive = False
overwrite = False
verbose = False
extensions = ['.jpg', '.png', '.jpeg', '.gif']

# Argument parsing
parser = argparse.ArgumentParser(description='Resize.me is a script used to resize a batch of images.')
parser.add_argument('-s','--size', help='The size of the longest border of the image after resizing', required=True)
parser.add_argument('-p','--path', help='The root path in which to search for images', required=True)
#parser.add_argument('-e','--extensions', nargs='+', type=str, help='The extensions that should be analyzed, (' + str(extensions) + ' per default)' , required=False)
# Flags parsing
parser.add_argument('-r','--recursive', action='store_true', help='A flag defining whether the files are to be searched in every subdirectory (' + str(recursive) + ' per default)', required=False)
parser.add_argument('-o','--overwrite', action='store_true', help='A flag defining whether the files are to be overwritten or new files to be created alongside (' + str(overwrite) + ' per default)', required=False)
parser.add_argument('-v','--verbose', action='store_true', help='Printout statements along the way (' + str(verbose) + ' per default)', required=False)

args = vars(parser.parse_args())

size = GetArgumentOrDefault("size")
rootPath = GetArgumentOrDefault("path")
recursive = GetArgumentOrDefault("recursive", recursive)
overwrite = GetArgumentOrDefault("overwrite", overwrite)
verbose = GetArgumentOrDefault("verbose", verbose)

# Discovering the images to resize
print extensions
allImages = DiscoverPaths(rootPath, recursive, extensions, verbose)

# Resizing the images
#ResizeImages(allImages, size, overwrite)


text:
(function ($) {
  'use strict';

  window.PWO = window.PWO || {};

  var pensionPotInput = {
    init: function () {
      this.insertHTML();
      this.cache();
      this.subscribe();
      this.bindEvents();
    },
    insertHTML: function () {
      var html = $('#pension-pot-input-error').html();
      $('.display_if_range').after(html);
    },
    cache: function () {
      this.$wrapper = $('.display_if_range');
      this.$inputs = $('.js-numbers-only');
      this.$input1 = $('#appointment_summary_value_of_pension_pots');
      this.$input2 = $('#appointment_summary_upper_value_of_pension_pots');
      this.$potCountInput = $('.js-pot-count');
      this.$accuracyInput = $('input[name="appointment_summary[accuracy]"]');
    },
    subscribe: function () {
      var that = this;
      $.subscribe('accuracyChange', function (e, value) {
        if (value === 'range') {
          that.$wrapper.fadeIn();
        } else {
          that.$wrapper.fadeOut();
          that.$input2.val('');
          that.$input2.trigger('keyup');
        }

        if (value === 'notprovided') {
          that.$input1.val('');
          that.$input1.trigger('keyup');
          that.$input2.val('');
          that.$input2.trigger('keyup');
          that.$potCountInput.val('').trigger('keyup');
        }
      });

      $.subscribe('eligibilityChange', function (e, value) {
        if (value === 'no') {
          that.$input1.val('');
          that.$input1.trigger('keyup');
          that.$input2.val('');
          that.$input2.trigger('keyup');
          that.$potCountInput.val('').trigger('keyup');
          that.$accuracyInput.prop('checked', false);
        }
      });
    },
    bindEvents: function () {
      this.$inputs.on('keypress', function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
          //display error message
          var error_input = $(e.target).parents('.form-group').find('.js-error-message');
          error_input.html('Only use numbers').show().attr('aria-live', 'polite').fadeOut('slow');
          return false;
        }
      });
    }
  };

  PWO.pensionPotInput = pensionPotInput;

})(jQuery);


text:
Complex Actions Needed (these are defined as being comprised of 2 or more basic actions needed to accomplish):

- place ward
- deward
- drop item
- pick-up item
- go to side-shop
- go to secret-shop
- drop tower aggro
- stack neutral camp
- pull neutral camp


text:
@interface SimpleDemoViewController : OpenWebRTCViewController

@end


text:
/* There are several race conditions in this plugin, but they should be
   happening pretty rarely and usually it's not a big problem if the results
   are temporarily wrong. Fixing the races would likely be a lot of work,
   so it's not really worth it. */

#include "lib.h"
#include "ioloop.h"
#include "array.h"
#include "str.h"
#include "master-service.h"
#include "dict.h"
#include "mail-namespace.h"
#include "index-mail.h"
#include "index-storage.h"
#include "expire-set.h"
#include "expire-plugin.h"

#define EXPIRE_CONTEXT(obj) \
	MODULE_CONTEXT(obj, expire_storage_module)
#define EXPIRE_MAIL_CONTEXT(obj) \
	MODULE_CONTEXT(obj, expire_mail_module)
#define EXPIRE_USER_CONTEXT(obj) \
	MODULE_CONTEXT(obj, expire_mail_user_module)

struct expire_mail_index_header {
	uint32_t timestamp;
};

struct expire_mail_user {
	union mail_user_module_context module_ctx;

	struct dict *db;
	struct expire_set *set;
	bool expire_cache;
};

struct expire_mailbox {
	union mailbox_module_context module_ctx;
	uint32_t expire_ext_id;
};

struct expire_transaction_context {
	union mailbox_transaction_module_context module_ctx;

	unsigned int saves:1;
	unsigned int first_expunged:1;
};

const char *expire_plugin_version = DOVECOT_ABI_VERSION;

static MODULE_CONTEXT_DEFINE_INIT(expire_storage_module,
				  &mail_storage_module_register);
static MODULE_CONTEXT_DEFINE_INIT(expire_mail_module, &mail_module_register);
static MODULE_CONTEXT_DEFINE_INIT(expire_mail_user_module,
				  &mail_user_module_register);

static struct mailbox_transaction_context *
expire_mailbox_transaction_begin(struct mailbox *box,
				 enum mailbox_transaction_flags flags)
{
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(box);
	struct mailbox_transaction_context *t;
	struct expire_transaction_context *xt;

	t = xpr_box->module_ctx.super.transaction_begin(box, flags);
	xt = i_new(struct expire_transaction_context, 1);

	MODULE_CONTEXT_SET(t, expire_storage_module, xt);
	return t;
}

static void first_save_timestamp(struct mailbox *box, time_t *stamp_r)
{
	struct mailbox_transaction_context *t;
	const struct mail_index_header *hdr;
	struct mail *mail;

	*stamp_r = ioloop_time;

	t = mailbox_transaction_begin(box, 0);
	mail = mail_alloc(t, 0, NULL);

	/* find the first non-expunged mail. we're here because the first
	   mail was expunged, so don't bother checking it. */
	hdr = mail_index_get_header(box->view);
	if (hdr->messages_count > 0) {
		mail_set_seq(mail, 1);
		(void)mail_get_save_date(mail, stamp_r);
	}
	mail_free(&mail);
	(void)mailbox_transaction_commit(&t);
}

static uint32_t expire_get_ext_id(struct mailbox *box)
{
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(box);

	if (xpr_box->expire_ext_id != (uint32_t)-1)
		return xpr_box->expire_ext_id;

	xpr_box->expire_ext_id =
		mail_index_ext_register(box->index, "expire",
			sizeof(struct expire_mail_index_header), 0, 0);
	return xpr_box->expire_ext_id;
}

static int expire_lookup(struct mailbox *box, const char *key,
			 time_t *new_stamp_r)
{
	struct expire_mail_user *euser =
		EXPIRE_USER_CONTEXT(box->storage->user);
	const struct expire_mail_index_header *hdr;
	const void *data;
	size_t data_size;
	const char *value;
	int ret;

	/* default to ioloop_time for newly saved mails. it may not be exactly
	   the first message's save time, but a few seconds difference doesn't
	   matter */
	*new_stamp_r = ioloop_time;

	if (euser->expire_cache) {
		mail_index_get_header_ext(box->view, expire_get_ext_id(box),
					  &data, &data_size);
		if (data_size == sizeof(*hdr)) {
			hdr = data;
			if (hdr->timestamp == 0)
				return 0;
			/* preserve the original timestamp */
			*new_stamp_r = hdr->timestamp;
			return 1;
		}
		/* cache doesn't exist yet */
	}

	ret = dict_lookup(euser->db, pool_datastack_create(),
			  key, &value);
	if (ret <= 0) {
		if (ret < 0)
			return -1;
		first_save_timestamp(box, new_stamp_r);
		return 0;
	}
	return strcmp(value, "0") != 0 ? 1 : 0;
}

static void
expire_update(struct mailbox *box, const char *key, time_t timestamp)
{
	struct expire_mail_user *euser =
		EXPIRE_USER_CONTEXT(box->storage->user);
	struct dict_transaction_context *dctx;
	struct mail_index_transaction *trans;
	struct expire_mail_index_header hdr;

	dctx = dict_transaction_begin(euser->db);
	dict_set(dctx, key, dec2str(timestamp));
	if (dict_transaction_commit(&dctx) < 0)
		i_error("expire: dict commit failed");
	else if (euser->expire_cache) {
		memset(&hdr, 0, sizeof(hdr));
		hdr.timestamp = timestamp;

		trans = mail_index_transaction_begin(box->view,
			MAIL_INDEX_TRANSACTION_FLAG_EXTERNAL);
		mail_index_update_header_ext(trans, expire_get_ext_id(box),
					     0, &hdr, sizeof(hdr));
		if (mail_index_transaction_commit(&trans) < 0)
			i_error("expire: index transaction commit failed");
	}
}

static void first_nonexpunged_timestamp(struct mailbox_transaction_context *t,
					time_t *stamp_r)
{
	struct mail_index_view *view = t->view;
	const struct mail_index_header *hdr;
	struct mail *mail;
	uint32_t seq;

	mail = mail_alloc(t, 0, NULL);

	/* find the first non-expunged mail. we're here because the first
	   mail was expunged, so don't bother checking it. */
	hdr = mail_index_get_header(view);
	for (seq = 2; seq <= hdr->messages_count; seq++) {
		if (!mail_index_is_expunged(view, seq)) {
			mail_set_seq(mail, seq);
			if (mail_get_save_date(mail, stamp_r) == 0)
				break;
		}
	}
	mail_free(&mail);

	if (seq > hdr->messages_count) {
		/* everything expunged */
		*stamp_r = 0;
	}
}

static int
expire_mailbox_transaction_commit(struct mailbox_transaction_context *t,
				  struct mail_transaction_commit_changes *changes_r)
{
	struct mail_user *user = t->box->storage->user;
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(t->box);
	struct expire_transaction_context *xt = EXPIRE_CONTEXT(t);
	struct mailbox *box = t->box;
	time_t new_stamp = 0;
	bool update_dict = FALSE;
	int ret;

	if (xt->first_expunged) {
		/* first mail expunged. dict needs updating. */
		first_nonexpunged_timestamp(t, &new_stamp);
		if (new_stamp == 0 && xt->saves) {
			/* everything was expunged, but also within this
			   transaction a new message was saved */
			new_stamp = ioloop_time;
		}
		if (user->mail_debug) {
			i_debug("expire: Expunging first message in %s, "
				"updating timestamp to %ld",
				box->vname, (long)new_stamp);
		}
		update_dict = TRUE;
	}

	if (xpr_box->module_ctx.super.transaction_commit(t, changes_r) < 0) {
		i_free(xt);
		return -1;
	}
	/* transaction is freed now */
	t = NULL;

	if (xt->first_expunged || xt->saves) T_BEGIN {
		const char *key;

		key = t_strconcat(DICT_EXPIRE_PREFIX,
				  box->storage->user->username, "/",
				  mailbox_get_vname(box), NULL);
		if (xt->first_expunged) {
			/* new_stamp is already set */
		} else {
			i_assert(xt->saves);
			/* saved new mails. dict needs to be updated only if
			   this is the first mail in the database */
			ret = expire_lookup(box, key, &new_stamp);
			if (ret <= 0) {
				/* first time saving here with expire enabled.
				   also handle lookup errors by just assuming
				   it didn't exist */
				if (ret < 0) {
					i_warning("expire: dict lookup failed, "
						  "assuming update is needed");
				}
				update_dict = TRUE;
			} else {
				/* already exists */
			}
			if (user->mail_debug && update_dict) {
				i_debug("expire: Saving first message to %s, "
					"updating timestamp to %ld",
					box->vname, (long)new_stamp);
			}
		}

		if (update_dict)
			expire_update(box, key, new_stamp);
	} T_END;
	i_free(xt);
	return 0;
}

static void
expire_mailbox_transaction_rollback(struct mailbox_transaction_context *t)
{
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(t->box);
	struct expire_transaction_context *xt = EXPIRE_CONTEXT(t);

	xpr_box->module_ctx.super.transaction_rollback(t);
	i_free(xt);
}

static void expire_mail_expunge(struct mail *_mail)
{
	struct mail_private *mail = (struct mail_private *)_mail;
	union mail_module_context *xpr_mail = EXPIRE_MAIL_CONTEXT(mail);
	struct expire_transaction_context *xt =
		EXPIRE_CONTEXT(_mail->transaction);

	if (_mail->seq == 1) {
		/* first mail expunged, database needs to be updated */
		xt->first_expunged = TRUE;
	}
	xpr_mail->super.expunge(_mail);
}

static void expire_mail_allocated(struct mail *_mail)
{
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(_mail->box);
	struct mail_private *mail = (struct mail_private *)_mail;
	struct mail_vfuncs *v = mail->vlast;
	union mail_module_context *xpr_mail;

	if (xpr_box == NULL)
		return;

	xpr_mail = p_new(mail->pool, union mail_module_context, 1);
	xpr_mail->super = *v;
	mail->vlast = &xpr_mail->super;

	v->expunge = expire_mail_expunge;
	MODULE_CONTEXT_SET_SELF(mail, expire_mail_module, xpr_mail);
}

static int expire_save_finish(struct mail_save_context *ctx)
{
	struct expire_transaction_context *xt =
		EXPIRE_CONTEXT(ctx->transaction);
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(ctx->transaction->box);

	xt->saves = TRUE;
	return xpr_box->module_ctx.super.save_finish(ctx);
}

static int
expire_copy(struct mail_save_context *ctx, struct mail *mail)
{
	struct expire_transaction_context *xt =
		EXPIRE_CONTEXT(ctx->transaction);
	struct expire_mailbox *xpr_box = EXPIRE_CONTEXT(ctx->transaction->box);

	xt->saves = TRUE;
	return xpr_box->module_ctx.super.copy(ctx, mail);
}

static void expire_mailbox_allocate_init(struct mailbox *box)
{
	struct mailbox_vfuncs *v = box->vlast;
	struct expire_mailbox *xpr_box;

	xpr_box = p_new(box->pool, struct expire_mailbox, 1);
	xpr_box->module_ctx.super = *v;
	box->vlast = &xpr_box->module_ctx.super;
	xpr_box->expire_ext_id = (uint32_t)-1;

	v->transaction_begin = expire_mailbox_transaction_begin;
	v->transaction_commit = expire_mailbox_transaction_commit;
	v->transaction_rollback = expire_mailbox_transaction_rollback;
	v->save_finish = expire_save_finish;
	v->copy = expire_copy;

	MODULE_CONTEXT_SET(box, expire_storage_module, xpr_box);
}

static void expire_mailbox_allocated(struct mailbox *box)
{
	struct expire_mail_user *euser =
		EXPIRE_USER_CONTEXT(box->storage->user);

	if (euser != NULL && expire_set_lookup(euser->set, box->vname))
		expire_mailbox_allocate_init(box);
}

static void expire_mail_user_deinit(struct mail_user *user)
{
	struct expire_mail_user *euser = EXPIRE_USER_CONTEXT(user);

	dict_deinit(&euser->db);
	expire_set_deinit(&euser->set);

	euser->module_ctx.super.deinit(user);
}

static const char *const *expire_get_patterns(struct mail_user *user)
{
	ARRAY_TYPE(const_string) patterns;
	const char *str;
	char set_name[6+MAX_INT_STRLEN+1];
	unsigned int i;

	t_array_init(&patterns, 16);
	str = mail_user_set_plugin_getenv(user->set, "expire");
	for (i = 2; str != NULL; i++) {
		array_append(&patterns, &str, 1);

		if (i_snprintf(set_name, sizeof(set_name), "expire%u", i) < 0)
			i_unreached();
		str = mail_user_set_plugin_getenv(user->set, set_name);
	}
	array_append_zero(&patterns);
	return array_idx(&patterns, 0);
}

static void expire_mail_namespaces_created(struct mail_namespace *ns)
{
	struct mail_user *user = ns->user;
	struct mail_user_vfuncs *v = user->vlast;
	struct expire_mail_user *euser;
	struct dict *db;
	const char *dict_uri, *error;

	dict_uri = mail_user_plugin_getenv(user, "expire_dict");
	if (mail_user_plugin_getenv(user, "expire") == NULL) {
		if (user->mail_debug)
			i_debug("expire: No expire setting - plugin disabled");
		return;
	}
	if (dict_uri == NULL) {
		i_error("expire plugin: expire_dict setting missing");
		return;
	}

	/* we're using only shared dictionary, the username doesn't matter. */
	if (dict_init(dict_uri, DICT_DATA_TYPE_UINT32, "",
		      user->set->base_dir, &db, &error) < 0) {
		i_error("expire plugin: dict_init(%s) failed: %s",
			dict_uri, error);
		return;
	}

	euser = p_new(user->pool, struct expire_mail_user, 1);
	euser->module_ctx.super = *v;
	user->vlast = &euser->module_ctx.super;
	v->deinit = expire_mail_user_deinit;

	euser->db = db;
	euser->set = expire_set_init(expire_get_patterns(user));
	euser->expire_cache = mail_user_plugin_getenv(user, "expire_cache") != NULL;
	MODULE_CONTEXT_SET(user, expire_mail_user_module, euser);
}

static struct mail_storage_hooks expire_mail_storage_hooks = {
	.mail_namespaces_created = expire_mail_namespaces_created,
	.mailbox_allocated = expire_mailbox_allocated,
	.mail_allocated = expire_mail_allocated
};

void expire_plugin_init(struct module *module)
{
	mail_storage_hooks_add(module, &expire_mail_storage_hooks);
}

void expire_plugin_deinit(void)
{
	mail_storage_hooks_remove(&expire_mail_storage_hooks);
}


text:
module VagrantPlugins
  module ProviderVMwareFree
    module Action
      class ClearSharedFolders
        def initialize(app, env)
          @app = app
        end

        def call(env)
          env[:machine].provider.driver.clear_shared_folders

          @app.call(env)
        end
      end
    end
  end
end


text:
import { getChildOfKind, isClassLikeDeclaration } from "tsutils";
import * as ts from "typescript";

import { showWarningOnce } from "../error";
import * as Lint from "../index";

const OPTION_NO_PUBLIC = "no-public";
const OPTION_CHECK_ACCESSOR = "check-accessor";
const OPTION_CHECK_CONSTRUCTOR = "check-constructor";

interface Options {
    noPublic: boolean;
    checkAccessor: boolean;
    checkConstructor: boolean;
}

export class Rule extends Lint.Rules.AbstractRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "member-access",
        description: "Requires explicit visibility declarations for class members.",
        rationale: "Explicit visibility declarations can make code more readable and accessible for those new to TS.",
        optionsDescription: Lint.Utils.dedent`
            These arguments may be optionally provided:

            * \`"no-public"\` forbids public accessibility to be specified, because this is the default.
            * \`"check-accessor"\` enforces explicit visibility on get/set accessors
            * \`"check-constructor"\`  enforces explicit visibility on constructors`,
        options: {
            type: "array",
            items: {
                type: "string",
                enum: [OPTION_NO_PUBLIC, OPTION_CHECK_ACCESSOR, OPTION_CHECK_CONSTRUCTOR],
            },
            minLength: 0,
            maxLength: 3,
        },
        optionExamples: [true, [true, OPTION_NO_PUBLIC], [true, OPTION_CHECK_ACCESSOR]],
        type: "typescript",
        typescriptOnly: true,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING_NO_PUBLIC = "'public' is implicit.";

    public static FAILURE_STRING_FACTORY(memberType: string, memberName: string | undefined): string {
        memberName = memberName === undefined ? "" : ` '${memberName}'`;
        return `The ${memberType}${memberName} must be marked either 'private', 'public', or 'protected'`;
    }

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        const options = this.ruleArguments;
        const noPublic = options.indexOf(OPTION_NO_PUBLIC) !== -1;
        let checkAccessor = options.indexOf(OPTION_CHECK_ACCESSOR) !== -1;
        let checkConstructor = options.indexOf(OPTION_CHECK_CONSTRUCTOR) !== -1;
        if (noPublic) {
            if (checkAccessor || checkConstructor) {
                showWarningOnce(`Warning: ${this.ruleName} - If 'no-public' is present, it should be the only option.`);
                return [];
            }
            checkAccessor = checkConstructor = true;
        }
        return this.applyWithFunction(sourceFile, walk, {
            checkAccessor,
            checkConstructor,
            noPublic,
        });
    }
}

function walk(ctx: Lint.WalkContext<Options>) {
    const {noPublic, checkAccessor, checkConstructor} = ctx.options;
    return ts.forEachChild(ctx.sourceFile, function recur(node: ts.Node): void {
        if (isClassLikeDeclaration(node)) {
            for (const child of node.members) {
                if (shouldCheck(child)) {
                    check(child);
                }
            }
        }
        return ts.forEachChild(node, recur);
    });

    function shouldCheck(node: ts.ClassElement): boolean {
        switch (node.kind) {
            case ts.SyntaxKind.Constructor:
                return checkConstructor;
            case ts.SyntaxKind.GetAccessor:
            case ts.SyntaxKind.SetAccessor:
                return checkAccessor;
            case ts.SyntaxKind.MethodDeclaration:
            case ts.SyntaxKind.PropertyDeclaration:
                return true;
            default:
                return false;
        }
    }

    function check(node: ts.ClassElement): void {
        if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.PrivateKeyword)) {
            return;
        }

        const isPublic = Lint.hasModifier(node.modifiers, ts.SyntaxKind.PublicKeyword);

        if (noPublic && isPublic) {
            const publicKeyword = node.modifiers!.find((m) => m.kind === ts.SyntaxKind.PublicKeyword)!;
            ctx.addFailureAtNode(publicKeyword, Rule.FAILURE_STRING_NO_PUBLIC);
        }
        if (!noPublic && !isPublic) {
            const nameNode = node.kind === ts.SyntaxKind.Constructor
                ? getChildOfKind(node, ts.SyntaxKind.ConstructorKeyword, ctx.sourceFile)!
                : node.name !== undefined ? node.name : node;
            const memberName = node.name !== undefined && node.name.kind === ts.SyntaxKind.Identifier ? node.name.text : undefined;
            ctx.addFailureAtNode(nameNode, Rule.FAILURE_STRING_FACTORY(typeToString(node), memberName));
        }
    }
}

function typeToString(node: ts.ClassElement): string {
    switch (node.kind) {
        case ts.SyntaxKind.MethodDeclaration:
            return "class method";
        case ts.SyntaxKind.PropertyDeclaration:
            return "class property";
        case ts.SyntaxKind.Constructor:
            return "class constructor";
        case ts.SyntaxKind.GetAccessor:
            return "get property accessor";
        case ts.SyntaxKind.SetAccessor:
            return "set property accessor";
        default:
            throw new Error(`unhandled node type ${ts.SyntaxKind[node.kind]}`);
    }
}


text:
var gDebug = 0;
var gLineCount = 0;
var gStartTargetLine = 0;
var gEndTargetLine = 0;
var gTargetNode = null;

var gEntityConverter = null;
var gWrapLongLines = false;
const gViewSourceCSS = 'resource://gre-resources/viewsource.css';
const NS_XHTML = 'http://www.w3.org/1999/xhtml';

// These are markers used to delimit the selection during processing. They
// are removed from the final rendering, but we pick space-like characters for
// safety (and futhermore, these are known to be mapped to a 0-length string
// in transliterate.properties). It is okay to set start=end, we use findNext()
// U+200B ZERO WIDTH SPACE
const MARK_SELECTION_START = '\u200B\u200B\u200B\u200B\u200B';
const MARK_SELECTION_END = '\u200B\u200B\u200B\u200B\u200B';

function onLoadViewPartialSource()
{
  // check the view_source.wrap_long_lines pref and set the menuitem's checked attribute accordingly
  if (gPrefs) {
    try {
      var wraplonglinesPrefValue = gPrefs.getBoolPref('view_source.wrap_long_lines');
      if (wraplonglinesPrefValue) {
        document.getElementById('menu_wrapLongLines').setAttribute('checked', 'true');
        gWrapLongLines = true;
      }
    } catch (e) { }
    try {
      document.getElementById("menu_highlightSyntax").setAttribute("checked", gPrefs.getBoolPref("view_source.syntax_highlight"));
    } catch (e) {
    }
  } else {
    document.getElementById("menu_highlightSyntax").setAttribute("hidden", "true");
  }

  if (window.arguments[3] == 'selection')
    viewPartialSourceForSelection(window.arguments[2]);
  else
    viewPartialSourceForFragment(window.arguments[2], window.arguments[3]);

  gBrowser.droppedLinkHandler = function (event, url, name) {
    viewSource(url)
    event.preventDefault();
  }

  window.content.focus();
}

////////////////////////////////////////////////////////////////////////////////
// view-source of a selection with the special effect of remapping the selection
// to the underlying view-source output
function viewPartialSourceForSelection(selection)
{
  var range = selection.getRangeAt(0);
  var ancestorContainer = range.commonAncestorContainer;
  var doc = ancestorContainer.ownerDocument;

  var startContainer = range.startContainer;
  var endContainer = range.endContainer;
  var startOffset = range.startOffset;
  var endOffset = range.endOffset;

  // let the ancestor be an element
  if (ancestorContainer.nodeType == Node.TEXT_NODE ||
      ancestorContainer.nodeType == Node.CDATA_SECTION_NODE)
    ancestorContainer = ancestorContainer.parentNode;

  // for selectAll, let's use the entire document, including ...
  // @see DocumentViewerImpl::SelectAll() for how selectAll is implemented
  try {
    if (ancestorContainer == doc.body)
      ancestorContainer = doc.documentElement;
  } catch (e) { }

  // each path is a "child sequence" (a.k.a. "tumbler") that
  // descends from the ancestor down to the boundary point
  var startPath = getPath(ancestorContainer, startContainer);
  var endPath = getPath(ancestorContainer, endContainer);

  // clone the fragment of interest and reset everything to be relative to it
  // note: it is with the clone that we operate/munge from now on
  ancestorContainer = ancestorContainer.cloneNode(true);
  startContainer = ancestorContainer;
  endContainer = ancestorContainer;

  // Only bother with the selection if it can be remapped. Don't mess with
  // leaf elements (such as <isindex>) that secretly use anynomous content
  // for their display appearance.
  var canDrawSelection = ancestorContainer.hasChildNodes();
  if (canDrawSelection) {
    var i;
    for (i = startPath ? startPath.length-1 : -1; i >= 0; i--) {
      startContainer = startContainer.childNodes.item(startPath[i]);
    }
    for (i = endPath ? endPath.length-1 : -1; i >= 0; i--) {
      endContainer = endContainer.childNodes.item(endPath[i]);
    }

    // add special markers to record the extent of the selection
    // note: |startOffset| and |endOffset| are interpreted either as
    // offsets in the text data or as child indices (see the Range spec)
    // (here, munging the end point first to keep the start point safe...)
    var tmpNode;
    if (endContainer.nodeType == Node.TEXT_NODE ||
        endContainer.nodeType == Node.CDATA_SECTION_NODE) {
      // do some extra tweaks to try to avoid the view-source output to look like
      // ...<tag>]... or ...]</tag>... (where ']' marks the end of the selection).
      // To get a neat output, the idea here is to remap the end point from:
      // 1. ...<tag>]...   to   ...]<tag>...
      // 2. ...]</tag>...  to   ...</tag>]...
      if ((endOffset > 0 && endOffset < endContainer.data.length) ||
          !endContainer.parentNode || !endContainer.parentNode.parentNode)
        endContainer.insertData(endOffset, MARK_SELECTION_END);
      else {
        tmpNode = doc.createTextNode(MARK_SELECTION_END);
        endContainer = endContainer.parentNode;
        if (endOffset == 0)
          endContainer.parentNode.insertBefore(tmpNode, endContainer);
        else
          endContainer.parentNode.insertBefore(tmpNode, endContainer.nextSibling);
      }
    }
    else {
      tmpNode = doc.createTextNode(MARK_SELECTION_END);
      endContainer.insertBefore(tmpNode, endContainer.childNodes.item(endOffset));
    }

    if (startContainer.nodeType == Node.TEXT_NODE ||
        startContainer.nodeType == Node.CDATA_SECTION_NODE) {
      // do some extra tweaks to try to avoid the view-source output to look like
      // ...<tag>[... or ...[</tag>... (where '[' marks the start of the selection).
      // To get a neat output, the idea here is to remap the start point from:
      // 1. ...<tag>[...   to   ...[<tag>...
      // 2. ...[</tag>...  to   ...</tag>[...
      if ((startOffset > 0 && startOffset < startContainer.data.length) ||
          !startContainer.parentNode || !startContainer.parentNode.parentNode ||
          startContainer != startContainer.parentNode.lastChild)
        startContainer.insertData(startOffset, MARK_SELECTION_START);
      else {
        tmpNode = doc.createTextNode(MARK_SELECTION_START);
        startContainer = startContainer.parentNode;
        if (startOffset == 0)
          startContainer.parentNode.insertBefore(tmpNode, startContainer);
        else
          startContainer.parentNode.insertBefore(tmpNode, startContainer.nextSibling);
      }
    }
    else {
      tmpNode = doc.createTextNode(MARK_SELECTION_START);
      startContainer.insertBefore(tmpNode, startContainer.childNodes.item(startOffset));
    }
  }

  // now extract and display the syntax highlighted source
  tmpNode = doc.createElementNS(NS_XHTML, 'div');
  tmpNode.appendChild(ancestorContainer);

  // the load is aynchronous and so we will wait until the view-source DOM is done
  // before drawing the selection.
  if (canDrawSelection) {
    window.document.getElementById("content").addEventListener("load", drawSelection, true);
  }

  // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
  var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE;
  getWebNavigation().loadURI("view-source:data:text/html;charset=utf-8,"
                             + encodeURIComponent(tmpNode.innerHTML),
                             loadFlags, null, null, null);
}

////////////////////////////////////////////////////////////////////////////////
// helper to get a path like FIXptr, but with an array instead of the "tumbler" notation
// see FIXptr: http://lists.w3.org/Archives/Public/www-xml-linking-comments/2001AprJun/att-0074/01-NOTE-FIXptr-20010425.htm
function getPath(ancestor, node)
{
  var n = node;
  var p = n.parentNode;
  if (n == ancestor || !p)
    return null;
  var path = new Array();
  if (!path)
    return null;
  do {
    for (var i = 0; i < p.childNodes.length; i++) {
      if (p.childNodes.item(i) == n) {
        path.push(i);
        break;
      }
    }
    n = p;
    p = n.parentNode;
  } while (n != ancestor && p);
  return path;
}

////////////////////////////////////////////////////////////////////////////////
// using special markers left in the serialized source, this helper makes the
// underlying markup of the selected fragment to automatically appear as selected
// on the inflated view-source DOM
function drawSelection()
{
  gBrowser.contentDocument.title =
    gViewSourceBundle.getString("viewSelectionSourceTitle");

  // find the special selection markers that we added earlier, and
  // draw the selection between the two...
  var findService = null;
  try {
    // get the find service which stores the global find state
    findService = Components.classes["@mozilla.org/find/find_service;1"]
                            .getService(Components.interfaces.nsIFindService);
  } catch(e) { }
  if (!findService)
    return;

  // cache the current global find state
  var matchCase     = findService.matchCase;
  var entireWord    = findService.entireWord;
  var wrapFind      = findService.wrapFind;
  var findBackwards = findService.findBackwards;
  var searchString  = findService.searchString;
  var replaceString = findService.replaceString;

  // setup our find instance
  var findInst = gBrowser.webBrowserFind;
  findInst.matchCase = true;
  findInst.entireWord = false;
  findInst.wrapFind = true;
  findInst.findBackwards = false;

  // ...lookup the start mark
  findInst.searchString = MARK_SELECTION_START;
  var startLength = MARK_SELECTION_START.length;
  findInst.findNext();

  var selection = content.getSelection();
  if (!selection.rangeCount)
    return;

  var range = selection.getRangeAt(0);

  var startContainer = range.startContainer;
  var startOffset = range.startOffset;

  // ...lookup the end mark
  findInst.searchString = MARK_SELECTION_END;
  var endLength = MARK_SELECTION_END.length;
  findInst.findNext();

  var endContainer = selection.anchorNode;
  var endOffset = selection.anchorOffset;

  // reset the selection that find has left
  selection.removeAllRanges();

  // delete the special markers now...
  endContainer.deleteData(endOffset, endLength);
  startContainer.deleteData(startOffset, startLength);
  if (startContainer == endContainer)
    endOffset -= startLength; // has shrunk if on same text node...
  range.setEnd(endContainer, endOffset);

  // show the selection and scroll it into view
  selection.addRange(range);
  // the default behavior of the selection is to scroll at the end of
  // the selection, whereas in this situation, it is more user-friendly
  // to scroll at the beginning. So we override the default behavior here
  try {
    getSelectionController().scrollSelectionIntoView(
                               Ci.nsISelectionController.SELECTION_NORMAL,
                               Ci.nsISelectionController.SELECTION_ANCHOR_REGION,
                               true);
  }
  catch(e) { }

  // restore the current find state
  findService.matchCase     = matchCase;
  findService.entireWord    = entireWord;
  findService.wrapFind      = wrapFind;
  findService.findBackwards = findBackwards;
  findService.searchString  = searchString;
  findService.replaceString = replaceString;

  findInst.matchCase     = matchCase;
  findInst.entireWord    = entireWord;
  findInst.wrapFind      = wrapFind;
  findInst.findBackwards = findBackwards;
  findInst.searchString  = searchString;
}

////////////////////////////////////////////////////////////////////////////////
// special handler for markups such as MathML where reformatting the output is
// helpful
function viewPartialSourceForFragment(node, context)
{
  gTargetNode = node;
  if (gTargetNode && gTargetNode.nodeType == Node.TEXT_NODE)
    gTargetNode = gTargetNode.parentNode;

  // walk up the tree to the top-level element (e.g., <math>, <svg>)
  var topTag;
  if (context == 'mathml')
    topTag = 'math';
  else
    throw 'not reached';
  var topNode = gTargetNode;
  while (topNode && topNode.localName != topTag)
    topNode = topNode.parentNode;
  if (!topNode)
    return;

  // serialize
  var title = gViewSourceBundle.getString("viewMathMLSourceTitle");
  var wrapClass = gWrapLongLines ? ' class="wrap"' : '';
  var source =
    '<!DOCTYPE html>'
  + ''
  + '<title>' + title + '</title>'
  + '<link rel="stylesheet" type="text/css" href="' + gViewSourceCSS + '">'
  + ''
  + ''
  + ''
  + '
'
  + getOuterMarkup(topNode, 0)
  + '
'
  ; // end

  // display
  gBrowser.loadURI("data:text/html;charset=utf-8," + encodeURIComponent(source));
}

////////////////////////////////////////////////////////////////////////////////
function getInnerMarkup(node, indent) {
  var str = '';
  for (var i = 0; i < node.childNodes.length; i++) {
    str += getOuterMarkup(node.childNodes.item(i), indent);
  }
  return str;
}

////////////////////////////////////////////////////////////////////////////////
function getOuterMarkup(node, indent) {
  var newline = '';
  var padding = '';
  var str = '';
  if (node == gTargetNode) {
    gStartTargetLine = gLineCount;
    str += '

';
  }

  switch (node.nodeType) {
  case Node.ELEMENT_NODE: // Element
    // to avoid the wide gap problem, '\n' is not emitted on the first
    // line and the lines before & after the
...

    if (gLineCount > 0 &&
        gLineCount != gStartTargetLine &&
        gLineCount != gEndTargetLine) {
      newline = '\n';
    }
    gLineCount++;
    if (gDebug) {
      newline += gLineCount;
    }
    for (var k = 0; k < indent; k++) {
      padding += ' ';
    }
    str += newline + padding
        +  '<' + node.nodeName + '';
    for (var i = 0; i < node.attributes.length; i++) {
      var attr = node.attributes.item(i);
      if (!gDebug && attr.nodeName.match(/^[-_]moz/)) {
        continue;
      }
      str += ' '
          +  attr.nodeName
          +  '="'
          +  unicodeTOentity(attr.nodeValue)
          +  '"';
    }
    if (!node.hasChildNodes()) {
      str += '/>';
    }
    else {
      str += '>';
      var oldLine = gLineCount;
      str += getInnerMarkup(node, indent + 2);
      if (oldLine == gLineCount) {
        newline = '';
        padding = '';
      }
      else {
        newline = (gLineCount == gEndTargetLine) ? '' : '\n';
        gLineCount++;
        if (gDebug) {
          newline += gLineCount;
        }
      }
      str += newline + padding
          +  '</' + node.nodeName + '>';
    }
    break;
  case Node.TEXT_NODE: // Text
    var tmp = node.nodeValue;
    tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
    tmp = tmp.replace(/^ +/, "");
    tmp = tmp.replace(/ +$/, "");
    if (tmp.length != 0) {
      str += '' + unicodeTOentity(tmp) + '';
    }
    break;
  default:
    break;
  }

  if (node == gTargetNode) {
    gEndTargetLine = gLineCount;
    str += '

';
  }
  return str;
}

////////////////////////////////////////////////////////////////////////////////
function unicodeTOentity(text)
{
  const charTable = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;'
  };

  function charTableLookup(letter) {
    return charTable[letter];
  }

  function convertEntity(letter) {
    try {
      var unichar = gEntityConverter.ConvertToEntity(letter, entityVersion);
      var entity = unichar.substring(1); // extract '&'
      return '&' + entity + '';
    } catch (ex) {
      return letter;
    }
  }

  if (!gEntityConverter) {
    try {
      gEntityConverter =
        Components.classes["@mozilla.org/intl/entityconverter;1"]
                  .createInstance(Components.interfaces.nsIEntityConverter);
    } catch(e) { }
  }

  const entityVersion = Components.interfaces.nsIEntityConverter.entityW3C;

  var str = text;

  // replace chars in our charTable
  str = str.replace(/[<>&"]/g, charTableLookup);

  // replace chars > 0x7f via nsIEntityConverter
  str = str.replace(/[^\0-\u007f]/g, convertEntity);

  return str;
}


text:
<?php
/**
 * The act of editing a recipient by removing one of its objects.
 *
 * @see    http://schema.org/DeleteAction
*/
abstract class TypeDeleteAction extends TypeUpdateAction
{
	/**
	 * The Schema.org Type Scope
	 *
	 * @var string
	 */
	protected static $scope = 'https://schema.org/DeleteAction';
}


text:
import { SortDescending20 } from "../../";

export = SortDescending20;


text:
package com.arrah.framework;

/* This file is used for getting information about
 * table - like pattern, duplicate total count,
 * fill ratio.
 *
 */

import com.arrahtec.dataquality.core.FillCheck;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Vector;

public class TableFirstInformation {
    private Vector<Double> patV;

    private Rdbms_NewConn conn;

    public TableFirstInformation(Rdbms_NewConn conn) {
        this.conn = conn;
    }

    public double getTableCount(String tableName) throws SQLException {

        double tabCount = 0;
        String countS = "0";

        QueryBuilder querybuilder = new QueryBuilder(conn, tableName);
        conn.openConn();
        String s2 = querybuilder.get_tableCount_query();

        for (ResultSet resultset1 = conn.runQuery(s2); resultset1
                .next(); )
            countS = resultset1.getString("row_count");

        tabCount = Double.parseDouble(countS);
        conn.closeConn();

        return tabCount;
        // end of table count
    }

    public double getPatternCount(String tableName) throws SQLException {
        double patCount = 0;
        patV = new Vector<Double>();

        QueryBuilder querybuilder = new QueryBuilder(conn, tableName,
                conn.getDBType());
        @SuppressWarnings("rawtypes")
        Vector[] avector = conn.populateColumn(tableName, null);
        conn.openConn();
        String s2 = querybuilder.get_table_duprow_query(avector[0], "");

        ResultSet resultset1 = conn.runQuery(s2);
        if (resultset1 == null) {
            return patCount;
        }
        while (resultset1.next()) {
            String patC = resultset1.getString(1); // get count details
            double patternC = Double.parseDouble(patC);
            patV.add(patternC);
            patCount++;
        }
        conn.closeConn();

        return patCount;
    }

    /* This function should be called after getPatternCount which will fill the vector
     *
     */
    public Vector<Double> getPatternValue() {
        return patV;
    }

    /* Get profiler information in hashmap.
     * Calling function should parse keys and get information.
     */
    public HashMap<String, Double> getTableProfile(String tableName) throws SQLException {
        double dupcount = 0;
        HashMap<String, Double> hm = new HashMap<String, Double>();
        double tabCount = getTableCount(tableName);
        hm.put("Total Count", tabCount);
        if (tabCount == 0) return hm; //Empty table no need to further progress.

        double patCount = getPatternCount(tableName);
        hm.put("Duplicate Pattern", patCount);
        for (int i = 0; i < patCount; i++) {
            dupcount += patV.get(i);
        }
        hm.put("Duplicate Count", dupcount);
        hm.put("Duplicate %", (dupcount / tabCount) * 100);
        hm.put("Unique Pattern", tabCount - dupcount);
        hm.put("Unique %", ((tabCount - dupcount) / tabCount) * 100);
        return hm;
    }

    /* Get the fill information
     *
     */
    public int[] getTableFill(String tableName) throws Exception {
        int[] emptyCount = null;

        QueryBuilder querybuilder = new QueryBuilder(conn, tableName
        );
        try {
            String s2 = querybuilder.get_tableAll_query();
            ResultSet resultset1 = conn.runQuery(s2);
            ResultsetToRTM resultsetToRTM = new ResultsetToRTM(conn);
            ReportTableModel rtm = resultsetToRTM.getSQLValue(resultset1, true);
            emptyCount = FillCheck.getEmptyCount(rtm);
            return emptyCount;

        } catch (SQLException e) {
            throw new Exception("\n Table Count Sql Error :" + e.getMessage());
        }
    }

}


text:
/** \file ElInfo3d.h */

#pragma once

#include <boost/numeric/mtl/mtl.hpp>

#include "ElInfo.hpp"

namespace AMDiS
{

  /** \ingroup Traverse
   * \brief
   * ElInfo class for 3-dimensional elements (\ref Tetrahedron).
   */
  class ElInfo3d : public ElInfo
  {
  public:
    /// Constructor. Calls ElInfo's protected Constructor.
    ElInfo3d(Mesh* aMesh)
      : ElInfo(aMesh)
    {
      tmpWorldVecs.resize(3);
      for (int i = 0; i < 3; i++)
        tmpWorldVecs[i].resize(3);
    }

    /// Assignment operator
    ElInfo3d& operator=(const ElInfo3d& rhs)
    {
      ElInfo::operator=(rhs);
      elType = rhs.elType;
      orientation = rhs.orientation;
      return *this;
    }

    /// get ElInfo's \ref orientation
    signed char getOrientation() const
    {
      return orientation;
    }

    /// set ElInfo's \ref orientation to o
    void setOrientation(signed char o)
    {
      orientation = o;
    }

    /// 3-dimensional realisation of ElInfo's fillElInfo method.
    virtual void fillElInfo(int ichild, const ElInfo* elinfo_old) override;

    /// 3-dimensional realisation of ElInfo's fillMacroInfo method.
    virtual void fillMacroInfo(const MacroElement*) override;

    /// 3-dimensional realisation of ElInfo's worldToCoord method.
    virtual int worldToCoord(const WorldVector<double>& w, DimVec<double>& l) const override;

    /// 3-dimensional realisation of ElInfo's calcGrdLambda method.
    virtual double calcGrdLambda(DimVec<WorldVector<double>>& grd_lam) override;

    /// 3-dimensional realisation of ElInfo's getNormal method.
    virtual double getNormal(int side, WorldVector<double>& normal) const override;

    virtual double getElementNormal(WorldVector<double>& /*normal*/) const override
    {
      FUNCNAME("ElInfo3d::getElementNormal()");
      ERROR_EXIT("ElementNormal not available in 3d!");
      return 0.0;
    }

    /// update ElInfo after refinement (of some neighbours). Only in 3d!
    void update();

    /// implements \ref Elnfo::getSubElemCoordsMat
    virtual mtl::dense2D<double>& getSubElemCoordsMat(int degree) const override;

  protected:
    /** \brief
     * +/- 1: sign of the determinant of the transformation to the reference
     * element with vertices (0,0,0), (1,1,1), (1,1,0), (1,0,0).
     */
    signed char orientation;

    /// Tmp vectors used for calculations in calcGrdLambda and getNormal().
    std::vector<std::vector<double>> tmpWorldVecs;

    static double mat_d1_left_val[4][4];
    static mtl::dense2D<double> mat_d1_left;

    static double mat_d1_l0_right_val[4][4];
    static mtl::dense2D<double> mat_d1_l0_right;

    static double mat_d1_l12_right_val[4][4];
    static mtl::dense2D<double> mat_d1_l12_right;

    static double mat_d4_left_val[35][35];
    static mtl::dense2D<double> mat_d4_left;

    static double mat_d4_l0_right_val[35][35];
    static mtl::dense2D<double> mat_d4_l0_right;

    static double mat_d4_l12_right_val[35][35];
    static mtl::dense2D<double> mat_d4_l12_right;
  };

} // end namespace AMDiS


text:
<?php

namespace Sylius\Bundle\CartBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This class contains the configuration information for the bundle.
 *
 * This information is solely responsible for how the different configuration
 * sections are normalized, and merged.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('sylius_cart');

        $rootNode
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('provider')->defaultValue('sylius.cart_provider.default')->end()
                ->scalarNode('resolver')->isRequired()->cannotBeEmpty()->end()
                ->scalarNode('storage')->defaultValue('sylius.cart_storage.session')->end()
            ->end()
        ;

        $this->addClassesSection($rootNode);
        $this->addValidationGroupsSection($rootNode);

        return $treeBuilder;
    }

    /**
     * Adds `validation_groups` section.
     *
     * @param ArrayNodeDefinition $node
     */
    private function addValidationGroupsSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('validation_groups')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('cart')
                            ->prototype('scalar')->end()
                            ->defaultValue(array('sylius'))
                        ->end()
                        ->arrayNode('item')
                            ->prototype('scalar')->end()
                            ->defaultValue(array('sylius'))
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * Adds `classes` section.
     *
     * @param ArrayNodeDefinition $node
     */
    private function addClassesSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('classes')
                    ->isRequired()
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('cart')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('controller')->defaultValue('Sylius\Bundle\CartBundle\Controller\CartController')->end()
                                ->scalarNode('form')->defaultValue('Sylius\Bundle\CartBundle\Form\Type\CartType')->end()
                            ->end()
                        ->end()
                        ->arrayNode('item')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('controller')->defaultValue('Sylius\Bundle\CartBundle\Controller\CartItemController')->end()
                                ->scalarNode('form')->defaultValue('Sylius\Bundle\CartBundle\Form\Type\CartItemType')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }
}


text:
<?php

namespace Guzzle\Service;

/**
 * Interface used for loading configuration data (service descriptions, service builder configs, etc)
 *
 * If a loaded configuration data sets includes a top level key containing an 'includes' section, then the data in the
 * file will extend the merged result of all of the included config files.
 */
interface ConfigLoaderInterface
{
    /**
     * Loads configuration data and returns an array of the loaded result
     *
     * @param mixed $config  Data to load (filename or array of data)
     * @param array $options Array of options to use when loading
     *
     * @return mixed
     */
    public function load($config, array $options = array());
}


text:
package Domineering;
/** The game of Cram. */
public class Cram extends Domineering{

	/** No special initialization is required. */
	public Cram(){
		super();
	}

	/** Play until someone wins. */
	public void play(){
		int player = 1;
		while(true){
			System.out.println("\n" + this);
				System.out.println("Player " + player + " to play");
			if(!(hasLegalMoveFor(HORIZONTAL) || hasLegalMoveFor(VERTICAL))){
				System.out.println("No legal moves -- you lose!");
				return;
			}
			System.out.println("Row: ");
			int row = INPUT.nextInt();
			System.out.println("Column: ");
			int column = INPUT.nextInt();
			INPUT.nextLine();			//To clear out input
			System.out.println("Play horizontally (y/n)? ");
			boolean direction = placeHorizontally(INPUT.nextLine());
			/*
			while(squares[row][column]
					|| row < 0 || column < 0
					|| (!player && (row > size - 1 || column > size - 2))		//ÊÇ·ñÔ½½ç
					|| (player && (row > size - 2 || column > size - 1))
					|| (!player && squares[row][column + 1])		//ÊÇ·ñÖظ´
					|| (player && squares[row + 1][column])
					){
				System.out.println("Invalid play!Try again: ");
				System.out.println("Row: ");
				row = INPUT.nextInt();
				System.out.println("Column: ");
				column = INPUT.nextInt();
				INPUT.nextLine();			//To clear out input
				System.out.println("Play horizontally (y/n)? ");
				direction = placeHorizontally(INPUT.nextLine());
			}
			*/
			playAt(row, column, direction);
			player = 3 - player;
		}
	}

	/** Return true if player wants to place horizontally. */
	public boolean placeHorizontally(String str){
		if(str.equals("y")){
			return false;
		}
		else{
			return true;
		}
	}

	/** Create and play the game. */
	public static void main(String[] args) {
		System.out.println("Welcome to Cram.");
		Cram game = new Cram();
		game.play();

	}

}
/** . */


text:
declare namespace javax {
  namespace swing {
    namespace text {

      class WrappedPlainView extends javax.swing.text.BoxView implements javax.swing.text.TabExpander {
        metrics: java.awt.FontMetrics
        lineBuffer: javax.swing.text.Segment
        widthChanging: boolean
        tabBase: int
        tabSize: float
        wordWrap: boolean
        sel0: int
        sel1: int
        unselected: java.awt.Color
        selected: java.awt.Color
        public constructor(arg0: javax.swing.text.Element)
        public constructor(arg0: javax.swing.text.Element, arg1: boolean | java.lang.Boolean)
        protected getTabSize(): number
        protected drawLine(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: java.awt.Graphics, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): void
        protected drawLine(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: java.awt.Graphics2D, arg3: number | java.lang.Float, arg4: number | java.lang.Float): void
        protected drawUnselectedText(arg0: java.awt.Graphics, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
        protected drawUnselectedText(arg0: java.awt.Graphics2D, arg1: number | java.lang.Float, arg2: number | java.lang.Float, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
        protected drawSelectedText(arg0: java.awt.Graphics, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
        protected drawSelectedText(arg0: java.awt.Graphics2D, arg1: number | java.lang.Float, arg2: number | java.lang.Float, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
        protected getLineBuffer(): javax.swing.text.Segment
        protected calculateBreakPosition(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer): number
        protected loadChildren(arg0: javax.swing.text.ViewFactory | javax.swing.text.ViewFactory$$lambda): void
        updateChildren(arg0: javax.swing.event.DocumentEvent, arg1: java.awt.Shape): void
        loadText(arg0: javax.swing.text.Segment, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): void
        updateMetrics(): void
        public nextTabStop(arg0: number | java.lang.Float, arg1: number | java.lang.Integer): number
        public paint(arg0: java.awt.Graphics, arg1: java.awt.Shape): void
        public setSize(arg0: number | java.lang.Float, arg1: number | java.lang.Float): void
        public getPreferredSpan(arg0: number | java.lang.Integer): number
        public getMinimumSpan(arg0: number | java.lang.Integer): number
        public getMaximumSpan(arg0: number | java.lang.Integer): number
        public insertUpdate(arg0: javax.swing.event.DocumentEvent, arg1: java.awt.Shape, arg2: javax.swing.text.ViewFactory | javax.swing.text.ViewFactory$$lambda): void
        public removeUpdate(arg0: javax.swing.event.DocumentEvent, arg1: java.awt.Shape, arg2: javax.swing.text.ViewFactory | javax.swing.text.ViewFactory$$lambda): void
        public changedUpdate(arg0: javax.swing.event.DocumentEvent, arg1: java.awt.Shape, arg2: javax.swing.text.ViewFactory | javax.swing.text.ViewFactory$$lambda): void
      }

    }
  }
}


text:
/**
 *
 */
package com.github.commons.utils.security;

/**
 * @author wangshuli
 *
 */

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*******************************************************************************
 * AES加解密算法
 *
 * @author arix04
 */

public class AESUtil {

    private static Logger log = LoggerFactory.getLogger(AESUtil.class);

    // 加密
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new IllegalArgumentException("sKey can't be null.");
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            throw new IllegalArgumentException("Key长度不是16位");
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return Base64.encodeBase64String(encrypted);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }

    /**
     * 解密
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                throw new IllegalArgumentException("sKey can't be null.");
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                throw new IllegalArgumentException("Key长度不是16位");
            }
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decodeBase64(sSrc);// 先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                log.error("解密异常,sKey:" + sKey, e);
                return null;
            }
        } catch (Exception ex) {
            log.error("解密异常,sSrc=" + sSrc + ",sKey=" + sKey, ex);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String encrypt = AESUtil.encrypt("test", "1234567890123456");

        System.out.println(encrypt);

        System.out.println(AESUtil.decrypt(encrypt, "1234567890123456"));
    }
}


text:
#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertices.h"
#include "Model/Reader/Slice1507/NMR_ModelReader_Slice1507_Vertex.h"
#include "Common/NMR_StringUtils.h"
#include "Model/Classes/NMR_ModelConstants.h"

namespace NMR {

	void CModelReaderNode_Slices1507_Vertices::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) {

	}

	void CModelReaderNode_Slices1507_Vertices::OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader) {
		if (strcmp(pChildName, XML_3MF_ELEMENT_SLICEVERTEX) == 0) {
			PModelReaderNode_Slices1507_Vertex pXMLNode = std::make_shared<CModelReaderNode_Slices1507_Vertex>(m_pSlice, m_pWarnings);
			pXMLNode->parseXML(pXMLReader);
		}
		else
			m_pWarnings->addException(CNMRException(NMR_ERROR_NAMESPACE_INVALID_ELEMENT), mrwInvalidOptionalValue);
	}

	CModelReaderNode_Slices1507_Vertices::CModelReaderNode_Slices1507_Vertices(_In_ CSlice *pSlice, _In_ PModelWarnings pWarnings) : CModelReaderNode(pWarnings) {
		m_pSlice = pSlice;
	}

	void CModelReaderNode_Slices1507_Vertices::parseXML(_In_ CXmlReader * pXMLReader) {
		// Parse name
		parseName(pXMLReader);

		// Parse attribute
		parseAttributes(pXMLReader);

		// Parse Content
		parseContent(pXMLReader);
	}
}


text:
==================
sophisticated-dmrg
==================

This code is an expanded `density-matrix renormalization group
<http://en.wikipedia.org/wiki/Density_matrix_renormalization_group>`_
(DMRG) program, based on code written for a `tutorial
<http://simple-dmrg.readthedocs.org/>`_ given originally at the `2013
summer school on quantum spin liquids
<http://www.democritos.it/qsl2013/>`_, in Trieste, Italy.  It
implements DMRG its traditional formulation (i.e. without using matrix
product states).  DMRG is a numerical method that allows for the
efficient simulation of quantum model Hamiltonians.  Since it is a
low-entanglement approximation, it often works quite well for
one-dimensional systems, giving results that are nearly exact.

Source code: https://github.com/simple-dmrg/sophisticated-dmrg/

Documentation: http://sophisticated-dmrg.readthedocs.org/

Authors
=======

* James R. Garrison (UCSB)
* Ryan V. Mishmash (UCSB)

Licensed under the MIT license.  If you plan to publish work based on
this code, please contact us to find out how to cite us.


text:
namespace SimpleMvc.Framework.Security
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class Authentication
    {
        internal Authentication()
        {
            this.IsAuthenticated = false;
        }

        internal Authentication(string name)
        {
            this.Name = name;

            this.IsAuthenticated = true;
        }

        public bool IsAuthenticated { get; private set; }

        public string Name { get; internal set; }
    }
}


text:
package com.optimaize.command4j;

import com.google.common.base.Optional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.ExecutorService;

/**
 * The executor that can execute commands either directly using {@link #execute} or with a
 * {@link CommandExecutorService} see {@link #service}.
 *
 * @author Eike Kettner
 * @author Fabian Kessler
 */
public interface CommandExecutor {

    /**
     * Executes it in the current thread, and blocks until it either finishes successfully or aborts by
     * throwing an exception.
     *
     * @param  argument
     * @param <R> Result
     */
    @NotNull
     Optional<R> execute(@NotNull Command cmd, @NotNull Mode mode, @Nullable A arg) throws Exception;

    /**
     * Creates a new command executor service based on your executorService and returns it.
     */
    @NotNull
    CommandExecutorService service(@NotNull final ExecutorService executorService);

    /**
     * @return The same default executor service on each call. It is a simple single-threaded service.
     *         For anything beyond testing you should use {@link #service(java.util.concurrent.ExecutorService)}.
     */
    @NotNull
    CommandExecutorService service();

}


text:
var util     = require('util');
var typedef  = require('typedef');
var _        = require('underscore');
var fs       = require('fs');
var wordwrap = require('wordwrap');
var Q        = require('q');

module.exports = Generator = require('typedef')

.class('Generator') .define({

    __constructor__: function()
    {
        this.code = '';
    },

    __fluent__append: function(txt)
    {
        this.code += txt;
        return this;
    },

    __fluent__addBreak: function(count)
    {
        count = count || 1;

        for (var x = 0; x < count; x++)
            this.code += '\n';

        return this;
    },

    // Append a wrapped comment block
    __fluent__addComment: function(txt, lvl)
    {
        var _this = this;
        lvl       = lvl || 0;
        wordwrap(80 - lvl*4)(txt).split('\n').forEach(function(line) {
            for (var n = 0; n < lvl; n++) _this.code += '    ';
            _this.code += '// ' + line + '\n';
        });

        return this;
    },

    // Standard banner
    __fluent__addDisclaimer: function()
    {
        this.addComment('THIS CODE WAS GENERATED BY AN AUTOMATED TOOL. ' +
            'Editing it is not recommended. For more information, see ' +
            'http://github.com/bvalosek/grunt-infusionsoft');
        this.addComment('Generated on ' + new Date());

        return this;
    },

    // Will probably just be a directory
    writeFile: function(filepath)
    {
        if (this.fileName)
            filepath = filepath + '/' + this.fileName;

        return Q.nfcall(fs.writeFile, filepath, this.code);
    },

});


text:
import sys
import os
import os.path

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('dirs', type=str, nargs='+',
                    help='directories containing simulation files')
parser.add_argument('--rate', type=float, default=0.1)
parser.add_argument('--sites', type=int, default=1)
parser.add_argument('-N', type=int, default=10000)
args = parser.parse_args()

import numpy as np
from scipy.optimize import leastsq
from io import StringIO
import matplotlib.pyplot as plt

NNEIGH=3.25
fraction = float(args.sites)/float(args.N)

# Open lammps log file to extract thermodynamic observables
def from_log(logfile,i0,i1):
    return np.loadtxt(StringIO(u''.join(logfile[i0+1:i1])), unpack=True)

fitfunc = lambda p, t: 1*(1.-np.exp(-t*p[0]-p[1]))
errfunc = lambda p, t, y: fitfunc(p, t) - y

p_data = []
for d in args.dirs:
    logfile = open(os.path.join(os.getcwd(), d, 'log.lammps')).readlines()
    start_indices = [(i,l) for (i,l) in enumerate(logfile) if l.startswith('Time ')]
    stop_indices = [(i,l) for (i,l) in enumerate(logfile) if l.startswith('Loop time')]
    time, e_tot, temp, e_kin, e_vdw, e_bond, e_pot, press, rho, n_bonds, n_bonds_max, bonds = from_log(logfile, start_indices[-1][0], stop_indices[-1][0])
    time -= time[0]
    n_bonds += float(args.sites)/float(args.N)
    plt.plot(time, n_bonds)
    nmax = min(int(1./(args.rate*fraction)), len(time))
    nmax = len(time)
    p, success = leastsq(errfunc, [args.rate*NNEIGH*fraction, 0./args.rate], args=(time[:nmax], n_bonds[:nmax]))
    p_data.append(p)
    print p

plt.plot(time, 1*(1.-np.exp(-time*args.rate*NNEIGH*fraction)))
p_data = np.array(p_data)
print "fit rate", p_data.mean(axis=0)[0]
print "th. rate", args.rate*NNEIGH*fraction
plt.plot(time, fitfunc(p_data.mean(axis=0), time), 'k--')

plt.show()


text:
package com.xrosstools.idea.gef.figures;

import java.awt.*;

public class RectangleFigure extends Figure {

    @Override
    public void paintComponent(Graphics graphics) {
        Color oldColor = graphics.getColor();

        if(getBackgroundColor() != null)
            graphics.setColor(getBackgroundColor());
        graphics.fillRect(getX(), getY(), getWidth(),getHeight());

        if(getForegroundColor() != null)
            graphics.setColor(getForegroundColor());

        graphics.drawRect(getX(), getY(), getWidth(),getHeight());
        graphics.setColor(oldColor);
    }
}


text:
---
title: Vanliga frågor
permalink: faq/
layout: default
header-title: Vanliga frågor
header-text:
cleanheader: för nu, tills vi hittar en bra bild
---

Webb

Film

Tryck

Övrigt

Webb

          {% for faq in site.data.faq %}
          {% if faq.t == 'webb' %}

          {{faq.q}}

{{faq.a}}

        {% endif %}
        {% endfor %}

Film

          {% for faq in site.data.faq %}
          {% if faq.t == 'film' %}

          {{faq.q}}

{{faq.a}}

        {% endif %}
        {% endfor %}

Tryck

          {% for faq in site.data.faq %}
          {% if faq.t == 'tryck' %}

          {{faq.q}}

{{faq.a}}

        {% endif %}
        {% endfor %}

Övrigt

          {% for faq in site.data.faq %}
          {% if faq.t == 'övrigt' %}

          {{faq.q}}

{{faq.a}}

        {% endif %}
        {% endfor %}

    Stäng


text:
package org.mifos.domain.builders;

import java.util.Date;

import org.joda.time.DateTime;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.CategoryTypeEntity;
import org.mifos.accounts.fees.business.FeeFrequencyTypeEntity;
import org.mifos.accounts.fees.business.FeePaymentEntity;
import org.mifos.accounts.fees.exceptions.FeeException;
import org.mifos.accounts.fees.util.helpers.FeeCategory;
import org.mifos.accounts.fees.util.helpers.FeeFrequencyType;
import org.mifos.accounts.fees.util.helpers.FeePayment;
import org.mifos.accounts.financial.business.GLCodeEntity;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.core.MifosRuntimeException;
import org.mifos.customers.office.business.OfficeBO;
import org.mifos.framework.TestUtils;
import org.mifos.framework.util.helpers.Money;
import org.mifos.security.util.UserContext;

/**
 *
 */
public class FeeBuilder {

    private final GLCodeEntity feeGLCode = new GLCodeEntity(Short.valueOf("1"), "10000");
    private MeetingBuilder meetingPeriodicity = new MeetingBuilder().periodicFeeMeeting().weekly().every(1);
    private FeeFrequencyType feeFrequencyType = FeeFrequencyType.PERIODIC;
    private String name = "weekly-client-periodic-fee";
    private FeeCategory category = FeeCategory.CLIENT;
    private Money feeAmount = new Money(TestUtils.RUPEE, "12.5");
    private FeePayment feePayment = FeePayment.UPFRONT;
    private final Date createdDate = new DateTime().minusDays(14).toDate();
    private final UserContext createdByUser = TestUtils.makeUserWithLocales();
    private OfficeBO office;

    public AmountFeeBO build() {
        AmountFeeBO fee = null;
        try {
        if (feeFrequencyType == FeeFrequencyType.PERIODIC) {
            fee = new AmountFeeBO(feeAmount, name, category, feeFrequencyType, feeGLCode,
                meetingPeriodicity.build(), office, createdDate, createdByUser.getId());
        } else { //one-time defaults to up-front payment
            fee = new AmountFeeBO(TestUtils.makeUserWithLocales(), name, new CategoryTypeEntity(category),
                    new FeeFrequencyTypeEntity(feeFrequencyType), feeGLCode, feeAmount, false,
                    new FeePaymentEntity(feePayment));
        }
        } catch (FeeException e) {
            throw new MifosRuntimeException("Error building AmountFeeBO", e);
        }
        return fee;
    }

    public FeeBuilder appliesToAllCustomers() {
        this.category = FeeCategory.ALLCUSTOMERS;
        return this;
    }

    public FeeBuilder appliesToCenterOnly() {
        this.category = FeeCategory.CENTER;
        return this;
    }

    public FeeBuilder appliesToGroupsOnly() {
        this.category = FeeCategory.GROUP;
        return this;
    }

    public FeeBuilder appliesToClientsOnly() {
        this.category = FeeCategory.CLIENT;
        return this;
    }

    public FeeBuilder appliesToLoans() {
        this.category = FeeCategory.LOAN;
        return this;
    }

    public FeeBuilder withFeeAmount(final String withFeeAmount) {
        this.feeAmount = new Money(TestUtils.RUPEE, withFeeAmount);
        return this;
    }

    public FeeBuilder withName(final String withName) {
        this.name = withName;
        return this;
    }

    public FeeBuilder withSameRecurrenceAs(final MeetingBO meeting) {
        this.meetingPeriodicity.withSameRecurrenceAs(meeting);
        return this;
    }

    public FeeBuilder with(final OfficeBO withOffice) {
        this.office = withOffice;
        return this;
    }

    public FeeBuilder with(MeetingBuilder withMeeting) {
        this.meetingPeriodicity = withMeeting;
        return this;
    }

    public FeeBuilder oneTime() {
        this.feeFrequencyType = FeeFrequencyType.ONETIME;
        return this;
    }

    public FeeBuilder periodic() {
        this.feeFrequencyType = FeeFrequencyType.PERIODIC;
        return this;
    }

    public FeeBuilder withFeePayment (FeePayment withFeePayment) {
        this.feePayment = withFeePayment;
        return this;
    }
}


text:
package com.facebook.buck.cxx;

import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.core.description.DescriptionCreationContext;
import com.facebook.buck.core.model.targetgraph.DescriptionProvider;
import com.facebook.buck.core.model.targetgraph.DescriptionWithTargetGraph;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.InferBuckConfig;
import com.facebook.buck.toolchain.ToolchainProvider;
import java.util.Arrays;
import java.util.Collection;
import org.pf4j.Extension;

@Extension
public class CxxDescriptionsProvider implements DescriptionProvider {

  @Override
  public Collection<DescriptionWithTargetGraph<?>> getDescriptions(
      DescriptionCreationContext context) {
    ToolchainProvider toolchainProvider = context.getToolchainProvider();
    BuckConfig config = context.getBuckConfig();
    CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(config);
    InferBuckConfig inferBuckConfig = new InferBuckConfig(config);

    CxxBinaryImplicitFlavors cxxBinaryImplicitFlavors =
        new CxxBinaryImplicitFlavors(toolchainProvider, cxxBuckConfig);
    CxxBinaryFactory cxxBinaryFactory =
        new CxxBinaryFactory(toolchainProvider, cxxBuckConfig, inferBuckConfig);
    CxxBinaryMetadataFactory cxxBinaryMetadataFactory =
        new CxxBinaryMetadataFactory(toolchainProvider);
    CxxBinaryFlavored cxxBinaryFlavored = new CxxBinaryFlavored(toolchainProvider, cxxBuckConfig);

    CxxBinaryDescription cxxBinaryDescription =
        new CxxBinaryDescription(
            toolchainProvider,
            cxxBinaryImplicitFlavors,
            cxxBinaryFactory,
            cxxBinaryMetadataFactory,
            cxxBinaryFlavored);

    CxxLibraryImplicitFlavors cxxLibraryImplicitFlavors =
        new CxxLibraryImplicitFlavors(toolchainProvider, cxxBuckConfig);
    CxxLibraryFlavored cxxLibraryFlavored =
        new CxxLibraryFlavored(toolchainProvider, cxxBuckConfig);
    CxxLibraryFactory cxxLibraryFactory =
        new CxxLibraryFactory(toolchainProvider, cxxBuckConfig, inferBuckConfig);
    CxxLibraryMetadataFactory cxxLibraryMetadataFactory =
        new CxxLibraryMetadataFactory(toolchainProvider);

    CxxLibraryDescription cxxLibraryDescription =
        new CxxLibraryDescription(
            cxxLibraryImplicitFlavors,
            cxxLibraryFlavored,
            cxxLibraryFactory,
            cxxLibraryMetadataFactory);

    return Arrays.asList(
        cxxBinaryDescription,
        cxxLibraryDescription,
        new CxxGenruleDescription(
            cxxBuckConfig, toolchainProvider, context.getSandboxExecutionStrategy()),
        new CxxTestDescription(toolchainProvider, cxxBuckConfig, cxxBinaryMetadataFactory),
        new PrebuiltCxxLibraryDescription(toolchainProvider, cxxBuckConfig),
        PrebuiltCxxLibraryGroupDescription.of(),
        new CxxPrecompiledHeaderDescription());
  }
}


text:
module Vm::Operations::Guest
  extend ActiveSupport::Concern

  included do
    api_relay_method :shutdown_guest
    api_relay_method :reboot_guest
    api_relay_method :reset
  end

  def validate_standby_guest
    validate_unsupported("Standby Guest Operation")
  end

  def raw_shutdown_guest
    raise NotImplementedError, _("must be implemented in a subclass")
  end

  def shutdown_guest
    raise _("VM has no Provider, unable to shutdown guest OS") unless has_active_ems?

    check_policy_prevent(:request_vm_shutdown_guest, :raw_shutdown_guest)
  end

  def raw_standby_guest
    raise NotImplementedError, _("must be implemented in a subclass")
  end

  def standby_guest
    raise _("VM has no Provider, unable to standby guest OS") unless has_active_ems?

    check_policy_prevent(:request_vm_standby_guest, :raw_standby_guest)
  end

  def raw_reboot_guest
    raise NotImplementedError, _("must be implemented in a subclass")
  end

  def reboot_guest
    raise _("VM has no Provider, unable to reboot guest OS") unless has_active_ems?

    check_policy_prevent(:request_vm_reboot_guest, :raw_reboot_guest)
  end

  def raw_reset
    raise NotImplementedError, _("must be implemented in a subclass")
  end

  def reset
    raise _("VM has no Provider, unable to reset VM") unless has_active_ems?

    check_policy_prevent(:request_vm_reset, :raw_reset)
  end
end


text:
var AboutPage = (function($){
    AboutPage.prototype = new SubordinatePage();

    /**
     * @type AboutPage Represent <this> in callback functions
     */
    var self;

    /**
     * @type jQueryElement
     */
    var $divContent;

    /**
     * Constructor
     */
    function AboutPage(selectors) {
       SubordinatePage.call(this, selectors);
       self = this;

       self.init(selectors);
    }

    AboutPage.prototype.init = function (selectors) {
        self.translate($("[data-t-name]"));
        self.clearData($("[data-empty]"));

        self.$divContent = new jQueryElement(selectors.divContent);
        self.$divContent.getElement().html(self.t("pageAboutText"));
    }

    return AboutPage;
}(window.jQuery));

var pageAbout = new AboutPage({
    buttonBack: "#back-button",
    divContent: "#pageText"
});


text:
package com.rho.net;

import java.io.IOException;

import javax.microedition.io.SocketConnection;

import com.rho.RhoClassFactory;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.lang.*;

public class SSLSocket extends BaseSocket {

	private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
		new RhoLogger("SSLSocket");

	public SSLSocket(RubyClass c) {
		super(c);
	}

	public static SSLSocket alloc(RubyValue receiver) {
    	return new SSLSocket((RubyClass)receiver);
    }

	public void initialize(String strHost, int nPort) throws IOException
    {
		NetworkAccess na = (NetworkAccess)RhoClassFactory.getNetworkAccess();
		SocketConnection conn = na.socketConnect("ssl", strHost, nPort);
    	setConnection(conn);
    	super.initialize(strHost, nPort);
    }

	public static void initMethods(RubyClass klass) {

		klass.defineAllocMethod(new RubyNoArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyBlock block )	{
				return SSLSocket.alloc(receiver);}
		});

		klass.defineMethod( "initialize", new RubyTwoArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block )
			{
		    	try{
					String strHost = arg1.toStr();
					int nPort = arg2.toInt();
					((SSLSocket)receiver).initialize(strHost, nPort);
			        return receiver;

				}catch(Exception e)
				{
					LOG.ERROR("initialize failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.getSingletonClass().defineMethod("open", new RubyTwoArgMethod() {
			protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block)
			{
				try{
					SSLSocket res = SSLSocket.alloc(RubyRuntime.SSLSocketClass);
					String strHost = arg1.toStr();
					int nPort = arg2.toInt();
					res.initialize(strHost, nPort);

					return res;
				}catch(Exception e)
				{
					LOG.ERROR("open failed", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.defineMethod( "closed?", new RubyNoArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyBlock block )
			{
		    	try{
					boolean bRes = ((SSLSocket)receiver).is_closed();

					return ObjectFactory.createBoolean(bRes);
				}catch(Exception e)
				{
					LOG.ERROR("closed? failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.defineMethod( "flush", new RubyNoArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyBlock block )
			{
		    	try{
					((SSLSocket)receiver).flush();

					return RubyConstant.QNIL;
				}catch(Exception e)
				{
					LOG.ERROR("close failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.defineMethod( "close", new RubyNoArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyBlock block )
			{
		    	try{
					((SSLSocket)receiver).close();

					return RubyConstant.QNIL;
				}catch(Exception e)
				{
					LOG.ERROR("close failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.defineMethod( "write", new RubyOneArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block )
			{
		    	try{
					int nRes = ((SSLSocket)receiver).write(arg.toStr());

					return ObjectFactory.createInteger(nRes);
				}catch(Exception e)
				{
					LOG.ERROR("write failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

		klass.defineMethod( "sysread", new RubyOneArgMethod(){
			protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block )
			{
		    	try{
					String strRes = ((SSLSocket)receiver).sysread(arg.toInt());

					return ObjectFactory.createString(strRes);
				}catch(Exception e)
				{
					if (e instanceof RubyException )
					{
						RubyException re = (RubyException)e;
						if ( re.getRubyValue().getRubyClass() == RubyRuntime.EOFErrorClass )
							throw re;
					}

					LOG.ERROR("sysread failed.", e);
					throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
				}
			}
		});

	}

}


text:
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
// import globals from 'rollup-plugin-node-globals'
import builtins from 'rollup-plugin-node-builtins'
export default {
  input: 'index.js',
  output: {
    file: 'index.mjs',
    format: 'esm'
  },
  plugins: [commonjs(), json(), builtins()]
}


text:
namespace typing
{
    struct CharInfo
    {
        unsigned int x;
        unsigned int y;
        unsigned int width;
    };

    class Font
    {
    public:
        // Ctors/Dtors
        Font()
            : m_texture(""), m_imageWidth(0), m_imageHeight(0), m_charHeight(0), m_charMap()
        {
        }

        // Enums
        enum Align { ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT };

        // Methods
        void  Load(const std::string& fileName);
        float GetLineWidth(float h, const std::string& text) const;
        void  Print(float x, float y, float h, ColourRGBA col, Align align, const std::string& text) const;
        bool  HasChar(char c);

    private:
        // Typedefs
        typedef std::map<char, CharInfo> CharMap;

        // Members
        std::string  m_texture;
        unsigned int m_imageWidth;
        unsigned int m_imageHeight;
        unsigned int m_charHeight;
        CharMap      m_charMap;
    };
    typedef std::shared_ptr<Font> FontPtr;

    class FontManager
    {
    public:
        // Singleton implementation
        static FontManager& GetFontManager();

        // Methods
        void        Add(const std::string& fontName);
        const Font& Get(const std::string& fontName) const;
        float       GetLineWidth(const std::string& fontName, float h, const std::string& text) const;
        void        Print(const std::string& fontName, float x, float y, float h, ColourRGBA col, Font::Align align, const std::string& text) const;

    private:
        // Ctors/Dtors
        FontManager()
        {
        }

        // Typedefs
        typedef std::map <std::string, FontPtr> FontMap;

        // Members
        FontMap m_fontMap;

        // Singleton implementation
        static std::auto_ptr<FontManager> m_singleton;
    };
    #define FONTS FontManager::GetFontManager()
}

#endif // _FONT_MANAGER_H_


text:
package com.metamx.tranquility.test

import com.metamx.common.parsers.ParseException
import com.metamx.tranquility.druid.DruidRollup
import com.metamx.tranquility.druid.SpecificDruidDimensions
import io.druid.granularity.QueryGranularity
import io.druid.query.aggregation.CountAggregatorFactory
import io.druid.query.aggregation.LongSumAggregatorFactory
import org.scalatest.FunSuite
import org.scalatest.MustMatchers

class DruidRollupTest extends FunSuite with MustMatchers
{
  test("Validations: Passing") {
    val rollup = DruidRollup(
      SpecificDruidDimensions(Vector("hey", "what"), Vector.empty),
      Seq(new CountAggregatorFactory("heyyo")),
      QueryGranularity.NONE
    )
    rollup.validate()
  }

  test("Validations: Dimension and metric with the same name") {
    val e = the[IllegalArgumentException] thrownBy {
      DruidRollup(
        SpecificDruidDimensions(Vector("hey", "what"), Vector.empty),
        Seq(new CountAggregatorFactory("hey")),
        QueryGranularity.NONE
      )
    }
    e.getMessage must be("Duplicate columns: hey")
  }

  test("Validations: Two dimensions with the same name") {
    val e = the[ParseException] thrownBy {
      DruidRollup(
        SpecificDruidDimensions(Vector("what", "what"), Vector.empty),
        Seq(new CountAggregatorFactory("hey")),
        QueryGranularity.NONE
      )
    }
    e.getMessage must be("Duplicate column entries found : [what]")
  }

  test("Validations: Two metrics with the same name") {
    val e = the[IllegalArgumentException] thrownBy {
      DruidRollup(
        SpecificDruidDimensions(Vector("what"), Vector.empty),
        Seq(new CountAggregatorFactory("hey"), new LongSumAggregatorFactory("hey", "blah")),
        QueryGranularity.NONE
      )
    }
    e.getMessage must be("Duplicate columns: hey")
  }
}