text:
namespace media {

GpuVideoDecoder::Factories::~Factories() {}

// Size of shared-memory segments we allocate.  Since we reuse them we let them
// be on the beefy side.
static const size_t kSharedMemorySegmentBytes = 100 << 10;

GpuVideoDecoder::SHMBuffer::SHMBuffer(base::SharedMemory* m, size_t s)
    : shm(m), size(s) {
}

GpuVideoDecoder::SHMBuffer::~SHMBuffer() {}

GpuVideoDecoder::BufferPair::BufferPair(
    SHMBuffer* s, const scoped_refptr<Buffer>& b) : shm_buffer(s), buffer(b) {
}

GpuVideoDecoder::BufferPair::~BufferPair() {}

GpuVideoDecoder::BufferTimeData::BufferTimeData(
    int32 bbid, base::TimeDelta ts, base::TimeDelta dur)
    : bitstream_buffer_id(bbid), timestamp(ts), duration(dur) {
}

GpuVideoDecoder::BufferTimeData::~BufferTimeData() {}

GpuVideoDecoder::GpuVideoDecoder(
    MessageLoop* message_loop,
    MessageLoop* vda_loop,
    const scoped_refptr<Factories>& factories)
    : gvd_loop_proxy_(message_loop->message_loop_proxy()),
      vda_loop_proxy_(vda_loop->message_loop_proxy()),
      factories_(factories),
      state_(kNormal),
      demuxer_read_in_progress_(false),
      decoder_texture_target_(0),
      next_picture_buffer_id_(0),
      next_bitstream_buffer_id_(0),
      shutting_down_(false),
      error_occured_(false) {
  DCHECK(gvd_loop_proxy_ && factories_);
}

GpuVideoDecoder::~GpuVideoDecoder() {
  DCHECK(!vda_);  // Stop should have been already called.
  DCHECK(pending_read_cb_.is_null());
  for (size_t i = 0; i < available_shm_segments_.size(); ++i) {
    available_shm_segments_[i]->shm->Close();
    delete available_shm_segments_[i];
  }
  available_shm_segments_.clear();
  for (std::map<int32, BufferPair>::iterator it =
           bitstream_buffers_in_decoder_.begin();
       it != bitstream_buffers_in_decoder_.end(); ++it) {
    it->second.shm_buffer->shm->Close();
  }
  bitstream_buffers_in_decoder_.clear();
}

void GpuVideoDecoder::Reset(const base::Closure& closure)  {
  if (!gvd_loop_proxy_->BelongsToCurrentThread() ||
      state_ == kDrainingDecoder) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::Reset, this, closure));
    return;
  }

  // Throw away any already-decoded, not-yet-delivered frames.
  ready_video_frames_.clear();

  if (!vda_) {
    closure.Run();
    return;
  }

  DCHECK(pending_reset_cb_.is_null());
  DCHECK(!closure.is_null());

  // VideoRendererBase::Flush() can't complete while it has a pending read to
  // us, so we fulfill such a read here.
  if (!pending_read_cb_.is_null())
    EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());

  if (shutting_down_) {
    // Immediately fire the callback instead of waiting for the reset to
    // complete (which will happen after PipelineImpl::Stop() completes).
    closure.Run();
  } else {
    pending_reset_cb_ = closure;
  }

  vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      &VideoDecodeAccelerator::Reset, vda_));
}

void GpuVideoDecoder::Stop(const base::Closure& closure) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::Stop, this, closure));
    return;
  }
  if (!vda_) {
    closure.Run();
    return;
  }
  vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      &VideoDecodeAccelerator::Destroy, vda_));
  vda_ = NULL;
  closure.Run();
}

void GpuVideoDecoder::Initialize(const scoped_refptr<DemuxerStream>& stream,
                                 const PipelineStatusCB& status_cb,
                                 const StatisticsCB& statistics_cb) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::Initialize,
        this, stream, status_cb, statistics_cb));
    return;
  }

  DCHECK(!demuxer_stream_);
  if (!stream) {
    status_cb.Run(PIPELINE_ERROR_DECODE);
    return;
  }

  const VideoDecoderConfig& config = stream->video_decoder_config();
  // TODO(scherkus): this check should go in Pipeline prior to creating
  // decoder objects.
  if (!config.IsValidConfig()) {
    DLOG(ERROR) << "Invalid video stream - " << config.AsHumanReadableString();
    status_cb.Run(PIPELINE_ERROR_DECODE);
    return;
  }

  vda_ = factories_->CreateVideoDecodeAccelerator(config.profile(), this);
  if (!vda_) {
    status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
    return;
  }

  demuxer_stream_ = stream;
  statistics_cb_ = statistics_cb;

  demuxer_stream_->EnableBitstreamConverter();

  natural_size_ = config.natural_size();
  config_frame_duration_ = GetFrameDuration(config);

  DVLOG(1) << "GpuVideoDecoder::Initialize() succeeded.";
  status_cb.Run(PIPELINE_OK);
}

void GpuVideoDecoder::Read(const ReadCB& read_cb) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::Read, this, read_cb));
    return;
  }

  if (error_occured_) {
    read_cb.Run(kDecodeError, NULL);
    return;
  }

  if (!vda_) {
    read_cb.Run(kOk, VideoFrame::CreateEmptyFrame());
    return;
  }

  DCHECK(pending_reset_cb_.is_null());
  DCHECK(pending_read_cb_.is_null());
  pending_read_cb_ = read_cb;

  if (!ready_video_frames_.empty()) {
    EnqueueFrameAndTriggerFrameDelivery(NULL);
    return;
  }

  switch (state_) {
    case kDecoderDrained:
      state_ = kNormal;
      // Fall-through.
    case kNormal:
      EnsureDemuxOrDecode();
      break;
    case kDrainingDecoder:
      // Do nothing.  Will be satisfied either by a PictureReady or
      // NotifyFlushDone below.
      break;
  }
}

void GpuVideoDecoder::RequestBufferDecode(const scoped_refptr<Buffer>& buffer) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::RequestBufferDecode, this, buffer));
    return;
  }
  demuxer_read_in_progress_ = false;

  if (!buffer) {
    if (pending_read_cb_.is_null())
      return;

    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        pending_read_cb_, kOk, scoped_refptr<VideoFrame>()));
    pending_read_cb_.Reset();
    return;
  }

  if (!vda_) {
    EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
    return;
  }

  if (buffer->IsEndOfStream()) {
    if (state_ == kNormal) {
      state_ = kDrainingDecoder;
      vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
          &VideoDecodeAccelerator::Flush, vda_));
    }
    return;
  }

  size_t size = buffer->GetDataSize();
  SHMBuffer* shm_buffer = GetSHM(size);
  memcpy(shm_buffer->shm->memory(), buffer->GetData(), size);
  BitstreamBuffer bitstream_buffer(
      next_bitstream_buffer_id_++, shm_buffer->shm->handle(), size);
  bool inserted = bitstream_buffers_in_decoder_.insert(std::make_pair(
      bitstream_buffer.id(), BufferPair(shm_buffer, buffer))).second;
  DCHECK(inserted);
  RecordBufferTimeData(bitstream_buffer, *buffer);

  vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      &VideoDecodeAccelerator::Decode, vda_, bitstream_buffer));
}

void GpuVideoDecoder::RecordBufferTimeData(
    const BitstreamBuffer& bitstream_buffer, const Buffer& buffer) {
  base::TimeDelta duration = buffer.GetDuration();
  if (duration == base::TimeDelta())
    duration = config_frame_duration_;
  input_buffer_time_data_.push_front(BufferTimeData(
      bitstream_buffer.id(), buffer.GetTimestamp(), duration));
  // Why this value?  Because why not.  avformat.h:MAX_REORDER_DELAY is 16, but
  // that's too small for some pathological B-frame test videos.  The cost of
  // using too-high a value is low (192 bits per extra slot).
  static const size_t kMaxInputBufferTimeDataSize = 128;
  // Pop from the back of the list, because that's the oldest and least likely
  // to be useful in the future data.
  if (input_buffer_time_data_.size() > kMaxInputBufferTimeDataSize)
    input_buffer_time_data_.pop_back();
}

void GpuVideoDecoder::GetBufferTimeData(
    int32 id, base::TimeDelta* timestamp, base::TimeDelta* duration) {
  // If all else fails later, at least we can set a default duration if there
  // was one in the config.
  *duration = config_frame_duration_;
  for (std::list<BufferTimeData>::const_iterator it =
           input_buffer_time_data_.begin(); it != input_buffer_time_data_.end();
       ++it) {
    if (it->bitstream_buffer_id != id)
      continue;
    *timestamp = it->timestamp;
    *duration = it->duration;
    return;
  }
  NOTREACHED() << "Missing bitstreambuffer id: " << id;
}

const gfx::Size& GpuVideoDecoder::natural_size() {
  return natural_size_;
}

bool GpuVideoDecoder::HasAlpha() const {
  return true;
}

void GpuVideoDecoder::PrepareForShutdownHack() {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::PrepareForShutdownHack, this));
    return;
  }
  shutting_down_ = true;
}

void GpuVideoDecoder::NotifyInitializeDone() {
  NOTREACHED() << "GpuVideoDecodeAcceleratorHost::Initialize is synchronous!";
}

void GpuVideoDecoder::ProvidePictureBuffers(uint32 count,
                                            const gfx::Size& size) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::ProvidePictureBuffers, this, count, size));
    return;
  }

  std::vector<uint32> texture_ids;
  if (!factories_->CreateTextures(
      count, size, &texture_ids, &decoder_texture_target_)) {
    NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
    return;
  }

  if (!vda_)
    return;

  std::vector<PictureBuffer> picture_buffers;
  for (size_t i = 0; i < texture_ids.size(); ++i) {
    picture_buffers.push_back(PictureBuffer(
        next_picture_buffer_id_++, size, texture_ids[i]));
    bool inserted = picture_buffers_in_decoder_.insert(std::make_pair(
        picture_buffers.back().id(), picture_buffers.back())).second;
    DCHECK(inserted);
  }
  vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      &VideoDecodeAccelerator::AssignPictureBuffers, vda_, picture_buffers));
}

void GpuVideoDecoder::DismissPictureBuffer(int32 id) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::DismissPictureBuffer, this, id));
    return;
  }
  std::map<int32, PictureBuffer>::iterator it =
      picture_buffers_in_decoder_.find(id);
  if (it == picture_buffers_in_decoder_.end()) {
    NOTREACHED() << "Missing picture buffer: " << id;
    return;
  }
  factories_->DeleteTexture(it->second.texture_id());
  picture_buffers_in_decoder_.erase(it);
}

void GpuVideoDecoder::PictureReady(const media::Picture& picture) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::PictureReady, this, picture));
    return;
  }
  std::map<int32, PictureBuffer>::iterator it =
      picture_buffers_in_decoder_.find(picture.picture_buffer_id());
  if (it == picture_buffers_in_decoder_.end()) {
    NOTREACHED() << "Missing picture buffer: " << picture.picture_buffer_id();
    NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
    return;
  }
  const PictureBuffer& pb = it->second;

  // Update frame's timestamp.
  base::TimeDelta timestamp;
  base::TimeDelta duration;
  GetBufferTimeData(picture.bitstream_buffer_id(), &timestamp, &duration);

  DCHECK(decoder_texture_target_);
  scoped_refptr<VideoFrame> frame(VideoFrame::WrapNativeTexture(
      pb.texture_id(), decoder_texture_target_, pb.size().width(),
      pb.size().height(), timestamp, duration,
      base::Bind(&GpuVideoDecoder::ReusePictureBuffer, this,
                 picture.picture_buffer_id())));

  EnqueueFrameAndTriggerFrameDelivery(frame);
}

void GpuVideoDecoder::EnqueueFrameAndTriggerFrameDelivery(
    const scoped_refptr<VideoFrame>& frame) {
  DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());

  // During a pending vda->Reset(), we don't accumulate frames.  Drop it on the
  // floor and return.
  if (!pending_reset_cb_.is_null())
    return;

  if (frame)
    ready_video_frames_.push_back(frame);
  else
    DCHECK(!ready_video_frames_.empty());

  if (pending_read_cb_.is_null())
    return;

  gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      pending_read_cb_, kOk, ready_video_frames_.front()));
  pending_read_cb_.Reset();
  ready_video_frames_.pop_front();
}

void GpuVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::ReusePictureBuffer, this, picture_buffer_id));
    return;
  }
  if (!vda_)
    return;
  vda_loop_proxy_->PostTask(FROM_HERE, base::Bind(
      &VideoDecodeAccelerator::ReusePictureBuffer, vda_, picture_buffer_id));
}

GpuVideoDecoder::SHMBuffer* GpuVideoDecoder::GetSHM(size_t min_size) {
  DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
  if (available_shm_segments_.empty() ||
      available_shm_segments_.back()->size < min_size) {
    size_t size_to_allocate = std::max(min_size, kSharedMemorySegmentBytes);
    base::SharedMemory* shm = factories_->CreateSharedMemory(size_to_allocate);
    DCHECK(shm);
    return new SHMBuffer(shm, size_to_allocate);
  }
  SHMBuffer* ret = available_shm_segments_.back();
  available_shm_segments_.pop_back();
  return ret;
}

void GpuVideoDecoder::PutSHM(SHMBuffer* shm_buffer) {
  DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
  available_shm_segments_.push_back(shm_buffer);
}

void GpuVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::NotifyEndOfBitstreamBuffer, this, id));
    return;
  }

  std::map<int32, BufferPair>::iterator it =
      bitstream_buffers_in_decoder_.find(id);
  if (it == bitstream_buffers_in_decoder_.end()) {
    NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
    NOTREACHED() << "Missing bitstream buffer: " << id;
    return;
  }

  PutSHM(it->second.shm_buffer);
  const scoped_refptr<Buffer>& buffer = it->second.buffer;
  if (buffer->GetDataSize()) {
    PipelineStatistics statistics;
    statistics.video_bytes_decoded = buffer->GetDataSize();
    statistics_cb_.Run(statistics);
  }
  bitstream_buffers_in_decoder_.erase(it);

  if (!pending_read_cb_.is_null() && pending_reset_cb_.is_null() &&
      state_ != kDrainingDecoder &&
      bitstream_buffers_in_decoder_.empty()) {
    DCHECK(ready_video_frames_.empty());
    EnsureDemuxOrDecode();
  }
}

void GpuVideoDecoder::EnsureDemuxOrDecode() {
  DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
  if (demuxer_read_in_progress_)
    return;
  demuxer_read_in_progress_ = true;
  demuxer_stream_->Read(base::Bind(
      &GpuVideoDecoder::RequestBufferDecode, this));
}

void GpuVideoDecoder::NotifyFlushDone() {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::NotifyFlushDone, this));
    return;
  }
  DCHECK_EQ(state_, kDrainingDecoder);
  state_ = kDecoderDrained;
  EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
}

void GpuVideoDecoder::NotifyResetDone() {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::NotifyResetDone, this));
    return;
  }

  if (!vda_)
    return;

  DCHECK(ready_video_frames_.empty());

  // This needs to happen after the Reset() on vda_ is done to ensure pictures
  // delivered during the reset can find their time data.
  input_buffer_time_data_.clear();

  if (!pending_reset_cb_.is_null())
    base::ResetAndReturn(&pending_reset_cb_).Run();

  if (!pending_read_cb_.is_null())
    EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
}

void GpuVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error) {
  if (!gvd_loop_proxy_->BelongsToCurrentThread()) {
    gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
        &GpuVideoDecoder::NotifyError, this, error));
    return;
  }
  if (!vda_)
    return;
  vda_ = NULL;
  DLOG(ERROR) << "VDA Error: " << error;

  error_occured_ = true;

  if (!pending_read_cb_.is_null()) {
    base::ResetAndReturn(&pending_read_cb_).Run(kDecodeError, NULL);
    return;
  }
}

}  // namespace media


text:
var cdb = require('cartodb.js');
var template = require('./undo-redo.tpl');

module.exports = cdb.core.View.extend({
  events: {
    'click .js-redo': '_onRedoClick',
    'click .js-undo': '_onUndoClick',
    'click .js-apply': '_onApplyClick'
  },

  initialize: function (opts) {
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.styleModel) throw new Error('styleModel is required');
    this._styleModel = opts.styleModel;
    this._editorModel = opts.editorModel;

    this._initBinds();
  },

  render: function () {
    this.$el.html(
      template({
        canUndo: this._styleModel.canUndo(),
        canRedo: this._styleModel.canRedo(),
        canApply: this._editorModel.isEditing()
      })
    );
    this._onStyleChange(this._editorModel);
    return this;
  },

  _initBinds: function () {
    this._styleModel.bind('undo redo', this.render, this);
    this._styleModel.bind('change', this._onStyleChange, this);
    this._editorModel.bind('change:edition', this._onStyleChange, this);
    this.add_related_model(this._styleModel);
    this.add_related_model(this._editorModel);
  },

  _onUndoClick: function () {
    if (this._styleModel.canUndo()) {
      this._styleModel.undo();
    }
  },

  _onRedoClick: function () {
    if (this._styleModel.canRedo()) {
      this._styleModel.redo();
    }
  },

  _onApplyClick: function () {
    console.log('applying');
  },

  _onStyleChange: function (m) {
    var editing = m.isEditing();
    this._getIcons().toggleClass('u-whiteTextColor', editing);
  },

  _getIcons: function () {
    return this.$('.js-theme');
  }
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel.DataAnnotations;
using Stations.Models.Enums;

namespace Stations.Models
{
    public class Trip
    {
        public const TripStatus DefaultStatus = TripStatus.OnTime;

        public int Id { get; set; }

	    public int OriginStationId { get; set; }

		[Required]
	    public Station OriginStation { get; set; }

	    public int DestinationStationId { get; set; }

	    [Required]
		public Station DestinationStation { get; set; }

		[Required]
	    public DateTime DepartureTime { get; set; }

		[Required]
	    public DateTime ArrivalTime { get; set; }

	    public int TrainId { get; set; }

		[Required]
	    public Train Train { get; set; }

	    public TripStatus Status { get; set; }

	    public TimeSpan? TimeDifference { get; set; }
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gray" >

    <LinearLayout
        android:id="@+id/main_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <include
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            layout="@layout/header_innner" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/main_header"
        android:orientation="vertical" >

        <include
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            layout="@layout/sub_header" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >

        <include layout="@layout/footer" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/navigator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/header"
        android:gravity="right"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:id="@+id/text_find_route_jaipur_bus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@drawable/monument_button"
            android:padding="5dp"
            android:text="@string/Find_Your_Bus"
            android:textColor="@color/blk" />
    </RelativeLayout>

    <ListView
        android:id="@+id/list_jaipur_bus_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/footer"
        android:layout_below="@id/navigator"
        android:divider="@drawable/button_background"
        android:dividerHeight="2dp" >
    </ListView>

</RelativeLayout>


text:
We'd love your help! If you would like to contribute code you can do so through GitHub
by forking the repository and sending a pull request into the `master` branch.

## Getting Started

This library uses [glide](https://github.com/Masterminds/glide) to manage dependencies.

To get started:

```bash
git submodule update --init --recursive
glide install
make test
```

## Making A Change

*Before making any significant changes, please [open an
issue](https://github.com/uber/jaeger-lib/issues).* Discussing your proposed
changes ahead of time will make the contribution process smooth for everyone.

Once we've discussed your changes and you've got your code ready, make sure
that tests are passing (`make test` or `make cover`) and open your PR! Your
pull request is most likely to be accepted if it:

* Includes tests for new functionality.
* Follows the guidelines in [Effective
  Go](https://golang.org/doc/effective_go.html) and the [Go team's common code
  review comments](https://github.com/golang/go/wiki/CodeReviewComments).
* Has a [good commit
  message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

## License

By contributing your code, you agree to license your contribution under the terms of the [Apache 2.0 License](LICENSE).

If you are adding a new file it should have a header like below. The easiest way to add such header is to run `make fmt`.

```
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
```


text:
'use strict';

describe('Service: private', function () {

  // load the service's module
  beforeEach(module('promomemxApp'));

  // instantiate service
  var private;
  beforeEach(inject(function (_private_) {
    private = _private_;
  }));

  it('should do something', function () {
    expect(!!private).toBe(true);
  });

});


text:
<?php namespace Draw\Swagger\Schema;

/**
 * @author Martin Poirier Theoret <mpoiriert@gmail.com>
 */
class SecurityRequirement
{
    private $data;

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param mixed $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

    /**
     * Each name must correspond to a security scheme which is declared in the Security Definitions.
     * If the security scheme is of type "oauth2", then the value is a list of scope names required for the execution.
     * For other security scheme types, the array MUST be empty.
     *
     * @param $name
     * @param string[] $value
     */
    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        return $this->data[$name];
    }
}


text:
namespace IECorePython
{
IECOREPYTHON_API void bindCubeColorLookupData();
}

#endif // IECOREPYTHON_CUBECOLORLOOKUPDATABINDING_H


text:
package org.apache.hadoop.hive.ql.plan;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator;
import org.apache.hadoop.hive.ql.plan.Explain.Level;

/**
 * Mux operator descriptor implementation..
 *
 */
@Explain(displayName = "Mux Operator", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
public class MuxDesc extends AbstractOperatorDesc {
  private static final long serialVersionUID = 1L;

  private List<List<ExprNodeDesc>> parentToKeyCols;
  private List<List<ExprNodeDesc>> parentToValueCols;
  private List<List<String>> parentToOutputKeyColumnNames;
  private List<List<String>> parentToOutputValueColumnNames;
  private List<Integer> parentToTag;
  private Map<Integer, Integer> newParentIndexToOldParentIndex;

  public MuxDesc() {
  }

  // A MuxDesc is only generated from a corresponding ReduceSinkDesc.
  public MuxDesc(List<Operator<? extends OperatorDesc>> ops){
    int numParents = ops.size();
    parentToKeyCols = new ArrayList<List<ExprNodeDesc>>(numParents);
    parentToOutputKeyColumnNames = new ArrayList<List<String>>(numParents);
    parentToValueCols = new ArrayList<List<ExprNodeDesc>>(numParents);
    parentToOutputValueColumnNames = new ArrayList<List<String>>(numParents);
    parentToTag = new ArrayList<Integer>(numParents);

    for (Operator<? extends OperatorDesc> op: ops) {
      if (op != null && op instanceof ReduceSinkOperator) {
        ReduceSinkOperator rsop = (ReduceSinkOperator)op;
        List<ExprNodeDesc> keyCols = rsop.getConf().getKeyCols();
        List<ExprNodeDesc> valueCols = rsop.getConf().getValueCols();
        List<String> outputKeyColumnNames = rsop.getConf().getOutputKeyColumnNames();
        List<String> outputValueColumnNames = rsop.getConf().getOutputValueColumnNames();
        int tag = rsop.getConf().getTag();
        parentToKeyCols.add(keyCols);
        parentToValueCols.add(valueCols);
        parentToOutputKeyColumnNames.add(outputKeyColumnNames);
        parentToOutputValueColumnNames.add(outputValueColumnNames);
        parentToTag.add(tag);
      } else {
        parentToKeyCols.add(null);
        parentToValueCols.add(null);
        parentToOutputKeyColumnNames.add(null);
        parentToOutputValueColumnNames.add(null);
        parentToTag.add(null);
      }
    }
  }

  public List<List<ExprNodeDesc>> getParentToKeyCols() {
    return parentToKeyCols;
  }

  public void setParentToKeyCols(List<List<ExprNodeDesc>> parentToKeyCols) {
    this.parentToKeyCols = parentToKeyCols;
  }

  public List<List<ExprNodeDesc>> getParentToValueCols() {
    return parentToValueCols;
  }

  public void setParentToValueCols(List<List<ExprNodeDesc>> parentToValueCols) {
    this.parentToValueCols = parentToValueCols;
  }

  public List<List<String>> getParentToOutputKeyColumnNames() {
    return parentToOutputKeyColumnNames;
  }

  public void setParentToOutputKeyColumnNames(
      List<List<String>> parentToOutputKeyColumnNames) {
    this.parentToOutputKeyColumnNames = parentToOutputKeyColumnNames;
  }

  public List<List<String>> getParentToOutputValueColumnNames() {
    return parentToOutputValueColumnNames;
  }

  public void setParentToOutputValueColumnNames(
      List<List<String>> parentToOutputValueColumnNames) {
    this.parentToOutputValueColumnNames = parentToOutputValueColumnNames;
  }

  public List<Integer> getParentToTag() {
    return parentToTag;
  }

  public void setParentToTag(List<Integer> parentToTag) {
    this.parentToTag = parentToTag;
  }

  public Map<Integer, Integer> getNewParentIndexToOldParentIndex() {
    return newParentIndexToOldParentIndex;
  }

  public void setNewParentIndexToOldParentIndex(
      Map<Integer, Integer> newParentIndexToOldParentIndex) {
    this.newParentIndexToOldParentIndex = newParentIndexToOldParentIndex;
  }
}


text:
/* global QUnit, $, testLog */

(function() {
    var viewer;

    QUnit.module('ReferenceStrip', {
        beforeEach: function () {
            $('

').appendTo("#qunit-fixture");

            testLog.reset();
        },
        afterEach: function () {
            if (viewer && viewer.close) {
                viewer.close();
            }

            viewer = null;
        }
    });

    // ----------
    var createViewer = function(options) {
        options = options || {};
        viewer = OpenSeadragon(OpenSeadragon.extend({
            id:            'example',
            prefixUrl:     '/build/openseadragon/images/',
            springStiffness: 100 // Faster animation = faster tests
        }, options));
    };

    // ----------
    QUnit.test('basics', function(assert) {
        var done = assert.async();
        createViewer({
            sequenceMode: true,
            showReferenceStrip: true,
            tileSources: [
                '/test/data/tall.dzi',
                '/test/data/wide.dzi',
            ]
        });

        assert.ok(viewer.referenceStrip, 'referenceStrip exists');
        done();
    });

    // ----------
    QUnit.test('shadow dom', function(assert) {
        if (document.head && document.head.attachShadow) {
            var done = assert.async();

            var shadowDiv = document.createElement('div');
            shadowDiv.attachShadow({
                mode: 'open'
            });
            shadowDiv.shadowRoot.innerHTML = `<div id="shadow-example"></div>`

            createViewer({
                element: shadowDiv.shadowRoot.querySelector('#shadow-example'),
                sequenceMode: true,
                showReferenceStrip: true,
                tileSources: [
                    '/test/data/tall.dzi',
                    '/test/data/wide.dzi'
                ]
            });

            $(shadowDiv).appendTo("#qunit-fixture");

            assert.ok(viewer.referenceStrip, 'referenceStrip exists');
            done();
        } else {
            assert.expect(0);
        }
    })

})();


text:
package com.gs.fw.common.mithra.connectionmanager;

public interface ObjectSourceTablePartitionManager
{
    /**
     * Returns the table name corresponding to the name in the runtime configuration file. For example, with a
     * configuration file that says:
     * <MithraObjectConfiguration className="com.gs.fw.myProject.mithra.Order" cacheType="partial" getTableNameFromConnectionManager="true"/>
     * The method will be passed "ORDERS" and expects to get the actual table (e.g. "ORDERS_ABC")
     * @param defaultTable DefaultTable value set in the mithra object xml file
     * @param source source attribute value
     * @return the table name that will be use to query
     */
    public String getTableName(String defaultTable, Object source);
}


text:
package cn.newcapec.foundation.ecardcity.makecard.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import cn.newcapec.framework.core.handler.springDatebind.CustomDateSerializer;
import cn.newcapec.framework.core.model.CommonModel;

/**
 *
 * @Description: 黑名单表:system_black 实体类
 * @author 高崇飞
 * @date 2014-4-23 下午01:33:13
 * @version V1.0
 */
@Table(name = "system_black")
@Entity
public class SystemBlack extends CommonModel {
	private static final long serialVersionUID = -3347324002396153840L;
	// 更新用户
	@Column(name = "edit_person", length = 12)
	private String edit_person;
	// 黑名单来源(0:清算平台;1:制卡中心;2:自助;3:记录上传;4:其他)
	@Column(name = "sourcetype", length = 1)
	private String sourcetype;
	// 操作类型 0挂失 1解挂
	@Column(name = "state", length = 1)
	private String state;
	// 卡应用序列号
	@Column(name = "asn", length = 13)
	private String asn;
	// 板本号
	@Column(name = "sn", length = 5)
	private Integer sn;
	// 有效期
	@JsonSerialize(using = CustomDateSerializer.class)
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "nousedate")
	private Date nousedate;
	// 生成时间(挂失时间)
	@JsonSerialize(using = CustomDateSerializer.class)
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "losscount")
	private Date losscount;
	// 更新日期
	@JsonSerialize(using = CustomDateSerializer.class)
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "edit_date")
	private Date edit_date;

	public Date getEdit_date() {
		return edit_date;
	}

	public void setEdit_date(Date edit_date) {
		this.edit_date = edit_date;
	}

	public String getSourcetype() {
		return sourcetype;
	}

	public void setSourcetype(String sourcetype) {
		this.sourcetype = sourcetype;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getAsn() {
		return asn;
	}

	public void setAsn(String asn) {
		this.asn = asn;
	}

	public Integer getSn() {
		return sn;
	}

	public void setSn(Integer sn) {
		this.sn = sn;
	}

	public Date getNousedate() {
		return nousedate;
	}

	public void setNousedate(Date nousedate) {
		this.nousedate = nousedate;
	}

	public Date getLosscount() {
		return losscount;
	}

	public void setLosscount(Date losscount) {
		this.losscount = losscount;
	}

	public String getEdit_person() {
		return edit_person;
	}

	public void setEdit_person(String edit_person) {
		this.edit_person = edit_person;
	}
}


text:
/**
 * Predmet:  IFJ / IAL
 * Projekt:  Implementace interpretu imperativniho jazyka
 * Varianta: a/1/I
 * Soubor:   stack.h
 *
 * Popis:
 *
 *
 * Datum:    21.10.2012
 *
 * Autori:   Frantisek Kolacek   <xkolac12@stud.fit.vutbr.cz>
 *           Matyas Petr         <xmatya03@stud.fit.vutbr.cz>
 *           Muzikarova Michaela <xmuzik04@stud.fit.vutbr.cz>
 *           Necasova Veronika   <xnecas21@stud.fit.vutbr.cz>
 *           Skacel Dalibor      <xskace11@stud.fit.vutbr.cz>
 */

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

#include <stdlib.h>
#include <stdbool.h>
#include "mmu.h"

#define STACK_EOK      0
#define STACK_ERR    -10
#define STACK_EMPTY  -11
#define STACK_MEMORY -12

typedef struct stackPtr{
    struct stackPtr *ptr;
    void* data;

} *tStackPtr;

typedef struct{
    unsigned int size;
    tStackPtr top;

} tStack;

tStack* stackCreate();
void stackDestroy(tStack*);

E_CODE stackInit(tStack*);
E_CODE stackDispose(tStack*);
E_CODE stackPush(tStack*, void*);
void* stackTop(tStack*);
void* stackPop(tStack*);

bool stackEmpty(tStack*);
unsigned int stackSize(tStack*);

#endif


text:
    <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
    <title>moveByLevel</title>
    <link href="../../../images/logo-icon.svg" rel="icon" type="image/svg">

    <link href="../../../styles/style.css" rel="Stylesheet">
    <link href="../../../styles/logo-styles.css" rel="Stylesheet">
    <link href="../../../styles/jetbrains-mono.css" rel="Stylesheet">
    <link href="../../../styles/main.css" rel="Stylesheet">

zircon.core/org.hexworks.zircon.api.graphics/LayerHandle/moveByLevel

<button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button>

move<wbr></wbr>By<wbr></wbr>Level

abstract fun moveByLevel(level: Int): Boolean
Content copied to clipboard

Moves this Layer levels up or down (positive is up, negative is down).

Return

true if the operation was successful false if not

Sources

(source)

Link copied to clipboard

© 2020 CopyrightSponsored and developed by dokka


text:
#import "DDFileLogger.h"

#import <unistd.h>
#import <sys/attr.h>
#import <sys/xattr.h>
#import <libkern/OSAtomic.h>

// We probably shouldn't be using DDLog() statements within the DDLog implementation.
// But we still want to leave our log statements for any future debugging,
// and to allow other developers to trace the implementation (which is a great learning tool).
//
// So we use primitive logging macros around NSLog.
// We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.

#define LOG_LEVEL 2

#define NSLogError(frmt, ...)    do{ if(LOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0)
#define NSLogWarn(frmt, ...)     do{ if(LOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0)
#define NSLogInfo(frmt, ...)     do{ if(LOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0)
#define NSLogVerbose(frmt, ...)  do{ if(LOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0)

@interface DDLogFileManagerDefault (PrivateAPI)

- (void)deleteOldLogFiles;

@end

@interface DDFileLogger (PrivateAPI)

#if GCD_MAYBE_UNAVAILABLE

- (void)lt_getMaximumFileSize:(NSMutableArray *)resultHolder;
- (void)lt_setMaximumFileSize:(NSNumber *)maximumFileSizeWrapper;

- (void)lt_getRollingFrequency:(NSMutableArray *)resultHolder;
- (void)lt_setRollingFrequency:(NSNumber *)rollingFrequencyWrapper;

#endif

- (void)rollLogFileNow;
- (void)maybeRollLogFileDueToAge:(NSTimer *)aTimer;
- (void)maybeRollLogFileDueToSize;
@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation DDLogFileManagerDefault

@synthesize maximumNumberOfLogFiles;

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

		NSKeyValueObservingOptions kvoOptions = NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew;

		[self addObserver:self forKeyPath:@"maximumNumberOfLogFiles" options:kvoOptions context:nil];

		NSLogVerbose(@"DDFileLogManagerDefault: logsDir:\n%@", [self logsDirectory]);
		NSLogVerbose(@"DDFileLogManagerDefault: sortedLogFileNames:\n%@", [self sortedLogFileNames]);
	}
	return self;
}

- (void)dealloc
{
	[super dealloc];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
	NSNumber *old = [change objectForKey:NSKeyValueChangeOldKey];
	NSNumber *new = [change objectForKey:NSKeyValueChangeNewKey];

	if ([old isEqual:new])
	{
		// No change in value - don't bother with any processing.
		return;
	}

	if ([keyPath isEqualToString:@"maximumNumberOfLogFiles"])
	{
		NSLogInfo(@"DDFileLogManagerDefault: Responding to configuration change: maximumNumberOfLogFiles");

		if (IS_GCD_AVAILABLE)
		{
		#if GCD_MAYBE_AVAILABLE

			dispatch_block_t block = ^{
				NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

				[self deleteOldLogFiles];

				[pool release];
			};

			dispatch_async([DDLog loggingQueue], block);

		#endif
		}
		else
		{
		#if GCD_MAYBE_UNAVAILABLE

			[self performSelector:@selector(deleteOldLogFiles)
			             onThread:[DDLog loggingThread]
			           withObject:nil
			        waitUntilDone:NO];

		#endif
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark File Deleting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Deletes archived log files that exceed the maximumNumberOfLogFiles configuration value.
**/
- (void)deleteOldLogFiles
{
	NSLogVerbose(@"DDLogFileManagerDefault: deleteOldLogFiles");

	NSArray *sortedLogFileInfos = [self sortedLogFileInfos];

	NSUInteger maxNumLogFiles = self.maximumNumberOfLogFiles;

	// Do we consider the first file?
	// We are only supposed to be deleting archived files.
	// In most cases, the first file is likely the log file that is currently being written to.
	// So in most cases, we do not want to consider this file for deletion.

	NSUInteger count = [sortedLogFileInfos count];
	BOOL excludeFirstFile = NO;

	if (count > 0)
	{
		DDLogFileInfo *logFileInfo = [sortedLogFileInfos objectAtIndex:0];

		if (!logFileInfo.isArchived)
		{
			excludeFirstFile = YES;
		}
	}

	NSArray *sortedArchivedLogFileInfos;
	if (excludeFirstFile)
	{
		count--;
		sortedArchivedLogFileInfos = [sortedLogFileInfos subarrayWithRange:NSMakeRange(1, count)];
	}
	else
	{
		sortedArchivedLogFileInfos = sortedLogFileInfos;
	}

	NSUInteger i;
	for (i = 0; i < count; i++)
	{
		if (i >= maxNumLogFiles)
		{
			DDLogFileInfo *logFileInfo = [sortedArchivedLogFileInfos objectAtIndex:i];

			NSLogInfo(@"DDLogFileManagerDefault: Deleting file: %@", logFileInfo.fileName);

			[[NSFileManager defaultManager] removeItemAtPath:logFileInfo.filePath error:nil];
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Log Files
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Returns the path to the logs directory.
 * If the logs directory doesn't exist, this method automatically creates it.
**/
- (NSString *)logsDirectory
{
#if TARGET_OS_IPHONE
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
#else
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();

	NSString *appName = [[NSProcessInfo processInfo] processName];

	NSString *baseDir = [basePath stringByAppendingPathComponent:appName];
#endif

	NSString *logsDir = [baseDir stringByAppendingPathComponent:@"Logs"];

	if(![[NSFileManager defaultManager] fileExistsAtPath:logsDir])
	{
		NSError *err = nil;
		if(![[NSFileManager defaultManager] createDirectoryAtPath:logsDir
		                              withIntermediateDirectories:YES attributes:nil error:&err])
		{
			NSLogError(@"DDFileLogManagerDefault: Error creating logsDirectory: %@", err);
		}
	}

	return logsDir;
}

- (BOOL)isLogFile:(NSString *)fileName
{
	// A log file has a name like "log-<uuid>.txt", where <uuid> is a HEX-string of 6 characters.
	//
	// For example: log-DFFE99.txt

	BOOL hasProperPrefix = [fileName hasPrefix:@"log-"];

	BOOL hasProperLength = [fileName length] >= 10;

	if (hasProperPrefix && hasProperLength)
	{
		NSCharacterSet *hexSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"];

		NSString *hex = [fileName substringWithRange:NSMakeRange(4, 6)];
		NSString *nohex = [hex stringByTrimmingCharactersInSet:hexSet];

		if ([nohex length] == 0)
		{
			return YES;
		}
	}

	return NO;
}

/**
 * Returns an array of NSString objects,
 * each of which is the filePath to an existing log file on disk.
**/
- (NSArray *)unsortedLogFilePaths
{
	NSString *logsDirectory = [self logsDirectory];

	NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logsDirectory error:nil];

	NSMutableArray *unsortedLogFilePaths = [NSMutableArray arrayWithCapacity:[fileNames count]];

	for (NSString *fileName in fileNames)
	{
		// Filter out any files that aren't log files. (Just for extra safety)

		if ([self isLogFile:fileName])
		{
			NSString *filePath = [logsDirectory stringByAppendingPathComponent:fileName];

			[unsortedLogFilePaths addObject:filePath];
		}
	}

	return unsortedLogFilePaths;
}

/**
 * Returns an array of NSString objects,
 * each of which is the fileName of an existing log file on disk.
**/
- (NSArray *)unsortedLogFileNames
{
	NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];

	NSMutableArray *unsortedLogFileNames = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];

	for (NSString *filePath in unsortedLogFilePaths)
	{
		[unsortedLogFileNames addObject:[filePath lastPathComponent]];
	}

	return unsortedLogFileNames;
}

/**
 * Returns an array of DDLogFileInfo objects,
 * each representing an existing log file on disk,
 * and containing important information about the log file such as it's modification date and size.
**/
- (NSArray *)unsortedLogFileInfos
{
	NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];

	NSMutableArray *unsortedLogFileInfos = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];

	for (NSString *filePath in unsortedLogFilePaths)
	{
		DDLogFileInfo *logFileInfo = [[DDLogFileInfo alloc] initWithFilePath:filePath];

		[unsortedLogFileInfos addObject:logFileInfo];
		[logFileInfo release];
	}

	return unsortedLogFileInfos;
}

/**
 * Just like the unsortedLogFilePaths method, but sorts the array.
 * The items in the array are sorted by modification date.
 * The first item in the array will be the most recently modified log file.
**/
- (NSArray *)sortedLogFilePaths
{
	NSArray *sortedLogFileInfos = [self sortedLogFileInfos];

	NSMutableArray *sortedLogFilePaths = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];

	for (DDLogFileInfo *logFileInfo in sortedLogFileInfos)
	{
		[sortedLogFilePaths addObject:[logFileInfo filePath]];
	}

	return sortedLogFilePaths;
}

/**
 * Just like the unsortedLogFileNames method, but sorts the array.
 * The items in the array are sorted by modification date.
 * The first item in the array will be the most recently modified log file.
**/
- (NSArray *)sortedLogFileNames
{
	NSArray *sortedLogFileInfos = [self sortedLogFileInfos];

	NSMutableArray *sortedLogFileNames = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];

	for (DDLogFileInfo *logFileInfo in sortedLogFileInfos)
	{
		[sortedLogFileNames addObject:[logFileInfo fileName]];
	}

	return sortedLogFileNames;
}

/**
 * Just like the unsortedLogFileInfos method, but sorts the array.
 * The items in the array are sorted by modification date.
 * The first item in the array will be the most recently modified log file.
**/
- (NSArray *)sortedLogFileInfos
{
	return [[self unsortedLogFileInfos] sortedArrayUsingSelector:@selector(reverseCompareByCreationDate:)];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Creation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Generates a short UUID suitable for use in the log file's name.
 * The result will have six characters, all in the hexadecimal set [0123456789ABCDEF].
**/
- (NSString *)generateShortUUID
{
	CFUUIDRef uuid = CFUUIDCreate(NULL);

	CFStringRef fullStr = CFUUIDCreateString(NULL, uuid);
	CFStringRef shortStr = CFStringCreateWithSubstring(NULL, fullStr, CFRangeMake(0, 6));

	CFRelease(fullStr);
	CFRelease(uuid);

	return [NSMakeCollectable(shortStr) autorelease];
}

/**
 * Generates a new unique log file path, and creates the corresponding log file.
**/
- (NSString *)createNewLogFile
{
	// Generate a random log file name, and create the file (if there isn't a collision)

	NSString *logsDirectory = [self logsDirectory];
	do
	{
		NSString *fileName = [NSString stringWithFormat:@"log-%@.txt", [self generateShortUUID]];

		NSString *filePath = [logsDirectory stringByAppendingPathComponent:fileName];

		if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
		{
			NSLogVerbose(@"DDLogFileManagerDefault: Creating new log file: %@", fileName);

			[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

			// Since we just created a new log file, we may need to delete some old log files
			[self deleteOldLogFiles];

			return filePath;
		}

	} while(YES);
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation DDLogFileFormatterDefault

- (id)init
{
	if((self = [super init]))
	{
		dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
		[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
	}
	return self;
}

- (NSString *)formatLogMessage:(DDLogMessage *)logMessage
{
	NSString *dateAndTime = [dateFormatter stringFromDate:(logMessage->timestamp)];

	return [NSString stringWithFormat:@"%@  %@", dateAndTime, logMessage->logMsg];
}

- (void)dealloc
{
	[dateFormatter release];
	[super dealloc];
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation DDFileLogger

@synthesize maximumFileSize;
@synthesize rollingFrequency;
@synthesize logFileManager;

- (id)init
{
	DDLogFileManagerDefault *defaultLogFileManager = [[[DDLogFileManagerDefault alloc] init] autorelease];

	return [self initWithLogFileManager:defaultLogFileManager];
}

- (id)initWithLogFileManager:(id <DDLogFileManager>)aLogFileManager
{
	if ((self = [super init]))
	{
		maximumFileSize = DEFAULT_LOG_MAX_FILE_SIZE;
		rollingFrequency = DEFAULT_LOG_ROLLING_FREQUENCY;

		logFileManager = [aLogFileManager retain];

		formatter = [[DDLogFileFormatterDefault alloc] init];
	}
	return self;
}

- (void)dealloc
{
	[formatter release];
	[logFileManager release];

	[currentLogFileInfo release];

	[currentLogFileHandle synchronizeFile];
	[currentLogFileHandle closeFile];
	[currentLogFileHandle release];

	[rollingTimer invalidate];
	[rollingTimer release];

	[super dealloc];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (unsigned long long)maximumFileSize
{
	// The design of this method is taken from the DDAbstractLogger implementation.
	// For documentation please refer to the DDAbstractLogger implementation.

	// Note: The internal implementation should access the maximumFileSize variable directly,
	// but if we forget to do this, then this method should at least work properly.

	if (IS_GCD_AVAILABLE)
	{
	#if GCD_MAYBE_AVAILABLE

		if (dispatch_get_current_queue() == loggerQueue)
		{
			return maximumFileSize;
		}

		__block unsigned long long result;

		dispatch_block_t block = ^{
			result = maximumFileSize;
		};
		dispatch_sync([DDLog loggingQueue], block);

		return result;

	#endif
	}
	else
	{
	#if GCD_MAYBE_UNAVAILABLE

		NSThread *loggingThread = [DDLog loggingThread];

		if ([NSThread currentThread] == loggingThread)
		{
			return maximumFileSize;
		}

		unsigned long long result;
		NSMutableArray *resultHolder = [[NSMutableArray alloc] init];

		[self performSelector:@selector(lt_getMaximumFileSize:)
		             onThread:loggingThread
		           withObject:resultHolder
		        waitUntilDone:YES];

		OSMemoryBarrier();

		result = [[resultHolder objectAtIndex:0] unsignedLongLongValue];
		[resultHolder release];

		return result;

	#endif
	}
}

- (void)setMaximumFileSize:(unsigned long long)newMaximumFileSize
{
	// The design of this method is taken from the DDAbstractLogger implementation.
	// For documentation please refer to the DDAbstractLogger implementation.

	if (IS_GCD_AVAILABLE)
	{
	#if GCD_MAYBE_AVAILABLE

		dispatch_block_t block = ^{
			NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

			maximumFileSize = newMaximumFileSize;
			[self maybeRollLogFileDueToSize];

			[pool release];
		};

		if (dispatch_get_current_queue() == loggerQueue)
			block();
		else
			dispatch_async([DDLog loggingQueue], block);

	#endif
	}
	else
	{
	#if GCD_MAYBE_UNAVAILABLE

		NSThread *loggingThread = [DDLog loggingThread];
		NSNumber *newMaximumFileSizeWrapper = [NSNumber numberWithUnsignedLongLong:newMaximumFileSize];

		if ([NSThread currentThread] == loggingThread)
		{
			[self lt_setMaximumFileSize:newMaximumFileSizeWrapper];
		}
		else
		{
			[self performSelector:@selector(lt_setMaximumFileSize:)
			             onThread:loggingThread
			           withObject:newMaximumFileSizeWrapper
			        waitUntilDone:NO];
		}

	#endif
	}
}

- (NSTimeInterval)rollingFrequency
{
	// The design of this method is taken from the DDAbstractLogger implementation.
	// For documentation please refer to the DDAbstractLogger implementation.

	// Note: The internal implementation should access the rollingFrequency variable directly,
	// but if we forget to do this, then this method should at least work properly.

	if (IS_GCD_AVAILABLE)
	{
	#if GCD_MAYBE_AVAILABLE

		if (dispatch_get_current_queue() == loggerQueue)
		{
			return rollingFrequency;
		}

		__block NSTimeInterval result;

		dispatch_block_t block = ^{
			result = rollingFrequency;
		};
		dispatch_sync([DDLog loggingQueue], block);

		return result;

	#endif
	}
	else
	{
	#if GCD_MAYBE_UNAVAILABLE

		NSThread *loggingThread = [DDLog loggingThread];

		if ([NSThread currentThread] == loggingThread)
		{
			return rollingFrequency;
		}

		NSTimeInterval result;
		NSMutableArray *resultHolder = [[NSMutableArray alloc] init];

		[self performSelector:@selector(lt_getRollingFrequency:)
		             onThread:loggingThread
		           withObject:resultHolder
		        waitUntilDone:YES];

		OSMemoryBarrier();

		result = [[resultHolder objectAtIndex:0] doubleValue];
		[resultHolder release];

		return result;

	#endif
	}
}

- (void)setRollingFrequency:(NSTimeInterval)newRollingFrequency
{
	// The design of this method is taken from the DDAbstractLogger implementation.
	// For documentation please refer to the DDAbstractLogger implementation.

	if (IS_GCD_AVAILABLE)
	{
	#if GCD_MAYBE_AVAILABLE

		dispatch_block_t block = ^{
			NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

			rollingFrequency = newRollingFrequency;
			[self maybeRollLogFileDueToAge:nil];

			[pool release];
		};

		if (dispatch_get_current_queue() == loggerQueue)
			block();
		else
			dispatch_async([DDLog loggingQueue], block);

	#endif
	}
	else
	{
	#if GCD_MAYBE_UNAVAILABLE

		NSThread *loggingThread = [DDLog loggingThread];
		NSNumber *newMaximumRollingFrequencyWrapper = [NSNumber numberWithDouble:newRollingFrequency];

		if ([NSThread currentThread] == loggingThread)
		{
			[self lt_setRollingFrequency:newMaximumRollingFrequencyWrapper];
		}
		else
		{
			[self performSelector:@selector(lt_setRollingFrequency:)
			             onThread:loggingThread
			           withObject:newMaximumRollingFrequencyWrapper
			        waitUntilDone:NO];
		}

	#endif
	}
}

#if GCD_MAYBE_UNAVAILABLE

- (void)lt_getMaximumFileSize:(NSMutableArray *)resultHolder
{
	// This method is executed on the logging thread.

	[resultHolder addObject:[NSNumber numberWithUnsignedLongLong:maximumFileSize]];
	OSMemoryBarrier();
}

- (void)lt_setMaximumFileSize:(NSNumber *)maximumFileSizeWrapper
{
	// This method is executed on the logging thread.

	maximumFileSize = [maximumFileSizeWrapper unsignedLongLongValue];

	[self maybeRollLogFileDueToSize];
}

- (void)lt_getRollingFrequency:(NSMutableArray *)resultHolder
{
	// This method is executed on the logging thread.

	[resultHolder addObject:[NSNumber numberWithDouble:rollingFrequency]];
	OSMemoryBarrier();
}

- (void)lt_setRollingFrequency:(NSNumber *)rollingFrequencyWrapper
{
	// This method is executed on the logging thread.

	rollingFrequency = [rollingFrequencyWrapper doubleValue];

	[self maybeRollLogFileDueToAge:nil];
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark File Rolling
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)scheduleTimerToRollLogFileDueToAge
{
	if (rollingTimer)
	{
		[rollingTimer invalidate];
		[rollingTimer release];
		rollingTimer = nil;
	}

	if (currentLogFileInfo == nil)
	{
		return;
	}

	NSDate *logFileCreationDate = [currentLogFileInfo creationDate];

	NSTimeInterval ti = [logFileCreationDate timeIntervalSinceReferenceDate];
	ti += rollingFrequency;

	NSDate *logFileRollingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:ti];

	NSLogVerbose(@"DDFileLogger: scheduleTimerToRollLogFileDueToAge");

	NSLogVerbose(@"DDFileLogger: logFileCreationDate: %@", logFileCreationDate);
	NSLogVerbose(@"DDFileLogger: logFileRollingDate : %@", logFileRollingDate);

	rollingTimer = [[NSTimer scheduledTimerWithTimeInterval:[logFileRollingDate timeIntervalSinceNow]
	                                                 target:self
	                                               selector:@selector(maybeRollLogFileDueToAge:)
	                                               userInfo:nil
	                                                repeats:NO] retain];
}

- (void)rollLogFile
{
	// This method is public.
	// We need to execute the rolling on our logging thread/queue.

	if (IS_GCD_AVAILABLE)
	{
	#if GCD_MAYBE_AVAILABLE

		dispatch_block_t block = ^{
			NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
			[self rollLogFileNow];
			[pool release];
		};
		dispatch_async([DDLog loggingQueue], block);

	#endif
	}
	else
	{
	#if GCD_MAYBE_UNAVAILABLE

		[self performSelector:@selector(rollLogFileNow)
		             onThread:[DDLog loggingThread]
		           withObject:nil
		        waitUntilDone:NO];

	#endif
	}
}

- (void)rollLogFileNow
{
	NSLogVerbose(@"DDFileLogger: rollLogFileNow");

	[currentLogFileHandle synchronizeFile];
	[currentLogFileHandle closeFile];
	[currentLogFileHandle release];
	currentLogFileHandle = nil;

	currentLogFileInfo.isArchived = YES;

	if ([logFileManager respondsToSelector:@selector(didRollAndArchiveLogFile:)])
	{
		[logFileManager didRollAndArchiveLogFile:(currentLogFileInfo.filePath)];
	}

	[currentLogFileInfo release];
	currentLogFileInfo = nil;
}

- (void)maybeRollLogFileDueToAge:(NSTimer *)aTimer
{
	if (currentLogFileInfo.age >= rollingFrequency)
	{
		NSLogVerbose(@"DDFileLogger: Rolling log file due to age...");

		[self rollLogFileNow];
	}
	else
	{
		[self scheduleTimerToRollLogFileDueToAge];
	}
}

- (void)maybeRollLogFileDueToSize
{
	// This method is called from logMessage.
	// Keep it FAST.

	unsigned long long fileSize = [currentLogFileHandle offsetInFile];

	// Note: Use direct access to maximumFileSize variable.
	// We specifically wrote our own getter/setter method to allow us to do this (for performance reasons).

	if (fileSize >= maximumFileSize) // YES, we are using direct access. Read note above.
	{
		NSLogVerbose(@"DDFileLogger: Rolling log file due to size...");

		[self rollLogFileNow];
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark File Logging
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Returns the log file that should be used.
 * If there is an existing log file that is suitable,
 * within the constraints of maximumFileSize and rollingFrequency, then it is returned.
 *
 * Otherwise a new file is created and returned.
**/
- (DDLogFileInfo *)currentLogFileInfo
{
	if (currentLogFileInfo == nil)
	{
		NSArray *sortedLogFileInfos = [logFileManager sortedLogFileInfos];

		if ([sortedLogFileInfos count] > 0)
		{
			DDLogFileInfo *mostRecentLogFileInfo = [sortedLogFileInfos objectAtIndex:0];

			BOOL useExistingLogFile = YES;
			BOOL shouldArchiveMostRecent = NO;

			if (mostRecentLogFileInfo.isArchived)
			{
				useExistingLogFile = NO;
				shouldArchiveMostRecent = NO;
			}
			else if (mostRecentLogFileInfo.fileSize >= maximumFileSize)
			{
				useExistingLogFile = NO;
				shouldArchiveMostRecent = YES;
			}
			else if (mostRecentLogFileInfo.age >= rollingFrequency)
			{
				useExistingLogFile = NO;
				shouldArchiveMostRecent = YES;
			}

			if (useExistingLogFile)
			{
				NSLogVerbose(@"DDFileLogger: Resuming logging with file %@", mostRecentLogFileInfo.fileName);

				currentLogFileInfo = [mostRecentLogFileInfo retain];
			}
			else
			{
				if (shouldArchiveMostRecent)
				{
					mostRecentLogFileInfo.isArchived = YES;

					if ([logFileManager respondsToSelector:@selector(didArchiveLogFile:)])
					{
						[logFileManager didArchiveLogFile:(mostRecentLogFileInfo.filePath)];
					}
				}
			}
		}

		if (currentLogFileInfo == nil)
		{
			NSString *currentLogFilePath = [logFileManager createNewLogFile];

			currentLogFileInfo = [[DDLogFileInfo alloc] initWithFilePath:currentLogFilePath];
		}
	}

	return currentLogFileInfo;
}

- (NSFileHandle *)currentLogFileHandle
{
	if (currentLogFileHandle == nil)
	{
		NSString *logFilePath = [[self currentLogFileInfo] filePath];

		currentLogFileHandle = [[NSFileHandle fileHandleForWritingAtPath:logFilePath] retain];
		[currentLogFileHandle seekToEndOfFile];

		if (currentLogFileHandle)
		{
			[self scheduleTimerToRollLogFileDueToAge];
		}
	}

	return currentLogFileHandle;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark DDLogger Protocol
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)logMessage:(DDLogMessage *)logMessage
{
	NSString *logMsg = logMessage->logMsg;

	if (formatter)
	{
		logMsg = [formatter formatLogMessage:logMessage];
	}

	if (logMsg)
	{
		if (![logMsg hasSuffix:@"\n"])
		{
			logMsg = [logMsg stringByAppendingString:@"\n"];
		}

		NSData *logData = [logMsg dataUsingEncoding:NSUTF8StringEncoding];

		[[self currentLogFileHandle] writeData:logData];

		[self maybeRollLogFileDueToSize];
	}
}

- (NSString *)loggerName
{
	return @"cocoa.lumberjack.fileLogger";
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#if TARGET_IPHONE_SIMULATOR
  #define XATTR_ARCHIVED_NAME  @"archived"
#else
  #define XATTR_ARCHIVED_NAME  @"lumberjack.log.archived"
#endif

@implementation DDLogFileInfo

@synthesize filePath;

@dynamic fileName;
@dynamic fileAttributes;
@dynamic creationDate;
@dynamic modificationDate;
@dynamic fileSize;
@dynamic age;

@dynamic isArchived;

#pragma mark Lifecycle

+ (id)logFileWithPath:(NSString *)aFilePath
{
	return [[[DDLogFileInfo alloc] initWithFilePath:aFilePath] autorelease];
}

- (id)initWithFilePath:(NSString *)aFilePath
{
	if ((self = [super init]))
	{
		filePath = [aFilePath copy];
	}
	return self;
}

- (void)dealloc
{
	[filePath release];
	[fileName release];

	[fileAttributes release];

	[creationDate release];
	[modificationDate release];

	[super dealloc];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Standard Info
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSDictionary *)fileAttributes
{
	if (fileAttributes == nil)
	{
		fileAttributes = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] retain];
	}
	return fileAttributes;
}

- (NSString *)fileName
{
	if (fileName == nil)
	{
		fileName = [[filePath lastPathComponent] retain];
	}
	return fileName;
}

- (NSDate *)modificationDate
{
	if (modificationDate == nil)
	{
		modificationDate = [[[self fileAttributes] objectForKey:NSFileModificationDate] retain];
	}

	return modificationDate;
}

- (NSDate *)creationDate
{
	if (creationDate == nil)
	{

	#if TARGET_OS_IPHONE

		const char *path = [filePath UTF8String];

		struct attrlist attrList;
		memset(&attrList, 0, sizeof(attrList));
		attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
		attrList.commonattr = ATTR_CMN_CRTIME;

		struct {
			u_int32_t attrBufferSizeInBytes;
			struct timespec crtime;
		} attrBuffer;

		int result = getattrlist(path, &attrList, &attrBuffer, sizeof(attrBuffer), 0);
		if (result == 0)
		{
			double seconds = (double)(attrBuffer.crtime.tv_sec);
			double nanos   = (double)(attrBuffer.crtime.tv_nsec);

			NSTimeInterval ti = seconds + (nanos / 1000000000.0);

			creationDate = [[NSDate dateWithTimeIntervalSince1970:ti] retain];
		}
		else
		{
			NSLogError(@"DDLogFileInfo: creationDate(%@): getattrlist result = %i", self.fileName, result);
		}

	#else

		creationDate = [[[self fileAttributes] objectForKey:NSFileCreationDate] retain];

	#endif

	}
	return creationDate;
}

- (unsigned long long)fileSize
{
	if (fileSize == 0)
	{
		fileSize = [[[self fileAttributes] objectForKey:NSFileSize] unsignedLongLongValue];
	}

	return fileSize;
}

- (NSTimeInterval)age
{
	return [[self creationDate] timeIntervalSinceNow] * -1.0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Archiving
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL)isArchived
{

#if TARGET_IPHONE_SIMULATOR

	// Extended attributes don't work properly on the simulator.
	// So we have to use a less attractive alternative.
	// See full explanation in the header file.

	return [self hasExtensionAttributeWithName:XATTR_ARCHIVED_NAME];

#else

	return [self hasExtendedAttributeWithName:XATTR_ARCHIVED_NAME];

#endif
}

- (void)setIsArchived:(BOOL)flag
{

#if TARGET_IPHONE_SIMULATOR

	// Extended attributes don't work properly on the simulator.
	// So we have to use a less attractive alternative.
	// See full explanation in the header file.

	if (flag)
		[self addExtensionAttributeWithName:XATTR_ARCHIVED_NAME];
	else
		[self removeExtensionAttributeWithName:XATTR_ARCHIVED_NAME];

#else

	if (flag)
		[self addExtendedAttributeWithName:XATTR_ARCHIVED_NAME];
	else
		[self removeExtendedAttributeWithName:XATTR_ARCHIVED_NAME];

#endif
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Changes
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)reset
{
	[fileName release];
	fileName = nil;

	[fileAttributes release];
	fileAttributes = nil;

	[creationDate release];
	creationDate = nil;

	[modificationDate release];
	modificationDate = nil;
}

- (void)renameFile:(NSString *)newFileName
{
	// This method is only used on the iPhone simulator, where normal extended attributes are broken.
	// See full explanation in the header file.

	if (![newFileName isEqualToString:[self fileName]])
	{
		NSString *fileDir = [filePath stringByDeletingLastPathComponent];

		NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];

		NSLogVerbose(@"DDLogFileInfo: Renaming file: '%@' -> '%@'", self.fileName, newFileName);

		NSError *error = nil;
		if (![[NSFileManager defaultManager] moveItemAtPath:filePath toPath:newFilePath error:&error])
		{
			NSLogError(@"DDLogFileInfo: Error renaming file (%@): %@", self.fileName, error);
		}

		[filePath release];
		filePath = [newFilePath retain];

		[self reset];
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Attribute Management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#if TARGET_IPHONE_SIMULATOR

// Extended attributes don't work properly on the simulator.
// So we have to use a less attractive alternative.
// See full explanation in the header file.

- (BOOL)hasExtensionAttributeWithName:(NSString *)attrName
{
	// This method is only used on the iPhone simulator, where normal extended attributes are broken.
	// See full explanation in the header file.

	// Split the file name into components.
	//
	// log-ABC123.archived.uploaded.txt
	//
	// 0. log-ABC123
	// 1. archived
	// 2. uploaded
	// 3. txt
	//
	// So we want to search for the attrName in the components (ignoring the first and last array indexes).

	NSArray *components = [[self fileName] componentsSeparatedByString:@"."];

	// Watch out for file names without an extension

	NSUInteger count = [components count];
	NSUInteger max = (count >= 2) ? count-1 : count;

	NSUInteger i;
	for (i = 1; i < max; i++)
	{
		NSString *attr = [components objectAtIndex:i];

		if ([attrName isEqualToString:attr])
		{
			return YES;
		}
	}

	return NO;
}

- (void)addExtensionAttributeWithName:(NSString *)attrName
{
	// This method is only used on the iPhone simulator, where normal extended attributes are broken.
	// See full explanation in the header file.

	if ([attrName length] == 0) return;

	// Example:
	// attrName = "archived"
	//
	// "log-ABC123.txt" -> "log-ABC123.archived.txt"

	NSArray *components = [[self fileName] componentsSeparatedByString:@"."];

	NSUInteger count = [components count];

	NSUInteger estimatedNewLength = [[self fileName] length] + [attrName length] + 1;
	NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];

	if (count > 0)
	{
		[newFileName appendString:[components objectAtIndex:0]];
	}

	NSString *lastExt = @"";

	NSUInteger i;
	for (i = 1; i < count; i++)
	{
		NSString *attr = [components objectAtIndex:i];
		if ([attr length] == 0)
		{
			continue;
		}

		if ([attrName isEqualToString:attr])
		{
			// Extension attribute already exists in file name
			return;
		}

		if ([lastExt length] > 0)
		{
			[newFileName appendFormat:@".%@", lastExt];
		}

		lastExt = attr;
	}

	[newFileName appendFormat:@".%@", attrName];

	if ([lastExt length] > 0)
	{
		[newFileName appendFormat:@".%@", lastExt];
	}

	[self renameFile:newFileName];
}

- (void)removeExtensionAttributeWithName:(NSString *)attrName
{
	// This method is only used on the iPhone simulator, where normal extended attributes are broken.
	// See full explanation in the header file.

	if ([attrName length] == 0) return;

	// Example:
	// attrName = "archived"
	//
	// "log-ABC123.txt" -> "log-ABC123.archived.txt"

	NSArray *components = [[self fileName] componentsSeparatedByString:@"."];

	NSUInteger count = [components count];

	NSUInteger estimatedNewLength = [[self fileName] length];
	NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];

	if (count > 0)
	{
		[newFileName appendString:[components objectAtIndex:0]];
	}

	BOOL found = NO;

	NSUInteger i;
	for (i = 1; i < count; i++)
	{
		NSString *attr = [components objectAtIndex:i];

		if ([attrName isEqualToString:attr])
		{
			found = YES;
		}
		else
		{
			[newFileName appendFormat:@".%@", attr];
		}
	}

	if (found)
	{
		[self renameFile:newFileName];
	}
}

#else

- (BOOL)hasExtendedAttributeWithName:(NSString *)attrName
{
	const char *path = [filePath UTF8String];
	const char *name = [attrName UTF8String];

	ssize_t result = getxattr(path, name, NULL, 0, 0, 0);

	return (result >= 0);
}

- (void)addExtendedAttributeWithName:(NSString *)attrName
{
	const char *path = [filePath UTF8String];
	const char *name = [attrName UTF8String];

	int result = setxattr(path, name, NULL, 0, 0, 0);

	if (result < 0)
	{
		NSLogError(@"DDLogFileInfo: setxattr(%@, %@): error = %i", attrName, self.fileName, result);
	}
}

- (void)removeExtendedAttributeWithName:(NSString *)attrName
{
	const char *path = [filePath UTF8String];
	const char *name = [attrName UTF8String];

	int result = removexattr(path, name, 0);

	if (result < 0 && errno != ENOATTR)
	{
		NSLogError(@"DDLogFileInfo: removexattr(%@, %@): error = %i", attrName, self.fileName, result);
	}
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Comparisons
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL)isEqual:(id)object
{
	if ([object isKindOfClass:[self class]])
	{
		DDLogFileInfo *another = (DDLogFileInfo *)object;

		return [filePath isEqualToString:[another filePath]];
	}

	return NO;
}

- (NSComparisonResult)reverseCompareByCreationDate:(DDLogFileInfo *)another
{
	NSDate *us = [self creationDate];
	NSDate *them = [another creationDate];

	NSComparisonResult result = [us compare:them];

	if (result == NSOrderedAscending)
		return NSOrderedDescending;

	if (result == NSOrderedDescending)
		return NSOrderedAscending;

	return NSOrderedSame;
}

- (NSComparisonResult)reverseCompareByModificationDate:(DDLogFileInfo *)another
{
	NSDate *us = [self modificationDate];
	NSDate *them = [another modificationDate];

	NSComparisonResult result = [us compare:them];

	if (result == NSOrderedAscending)
		return NSOrderedDescending;

	if (result == NSOrderedDescending)
		return NSOrderedAscending;

	return NSOrderedSame;
}

@end


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Select = require('./Select');

var _Select2 = _interopRequireDefault(_Select);

var _utilsDefaultFilterOptions = require('./utils/defaultFilterOptions');

var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions);

var _utilsDefaultMenuRenderer = require('./utils/defaultMenuRenderer');

var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer);

var Creatable = _react2['default'].createClass({
	displayName: 'CreatableSelect',

	propTypes: {
		// Child function responsible for creating the inner Select component
		// This component can be used to compose HOCs (eg Creatable and Async)
		// (props: Object): PropTypes.element
		children: _react2['default'].PropTypes.func,

		// See Select.propTypes.filterOptions
		filterOptions: _react2['default'].PropTypes.any,

		// Searches for any matching option within the set of options.
		// This function prevents duplicate options from being created.
		// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
		isOptionUnique: _react2['default'].PropTypes.func,

		// Determines if the current input text represents a valid option.
		// ({ label: string }): boolean
		isValidNewOption: _react2['default'].PropTypes.func,

		// See Select.propTypes.menuRenderer
		menuRenderer: _react2['default'].PropTypes.any,

		// Factory to create new option.
		// ({ label: string, labelKey: string, valueKey: string }): Object
		newOptionCreator: _react2['default'].PropTypes.func,

		// See Select.propTypes.options
		options: _react2['default'].PropTypes.array,

		// Creates prompt/placeholder option text.
		// (filterText: string): string
		promptTextCreator: _react2['default'].PropTypes.func,

		// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
		shouldKeyDownEventCreateNewOption: _react2['default'].PropTypes.func
	},

	// Default prop methods
	statics: {
		isOptionUnique: isOptionUnique,
		isValidNewOption: isValidNewOption,
		newOptionCreator: newOptionCreator,
		promptTextCreator: promptTextCreator,
		shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption
	},

	getDefaultProps: function getDefaultProps() {
		return {
			filterOptions: _utilsDefaultFilterOptions2['default'],
			isOptionUnique: isOptionUnique,
			isValidNewOption: isValidNewOption,
			menuRenderer: _utilsDefaultMenuRenderer2['default'],
			newOptionCreator: newOptionCreator,
			promptTextCreator: promptTextCreator,
			shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption
		};
	},

	createNewOption: function createNewOption() {
		var _props = this.props;
		var isValidNewOption = _props.isValidNewOption;
		var newOptionCreator = _props.newOptionCreator;
		var _props$options = _props.options;
		var options = _props$options === undefined ? [] : _props$options;
		var shouldKeyDownEventCreateNewOption = _props.shouldKeyDownEventCreateNewOption;

		if (isValidNewOption({ label: this.inputValue })) {
			var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
			var _isOptionUnique = this.isOptionUnique({ option: option });

			// Don't add the same option twice.
			if (_isOptionUnique) {
				options.unshift(option);

				this.select.selectValue(option);
			}
		}
	},

	filterOptions: function filterOptions() {
		var _props2 = this.props;
		var filterOptions = _props2.filterOptions;
		var isValidNewOption = _props2.isValidNewOption;
		var options = _props2.options;
		var promptTextCreator = _props2.promptTextCreator;

		// TRICKY Check currently selected options as well.
		// Don't display a create-prompt for a value that's selected.
		// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
		var excludeOptions = arguments[2] || [];

		var filteredOptions = filterOptions.apply(undefined, arguments) || [];

		if (isValidNewOption({ label: this.inputValue })) {
			var _newOptionCreator = this.props.newOptionCreator;

			var option = _newOptionCreator({
				label: this.inputValue,
				labelKey: this.labelKey,
				valueKey: this.valueKey
			});

			// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
			// For multi-selects, this would remove it from the filtered list.
			var _isOptionUnique2 = this.isOptionUnique({
				option: option,
				options: excludeOptions.concat(filteredOptions)
			});

			if (_isOptionUnique2) {
				var _prompt = promptTextCreator(this.inputValue);

				this._createPlaceholderOption = _newOptionCreator({
					label: _prompt,
					labelKey: this.labelKey,
					valueKey: this.valueKey
				});

				filteredOptions.unshift(this._createPlaceholderOption);
			}
		}

		return filteredOptions;
	},

	isOptionUnique: function isOptionUnique(_ref2) {
		var option = _ref2.option;
		var options = _ref2.options;
		var isOptionUnique = this.props.isOptionUnique;

		options = options || this.select.filterOptions();

		return isOptionUnique({
			labelKey: this.labelKey,
			option: option,
			options: options,
			valueKey: this.valueKey
		});
	},

	menuRenderer: function menuRenderer(params) {
		var menuRenderer = this.props.menuRenderer;

		return menuRenderer(_extends({}, params, {
			onSelect: this.onOptionSelect
		}));
	},

	onInputChange: function onInputChange(input) {
		// This value may be needed in between Select mounts (when this.select is null)
		this.inputValue = input;
	},

	onInputKeyDown: function onInputKeyDown(event) {
		var shouldKeyDownEventCreateNewOption = this.props.shouldKeyDownEventCreateNewOption;

		var focusedOption = this.select.getFocusedOption();

		if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) {
			this.createNewOption();

			// Prevent decorated Select from doing anything additional with this keyDown event
			event.preventDefault();
		}
	},

	onOptionSelect: function onOptionSelect(option, event) {
		if (option === this._createPlaceholderOption) {
			this.createNewOption();
		} else {
			this.select.selectValue(option);
		}
	},

	render: function render() {
		var _this = this;

		var _props3 = this.props;
		var _props3$children = _props3.children;
		var children = _props3$children === undefined ? defaultChildren : _props3$children;
		var newOptionCreator = _props3.newOptionCreator;
		var shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption;

		var restProps = _objectWithoutProperties(_props3, ['children', 'newOptionCreator', 'shouldKeyDownEventCreateNewOption']);

		var props = _extends({}, restProps, {
			allowCreate: true,
			filterOptions: this.filterOptions,
			menuRenderer: this.menuRenderer,
			onInputChange: this.onInputChange,
			onInputKeyDown: this.onInputKeyDown,
			ref: function ref(_ref) {
				_this.select = _ref;

				// These values may be needed in between Select mounts (when this.select is null)
				if (_ref) {
					_this.labelKey = _ref.props.labelKey;
					_this.valueKey = _ref.props.valueKey;
				}
			}
		});

		return children(props);
	}
});

function defaultChildren(props) {
	return _react2['default'].createElement(_Select2['default'], props);
};

function isOptionUnique(_ref3) {
	var option = _ref3.option;
	var options = _ref3.options;
	var labelKey = _ref3.labelKey;
	var valueKey = _ref3.valueKey;

	return options.filter(function (existingOption) {
		return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey];
	}).length === 0;
};

function isValidNewOption(_ref4) {
	var label = _ref4.label;

	return !!label;
};

function newOptionCreator(_ref5) {
	var label = _ref5.label;
	var labelKey = _ref5.labelKey;
	var valueKey = _ref5.valueKey;

	var option = {};
	option[valueKey] = label;
	option[labelKey] = label;
	option.className = 'Select-create-option-placeholder';
	return option;
};

function promptTextCreator(label) {
	return 'Create option "' + label + '"';
}

function shouldKeyDownEventCreateNewOption(_ref6) {
	var keyCode = _ref6.keyCode;

	switch (keyCode) {
		case 9: // TAB
		case 13: // ENTER
		case 188:
			// COMMA
			return true;
	}

	return false;
};

module.exports = Creatable;


text:
echo "Installing Package: visual-studio-code"

# make sure we're in the bin directory
mkdir -p "${HOME}/bin"
cd "${HOME}/bin"

# download the zipped application
wget http://go.microsoft.com/fwlink/?LinkID=534108 -O visual-studio-code.zip > /dev/null

# extract the files into a new directory
unzip visual-studio-code.zip -d ./visual-studio-code-bin > /dev/null

# symlink the binary into the path as visual-studio-code
ln -s ./visual-studio-code-bin/Code ./visual-studio-code

# clean up
rm visual-studio-code.zip


text:
license: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations

   under the License.
---

# Guías de plataforma

Antes de desarrollar para cualquiera de las plataformas que se enumeran a continuación, instalar la interfaz de cordova de comandos (CLI). (Para más detalles, ver la interfaz de línea de comandos).

Para desarrollar aplicaciones de Cordova, debe instalar los SDK para cada plataforma móvil que usted está apuntando. Esta instalación es necesaria independientemente de los hacen la mayoría de su trabajo en el SDK o utiliza la CLI para su ciclo de construir.

Cada *Plataforma guía* a continuación te dice lo que necesitas saber para configurar el entorno de desarrollo de cada plataforma: dónde obtener el SDK, cómo configurar emuladores de dispositivo, cómo conectar dispositivos para pruebas directas y cómo administrar los requerimientos claves de firma. Guías adicionales proporcionan información sobre el conjunto único de cada plataforma de opciones de configuración, instrucciones para agregar plugins, cómo actualizar cada plataforma y herramientas de línea de comandos específicos a la plataforma que sirven como una alternativa de nivel inferior a la utilidad de línea de comandos de `cordova`.

## Android

*   Guía de la plataforma Android
*   Configuración de Android
*   Android WebViews
*   Android Plugins
*   Android Herramientas de línea de comandos
*   Actualizar Android

## BlackBerry

*   Guía de la plataforma BlackBerry
*   Configuración de BlackBerry
*   Herramientas de línea de comandos de BlackBerry
*   Actualizar BlackBerry

## BlackBerry 10

*   Guía de la plataforma BlackBerry 10
*   Configuración de blackBerry 10
*   BlackBerry 10 Plugins
*   BlackBerry 10 herramientas de línea de comandos

## iOS

*   Guía de la plataforma iOS
*   iOS configuración
*   iOS WebViews
*   iOS Plugins
*   iOS herramientas de línea de comandos
*   Actualizar iOS

## Windows Phone

*   Guía de la plataforma de Windows Phone 8
*   Guía de la plataforma de Windows Phone 7
*   Configuración de Windows Phone
*   Windows Phone herramientas de línea de comandos
*   Actualización de Windows Phone

## Windows 8

*   Windows 8 plataforma guía
*   Herramientas de línea de comandos de Windows 8
*   Actualización de Windows 8

## Tizen

*   Guía de la plataforma Tizen


text:
<?php

namespace Symfony\Component\Finder\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;

class GlobTest extends TestCase
{
    public function testGlobToRegexDelimiters()
    {
        $this->assertEquals('#^(?=[^\.])\#$#', Glob::toRegex('#'));
        $this->assertEquals('#^\.[^/]*$#', Glob::toRegex('.*'));
        $this->assertEquals('^\.[^/]*$', Glob::toRegex('.*', true, true, ''));
        $this->assertEquals('/^\.[^/]*$/', Glob::toRegex('.*', true, true, '/'));
    }

    public function testGlobToRegexDoubleStarStrictDots()
    {
        $finder = new Finder();
        $finder->ignoreDotFiles(false);
        $regex = Glob::toRegex('/**/*.neon');

        foreach ($finder->in(__DIR__) as $k => $v) {
            $k = str_replace(DIRECTORY_SEPARATOR, '/', $k);
            if (preg_match($regex, substr($k, strlen(__DIR__)))) {
                $match[] = substr($k, 10 + strlen(__DIR__));
            }
        }
        sort($match);

        $this->assertSame(array('one/b/c.neon', 'one/b/d.neon'), $match);
    }

    public function testGlobToRegexDoubleStarNonStrictDots()
    {
        $finder = new Finder();
        $finder->ignoreDotFiles(false);
        $regex = Glob::toRegex('/**/*.neon', false);

        foreach ($finder->in(__DIR__) as $k => $v) {
            $k = str_replace(DIRECTORY_SEPARATOR, '/', $k);
            if (preg_match($regex, substr($k, strlen(__DIR__)))) {
                $match[] = substr($k, 10 + strlen(__DIR__));
            }
        }
        sort($match);

        $this->assertSame(array('.dot/b/c.neon', '.dot/b/d.neon', 'one/b/c.neon', 'one/b/d.neon'), $match);
    }
}


text:
import React from "react";
import { GatsbyImage, getImage } from "gatsby-plugin-image";

const LandingPageGallery = ({ data }) => {
  return (
    <div className="flex flex-wrap w-full">
      {data.images.map((image, i) => (
        <GatsbyImage
          alt={image.title}
          image={getImage(image)}
          className="w-full sm:w-1/2 px-2"
          key={i}
        />
      ))}
    </div>
  );
};
export default LandingPageGallery;


text:
# /* encoding: utf-8 */
# Copyright Altaire bot © Assassin, 2011 - 2012
# This program published under Apache 2.0 license
# See LICENSE for more details
# My EMail: assassin@sonikelf.ru
# packman package for Altaire XMPP bot

from urllib import urlretrieve as download
from urllib2 import urlopen
from re import compile
# заюзать finderFiles (удалить ..)

finderDirs 			= compile('
(.*)/
')
finderFiles			= compile('
(.*)
')
getDirs 			= lambda url: finderDirs.findall(urlopen(url).read())
getAllPacks 		= lambda: getDirs('http://altaire-packages.googlecode.com/git/packages')
getAllDeps 			= lambda: getDirs('http://altaire-packages.googlecode.com/git/depends')
getDepFiles 		= lambda: os.listdir('depends')
getInstalledPacks 	= lambda: os.listdir('packages')
removeItem = '..'

def getFiles(url):
	found = finderFiles.findall(urlopen(url).read())
	if removeItem in found: found.remove(removeItem)
	return found

def downloadDir(url, dir):
	if not os.path.exists(dir): os.makedirs(dir)
	files = getFiles(url)
	for file in files:
		if file.endswith('/'):
			downloadDir('%s/%s' % (url, file), '%s/%s' % (dir, file))
		else:
			path = ('locales/%s' % file if (file.endswith('.help') or file.endswith('.comms')) else dir + '/%s' % file)
			if os.path.exists(path): os.remove(path)
			download(url + '/%s' % file, path)

def packman_init(pack, depend = False):
	if (pack in getAllPacks()) or (depend and (pack in getAllDeps())):
		temp = ('depends' if depend else 'packages')
		depPacks, depFiles = [eval(x) for x in urlopen('http://altaire-packages.googlecode.com/git/%s/%s/depends' % (temp, pack)).read().splitlines()]
		packs, files = getAllPacks(), getDepFiles()
		installed = list()
		for file in depFiles:
			if file not in files:
				installed += packman_init(file, True)
		for Pack in depPacks:
			if Pack not in packs:
				installed += packman_init(Pack)
		downloadDir('http://altaire-packages.googlecode.com/git/%s/%s' % (temp, pack), '%s/%s' % (temp, pack))
		return installed
	else: return False

# доделать работу с ретурном функции packman_init (чтобы бот писал какие пакеты установил в качестве зависимостей)
def command_packman(source, parameters):
	parameters = parameters.split()
	lenp = len(parameters)
	if lenp > 0:
		if parameters[0] in translate['comms']['packman']['all']:
			if lenp == 1:
				allPacks = getAllPacks()
				installedPacks, availablePacks = list(allPacks), list(allPacks)
				for pack in getInstalledPacks():
					if pack in allPacks:
						availablePacks.remove(pack)
				for pack in availablePacks:
					installedPacks.remove(pack)
				replic = translate['comms']['packman']['allPacks'] + ', '.join(allPacks)
				if installedPacks:
					replic += chr(10) + translate['comms']['packman']['installedPacks'] + \
						', '.join(installedPacks)
				if availablePacks:
					replic += chr(10) + translate['comms']['packman']['availablePacks'] + \
						', '.join(availablePacks)
				fmsg(source, replic)
			else: fmsg(source, translate['outOfArguments'])
		elif parameters[0] in translate['comms']['packman']['install']:
			if lenp > 1:
				if parameters[1] in translate['comms']['packman']['all']:
					# install
					availablePacks = getAllPacks()
					for pack in getInstalledPacks():
						if pack in availablePacks:
							availablePacks.remove(pack)
					for pack in availablePacks:
						result = packman_init(pack)
						if result:
							load_package(parameters[1])
					fmsg(source, translate['performed'])
					if result: fmsg(source, translate['comms']['packman']['installedDepends'] % ', '.join(result))
				else:
					# install
					allResults = list()
					for pack in parameters[1:]:
						if os.path.exists('packages/' + pack):
							fmsg(source, translate['comms']['packman']['nowPackInstalled'] % pack)
						else:
							result = packman_init(pack)
							if not (result is False):
								allResults += result
								load_package(parameters[1])
							else:
								fmsg(source, translate['comms']['packman']['packNotFound'] % pack)
								return
					fmsg(source, translate['performed'])
					if allResults: fmsg(source, translate['comms']['packman']['installedDepends'] % ', '.join(allResults))
			else: fmsg(source, translate['outOfArguments'])
		elif parameters[0] in translate['comms']['packman']['upgrade']:
			if lenp >= 2:
				# install
				if parameters[1] in translate['comms']['packman']['all']:
					installedPacks = getInstalledPacks()
					installedPacks.remove('packman')
					for pack in installedPacks:
						result = packman_init(pack)
						if result:
							load_package(pack)
					fmsg(source, translate['performed'])
				else:
					# install
					for pack in parameters[1:]:
						if os.path.exists('packages/' + pack):
							result = packman_init(pack)
							if result:
								load_package(parameters[1])
						else:
							fmsg(source, translate['comms']['packman']['packNotFound'] % pack)
					fmsg(source, translate['performed'])
			else: fmsg(source, translate['outOfArguments'])
		else: fmsg(source, translate['badArguments'])
	else: fmsg(source, translate['outOfArguments'])

reg_command('packman', command_packman, 8)


text:
<?php

namespace Drupal\migrate\Plugin\Discovery;

use Doctrine\Common\Reflection\StaticReflectionParser as BaseStaticReflectionParser;

/**
 * Allows getting the reflection parser for the parent class.
 *
 * @internal
 *   This is a temporary solution to the fact that migration source plugins have
 *   more than one provider. This functionality will be moved to core in
 *   https://www.drupal.org/node/2786355.
 */
class StaticReflectionParser extends BaseStaticReflectionParser {

  /**
   * If the current class extends another, get the parser for the latter.
   *
   * @param \Doctrine\Common\Reflection\StaticReflectionParser $parser
   *   The current static parser.
   * @param $finder
   *   The class finder. Must implement
   *   \Doctrine\Common\Reflection\ClassFinderInterface, but can do so
   *   implicitly (i.e., implements the interface's methods but not the actual
   *   interface).
   *
   * @return static|null
   *   The static parser for the parent if there's a parent class or NULL.
   */
  public static function getParentParser(BaseStaticReflectionParser $parser, $finder) {
    // Ensure the class has been parsed before accessing the parentClassName
    // property.
    $parser->parse();
    if ($parser->parentClassName) {
      return new static($parser->parentClassName, $finder, $parser->classAnnotationOptimize);
    }
  }

}


text:
package com.jjjx.function.find;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jjjx.R;
import com.jjjx.function.base.BaseFragment;
import com.jjjx.function.entity.TabEntity;
import com.jjjx.function.find.adapter.FindPagerAdapter;
import com.jjjx.function.find.view.FindPublishActivity;
import com.jjjx.utils.CacheTask;
import com.jjjx.utils.NToast;

import java.util.ArrayList;

/**
 *
 * @author AMing
 * @date 17/5/8
 * Company RongCloud
 * 发现首页
 */
public class FindFragment extends BaseFragment {

    private ViewPager mViewPager;
    private CommonTabLayout mTabLayout;
    private TextView findPublish;

    @Override
    public View onCreateFragmentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mTabLayout = view.findViewById(R.id.ff_stl);
        mViewPager =  view.findViewById(R.id.ff_viewpager);
        //
        mViewPager.setAdapter(new FindPagerAdapter(getChildFragmentManager(), "热门", "关注", "同城"));
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        mTabEntities.add(new TabEntity("热门", 0, 0));
        mTabEntities.add(new TabEntity("关注", 0, 0));
        mTabEntities.add(new TabEntity("同城", 0, 0));
        mTabLayout.setTabData(mTabEntities);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        findPublish = view.findViewById(R.id.jx_find_publish);
        findPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CacheTask.getInstance().isLogin()) {
                    startActivity(new Intent(getActivity(), FindPublishActivity.class));
                }else {
                    NToast.shortToast(getActivity(),"请登录后操作");
                }
            }
        });
    }

}


text:
package xor

import (
	"fmt"
)

const (
	keyParam = "key"
	dstParam = "dst"
)

// SizeError records an error when the size of a parameter does not match the
// the constraints of the function
type SizeError struct {
	size  int
	param string
}

func (s SizeError) Error() string {
	return fmt.Sprintf("crypto/xor: invalid size %d for parameter %s", s.size, s.param)
}

// EncryptRepeatingKey XORs each byte from src with bytes from key as a
// repeating key, storing the result in dst. Dst and src may point to the same
// memory. EncryptRepeatingKey expects key to have a non-zero length and dst to
// be at least as long as src, retuning errors otherwise. EncryptRepeatingKey is
// a more general XOR cipher and the functions EncryptFixedKey and
// EncryptByteKey are provided as helpers.
func EncryptRepeatingKey(dst, src, key []byte) error {
	if len(key) == 0 {
		return SizeError{0, keyParam}
	}
	if len(dst) < len(src) {
		return SizeError{len(dst), dstParam}
	}

	keyLen := len(key)
	for i := range src {
		dst[i] = src[i] ^ key[i%keyLen]
	}

	return nil
}

// EncryptFixedKey is the same as EncryptRepeatingKey with the added constraint
// that key is at least as long as src.
func EncryptFixedKey(dst, src, key []byte) error {
	if len(dst) > len(key) {
		return SizeError{len(key), keyParam}
	}

	return EncryptRepeatingKey(dst, src, key)
}

// EncryptByteKey is the same as EncryptRepeatingKey, execpt key is passed in as
// a byte slice with a length of 1
func EncryptByteKey(dst, src []byte, key byte) error {
	return EncryptRepeatingKey(dst, src, []byte{key})
}