text:
require 'active_record/base'
require File.join(File.dirname(__FILE__), '..', 'currency')

# See Currency::ActiveRecord::ClassMethods
class ActiveRecord::Base
    @@money_attributes = { }

    # Called by money macro when a money attribute
    # is created.
    def self.register_money_attribute(attr_opts)
      (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts
    end

    # Returns an array of option hashes for all the money attributes of
    # this class.
    #
    # Superclass attributes are not included.
    def self.money_attributes_for_class(cls)
      (@@money_atttributes[cls] || { }).values
    end

    # Iterates through all known money attributes in all classes.
    #
    # each_money_attribute { | money_opts |
    #   ...
    # }
    def self.each_money_attribute(&blk)
      @@money_attributes.each do | cls, hash |
        hash.each do | attr_name, attr_opts |
          yield attr_opts
        end
      end
    end

end # class

# See Currency::ActiveRecord::ClassMethods
module Currency::ActiveRecord

    def self.append_features(base) # :nodoc:
      # $stderr.puts "  Currency::ActiveRecord#append_features(#{base})"
      super
      base.extend(ClassMethods)
    end

# == ActiveRecord Suppport
#
# Support for Money attributes in ActiveRecord::Base subclasses:
#
#    require 'currency'
#    require 'currency/active_record'
#
#    class Entry < ActiveRecord::Base
#       attr_money :amount
#    end
#
    module ClassMethods

      # Deprecated: use attr_money.
      def money(*args)
        $stderr.puts "WARNING: money(#{args.inspect}) deprecated, use attr_money: in #{caller(1)[0]}"
        attr_money(*args)
      end

      # Defines a Money object attribute that is bound
      # to a database column.  The database column to store the
      # Money value representation is assumed to be
      # INTEGER and will store Money#rep values.
      #
      # Options:
      #
      #    :column => undef
      #
      # Defines the column to use for storing the money value.
      # Defaults to the attribute name.
      #
      # If this column is different from the attribute name,
      # the money object will intercept column=(x) to flush
      # any cached Money object.
      #
      #    :currency => currency_code (e.g.: :USD)
      #
      # Defines the Currency to use for storing a normalized Money
      # value.
      #
      # All Money values will be converted to this Currency before
      # storing.  This allows SQL summary operations,
      # like SUM(), MAX(), AVG(), etc., to produce meaningful results,
      # regardless of the initial currency specified.  If this
      # option is used, subsequent reads will be in the specified
      # normalization :currency.
      #
      #    :currency_column => undef
      #
      # Defines the name of the CHAR(3) column used to store and
      # retrieve the Money's Currency code.  If this option is used, each
      # record may use a different Currency to store the result, such
      # that SQL summary operations, like SUM(), MAX(), AVG(),
      # may return meaningless results.
      #
      #    :currency_preferred_column => undef
      #
      # Defines the name of a CHAR(3) column used to store and
      # retrieve the Money's Currency code.  This option can be used
      # with normalized Money values to retrieve the Money value
      # in its original Currency, while
      # allowing SQL summary operations on the normalized Money values
      # to still be valid.
      #
      #    :time => undef
      #
      # Defines the name of attribute used to
      # retrieve the Money's time.  If this option is used, each
      # Money value will use this attribute during historical Currency
      # conversions.
      #
      # Money values can share a time value with other attributes
      # (e.g. a created_on column).
      #
      # If this option is true, the money time attribute will be named
      # "#{attr_name}_time" and :time_update will be true.
      #
      #    :time_update => undef
      #
      # If true, the Money time value is updated upon setting the
      # money attribute.
      #
      def attr_money(attr_name, *opts)
        opts = Hash[*opts]

        attr_name = attr_name.to_s
        opts[:class] = self
        opts[:table] = self.table_name
        opts[:attr_name] = attr_name.intern
        ::ActiveRecord::Base.register_money_attribute(opts)

        column = opts[:column] || opts[:attr_name]
        opts[:column] = column

        if column.to_s != attr_name.to_s
          alias_accessor = <<-"end_eval"
alias :before_money_#{column}=, :#{column}=

def #{column}=(__value)
  @{attr_name} = nil # uncache
  before_money#{column} = __value
end

end_eval
        end

        currency = opts[:currency]

        currency_column = opts[:currency_column]
        if currency_column && ! currency_column.kind_of?(String)
          currency_column = currency_column.to_s
          currency_column = "#{column}_currency"
        end
        if currency_column
          read_currency = "read_attribute(:#{currency_column.to_s})"
          write_currency = "write_attribute(:#{currency_column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code.to_s)"
        end
        opts[:currency_column] = currency_column

        currency_preferred_column = opts[:currency_preferred_column]
        if currency_preferred_column
          currency_preferred_column = currency_preferred_column.to_s
          read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(read_attribute(:#{currency_preferred_column}))"
          write_preferred_currency = "write_attribute(:#{currency_preferred_column}, @#{attr_name}_money.currency.code)"
        end

        time = opts[:time]
        write_time = ''
        if time
          if time == true
            time = "#{attr_name}_time"
            opts[:time_update] = true
          end
          read_time = "self.#{time}"
        end
        opts[:time] = time
        if opts[:time_update]
          write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time"
        end

        currency ||= ':USD'
        time ||= 'nil'

        read_currency ||= currency
        read_time ||= time

        money_rep ||= "#{attr_name}_money.rep"

        validate = "# Validation\n"
        validate << "\nvalidates_numericality_of :#{attr_name}\n" unless opts[:allow_nil]
        validate << "\nvalidates_format_of :#{currency_column}, :with => /^[A-Z][A-Z][A-Z]$/\n" if currency_column && ! opts[:allow_nil]

        alias_accessor ||= ''

        module_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__
#{validate}

#{alias_accessor}

def #{attr_name}
  # $stderr.puts "  \#{self.class.name}##{attr_name}"
  unless @#{attr_name}
    #{attr_name}_rep = read_attribute(:#{column})
    unless #{attr_name}_rep.nil?
      @#{attr_name} = ::Currency::Money.new_rep(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time})
      #{read_preferred_currency}
    end
  end
  @#{attr_name}
end

def #{attr_name}=(value)
  if value.nil?
    #{attr_name}_money = nil
  elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float)
    #{attr_name}_money = ::Currency::Money(value, #{currency})
    #{write_preferred_currency}
  elsif value.kind_of?(::Currency::Money)
    #{attr_name}_money = value
    #{write_preferred_currency}
    #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"}
  else
    throw ::Currency::Exception::InvalidMoneyValue.new(value)
  end

  @#{attr_name} = #{attr_name}_money

  write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{money_rep})
  #{write_time}

  value
end

def #{attr_name}_before_type_cast
  # FIXME: User cannot specify Currency
  x = #{attr_name}
  x &&= x.format(:symbol => false, :currency => false, :thousands => false)
  x
end

end_eval
        # $stderr.puts "   CODE = #{x}"
      end
    end
end

ActiveRecord::Base.class_eval do
  include Currency::ActiveRecord
end


text:
require 'rails_markdown/formatter'
require 'rails_markdown/markdown'
require 'rails_markdown/action_view/helpers'
require 'rails_markdown/railtie'
module RailsMarkdown

end

redpajama_set_name: RedPajamaGithub


text:
@implementation UIViewController(OrientationFix)

- (BOOL)shouldAutorotate {
    return [self supportsLandscape] && [self supportsPortait];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    UIInterfaceOrientationMask supportedOrientation = 0;
    if ([self supportsLandscape]) {
        supportedOrientation |= UIInterfaceOrientationMaskLandscape;
    }

    if ([self supportsPortait]) {
        supportedOrientation |= UIInterfaceOrientationMaskPortrait;
        supportedOrientation |= UIInterfaceOrientationMaskPortraitUpsideDown;
    }

    return supportedOrientation;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [UIApplication sharedApplication].statusBarOrientation;
}

#pragma mark - private

- (NSArray *)supportedOrientations {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        return [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UISupportedInterfaceOrientations"];
    } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UISupportedInterfaceOrientations~ipad"];
    } else {
        return @[@"UIInterfaceOrientationPortrait"];
    }
}

- (BOOL)supportsPortait {
    NSArray *supportedOrientation = [self supportedOrientations];
    BOOL support = NO;

    if ([supportedOrientation containsObject:@"UIInterfaceOrientationPortrait"] ||
        [supportedOrientation containsObject:@"UIInterfaceOrientationPortraitUpsideDown"]) {
        support = YES;
    }

    return support;
}

- (BOOL)supportsLandscape {
    NSArray *supportedOrientation = [self supportedOrientations];
    BOOL support = NO;

    if ([supportedOrientation containsObject:@"UIInterfaceOrientationLandscapeLeft"] ||
        [supportedOrientation containsObject:@"UIInterfaceOrientationLandscapeRight"]) {
        support = YES;
    }

    return support;
}

@end


text:
namespace media {

// Mapping from Chrome's channel layout to CoreAudio layout. This must match the
// layout of the Channels enum in |channel_layout.h|
static const AudioChannelLabel kCoreAudioChannelMapping[] = {
    kAudioChannelLabel_Left,
    kAudioChannelLabel_Right,
    kAudioChannelLabel_Center,
    kAudioChannelLabel_LFEScreen,
    kAudioChannelLabel_LeftSurround,
    kAudioChannelLabel_RightSurround,
    kAudioChannelLabel_LeftCenter,
    kAudioChannelLabel_RightCenter,
    kAudioChannelLabel_CenterSurround,
    kAudioChannelLabel_LeftSurroundDirect,
    kAudioChannelLabel_RightSurroundDirect,
};
static_assert(0 == LEFT && 1 == RIGHT && 2 == CENTER && 3 == LFE &&
                  4 == BACK_LEFT &&
                  5 == BACK_RIGHT &&
                  6 == LEFT_OF_CENTER &&
                  7 == RIGHT_OF_CENTER &&
                  8 == BACK_CENTER &&
                  9 == SIDE_LEFT &&
                  10 == SIDE_RIGHT &&
                  10 == CHANNELS_MAX,
              "Channel positions must match CoreAudio channel order.");

static void WrapBufferList(AudioBufferList* buffer_list,
                           AudioBus* bus,
                           int frames) {
  const int channels = bus->channels();
  const int buffer_list_channels = buffer_list->mNumberBuffers;
  CHECK_EQ(channels, buffer_list_channels);

  // Copy pointers from AudioBufferList.
  for (int i = 0; i < channels; ++i)
    bus->SetChannelData(i, static_cast<float*>(buffer_list->mBuffers[i].mData));

  // Finally set the actual length.
  bus->set_frames(frames);
}

// Sets the stream format on the AUHAL to PCM Float32 non-interleaved for the
// given number of channels on the given scope and element. The created stream
// description will be stored in |desc|.
static bool SetStreamFormat(int channels,
                            int sample_rate,
                            AudioUnit audio_unit,
                            AudioStreamBasicDescription* format) {
  format->mSampleRate = sample_rate;
  format->mFormatID = kAudioFormatLinearPCM;
  format->mFormatFlags =
      kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  format->mBytesPerPacket = sizeof(Float32);
  format->mFramesPerPacket = 1;
  format->mBytesPerFrame = sizeof(Float32);
  format->mChannelsPerFrame = channels;
  format->mBitsPerChannel = 32;
  format->mReserved = 0;

  // Set stream formats. See Apple's tech note for details on the peculiar way
  // that inputs and outputs are handled in the AUHAL concerning scope and bus
  // (element) numbers:
  // http://developer.apple.com/library/mac/#technotes/tn2091/_index.html
  return AudioUnitSetProperty(audio_unit, kAudioUnitProperty_StreamFormat,
                              kAudioUnitScope_Input, AUElement::OUTPUT, format,
                              sizeof(*format)) == noErr;
}

// Converts |channel_layout| into CoreAudio format and sets up the AUHAL with
// our layout information so it knows how to remap the channels.
static void SetAudioChannelLayout(int channels,
                                  ChannelLayout channel_layout,
                                  AudioUnit audio_unit) {
  DCHECK(audio_unit);
  DCHECK_GT(channels, 0);
  DCHECK_GT(channel_layout, CHANNEL_LAYOUT_UNSUPPORTED);

  // AudioChannelLayout is structure ending in a variable length array, so we
  // can't directly allocate one. Instead compute the size and and allocate one
  // inside of a byte array.
  //
  // Code modeled after example from Apple documentation here:
  // https://developer.apple.com/library/content/qa/qa1627/_index.html
  const size_t layout_size =
      offsetof(AudioChannelLayout, mChannelDescriptions[channels]);
  std::unique_ptr<uint8_t[]> layout_storage(new uint8_t[layout_size]);
  memset(layout_storage.get(), 0, layout_size);
  AudioChannelLayout* coreaudio_layout =
      reinterpret_cast<AudioChannelLayout*>(layout_storage.get());

  coreaudio_layout->mNumberChannelDescriptions = channels;
  coreaudio_layout->mChannelLayoutTag =
      kAudioChannelLayoutTag_UseChannelDescriptions;
  AudioChannelDescription* descriptions =
      coreaudio_layout->mChannelDescriptions;

  if (channel_layout == CHANNEL_LAYOUT_DISCRETE) {
    // For the discrete case just assume common input mappings; once we run out
    // of known channels mark them as unknown.
    for (int ch = 0; ch < channels; ++ch) {
      descriptions[ch].mChannelLabel = ch > CHANNELS_MAX
                                           ? kAudioChannelLabel_Unknown
                                           : kCoreAudioChannelMapping[ch];
      descriptions[ch].mChannelFlags = kAudioChannelFlags_AllOff;
    }
  } else if (channel_layout == CHANNEL_LAYOUT_MONO) {
    // CoreAudio has a special label for mono.
    DCHECK_EQ(channels, 1);
    descriptions[0].mChannelLabel = kAudioChannelLabel_Mono;
    descriptions[0].mChannelFlags = kAudioChannelFlags_AllOff;
  } else {
    for (int ch = 0; ch <= CHANNELS_MAX; ++ch) {
      const int order = ChannelOrder(channel_layout, static_cast<Channels>(ch));
      if (order == -1)
        continue;
      descriptions[order].mChannelLabel = kCoreAudioChannelMapping[ch];
      descriptions[order].mChannelFlags = kAudioChannelFlags_AllOff;
    }
  }

  OSStatus result = AudioUnitSetProperty(
      audio_unit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input,
      AUElement::OUTPUT, coreaudio_layout, layout_size);
  if (result != noErr) {
    OSSTATUS_DLOG(ERROR, result)
        << "Failed to set audio channel layout. Using default layout.";
  }
}

AUHALStream::AUHALStream(AudioManagerMac* manager,
                         const AudioParameters& params,
                         AudioDeviceID device,
                         const AudioManager::LogCallback& log_callback)
    : manager_(manager),
      params_(params),
      number_of_frames_(params_.frames_per_buffer()),
      number_of_frames_requested_(0),
      source_(NULL),
      device_(device),
      volume_(1),
      stopped_(true),
      current_lost_frames_(0),
      last_sample_time_(0.0),
      last_number_of_frames_(0),
      total_lost_frames_(0),
      largest_glitch_frames_(0),
      glitches_detected_(0),
      log_callback_(log_callback) {
  // We must have a manager.
  DCHECK(manager_);
  DCHECK(params_.IsValid());
  DCHECK_NE(device, kAudioObjectUnknown);
}

AUHALStream::~AUHALStream() {
  DCHECK(thread_checker_.CalledOnValidThread());
  CHECK(!audio_unit_);

  base::AutoLock al(lock_);
  ReportAndResetStats();
}

bool AUHALStream::Open() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!output_bus_);
  DCHECK(!audio_unit_);

  // The output bus will wrap the AudioBufferList given to us in
  // the Render() callback.
  output_bus_ = AudioBus::CreateWrapper(params_.channels());

  bool configured = ConfigureAUHAL();
  if (configured) {
    DCHECK(audio_unit_);
    DCHECK(audio_unit_->is_valid());
    hardware_latency_ = AudioManagerMac::GetHardwareLatency(
        audio_unit_->audio_unit(), device_, kAudioDevicePropertyScopeOutput,
        params_.sample_rate());
  }

  return configured;
}

void AUHALStream::Close() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (audio_unit_) {
    Stop();

    // Clear the render callback to try and prevent any callbacks from coming
    // in after we've called stop. https://crbug.com/737527.
    AURenderCallbackStruct callback = {0};
    auto result = AudioUnitSetProperty(
        audio_unit_->audio_unit(), kAudioUnitProperty_SetRenderCallback,
        kAudioUnitScope_Input, AUElement::OUTPUT, &callback, sizeof(callback));
    OSSTATUS_DLOG_IF(ERROR, result != noErr, result)
        << "Failed to clear input callback.";
  }

  audio_unit_.reset();
  // Inform the audio manager that we have been closed. This will cause our
  // destruction. Also include the device ID as a signal to the audio manager
  // that it should try to increase the native I/O buffer size after the stream
  // has been closed.
  manager_->ReleaseOutputStreamUsingRealDevice(this, device_);
}

void AUHALStream::Start(AudioSourceCallback* callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(callback);
  if (!audio_unit_) {
    DLOG(ERROR) << "Open() has not been called successfully";
    return;
  }

  if (!stopped_) {
    base::AutoLock al(lock_);
    CHECK_EQ(source_, callback);
    return;
  }

  // Check if we should defer Start() for http://crbug.com/160920.
  if (manager_->ShouldDeferStreamStart()) {
    // Use a cancellable closure so that if Stop() is called before Start()
    // actually runs, we can cancel the pending start.
    deferred_start_cb_.Reset(
        base::BindOnce(&AUHALStream::Start, base::Unretained(this), callback));
    manager_->GetTaskRunner()->PostDelayedTask(
        FROM_HERE, deferred_start_cb_.callback(),
        base::Seconds(AudioManagerMac::kStartDelayInSecsForPowerEvents));
    return;
  }

  stopped_ = false;

  {
    base::AutoLock al(lock_);
    audio_fifo_.reset();
    source_ = callback;
  }

  OSStatus result = AudioOutputUnitStart(audio_unit_->audio_unit());
  if (result == noErr)
    return;

  Stop();
  OSSTATUS_DLOG(ERROR, result) << "AudioOutputUnitStart() failed.";
  callback->OnError(AudioSourceCallback::ErrorType::kUnknown);
}

// This stream is always used with sub second buffer sizes, where it's
// sufficient to simply always flush upon Start().
void AUHALStream::Flush() {}

void AUHALStream::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());
  deferred_start_cb_.Cancel();
  if (stopped_)
    return;

  OSStatus result = AudioOutputUnitStop(audio_unit_->audio_unit());
  OSSTATUS_DLOG_IF(ERROR, result != noErr, result)
      << "AudioOutputUnitStop() failed.";

  {
    base::AutoLock al(lock_);
    if (result != noErr)
      source_->OnError(AudioSourceCallback::ErrorType::kUnknown);

    ReportAndResetStats();
    source_ = nullptr;
  }

  stopped_ = true;
}

void AUHALStream::SetVolume(double volume) {
  volume_ = static_cast<float>(volume);
}

void AUHALStream::GetVolume(double* volume) {
  *volume = volume_;
}

// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks which can
// be contended in the middle of stream processing here (starting and stopping
// the stream are ok) because this is running on a real-time thread.
OSStatus AUHALStream::Render(AudioUnitRenderActionFlags* flags,
                             const AudioTimeStamp* output_time_stamp,
                             UInt32 bus_number,
                             UInt32 number_of_frames,
                             AudioBufferList* data) {
  TRACE_EVENT2("audio", "AUHALStream::Render", "input buffer size",
               number_of_frames_, "output buffer size", number_of_frames);

  base::AutoLock al(lock_);

  // There's no documentation on what we should return here, but if we're here
  // something is wrong so just return an AudioUnit error that looks reasonable.
  if (!source_)
    return kAudioUnitErr_Uninitialized;

  UpdatePlayoutTimestamp(output_time_stamp);

  // If the stream parameters change for any reason, we need to insert a FIFO
  // since the OnMoreData() pipeline can't handle frame size changes.
  if (number_of_frames != number_of_frames_) {
    // Create a FIFO on the fly to handle any discrepancies in callback rates.
    if (!audio_fifo_) {
      // TODO(grunell): We'll only care about the first buffer size change,
      // any further changes will be ignored. It would be nice to have all
      // changes reflected in UMA stats.
      number_of_frames_requested_ = number_of_frames;
      DVLOG(1) << "Audio frame size changed from " << number_of_frames_
               << " to " << number_of_frames << " adding FIFO to compensate.";
      audio_fifo_ = std::make_unique<AudioPullFifo>(
          params_.channels(), number_of_frames_,
          base::BindRepeating(&AUHALStream::ProvideInput,
                              base::Unretained(this)));
    }
  }

  // Make |output_bus_| wrap the output AudioBufferList.
  WrapBufferList(data, output_bus_.get(), number_of_frames);

  current_playout_time_ = GetPlayoutTime(output_time_stamp);

  if (audio_fifo_)
    audio_fifo_->Consume(output_bus_.get(), output_bus_->frames());
  else
    ProvideInput(0, output_bus_.get());

  last_number_of_frames_ = number_of_frames;

  return noErr;
}

void AUHALStream::ProvideInput(int frame_delay, AudioBus* dest) {
  lock_.AssertAcquired();
  DCHECK(source_);

  const base::TimeTicks playout_time =
      current_playout_time_ +
      AudioTimestampHelper::FramesToTime(frame_delay, params_.sample_rate());
  const base::TimeTicks now = base::TimeTicks::Now();
  const base::TimeDelta delay = playout_time - now;

  // Supply the input data and render the output data.
  source_->OnMoreData(delay, now, current_lost_frames_, dest);
  dest->Scale(volume_);
  current_lost_frames_ = 0;
}

// AUHAL callback.
OSStatus AUHALStream::InputProc(void* user_data,
                                AudioUnitRenderActionFlags* flags,
                                const AudioTimeStamp* output_time_stamp,
                                UInt32 bus_number,
                                UInt32 number_of_frames,
                                AudioBufferList* io_data) {
  // Dispatch to our class method.
  AUHALStream* audio_output = static_cast<AUHALStream*>(user_data);
  if (!audio_output)
    return -1;

  return audio_output->Render(flags, output_time_stamp, bus_number,
                              number_of_frames, io_data);
}

base::TimeTicks AUHALStream::GetPlayoutTime(
    const AudioTimeStamp* output_time_stamp) {
  // A platform bug has been observed where the platform sometimes reports that
  // the next frames will be output at an invalid time or a time in the past.
  // Because the target playout time cannot be invalid or in the past, return
  // "now" in these cases.
  if ((output_time_stamp->mFlags & kAudioTimeStampHostTimeValid) == 0)
    return base::TimeTicks::Now();

  return std::max(base::TimeTicks::FromMachAbsoluteTime(
                      output_time_stamp->mHostTime),
                  base::TimeTicks::Now()) +
         hardware_latency_;
}

void AUHALStream::UpdatePlayoutTimestamp(const AudioTimeStamp* timestamp) {
  lock_.AssertAcquired();

  if ((timestamp->mFlags & kAudioTimeStampSampleTimeValid) == 0)
    return;

  if (last_sample_time_) {
    DCHECK_NE(0U, last_number_of_frames_);
    UInt32 diff =
        static_cast<UInt32>(timestamp->mSampleTime - last_sample_time_);
    if (diff != last_number_of_frames_) {
      DCHECK_GT(diff, last_number_of_frames_);
      // We're being asked to render samples post what we expected. Update the
      // glitch count etc and keep a record of the largest glitch.
      auto lost_frames = diff - last_number_of_frames_;
      total_lost_frames_ += lost_frames;
      current_lost_frames_ += lost_frames;
      if (lost_frames > largest_glitch_frames_)
        largest_glitch_frames_ = lost_frames;
      ++glitches_detected_;
    }
  }

  // Store the last sample time for use next time we get called back.
  last_sample_time_ = timestamp->mSampleTime;
}

void AUHALStream::ReportAndResetStats() {
  lock_.AssertAcquired();

  if (!last_sample_time_)
    return;  // No stats gathered to report.

  // A value of 0 indicates that we got the buffer size we asked for.
  UMA_HISTOGRAM_COUNTS_1M("Media.Audio.Render.FramesRequested",
                          number_of_frames_requested_);
  // Even if there aren't any glitches, we want to record it to get a feel for
  // how often we get no glitches vs the alternative.
  UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Audio.Render.Glitches", glitches_detected_,
                              1, 999999, 100);

  auto lost_frames_ms = (total_lost_frames_ * 1000) / params_.sample_rate();

  std::string log_message = base::StringPrintf(
      "AU out: Total glitches=%d. Total frames lost=%d (%d ms).",
      glitches_detected_, total_lost_frames_, lost_frames_ms);

  if (!log_callback_.is_null())
    log_callback_.Run(log_message);

  if (glitches_detected_ != 0) {
    UMA_HISTOGRAM_COUNTS_1M("Media.Audio.Render.LostFramesInMs",
                            lost_frames_ms);
    auto largest_glitch_ms =
        (largest_glitch_frames_ * 1000) / params_.sample_rate();
    UMA_HISTOGRAM_COUNTS_1M("Media.Audio.Render.LargestGlitchMs",
                            largest_glitch_ms);
    DLOG(WARNING) << log_message;
  }

  number_of_frames_requested_ = 0;
  glitches_detected_ = 0;
  last_sample_time_ = 0;
  last_number_of_frames_ = 0;
  total_lost_frames_ = 0;
  largest_glitch_frames_ = 0;
}

bool AUHALStream::ConfigureAUHAL() {
  DCHECK(thread_checker_.CalledOnValidThread());

  std::unique_ptr<ScopedAudioUnit> local_audio_unit(
      new ScopedAudioUnit(device_, AUElement::OUTPUT));
  if (!local_audio_unit->is_valid())
    return false;

  if (!SetStreamFormat(params_.channels(), params_.sample_rate(),
                       local_audio_unit->audio_unit(), &output_format_)) {
    return false;
  }

  bool size_was_changed = false;
  size_t io_buffer_frame_size = 0;
  if (!manager_->MaybeChangeBufferSize(device_, local_audio_unit->audio_unit(),
                                       0, number_of_frames_, &size_was_changed,
                                       &io_buffer_frame_size)) {
    return false;
  }

  // Setup callback.
  AURenderCallbackStruct callback;
  callback.inputProc = InputProc;
  callback.inputProcRefCon = this;
  OSStatus result = AudioUnitSetProperty(
      local_audio_unit->audio_unit(), kAudioUnitProperty_SetRenderCallback,
      kAudioUnitScope_Input, AUElement::OUTPUT, &callback, sizeof(callback));
  if (result != noErr)
    return false;

  SetAudioChannelLayout(params_.channels(), params_.channel_layout(),
                        local_audio_unit->audio_unit());

  result = AudioUnitInitialize(local_audio_unit->audio_unit());
  if (result != noErr) {
    OSSTATUS_DLOG(ERROR, result) << "AudioUnitInitialize() failed.";
    return false;
  }

  audio_unit_ = std::move(local_audio_unit);
  return true;
}

}  // namespace media


text:
'use strict'
// eslint-disable-next-line
/**
 * Initialize a new `Submit` button with the given `node`.
 * If `initialValue` is undefined, uses the "value" attribute of `node`.
 *
 * @param {Element} node
 * @param {String} initialValue
 * @api public
 */
const { newButton } = require('./button')

exports.newSubmit = (node, initialValue) => {
  const button = newButton(node, initialValue)
  const fieldType = 'submit'
  const formAction = button.getAttribute('formaction')
  const formTarget = button.getAttribute('formtarget')

  const getEnctype = button => {
    const attribute = button.getAttribute('formecntype')
    if (!attribute) {
      return undefined
    } else if (attribute === 'multipart/form-data' ||
                 attribute === 'text/plain') {
      return attribute
    }
    return 'application/x-www-form-urlencoded'
  }

  const getMethod = button => {
    const attribute = button.getAttribute('formmethod')
    if (!attribute) {
      return undefined
    } else if (attribute.match(/^post$/i)) {
      return 'post'
    }
    return 'get'
  }

  const getBoolean = (button, name) => Boolean(button.getAttribute(name))

  const formEcntype = getEnctype(button)
  const formMethod = getMethod(button)
  const formNoValidate = getBoolean(button, 'formnovalidate')

  return Object.freeze({
    disabled: button.disabled,
    domId: button.domId,
    fieldType,
    formAction,
    formEcntype,
    formMethod,
    formNoValidate,
    formTarget,
    getAttribute: button.getAttribute,
    name: button.name,
    queryValue: button.queryValue,
    rawValue: button.rawValue,
    setValue: button.setValue,
    type: button.type,
    value: button.value,
  })
}


text:
module Reality::Describers::Wikidata::Impl
  module Modules
    # Return a data representation of references associated with the given pages.
    #
    # The "submodule" (MediaWiki API term) is included in action after setting some param, providing
    # additional tweaking for this param. Example (for {Reality::Describers::Wikidata::Impl::Actions::Query} and
    # its submodules):
    #
    # ```ruby
    # api.query             # returns Actions::Query
    #    .prop(:revisions)  # adds prop=revisions to action URL, and includes Modules::Revisions into action
    #    .limit(10)         # method of Modules::Revisions, adds rvlimit=10 to URL
    # ```
    #
    # All submodule's parameters are documented as its public methods, see below.
    #
    module References

      # When more results are available, use this to continue.
      #
      # @param value [String]
      # @return [self]
      def continue(value)
        merge(rfcontinue: value.to_s)
      end
    end
  end
end


text:
#ifndef HANDLER_TEST_H_1
#define HANDLER_TEST_H_1
/*************************************************************************
	> File Name:    src/mahjong/handler_test.h
	> Author:       D_L
	> Mail:         deel@d-l.top
	> Created Time: 2016/8/26 9:49:27
 ************************************************************************/

// 本文件中的代码,只是演示用的
// 使用责任链模式,来处理 客户端发来的数据

#include <engine/log.h>
#include <engine/event.h>

namespace Mahjong {

class handler_test;
typedef std::shared_ptr<handler_test> shared_handler_test_t;

typedef std::weak_ptr<Engine::Server::Session> weak_session_t;
typedef std::shared_ptr<Engine::Server::Session> shared_session_t;
typedef std::shared_ptr<Engine::Server::Connection> shared_connection_t;

// handler 抽象类
class handler_test : public std::enable_shared_from_this<handler_test> {
    weak_session_t            m_session; // 不可使用 shared_ptr, 否则无法析构它
protected:
    shared_handler_test_t     m_successor = nullptr;
    Engine::Event&            m_event;
    // 非必须的; 专供 Event::strand_post 使用.
    // 如果想让 Event 按照 特定的(post 的先后) 顺序处理异步事件,
    // 那么就使用  Event::strand_post, 否则使用 Event::post 即可
    Engine::io_service::strand&  m_strand;
public:
    handler_test(const weak_session_t& session,
            Engine::io_service::strand& strand)
        : m_session(session),
          m_event(Engine::Event::get_instance()),
          m_strand(strand) {}
    void set_successor(shared_handler_test_t successor) {
        m_successor = successor;
    }
    virtual void handle_request(Engine::shared_data_type) = 0;
protected:
    template <typename DataType>
    void send_message(DataType&& data) {
        if(shared_session_t session = m_session.lock()) {
            if (shared_connection_t conn
                    = session->get_connection_weak_ptr().lock()) {
                conn->send_message(std::forward<DataType>(data));
            }
            else {
                logwarn("Connection has been lost.");
            }
        }
    }
    template <typename DataType, typename SendSucceededHandler>
    void send_message(
            DataType&& data,
            SendSucceededHandler&& succeeded_handler) {
        if(shared_session_t session = m_session.lock()) {
            if (shared_connection_t conn
                    = session->get_connection_weak_ptr().lock()) {
                conn->send_message(
                        std::forward<DataType>(data),
                        std::forward<SendSucceededHandler>(succeeded_handler));
            }
            else {
                logwarn("Connection has been lost.");
            }
        }
    }
}; // class Mahjong::handler_test

#include <mahjong/connection.h> // for Engine::Server::Connection
// handler 具体类
class handler_test1 : public handler_test {
public:
    using handler_test::handler_test; // 继承基类的构造函数
    virtual void handle_request(Engine::shared_data_type shared_data) override {
        // 处理 "hello"
        if (*shared_data == Engine::const_byte_ptr("hello")) {
            // 放到 Event 中处理
            m_event.post(
                    std::bind(&handler_test1::handler, this,
                        shared_from_this()));
        }
        else if (m_successor) {
            // 交给下任者
            m_successor->handle_request(shared_data);
        }
    }
private:
    // 真正的事件处理函数(在 event 中被执行)
    void handler(shared_handler_test_t) {
        loginfo("********* handler_test1: hello **********");

        loginfo("send 'say hello from server.' to client");
        // 反馈给客户端
        Engine::data_t data(
                Engine::const_byte_ptr("say hello from server."));
        send_message(std::move(data));

    }
}; // class Nahjong::handler_test1

class handler_test2 : public handler_test {
public:
    using handler_test::handler_test; // 继承基类的构造函数
    virtual void handle_request(Engine::shared_data_type shared_data) override {
        // 处理 world
        if (*shared_data == Engine::const_byte_ptr("world")) {
            // 放到 Event 中处理, 这次使用 strand
            // 使所有通过 strand 异步执行的 事件,都有序进行
            m_event.strand_post(m_strand,
                    std::bind(&handler_test2::handler, this,
                        shared_from_this()));
        }
        else if (m_successor) {
            // 交给下任者
            m_successor->handle_request(shared_data);
        }
    }
private:
    // 真正的事件处理函数(在 event 被执行)
    void handler(shared_handler_test_t) {
        loginfo("********* handler_test2: world *********");
    }
}; // class Nahjong::handler_test2

// 边界
class handler_test_boundary : public handler_test {
public:
    using handler_test::handler_test; // 继承基类的构造函数
    virtual void handle_request(Engine::shared_data_type shared_data) override {
        // 处理边界
        //if (*shared_data == Engine::const_byte_ptr("hello")) {
            // 放到 Event 中处理
            m_event.post(
                    std::bind(&handler_test_boundary::handler, this,
                        shared_from_this()));
        // 这里是边界, 没有下任者
        //}
        //else if (m_successor) {
        //    // 交给下任者
        //    m_successor->handle_request(shared_data);
        //}
    }
private:
    // 真正的事件处理函数(在 event 中被执行)
    void handler(shared_handler_test_t) {
        loginfo("********* handler_test_boundary: unknown data **********");

        loginfo("send 'say unknown data from server' to client");
        // 反馈给客户端
        Engine::data_t data(
             Engine::const_byte_ptr("say unknown data from server."));
        send_message(std::move(data));
    }
}; // class Nahjong::handler_test_boundary

} // namespace Mahjong

#endif // HANDLER_TEST_H_1


text:
package com.google.api.ads.adwords.jaxws.v201601.cm;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ShoppingProductChannel.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="ShoppingProductChannel">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UNKNOWN"/>
 *     <enumeration value="ONLINE"/>
 *     <enumeration value="LOCAL"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "ShoppingProductChannel")
@XmlEnum
public enum ShoppingProductChannel {

    /**
     *
     *                 Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.
     *
     *
     */
    UNKNOWN,

    /**
     *
     *                 The item is sold online.
     *
     *
     */
    ONLINE,

    /**
     *
     *                 The item is sold in local stores.
     *
     *
     */
    LOCAL;

    public String value() {
        return name();
    }

    public static ShoppingProductChannel fromValue(String v) {
        return valueOf(v);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
<!DOCTYPE web-app
	[
		<!ENTITY services_appli1 SYSTEM "services_appli1.xml">
		<!ENTITY services_referentiel1 SYSTEM "services_referentiel1.xml">
	]>
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

	<!-- Services
	&services_appli1;
	&services_referentiel1;
	 -->

	<!-- configuration datasource -->
	<context-param>
		<param-name>appwhite1.datasource</param-name>
		<param-value>java:comp/env/jdbc/demo_javamelody</param-value>
	</context-param>

	<!-- configuration pour monitoring javamelody -->
	<context-param>
		<param-name>javamelody.rum-enabled</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>javamelody.log</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>javamelody.sql-transform-pattern</param-name>
		<!-- regexp pour agréger les paramètres bindés dans les critères de requêtes
			SQL tels que "in (?, ?, ?, ?)" et ainsi pour éviter que ces requêtes ayant
			un nombre variable de paramètres soient considérées comme différentes ;
			de fait cela agrège aussi les values des inserts -->
		<param-value>\([\?, ]+\)</param-value>
	</context-param>
	<!-- <context-param> <param-name>javamelody.disabled</param-name> <param-value>true</param-value>
		</context-param> -->
	<!-- paramétrage du monitoring pour GWT -->
	<context-param>
		<param-name>javamelody.http-transform-pattern</param-name>
		<param-value>[A-F,0-9]+\.cache</param-value>
	</context-param>
	<context-param>
		<param-name>javamelody.custom-reports</param-name>
		<param-value>Send feedback,My custom report</param-value>
	</context-param>
	<context-param>
		<param-name>javamelody.Send feedback</param-name>
		<param-value>https://groups.google.com/forum/#!forum/javamelody</param-value>
	</context-param>
	<context-param>
		<param-name>javamelody.My custom report</param-name>
		<param-value>/WEB-INF/pages/myCustomReport.jsp</param-value>
	</context-param>

	<!-- these are for MDC of Log4j and for display of the user in the monitoring -->
	<filter>
		<filter-name>remoteUser</filter-name>
		<filter-class>fr.spi4j.lib.security.RemoteUserFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>remoteUser</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>forbiddenActions</filter-name>
		<filter-class>ForbiddenActionsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>forbiddenActions</filter-name>
		<url-pattern>/monitoring</url-pattern>
	</filter-mapping>

	<!-- these are for monitoring -->
	<filter>
		<filter-name>monitoring</filter-name>
		<filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>monitoring</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
		<listener-class>net.bull.javamelody.SessionListener</listener-class>
	</listener>

	<!-- these are for getting the session for the current thread -->
	<filter>
		<filter-name>httpSessionInThread</filter-name>
		<filter-class>fr.spi4j.filter.HttpSessionFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>httpSessionInThread</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- Servlet d'informations sur le build -->
	<servlet>
		<servlet-name>BuildInfoServlet</servlet-name>
		<servlet-class>fr.appwhite1.Appli1BuildInfoServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>BuildInfoServlet</servlet-name>
		<url-pattern>/version</url-pattern>
	</servlet-mapping>

    <servlet>
        <servlet-name>AdresseService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.annuaire.AdresseGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AdresseService</servlet-name>
        <url-pattern>/appli1/AdresseService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>CompetenceService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.annuaire.CompetenceGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CompetenceService</servlet-name>
        <url-pattern>/appli1/CompetenceService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>MailService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.annuaire.MailGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MailService</servlet-name>
        <url-pattern>/appli1/MailService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>PermissionService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.secu.PermissionGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PermissionService</servlet-name>
        <url-pattern>/appli1/PermissionService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>PersonneService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.annuaire.PersonneGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PersonneService</servlet-name>
        <url-pattern>/appli1/PersonneService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>RoleService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.secu.RoleGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RoleService</servlet-name>
        <url-pattern>/appli1/RoleService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>TelephoneService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.annuaire.TelephoneGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TelephoneService</servlet-name>
        <url-pattern>/appli1/TelephoneService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>UtilisateurService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.secu.UtilisateurGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UtilisateurService</servlet-name>
        <url-pattern>/appli1/UtilisateurService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>AuthentificationService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.secu.AuthentificationGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AuthentificationService</servlet-name>
        <url-pattern>/appli1/AuthentificationService</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>PrintUtilsService</servlet-name>
        <servlet-class>fr.appwhite1.server.business.utils.PrintUtilsGwtServiceImpl</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PrintUtilsService</servlet-name>
        <url-pattern>/appli1/PrintUtilsService</url-pattern>
    </servlet-mapping>

	<servlet>
		<servlet-name>GradeService</servlet-name>
		<servlet-class>fr.referentiel.server.business.ref.GradeGwtServiceImpl</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>GradeService</servlet-name>
		<url-pattern>/referentiel1/GradeService</url-pattern>
	</servlet-mapping>

	<!-- Initialisation de la webapp -->
	<listener>
		<listener-class>fr.appwhite1.InitializationListener</listener-class>
	</listener>

	<!-- Default page to serve -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>

	<!-- time out des sessions en minutes (il est recommandé 30 ou 60 minutes
		pour le timeout) -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

	<resource-ref>
		<res-ref-name>jdbc/demo_javamelody</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>
</web-app>


text:
from __future__ import (unicode_literals, division, absolute_import, print_function)

import sys

from time import sleep
from subprocess import Popen, PIPE

from powerline import Powerline
from powerline.lib.monotonic import monotonic

powerline = Powerline('wm', renderer_module='pango_markup')
powerline.update_renderer()

try:
	interval = float(sys.argv[1])
except IndexError:
	interval = 2

def read_to_log(pl, client):
	for line in client.stdout:
		if line:
			pl.info(line, prefix='awesome-client')
	for line in client.stderr:
		if line:
			pl.error(line, prefix='awesome-client')
	if client.wait():
		pl.error('Client exited with {0}', client.returncode, prefix='awesome')

while True:
	start_time = monotonic()
	s = powerline.render(side='right')
	request = "powerline_widget:set_markup('" + s.replace('\\', '\\\\').replace("'", "\\'") + "')\n"
	client = Popen(['awesome-client'], shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
	client.stdin.write(request.encode('utf-8'))
	client.stdin.close()
	read_to_log(powerline.pl, client)
	sleep(max(interval - (monotonic() - start_time), 0.1))


text:
Using Florence
================

A basic guide to adding content and publishing through Florence.

#### Sign in
Browse to the Florence homepage http://localhost:8081/florence/index.html

If you are running Florence for the first time you will need to login with the setup credentials. You will be asked to change this password.

Username: florence@magicroundabout.ons.gov.uk
Password: Doug4l

#### Create a collection
Content in Florence must be created through a collection. This includes bulletins, articles, content pages, and dataset landing pages.
This does not include [importing a V4 file](#import-a-v4-file), which can be done without a collection, but the content must be
added to a collection in order to be published.

Once signed in to Florence, `Create a collection` options should be apparent.

- Give it any name you want
- Unless specifically testing teams, you can ignore the `Select a team` drop-down
- Choose between manual or scheduled publish - for a quick test manual is usually easiest
- Hit the `Create collection` button

Your collection should now be available in the Collection list

#### Create a content page

- Select an existing collection
- Choose `Create/edit page`
- You will be taken to the 'browse tree' where you can navigate to the 'product page' you want to create content under (for example navigate through `Economy` through to the `Gross Domestic Product` page).
- When you've found the right place, choose `Create`
- On the next page, select the content type from the drop down and fill in the required details (some types will only be available at certain levels, for example bulletins can only be created under a product page) and create the page

#### Create a CMD dataset page

- Check the [recipe](https://github.com/ONSdigital/dp-recipe-api/blob/cmd-develop/recipe/data.go) exists
- Navigate to a product page as described [above](#create-a-content-page)
- Select the 'API dataset' page type
- Select the relevant dataset (this list come from available recipes)

This creates the JSON document that Zebedee and Babbage would use, as well as creating a dataset document in Mongo.
This must be done before importing a V4 file.

#### Import a V4 file

The quickest file to test with is CPIH. These instructions specifically reference a CPIH import file, but any V4 file would work.
- Download the latest [CPIH](https://beta.ons.gov.uk/datasets/cpih01/editions/time-series/versions) CSV file from the Beta
- Sign in to Florence
- Choose the `Datasets` tab
- Select the relevant dataset
- Upload the CSV file
- Select the edition of the dataset you are uploaded. Typically, there is only one value available: `time-series`
- Click the `Submit to publishing` button to start the import process.
- Once you reach the `Your dataset has been submitted` page, there are a few ways you can track the import process:
 - To determine if the entire import is complete, you can refresh the page. Once the import is complete the page will display: `Your dataset upload is complete`
 - If you need more detail, you can use the instance's endpoint: http://localhost:8081/dataset/instances. See the `import_tasks` value for the status of each task within the import. The most recent instance is the first one in the array. Each task will start with a state of `created`, and once complete it will show the state `completed`
For more details on the CMD import process, refer to the [CMD dataset import sequence diagram](https://github.com/ONSdigital/dp-import/blob/develop/docs/import-sequence/CMDDatasetImport.png)

#### Create an account

- Choose `Users and access` from the nav bar
- Provide an email address and password for the new account
- Select the account type - in order to review and approve content, the user must be of type `administrator` or `publisher`
- `Create user`
- Sign out and sign back in - you will be asked to update the password on first sign in

#### Publish a collection

In order to publish a collection, it must be submitted, reviewed and approved.

- In an existing collection, go into any content that's in the `In progress` area and `Submit for review`
- Sign in as another user ([create one](#create-an-account) if needed)
- Select the collection and go into each piece of content and `Approve`
- Once all content in the collection has been approved, the `Approve` option will also appear on the collection
- Approving the collection will move it to the 'publishing queue'
- If it's a manual collection:
  - Choose `Publishing queue` from the nav bar
  - Select the `[manual collection]` category in the publish date list
  - Select your collection and `Publish`


text:
import { IContainer } from '../../../../../../../model/IContainer';
import { ElementProvider } from '../../graphical-editor/providers/properties/element-provider';
import { ToolBase } from './tool-base';

export abstract class TypeAwareToolBase extends ToolBase {
    protected abstract get modelType(): {className: string};

    private _elementProvider: ElementProvider;
    private get elementProvider(): ElementProvider {
        if (!this._elementProvider && this.modelType) {
            this._elementProvider = new ElementProvider(this.modelType);
        }
        return this._elementProvider;
    }

    public isNode(element: IContainer): boolean {
        return this.elementProvider.isNode(element);
    }

    public isConnection(element: IContainer): boolean {
        return this.elementProvider.isConnection(element);
    }
}


text:
module React
  module Plotly
    module Rails
      VERSION = "0.0.0"
    end
  end
end


text:
var browserify = require('browserify');
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

var bundler = watchify(browserify(watchify.args));

bundler.add('./index.js');

bundler.on('update', bundle);
bundler.on('log', gutil.log);

function bundle() {
  return bundler.bundle()
    .on('error', gutil.log.bind(gutil, 'Bundle Error'))
    .pipe(source('hyper-validator-base.js'))
    .pipe(gulp.dest('./dist'));
}

gulp.task('build', bundle);

gulp.task('default', ['build']);


text:
package org.hisp.dhis.importexport.dhis14.xml.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import org.amplecode.staxwax.reader.XMLReader;
import org.amplecode.staxwax.writer.XMLWriter;
import org.hisp.dhis.importexport.ExportParams;
import org.hisp.dhis.importexport.ImportObjectService;
import org.hisp.dhis.importexport.ImportParams;
import org.hisp.dhis.importexport.XMLConverter;
import org.hisp.dhis.importexport.dhis14.util.Dhis14DateUtil;
import org.hisp.dhis.importexport.dhis14.util.Dhis14ObjectMappingUtil;
import org.hisp.dhis.importexport.importer.PeriodImporter;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.joda.time.DateTime;
import org.joda.time.Days;

/**
 * @author Lars Helge Overland
 * @version $Id$
 */
public class PeriodConverter
    extends PeriodImporter
    implements XMLConverter
{
    public static final String ELEMENT_NAME = "DataPeriod";

    private static final String FIELD_ID = "DataPeriodID";

    private static final String FIELD_DATA_PERIODNAMEENG = "DataPeriodNameEng";

    private static final String FIELD_DATA_PERIODNAME = "DataPeriodName";

    private static final String FIELD_PERIOD_TYPE = "DataPeriodTypeID";

    private static final String FIELD_START_DATE = "ValidFrom";

    private static final String FIELD_END_DATE = "ValidTo";

    private static final String FIELD_SELECTED = "Selected";

    private static final String FIELD_DATAPERIODNAMEALT1 = "DataPeriodNameAlt1";

    private static final String FIELD_DATAPERIODNAMEALT2 = "DataPeriodNameAlt2";

    private static final String FIELD_DATAPERIODNAMEALT3 = "DataPeriodNameAlt3";

    private Map<String, Integer> periodTypeMapping;

    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------

    /**
     * Constructor for write operations.
     */
    public PeriodConverter( PeriodService periodService )
    {
        this.periodService = periodService;
    }

    /**
     * Constructor for read operations.
     *
     * @param importObjectService the importObjectService to use.
     * @param periodService the periodService to use.
     * @param periodTypeMapping the periodTypeMapping to use.
     */
    public PeriodConverter( ImportObjectService importObjectService, PeriodService periodService,
        Map<String, Integer> periodTypeMapping )
    {
        this.importObjectService = importObjectService;
        this.periodService = periodService;
        this.periodTypeMapping = periodTypeMapping;
    }

    // -------------------------------------------------------------------------
    // XMLConverter implementation
    // -------------------------------------------------------------------------

    @Override
    public void write( XMLWriter writer, ExportParams params )
    {
        Collection<Period> periods = periodService.getPeriods( params.getPeriods() );

        if ( periods != null && periods.size() > 0 )
        {
            for ( Period period : periods )
            {
                if ( period.getPeriodType().getName().equals( MonthlyPeriodType.NAME ) )
                {

                    writer.openElement( ELEMENT_NAME );

                    writer.writeElement( FIELD_ID, String.valueOf( period.getId() ) );

                    String startDate = period.getStartDateString();
                    String endDate = period.getEndDateString();

                    String dataPeriodNameEng = null;
                    String dataPeriodName = null;
                    String validFrom = null;
                    String validTo = null;

                    Calendar msAccessCalendarDate = getCalendarDate( "1899-12-29" );

                    Calendar startCalendarDate = getCalendarDate( startDate );
                    Calendar endCalendarDate = getCalendarDate( endDate );

                    dataPeriodNameEng = getDateName( startDate );
                    dataPeriodName = getDateName( startDate );

                    validFrom = Days.daysBetween( new DateTime( msAccessCalendarDate ),
                        new DateTime( startCalendarDate ) ).getDays()
                        + "";
                    validTo = Days.daysBetween( new DateTime( msAccessCalendarDate ), new DateTime( endCalendarDate ) )
                        .getDays() + "";

                    writer.writeElement( FIELD_DATA_PERIODNAMEENG, dataPeriodNameEng );
                    writer.writeElement( FIELD_DATA_PERIODNAME, dataPeriodName );
                    writer.writeElement( FIELD_PERIOD_TYPE, String.valueOf( 1 ) );
                    writer.writeElement( FIELD_START_DATE, validFrom );
                    writer.writeElement( FIELD_END_DATE, validTo );
                    writer.writeElement( FIELD_SELECTED, String.valueOf( 0 ) );
                    writer.writeElement( FIELD_DATAPERIODNAMEALT1, "" );
                    writer.writeElement( FIELD_DATAPERIODNAMEALT2, "" );
                    writer.writeElement( FIELD_DATAPERIODNAMEALT3, "" );

                    writer.closeElement();

                }
            }
        }
    }

    @Override
    public void read( XMLReader reader, ImportParams params )
    {
        Period period = new Period();

        Map<String, String> values = reader.readElements( ELEMENT_NAME );

        Integer periodTypeId = Integer.parseInt( values.get( FIELD_PERIOD_TYPE ) );
        PeriodType periodType = Dhis14ObjectMappingUtil.getPeriodTypeMap().get( periodTypeId );
        period.setPeriodType( periodType );

        period.setId( Integer.valueOf( values.get( FIELD_ID ) ) );
        period.getPeriodType().setId( periodTypeMapping.get( periodType.getName() ) );
        period.setStartDate( Dhis14DateUtil.getDate( Integer.parseInt( values.get( FIELD_START_DATE ) ) ) );
        period.setEndDate( Dhis14DateUtil.getDate( Integer.parseInt( values.get( FIELD_END_DATE ) ) ) );

        importObject( period, params );
    }

    public Calendar getCalendarDate( String date )
    {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        try
        {
            cal.setTime( sdf.parse( date ) );
        }
        catch ( ParseException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return cal;
    }

    public String getDateName( String date )
    {
        DateFormat dateFormat = new SimpleDateFormat( "MMM-yy" );
        Date predefined;
        String name = "";
        try
        {
            predefined = new SimpleDateFormat( "yyyy-MM-dd" ).parse( date );
            name = dateFormat.format( predefined );
        }
        catch ( ParseException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return name;
    }

}