text:
// Generated from /POI/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java

#pragma once

#include <fwd-POI.hpp>
#include <org/apache/poi/ddf/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <org/apache/poi/hssf/usermodel/fwd-POI.hpp>
#include <org/apache/poi/hssf/usermodel/HSSFSimpleShape.hpp>

struct default_init_tag;

class poi::hssf::usermodel::HSSFTextbox
    : public HSSFSimpleShape
{

public:
    typedef HSSFSimpleShape super;
    static constexpr int16_t OBJECT_TYPE_TEXT { int16_t(6) };
    static constexpr int16_t HORIZONTAL_ALIGNMENT_LEFT { int16_t(1) };
    static constexpr int16_t HORIZONTAL_ALIGNMENT_CENTERED { int16_t(2) };
    static constexpr int16_t HORIZONTAL_ALIGNMENT_RIGHT { int16_t(3) };
    static constexpr int16_t HORIZONTAL_ALIGNMENT_JUSTIFIED { int16_t(4) };
    static constexpr int16_t HORIZONTAL_ALIGNMENT_DISTRIBUTED { int16_t(7) };
    static constexpr int16_t VERTICAL_ALIGNMENT_TOP { int16_t(1) };
    static constexpr int16_t VERTICAL_ALIGNMENT_CENTER { int16_t(2) };
    static constexpr int16_t VERTICAL_ALIGNMENT_BOTTOM { int16_t(3) };
    static constexpr int16_t VERTICAL_ALIGNMENT_JUSTIFY { int16_t(4) };
    static constexpr int16_t VERTICAL_ALIGNMENT_DISTRIBUTED { int16_t(7) };
protected:
    void ctor(::poi::ddf::EscherContainerRecord* spContainer, ::poi::hssf::record::ObjRecord* objRecord, ::poi::hssf::record::TextObjectRecord* textObjectRecord);
    void ctor(HSSFShape* parent, HSSFAnchor* anchor);

public: /* protected */
    ::poi::hssf::record::ObjRecord* createObjRecord() override;
    ::poi::ddf::EscherContainerRecord* createSpContainer() override;

public: /* package */
    void afterInsert(HSSFPatriarch* patriarch) override;

public:
    virtual int32_t getMarginLeft();
    virtual void setMarginLeft(int32_t marginLeft);
    virtual int32_t getMarginRight();
    virtual void setMarginRight(int32_t marginRight);
    virtual int32_t getMarginTop();
    virtual void setMarginTop(int32_t marginTop);
    virtual int32_t getMarginBottom();
    virtual void setMarginBottom(int32_t marginBottom);
    virtual int16_t getHorizontalAlignment();
    virtual void setHorizontalAlignment(int16_t align);
    virtual int16_t getVerticalAlignment();
    virtual void setVerticalAlignment(int16_t align);
    void setShapeType(int32_t shapeType) override;

public: /* protected */
    HSSFShape* cloneShape() override;
    void afterRemove(HSSFPatriarch* patriarch) override;

    // Generated

public:
    HSSFTextbox(::poi::ddf::EscherContainerRecord* spContainer, ::poi::hssf::record::ObjRecord* objRecord, ::poi::hssf::record::TextObjectRecord* textObjectRecord);
    HSSFTextbox(HSSFShape* parent, HSSFAnchor* anchor);
protected:
    HSSFTextbox(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
<?php

namespace Cake\Test\TestCase\ORM;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * Integration tests for using the bindingKey in associations
 */
class BindingKeyTest extends TestCase
{

    /**
     * Fixture to be used
     *
     * @var array
     */
    public $fixtures = [
        'core.auth_users',
        'core.site_authors',
        'core.users'
    ];

    /**
     * Data provider for the two types of strategies BelongsTo and HasOne implements
     *
     * @return void
     */
    public function strategiesProviderJoinable()
    {
        return [['join'], ['select']];
    }

    /**
     * Data provider for the two types of strategies HasMany and BelongsToMany implements
     *
     * @return void
     */
    public function strategiesProviderExternal()
    {
        return [['subquery'], ['select']];
    }

    /**
     * Tests that bindingKey can be used in belongsTo associations
     *
     * @dataProvider strategiesProviderJoinable
     * @return void
     */
    public function testBelongsto($strategy)
    {
        $users = TableRegistry::get('Users');
        $users->belongsTo('AuthUsers', [
            'bindingKey' => 'username',
            'foreignKey' => 'username',
            'strategy' => $strategy
        ]);

        $result = $users->find()
            ->contain(['AuthUsers']);

        $expected = ['mariano', 'nate', 'larry', 'garrett'];
        $expected = array_combine($expected, $expected);
        $this->assertEquals(
            $expected,
            $result->combine('username', 'auth_user.username')->toArray()
        );

        $expected = [1 => 1, 2 => 5, 3 => 2, 4 => 4];
        $this->assertEquals(
            $expected,
            $result->combine('id', 'auth_user.id')->toArray()
        );
    }

    /**
     * Tests that bindingKey can be used in hasOne associations
     *
     * @dataProvider strategiesProviderJoinable
     * @return void
     */
    public function testHasOne($strategy)
    {
        $users = TableRegistry::get('Users');
        $users->hasOne('SiteAuthors', [
            'bindingKey' => 'username',
            'foreignKey' => 'name',
            'strategy' => $strategy
        ]);

        $users->updateAll(['username' => 'jose'], ['username' => 'garrett']);
        $result = $users->find()
            ->contain(['SiteAuthors'])
            ->where(['username' => 'jose'])
            ->first();

        $this->assertEquals(3, $result->site_author->id);
    }

    /**
     * Tests that bindingKey can be used in hasOne associations
     *
     * @dataProvider strategiesProviderExternal
     * @return void
     */
    public function testHasMany($strategy)
    {
        $users = TableRegistry::get('Users');
        $authors = $users->hasMany('SiteAuthors', [
            'bindingKey' => 'username',
            'foreignKey' => 'name',
            'strategy' => $strategy
        ]);

        $authors->updateAll(['name' => 'garrett'], ['id >' => 2]);
        $result = $users->find()
            ->contain(['SiteAuthors'])
            ->where(['username' => 'garrett']);

        $expected = [3, 4];
        $result = $result->extract('site_authors.{*}.id')->toList();
        $this->assertEquals($expected, $result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.android.exoplayer.hls;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.LoadControl;
import com.google.android.exoplayer.MediaFormat;
import com.google.android.exoplayer.MediaFormatHolder;
import com.google.android.exoplayer.SampleHolder;
import com.google.android.exoplayer.SampleSource;
import com.google.android.exoplayer.SampleSource.SampleSourceReader;
import com.google.android.exoplayer.TrackRenderer;
import com.google.android.exoplayer.chunk.BaseChunkSampleSourceEventListener;
import com.google.android.exoplayer.chunk.Chunk;
import com.google.android.exoplayer.chunk.ChunkOperationHolder;
import com.google.android.exoplayer.chunk.Format;
import com.google.android.exoplayer.upstream.Loader;
import com.google.android.exoplayer.upstream.Loader.Loadable;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.MimeTypes;

import android.os.Handler;
import android.os.SystemClock;

import java.io.IOException;
import java.util.LinkedList;

/**
 * A {@link SampleSource} for HLS streams.
 */
public final class HlsSampleSource implements SampleSource, SampleSourceReader, Loader.Callback {

  /**
   * Interface definition for a callback to be notified of {@link HlsSampleSource} events.
   */
  public interface EventListener extends BaseChunkSampleSourceEventListener {}

  /**
   * The default minimum number of times to retry loading data prior to failing.
   */
  public static final int DEFAULT_MIN_LOADABLE_RETRY_COUNT = 3;

  private static final long NO_RESET_PENDING = Long.MIN_VALUE;

  private final HlsChunkSource chunkSource;
  private final LinkedList<HlsExtractorWrapper> extractors;
  private final int minLoadableRetryCount;
  private final int bufferSizeContribution;
  private final ChunkOperationHolder chunkOperationHolder;

  private final int eventSourceId;
  private final LoadControl loadControl;
  private final Handler eventHandler;
  private final EventListener eventListener;

  private int remainingReleaseCount;
  private boolean prepared;
  private boolean loadControlRegistered;
  private int trackCount;
  private int enabledTrackCount;
  private boolean[] trackEnabledStates;
  private boolean[] pendingDiscontinuities;
  private MediaFormat[] trackFormat;
  private MediaFormat[] downstreamMediaFormats;
  private Format downstreamFormat;

  private long downstreamPositionUs;
  private long lastSeekPositionUs;
  private long pendingResetPositionUs;

  private boolean loadingFinished;
  private Chunk currentLoadable;
  private TsChunk currentTsLoadable;
  private TsChunk previousTsLoadable;

  private Loader loader;
  private IOException currentLoadableException;
  private int currentLoadableExceptionCount;
  private long currentLoadableExceptionTimestamp;
  private long currentLoadStartTimeMs;

  public HlsSampleSource(HlsChunkSource chunkSource, LoadControl loadControl,
      int bufferSizeContribution) {
    this(chunkSource, loadControl, bufferSizeContribution, null, null, 0);
  }

  public HlsSampleSource(HlsChunkSource chunkSource, LoadControl loadControl,
      int bufferSizeContribution, Handler eventHandler, EventListener eventListener,
      int eventSourceId) {
    this(chunkSource, loadControl, bufferSizeContribution, eventHandler, eventListener,
        eventSourceId, DEFAULT_MIN_LOADABLE_RETRY_COUNT);
  }

  public HlsSampleSource(HlsChunkSource chunkSource, LoadControl loadControl,
      int bufferSizeContribution, Handler eventHandler, EventListener eventListener,
      int eventSourceId, int minLoadableRetryCount) {
    this.chunkSource = chunkSource;
    this.loadControl = loadControl;
    this.bufferSizeContribution = bufferSizeContribution;
    this.minLoadableRetryCount = minLoadableRetryCount;
    this.eventHandler = eventHandler;
    this.eventListener = eventListener;
    this.eventSourceId = eventSourceId;
    this.pendingResetPositionUs = NO_RESET_PENDING;
    extractors = new LinkedList<>();
    chunkOperationHolder = new ChunkOperationHolder();
  }

  @Override
  public SampleSourceReader register() {
    remainingReleaseCount++;
    return this;
  }

  @Override
  public boolean prepare(long positionUs) {
    if (prepared) {
      return true;
    }
    if (!extractors.isEmpty()) {
      while (true) {
        // We're not prepared, but we might have loaded what we need.
        HlsExtractorWrapper extractor = extractors.getFirst();
        if (extractor.isPrepared()) {
          trackCount = extractor.getTrackCount();
          trackEnabledStates = new boolean[trackCount];
          pendingDiscontinuities = new boolean[trackCount];
          downstreamMediaFormats = new MediaFormat[trackCount];
          trackFormat = new MediaFormat[trackCount];
          long durationUs = chunkSource.getDurationUs();
          for (int i = 0; i < trackCount; i++) {
            MediaFormat format = extractor.getMediaFormat(i).copyWithDurationUs(durationUs);
            if (MimeTypes.isVideo(format.mimeType)) {
              format = format.copyAsAdaptive();
            }
            trackFormat[i] = format;
          }
          prepared = true;
          return true;
        } else if (extractors.size() > 1) {
          extractors.removeFirst().clear();
        } else {
          break;
        }
      }
    }
    // We're not prepared and we haven't loaded what we need.
    if (loader == null) {
      loader = new Loader("Loader:HLS");
    }
    if (!loadControlRegistered) {
      loadControl.register(this, bufferSizeContribution);
      loadControlRegistered = true;
    }
    if (!loader.isLoading()) {
      // We're going to have to start loading a chunk to get what we need for preparation. We should
      // attempt to load the chunk at positionUs, so that we'll already be loading the correct chunk
      // in the common case where the renderer is subsequently enabled at this position.
      pendingResetPositionUs = positionUs;
      downstreamPositionUs = positionUs;
    }
    maybeStartLoading();
    return false;
  }

  @Override
  public int getTrackCount() {
    Assertions.checkState(prepared);
    return trackCount;
  }

  @Override
  public MediaFormat getFormat(int track) {
    Assertions.checkState(prepared);
    return trackFormat[track];
  }

  @Override
  public void enable(int track, long positionUs) {
    Assertions.checkState(prepared);
    Assertions.checkState(!trackEnabledStates[track]);
    enabledTrackCount++;
    trackEnabledStates[track] = true;
    downstreamMediaFormats[track] = null;
    pendingDiscontinuities[track] = false;
    downstreamFormat = null;
    boolean wasLoadControlRegistered = loadControlRegistered;
    if (!loadControlRegistered) {
      loadControl.register(this, bufferSizeContribution);
      loadControlRegistered = true;
    }
    if (enabledTrackCount == 1) {
      lastSeekPositionUs = positionUs;
      if (wasLoadControlRegistered && downstreamPositionUs == positionUs) {
        // TODO: Address [Internal: b/21743989] to remove the need for this kind of hack.
        // This is the first track to be enabled after preparation and the position is the same as
        // was passed to prepare. In this case we can avoid restarting, which would reload the same
        // chunks as were loaded during preparation.
        maybeStartLoading();
      } else {
        downstreamPositionUs = positionUs;
        restartFrom(positionUs);
      }
    }
  }

  @Override
  public void disable(int track) {
    Assertions.checkState(prepared);
    Assertions.checkState(trackEnabledStates[track]);
    enabledTrackCount--;
    trackEnabledStates[track] = false;
    if (enabledTrackCount == 0) {
      chunkSource.reset();
      downstreamPositionUs = Long.MIN_VALUE;
      if (loadControlRegistered) {
        loadControl.unregister(this);
        loadControlRegistered = false;
      }
      if (loader.isLoading()) {
        loader.cancelLoading();
      } else {
        clearState();
        loadControl.trimAllocator();
      }
    }
  }

  @Override
  public boolean continueBuffering(int track, long playbackPositionUs) {
    Assertions.checkState(prepared);
    Assertions.checkState(trackEnabledStates[track]);
    downstreamPositionUs = playbackPositionUs;
    if (!extractors.isEmpty()) {
      discardSamplesForDisabledTracks(getCurrentExtractor(), downstreamPositionUs);
    }
    if (loadingFinished) {
      return true;
    }
    maybeStartLoading();
    if (isPendingReset() || extractors.isEmpty()) {
      return false;
    }
    for (int extractorIndex = 0; extractorIndex < extractors.size(); extractorIndex++) {
      HlsExtractorWrapper extractor = extractors.get(extractorIndex);
      if (!extractor.isPrepared()) {
        break;
      }
      if (extractor.hasSamples(track)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public int readData(int track, long playbackPositionUs, MediaFormatHolder formatHolder,
      SampleHolder sampleHolder, boolean onlyReadDiscontinuity) {
    Assertions.checkState(prepared);
    downstreamPositionUs = playbackPositionUs;

    if (pendingDiscontinuities[track]) {
      pendingDiscontinuities[track] = false;
      return DISCONTINUITY_READ;
    }

    if (onlyReadDiscontinuity) {
      return NOTHING_READ;
    }

    if (isPendingReset()) {
      return NOTHING_READ;
    }

    HlsExtractorWrapper extractor = getCurrentExtractor();
    if (!extractor.isPrepared()) {
      return NOTHING_READ;
    }

    if (downstreamFormat == null || !downstreamFormat.equals(extractor.format)) {
      // Notify a change in the downstream format.
      notifyDownstreamFormatChanged(extractor.format, extractor.trigger, extractor.startTimeUs);
      downstreamFormat = extractor.format;
    }

    if (extractors.size() > 1) {
      // If there's more than one extractor, attempt to configure a seamless splice from the
      // current one to the next one.
      extractor.configureSpliceTo(extractors.get(1));
    }

    int extractorIndex = 0;
    while (extractors.size() > extractorIndex + 1 && !extractor.hasSamples(track)) {
      // We're finished reading from the extractor for this particular track, so advance to the
      // next one for the current read.
      extractor = extractors.get(++extractorIndex);
      if (!extractor.isPrepared()) {
        return NOTHING_READ;
      }
    }

    MediaFormat mediaFormat = extractor.getMediaFormat(track);
    if (mediaFormat != null && !mediaFormat.equals(downstreamMediaFormats[track])) {
      formatHolder.format = mediaFormat;
      downstreamMediaFormats[track] = mediaFormat;
      return FORMAT_READ;
    }

    if (extractor.getSample(track, sampleHolder)) {
      boolean decodeOnly = sampleHolder.timeUs < lastSeekPositionUs;
      sampleHolder.flags |= decodeOnly ? C.SAMPLE_FLAG_DECODE_ONLY : 0;
      return SAMPLE_READ;
    }

    if (loadingFinished) {
      return END_OF_STREAM;
    }

    return NOTHING_READ;
  }

  @Override
  public void maybeThrowError() throws IOException {
    if (currentLoadableException != null && currentLoadableExceptionCount > minLoadableRetryCount) {
      throw currentLoadableException;
    } else if (currentLoadable == null) {
      chunkSource.maybeThrowError();
    }
  }

  @Override
  public void seekToUs(long positionUs) {
    Assertions.checkState(prepared);
    Assertions.checkState(enabledTrackCount > 0);

    long currentPositionUs = isPendingReset() ? pendingResetPositionUs : downstreamPositionUs;
    downstreamPositionUs = positionUs;
    lastSeekPositionUs = positionUs;
    if (currentPositionUs == positionUs) {
      return;
    }

    // TODO: Optimize the seek for the case where the position is already buffered.
    downstreamPositionUs = positionUs;
    for (int i = 0; i < pendingDiscontinuities.length; i++) {
      pendingDiscontinuities[i] = true;
    }
    restartFrom(positionUs);
  }

  @Override
  public long getBufferedPositionUs() {
    Assertions.checkState(prepared);
    Assertions.checkState(enabledTrackCount > 0);
    if (isPendingReset()) {
      return pendingResetPositionUs;
    } else if (loadingFinished) {
      return TrackRenderer.END_OF_TRACK_US;
    } else {
      long largestParsedTimestampUs = extractors.getLast().getLargestParsedTimestampUs();
      if (extractors.size() > 1) {
        // When adapting from one format to the next, the penultimate extractor may have the largest
        // parsed timestamp (e.g. if the last extractor hasn't parsed any timestamps yet).
        largestParsedTimestampUs = Math.max(largestParsedTimestampUs,
            extractors.get(extractors.size() - 2).getLargestParsedTimestampUs());
      }
      return largestParsedTimestampUs == Long.MIN_VALUE ? downstreamPositionUs
          : largestParsedTimestampUs;
    }
  }

  @Override
  public void release() {
    Assertions.checkState(remainingReleaseCount > 0);
    if (--remainingReleaseCount == 0 && loader != null) {
      loader.release();
      loader = null;
    }
  }

  // Loader.Callback implementation.

  @Override
  public void onLoadCompleted(Loadable loadable) {
    Assertions.checkState(loadable == currentLoadable);
    long now = SystemClock.elapsedRealtime();
    long loadDurationMs = now - currentLoadStartTimeMs;
    chunkSource.onChunkLoadCompleted(currentLoadable);
    if (isTsChunk(currentLoadable)) {
      Assertions.checkState(currentLoadable == currentTsLoadable);
      previousTsLoadable = currentTsLoadable;
      notifyLoadCompleted(currentLoadable.bytesLoaded(), currentTsLoadable.type,
          currentTsLoadable.trigger, currentTsLoadable.format, currentTsLoadable.startTimeUs,
          currentTsLoadable.endTimeUs, now, loadDurationMs);
    } else {
      notifyLoadCompleted(currentLoadable.bytesLoaded(), currentLoadable.type,
          currentLoadable.trigger, currentLoadable.format, -1, -1, now, loadDurationMs);
    }
    clearCurrentLoadable();
    if (enabledTrackCount > 0 || !prepared) {
      maybeStartLoading();
    }
  }

  @Override
  public void onLoadCanceled(Loadable loadable) {
    notifyLoadCanceled(currentLoadable.bytesLoaded());
    if (enabledTrackCount > 0) {
      restartFrom(pendingResetPositionUs);
    } else {
      clearState();
      loadControl.trimAllocator();
    }
  }

  @Override
  public void onLoadError(Loadable loadable, IOException e) {
    if (chunkSource.onChunkLoadError(currentLoadable, e)) {
      // Error handled by source.
      if (previousTsLoadable == null && !isPendingReset()) {
        pendingResetPositionUs = lastSeekPositionUs;
      }
      clearCurrentLoadable();
    } else {
      currentLoadableException = e;
      currentLoadableExceptionCount++;
      currentLoadableExceptionTimestamp = SystemClock.elapsedRealtime();
    }
    notifyLoadError(e);
    maybeStartLoading();
  }

  // Internal stuff.

  /**
   * Gets the current extractor from which samples should be read.
   *

   * Calling this method discards extractors without any samples from the front of the queue. The
   * last extractor is retained even if it doesn't have any samples.
   *

   * This method must not be called unless {@link #extractors} is non-empty.
   *
   * @return The current extractor from which samples should be read. Guaranteed to be non-null.
   */
  private HlsExtractorWrapper getCurrentExtractor() {
    HlsExtractorWrapper extractor = extractors.getFirst();
    while (extractors.size() > 1 && !haveSamplesForEnabledTracks(extractor)) {
      // We're finished reading from the extractor for all tracks, and so can discard it.
      extractors.removeFirst().clear();
      extractor = extractors.getFirst();
    }
    return extractor;
  }

  private void discardSamplesForDisabledTracks(HlsExtractorWrapper extractor, long timeUs) {
    if (!extractor.isPrepared()) {
      return;
    }
    for (int i = 0; i < trackEnabledStates.length; i++) {
      if (!trackEnabledStates[i]) {
        extractor.discardUntil(i, timeUs);
      }
    }
  }

  private boolean haveSamplesForEnabledTracks(HlsExtractorWrapper extractor) {
    if (!extractor.isPrepared()) {
      return false;
    }
    for (int i = 0; i < trackEnabledStates.length; i++) {
      if (trackEnabledStates[i] && extractor.hasSamples(i)) {
        return true;
      }
    }
    return false;
  }

  private void restartFrom(long positionUs) {
    pendingResetPositionUs = positionUs;
    loadingFinished = false;
    if (loader.isLoading()) {
      loader.cancelLoading();
    } else {
      clearState();
      maybeStartLoading();
    }
  }

  private void clearState() {
    for (int i = 0; i < extractors.size(); i++) {
      extractors.get(i).clear();
    }
    extractors.clear();
    clearCurrentLoadable();
    previousTsLoadable = null;
  }

  private void clearCurrentLoadable() {
    currentTsLoadable = null;
    currentLoadable = null;
    currentLoadableException = null;
    currentLoadableExceptionCount = 0;
  }

  private void maybeStartLoading() {
    long now = SystemClock.elapsedRealtime();
    long nextLoadPositionUs = getNextLoadPositionUs();
    boolean isBackedOff = currentLoadableException != null;
    boolean loadingOrBackedOff = loader.isLoading() || isBackedOff;

    // Update the control with our current state, and determine whether we're the next loader.
    boolean nextLoader = loadControl.update(this, downstreamPositionUs, nextLoadPositionUs,
        loadingOrBackedOff);

    if (isBackedOff) {
      long elapsedMillis = now - currentLoadableExceptionTimestamp;
      if (elapsedMillis >= getRetryDelayMillis(currentLoadableExceptionCount)) {
        currentLoadableException = null;
        loader.startLoading(currentLoadable, this);
      }
      return;
    }

    if (loader.isLoading() || !nextLoader) {
      return;
    }

    chunkSource.getChunkOperation(previousTsLoadable, pendingResetPositionUs,
        downstreamPositionUs, chunkOperationHolder);
    boolean endOfStream = chunkOperationHolder.endOfStream;
    Chunk nextLoadable = chunkOperationHolder.chunk;
    chunkOperationHolder.clear();

    if (endOfStream) {
      loadingFinished = true;
      return;
    }
    if (nextLoadable == null) {
      return;
    }

    currentLoadStartTimeMs = now;
    currentLoadable = nextLoadable;
    if (isTsChunk(currentLoadable)) {
      TsChunk tsChunk = (TsChunk) currentLoadable;
      if (isPendingReset()) {
        pendingResetPositionUs = NO_RESET_PENDING;
      }
      HlsExtractorWrapper extractorWrapper = tsChunk.extractorWrapper;
      if (extractors.isEmpty() || extractors.getLast() != extractorWrapper) {
        extractorWrapper.init(loadControl.getAllocator());
        extractors.addLast(extractorWrapper);
      }
      notifyLoadStarted(tsChunk.dataSpec.length, tsChunk.type, tsChunk.trigger, tsChunk.format,
          tsChunk.startTimeUs, tsChunk.endTimeUs);
      currentTsLoadable = tsChunk;
    } else {
      notifyLoadStarted(currentLoadable.dataSpec.length, currentLoadable.type,
          currentLoadable.trigger, currentLoadable.format, -1, -1);
    }
    loader.startLoading(currentLoadable, this);
  }

  /**
   * Gets the next load time, assuming that the next load starts where the previous chunk ended (or
   * from the pending reset time, if there is one).
   */
  private long getNextLoadPositionUs() {
    if (isPendingReset()) {
      return pendingResetPositionUs;
    } else {
      return loadingFinished ? -1
          : currentTsLoadable != null ? currentTsLoadable.endTimeUs : previousTsLoadable.endTimeUs;
    }
  }

  private boolean isTsChunk(Chunk chunk) {
    return chunk instanceof TsChunk;
  }

  private boolean isPendingReset() {
    return pendingResetPositionUs != NO_RESET_PENDING;
  }

  private long getRetryDelayMillis(long errorCount) {
    return Math.min((errorCount - 1) * 1000, 5000);
  }

  /* package */ long usToMs(long timeUs) {
    return timeUs / 1000;
  }

  private void notifyLoadStarted(final long length, final int type, final int trigger,
      final Format format, final long mediaStartTimeUs, final long mediaEndTimeUs) {
    if (eventHandler != null && eventListener != null) {
      eventHandler.post(new Runnable()  {
        @Override
        public void run() {
          eventListener.onLoadStarted(eventSourceId, length, type, trigger, format,
              usToMs(mediaStartTimeUs), usToMs(mediaEndTimeUs));
        }
      });
    }
  }

  private void notifyLoadCompleted(final long bytesLoaded, final int type, final int trigger,
      final Format format, final long mediaStartTimeUs, final long mediaEndTimeUs,
      final long elapsedRealtimeMs, final long loadDurationMs) {
    if (eventHandler != null && eventListener != null) {
      eventHandler.post(new Runnable()  {
        @Override
        public void run() {
          eventListener.onLoadCompleted(eventSourceId, bytesLoaded, type, trigger, format,
              usToMs(mediaStartTimeUs), usToMs(mediaEndTimeUs), elapsedRealtimeMs, loadDurationMs);
        }
      });
    }
  }

  private void notifyLoadCanceled(final long bytesLoaded) {
    if (eventHandler != null && eventListener != null) {
      eventHandler.post(new Runnable()  {
        @Override
        public void run() {
          eventListener.onLoadCanceled(eventSourceId, bytesLoaded);
        }
      });
    }
  }

  private void notifyLoadError(final IOException e) {
    if (eventHandler != null && eventListener != null) {
      eventHandler.post(new Runnable()  {
        @Override
        public void run() {
          eventListener.onLoadError(eventSourceId, e);
        }
      });
    }
  }

  private void notifyDownstreamFormatChanged(final Format format, final int trigger,
      final long positionUs) {
    if (eventHandler != null && eventListener != null) {
      eventHandler.post(new Runnable()  {
        @Override
        public void run() {
          eventListener.onDownstreamFormatChanged(eventSourceId, format, trigger,
              usToMs(positionUs));
        }
      });
    }
  }

}


text:
package cd

import som._

class CDBenchmark extends benchmarks.Benchmark[(Int, Int)] {

  private val numAircrafts = Array(1000, 500, 250, 100, 10)
  private var i            = 0

  override def run(): (Int, Int) = {
    disableBenchmark()
    val aircrafts = numAircrafts(i % numAircrafts.length)
    i = i + 1
    (aircrafts, benchmark(aircrafts))
  }

  override def check(t: (Int, Int)): Boolean =
    check(t._2, t._1)

  def benchmark(numAircrafts: Int): Int = {
    val numFrames        = 200
    val simulator        = new Simulator(numAircrafts);
    val detector         = new CollisionDetector();
    var actualCollisions = 0

    (0 until numFrames).map { i =>
      val time       = i / 10.0
      val collisions = detector.handleNewFrame(simulator.simulate(time))
      actualCollisions += collisions.size()
    }

    actualCollisions
  }

  def check(actualCollisions: Int, numAircrafts: Int): Boolean = {
    if (numAircrafts == 1000) { return actualCollisions == 14484 }
    if (numAircrafts == 500) { return actualCollisions == 14484 }
    if (numAircrafts == 250) { return actualCollisions == 10830 }
    if (numAircrafts == 100) { return actualCollisions == 4305 }
    if (numAircrafts == 10) { return actualCollisions == 390 }

    System.out.println("No verification result for " + numAircrafts + " found")
    System.out.println("Result is: " + actualCollisions)

    return false
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="JsonMediaType.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Marker class for JSON format.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Net.Mime
{
    /// <summary>
    /// Marker class for JSON format.
    /// </summary>
    [SupportedMediaTypes(new[] { MediaTypeNames.Application.Json })]
    [SupportedFileExtensions(new[] { "json" })]
    public sealed class JsonMediaType : IMediaType
    {
    }
}


text:
@implementation DPImage

- (void)setImageImp:(DPImageImp *)imgImp
{
    _imgImp = imgImp;
}

- (void)parseFile:(NSString *)fileName
{
    NSLog(@"do nothing");
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 55(4): 428 (1963)

#### Original name
Macowanites olidus A.H. Sm.

### Remarks
null


text:
package effectivejava.chapter6.item37;
import java.util.*;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;

// Using an EnumMap to associate data with an enum (Pages 171-3)

// Simplistic class representing a plant (Page 171)
class Plant {
    enum LifeCycle { ANNUAL, PERENNIAL, BIENNIAL }

    final String name;
    final LifeCycle lifeCycle;

    Plant(String name, LifeCycle lifeCycle) {
        this.name = name;
        this.lifeCycle = lifeCycle;
    }

    @Override public String toString() {
        return name;
    }

    public static void main(String[] args) {
        Plant[] garden = {
            new Plant("Basil",    LifeCycle.ANNUAL),
            new Plant("Carroway", LifeCycle.BIENNIAL),
            new Plant("Dill",     LifeCycle.ANNUAL),
            new Plant("Lavendar", LifeCycle.PERENNIAL),
            new Plant("Parsley",  LifeCycle.BIENNIAL),
            new Plant("Rosemary", LifeCycle.PERENNIAL)
        };

        // Using ordinal() to index into an array - DON'T DO THIS!  (Page 171)
        Set<Plant>[] plantsByLifeCycleArr =
                (Set<Plant>[]) new Set[LifeCycle.values().length];
        for (int i = 0; i < plantsByLifeCycleArr.length; i++)
            plantsByLifeCycleArr[i] = new HashSet<>();
        for (Plant p : garden)
            plantsByLifeCycleArr[p.lifeCycle.ordinal()].add(p);
        // Print the results
        for (int i = 0; i < plantsByLifeCycleArr.length; i++) {
            System.out.printf("%s: %s%n",
                    LifeCycle.values()[i], plantsByLifeCycleArr[i]);
        }

        // Using an EnumMap to associate data with an enum (Page 172)
        Map<LifeCycle, Set<Plant>> plantsByLifeCycle =
                new EnumMap<>(LifeCycle.class);
        for (LifeCycle lc : LifeCycle.values())
            plantsByLifeCycle.put(lc, new HashSet<>());
        for (Plant p : garden)
            plantsByLifeCycle.get(p.lifeCycle).add(p);
        System.out.println(plantsByLifeCycle);

        // Naive stream-based approach - unlikely to produce an EnumMap!  (Page 172)
        System.out.println(Arrays.stream(garden)
                .collect(groupingBy(p -> p.lifeCycle)));

        // Using a stream and an EnumMap to associate data with an enum (Page 173)
        System.out.println(Arrays.stream(garden)
                .collect(groupingBy(p -> p.lifeCycle,
                        () -> new EnumMap<>(LifeCycle.class), toSet())));
    }
}


text:
import React from 'react'
import 'react-date-picker/index.css!'

export default (props) => {
  return <div>
    new event
  </div>
}


text:
namespace Envoy {
namespace Api {

class OsSysCallsImpl : public OsSysCalls {
public:
  // Api::OsSysCalls
  SysCallIntResult bind(os_fd_t sockfd, const sockaddr* addr, socklen_t addrlen) override;
  SysCallIntResult chmod(const std::string& path, mode_t mode) override;
  SysCallIntResult ioctl(os_fd_t sockfd, unsigned long int request, void* argp, unsigned long,
                         void*, unsigned long, unsigned long*) override;
  SysCallSizeResult writev(os_fd_t fd, const iovec* iov, int num_iov) override;
  SysCallSizeResult readv(os_fd_t fd, const iovec* iov, int num_iov) override;
  SysCallSizeResult pwrite(os_fd_t fd, const void* buffer, size_t length,
                           off_t offset) const override;
  SysCallSizeResult pread(os_fd_t fd, void* buffer, size_t length, off_t offset) const override;
  SysCallSizeResult recv(os_fd_t socket, void* buffer, size_t length, int flags) override;
  SysCallSizeResult recvmsg(os_fd_t sockfd, msghdr* msg, int flags) override;
  SysCallIntResult recvmmsg(os_fd_t sockfd, struct mmsghdr* msgvec, unsigned int vlen, int flags,
                            struct timespec* timeout) override;
  bool supportsMmsg() const override;
  bool supportsUdpGro() const override;
  bool supportsUdpGso() const override;
  bool supportsIpTransparent() const override;
  bool supportsMptcp() const override;
  SysCallIntResult close(os_fd_t fd) override;
  SysCallIntResult ftruncate(int fd, off_t length) override;
  SysCallPtrResult mmap(void* addr, size_t length, int prot, int flags, int fd,
                        off_t offset) override;
  SysCallIntResult stat(const char* pathname, struct stat* buf) override;
  SysCallIntResult setsockopt(os_fd_t sockfd, int level, int optname, const void* optval,
                              socklen_t optlen) override;
  SysCallIntResult getsockopt(os_fd_t sockfd, int level, int optname, void* optval,
                              socklen_t* optlen) override;
  SysCallSocketResult socket(int domain, int type, int protocol) override;
  SysCallSizeResult sendmsg(os_fd_t fd, const msghdr* message, int flags) override;
  SysCallIntResult getsockname(os_fd_t sockfd, sockaddr* addr, socklen_t* addrlen) override;
  SysCallIntResult gethostname(char* name, size_t length) override;
  SysCallIntResult getpeername(os_fd_t sockfd, sockaddr* name, socklen_t* namelen) override;
  SysCallIntResult setsocketblocking(os_fd_t sockfd, bool blocking) override;
  SysCallIntResult connect(os_fd_t sockfd, const sockaddr* addr, socklen_t addrlen) override;
  SysCallIntResult open(const char* pathname, int flags) const override;
  SysCallIntResult open(const char* pathname, int flags, mode_t mode) const override;
  SysCallIntResult unlink(const char* pathname) const override;
  SysCallIntResult linkat(os_fd_t olddirfd, const char* oldpath, os_fd_t newdirfd,
                          const char* newpath, int flags) const override;
  SysCallIntResult mkstemp(char* tmplate) const override;
  bool supportsAllPosixFileOperations() const override;
  SysCallIntResult shutdown(os_fd_t sockfd, int how) override;
  SysCallIntResult socketpair(int domain, int type, int protocol, os_fd_t sv[2]) override;
  SysCallIntResult listen(os_fd_t sockfd, int backlog) override;
  SysCallSizeResult write(os_fd_t socket, const void* buffer, size_t length) override;
  SysCallSocketResult duplicate(os_fd_t oldfd) override;
  SysCallSocketResult accept(os_fd_t socket, sockaddr* addr, socklen_t* addrlen) override;
  SysCallBoolResult socketTcpInfo(os_fd_t sockfd, EnvoyTcpInfo* tcp_info) override;
  bool supportsGetifaddrs() const override;
  SysCallIntResult getifaddrs(InterfaceAddressVector& interfaces) override;
  SysCallIntResult getaddrinfo(const char* node, const char* service, const addrinfo* hints,
                               addrinfo** res) override;
  void freeaddrinfo(addrinfo* res) override;
};

using OsSysCallsSingleton = ThreadSafeSingleton<OsSysCallsImpl>;

} // namespace Api
} // namespace Envoy


text:
public class Demo {

	public static void main(String[] srgs) {

//		ArrayStack<Integer> stack = new ArrayStack<Integer>();
		ArrayListStack<Integer> stack = new ArrayListStack<Integer>();

		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		stack.push(6);
		System.out.println(stack.isEmpty());
		System.out.println(stack.peek());
		System.out.println(stack.pop());
		// System.out.println(stack.pop());
		System.out.println(stack.getSize());
		stack.clear();
		System.out.println(stack.getSize());
	}

}


text:
package test

// Session functional tests.

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"strings"
	"testing"

	"golang.org/x/crypto/ssh"
)

func TestRunCommandSuccess(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()
	err = session.Run("true")
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
}

func TestHostKeyCheck(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()

	conf := clientConfig()
	hostDB := hostKeyDB()
	conf.HostKeyCallback = hostDB.Check

	// change the keys.
	hostDB.keys[ssh.KeyAlgoRSA][25]++
	hostDB.keys[ssh.KeyAlgoDSA][25]++
	hostDB.keys[ssh.KeyAlgoECDSA256][25]++

	conn, err := server.TryDial(conf)
	if err == nil {
		conn.Close()
		t.Fatalf("dial should have failed.")
	} else if !strings.Contains(err.Error(), "host key mismatch") {
		t.Fatalf("'host key mismatch' not found in %v", err)
	}
}

func TestRunCommandStdin(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	r, w := io.Pipe()
	defer r.Close()
	defer w.Close()
	session.Stdin = r

	err = session.Run("true")
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
}

func TestRunCommandStdinError(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	r, w := io.Pipe()
	defer r.Close()
	session.Stdin = r
	pipeErr := errors.New("closing write end of pipe")
	w.CloseWithError(pipeErr)

	err = session.Run("true")
	if err != pipeErr {
		t.Fatalf("expected %v, found %v", pipeErr, err)
	}
}

func TestRunCommandFailed(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()
	err = session.Run(`bash -c "kill -9 $$"`)
	if err == nil {
		t.Fatalf("session succeeded: %v", err)
	}
}

func TestRunCommandWeClosed(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	err = session.Shell()
	if err != nil {
		t.Fatalf("shell failed: %v", err)
	}
	err = session.Close()
	if err != nil {
		t.Fatalf("shell failed: %v", err)
	}
}

func TestFuncLargeRead(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("unable to create new session: %s", err)
	}

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	err = session.Start("dd if=/dev/urandom bs=2048 count=1024")
	if err != nil {
		t.Fatalf("unable to execute remote command: %s", err)
	}

	buf := new(bytes.Buffer)
	n, err := io.Copy(buf, stdout)
	if err != nil {
		t.Fatalf("error reading from remote stdout: %s", err)
	}

	if n != 2048*1024 {
		t.Fatalf("Expected %d bytes but read only %d from remote command", 2048, n)
	}
}

func TestKeyChange(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conf := clientConfig()
	hostDB := hostKeyDB()
	conf.HostKeyCallback = hostDB.Check
	conf.RekeyThreshold = 1024
	conn := server.Dial(conf)
	defer conn.Close()

	for i := 0; i < 4; i++ {
		session, err := conn.NewSession()
		if err != nil {
			t.Fatalf("unable to create new session: %s", err)
		}

		stdout, err := session.StdoutPipe()
		if err != nil {
			t.Fatalf("unable to acquire stdout pipe: %s", err)
		}

		err = session.Start("dd if=/dev/urandom bs=1024 count=1")
		if err != nil {
			t.Fatalf("unable to execute remote command: %s", err)
		}
		buf := new(bytes.Buffer)
		n, err := io.Copy(buf, stdout)
		if err != nil {
			t.Fatalf("error reading from remote stdout: %s", err)
		}

		want := int64(1024)
		if n != want {
			t.Fatalf("Expected %d bytes but read only %d from remote command", want, n)
		}
	}

	if changes := hostDB.checkCount; changes < 4 {
		t.Errorf("got %d key changes, want 4", changes)
	}
}

func TestInvalidTerminalMode(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	if err = session.RequestPty("vt100", 80, 40, ssh.TerminalModes{255: 1984}); err == nil {
		t.Fatalf("req-pty failed: successful request with invalid mode")
	}
}

func TestValidTerminalMode(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	stdin, err := session.StdinPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdin pipe: %s", err)
	}

	tm := ssh.TerminalModes{ssh.ECHO: 0}
	if err = session.RequestPty("xterm", 80, 40, tm); err != nil {
		t.Fatalf("req-pty failed: %s", err)
	}

	err = session.Shell()
	if err != nil {
		t.Fatalf("session failed: %s", err)
	}

	stdin.Write([]byte("stty -a && exit\n"))

	var buf bytes.Buffer
	if _, err := io.Copy(&buf, stdout); err != nil {
		t.Fatalf("reading failed: %s", err)
	}

	if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "-echo ") {
		t.Fatalf("terminal mode failure: expected -echo in stty output, got %s", sttyOutput)
	}
}

func TestWindowChange(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("session failed: %v", err)
	}
	defer session.Close()

	stdout, err := session.StdoutPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdout pipe: %s", err)
	}

	stdin, err := session.StdinPipe()
	if err != nil {
		t.Fatalf("unable to acquire stdin pipe: %s", err)
	}

	tm := ssh.TerminalModes{ssh.ECHO: 0}
	if err = session.RequestPty("xterm", 80, 40, tm); err != nil {
		t.Fatalf("req-pty failed: %s", err)
	}

	if err := session.WindowChange(100, 100); err != nil {
		t.Fatalf("window-change failed: %s", err)
	}

	err = session.Shell()
	if err != nil {
		t.Fatalf("session failed: %s", err)
	}

	stdin.Write([]byte("stty size && exit\n"))

	var buf bytes.Buffer
	if _, err := io.Copy(&buf, stdout); err != nil {
		t.Fatalf("reading failed: %s", err)
	}

	if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "100 100") {
		t.Fatalf("terminal WindowChange failure: expected \"100 100\" stty output, got %s", sttyOutput)
	}
}

func testOneCipher(t *testing.T, cipher string, cipherOrder []string) {
	server := newServer(t)
	defer server.Shutdown()
	conf := clientConfig()
	conf.Ciphers = []string{cipher}
	// Don't fail if sshd doesn't have the cipher.
	conf.Ciphers = append(conf.Ciphers, cipherOrder...)
	conn, err := server.TryDial(conf)
	if err != nil {
		t.Fatalf("TryDial: %v", err)
	}
	defer conn.Close()

	numBytes := 4096

	// Exercise sending data to the server
	if _, _, err := conn.Conn.SendRequest("drop-me", false, make([]byte, numBytes)); err != nil {
		t.Fatalf("SendRequest: %v", err)
	}

	// Exercise receiving data from the server
	session, err := conn.NewSession()
	if err != nil {
		t.Fatalf("NewSession: %v", err)
	}

	out, err := session.Output(fmt.Sprintf("dd if=/dev/zero of=/dev/stdout bs=%d count=1", numBytes))
	if err != nil {
		t.Fatalf("Output: %v", err)
	}

	if len(out) != numBytes {
		t.Fatalf("got %d bytes, want %d bytes", len(out), numBytes)
	}
}

var deprecatedCiphers = []string{
	"aes128-cbc", "3des-cbc",
	"arcfour128", "arcfour256",
}

func TestCiphers(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	cipherOrder := append(config.Ciphers, deprecatedCiphers...)

	for _, ciph := range cipherOrder {
		t.Run(ciph, func(t *testing.T) {
			testOneCipher(t, ciph, cipherOrder)
		})
	}
}

func TestMACs(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	macOrder := config.MACs

	for _, mac := range macOrder {
		server := newServer(t)
		defer server.Shutdown()
		conf := clientConfig()
		conf.MACs = []string{mac}
		// Don't fail if sshd doesn't have the MAC.
		conf.MACs = append(conf.MACs, macOrder...)
		if conn, err := server.TryDial(conf); err == nil {
			conn.Close()
		} else {
			t.Fatalf("failed for MAC %q", mac)
		}
	}
}

func TestKeyExchanges(t *testing.T) {
	var config ssh.Config
	config.SetDefaults()
	kexOrder := config.KeyExchanges
	for _, kex := range kexOrder {
		server := newServer(t)
		defer server.Shutdown()
		conf := clientConfig()
		// Don't fail if sshd doesn't have the kex.
		conf.KeyExchanges = append([]string{kex}, kexOrder...)
		conn, err := server.TryDial(conf)
		if err == nil {
			conn.Close()
		} else {
			t.Errorf("failed for kex %q", kex)
		}
	}
}

func TestClientAuthAlgorithms(t *testing.T) {
	for _, key := range []string{
		"rsa",
		"dsa",
		"ecdsa",
		"ed25519",
	} {
		server := newServer(t)
		conf := clientConfig()
		conf.SetDefaults()
		conf.Auth = []ssh.AuthMethod{
			ssh.PublicKeys(testSigners[key]),
		}

		conn, err := server.TryDial(conf)
		if err == nil {
			conn.Close()
		} else {
			t.Errorf("failed for key %q", key)
		}

		server.Shutdown()
	}
}


text:
package joshie.harvest.core.base.tile;

import joshie.harvest.animals.packet.PacketClearNeighbours;
import joshie.harvest.api.animals.AnimalFoodType;
import joshie.harvest.core.helpers.MCServerHelper;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;

import javax.annotation.Nonnull;

import static net.minecraft.util.EnumFacing.*;

public abstract class TileFillableConnected<T extends TileFillableConnected> extends TileFillable {
    private final int maxWidth;
    private boolean facingX;
    private int offsetX;
    private int offsetZ;
    private int size;

    public TileFillableConnected(AnimalFoodType foodType, int maxFill, int fillPer, int maxWidth) {
        super(foodType, maxFill, fillPer);
        this.maxWidth = maxWidth;
    }

    @Override
    protected T getTile() {
        return getMaster();
    }

    @Override
    public int getMaximumFill() {
        return size * super.getMaximumFill();
    }

    public abstract void resetClientData();

    @SuppressWarnings("unchecked")
    public T getMaster() {
        BlockPos connection = pos.add(offsetX, 0, offsetZ);
        return isValidConnection(connection) ? (T) world.getTileEntity(connection) : (T) this;
    }

    @SuppressWarnings("unchecked, ConstantConditions")
    private boolean updateMasterInDirection(EnumFacing facing) {
        BlockPos offset = pos.offset(facing);
        if (isValidConnection(offset)) {
            TileFillableConnected master = ((TileFillableConnected)world.getTileEntity(offset)).getMaster();
            if (master.getSize() < maxWidth) {
                int offsetX = master.getPos().getX() - getPos().getX();
                int offsetZ = master.getPos().getZ() - getPos().getZ();
                if (offsetX != 0 && offsetZ != 0) return false;
                if (master.size > 1) {
                    if (master.facingX && offsetX != 0) return false;
                    else if (!master.facingX && offsetZ != 0) return false;
                }

                if (offsetZ != 0) master.facingX = true;
                if (offsetX != 0) master.facingX = false;
                this.offsetX = offsetX;
                this.offsetZ = offsetZ;
                master.size++; //Increase the trough size
                master.markDirty();
                return true;
            }
        }

        return false;
    }

    private void updateMaster() {
        if (updateMasterInDirection(NORTH)) return;
        if (updateMasterInDirection(SOUTH)) return;
        if (updateMasterInDirection(EAST)) return;
        if (!updateMasterInDirection(WEST)) {
            //Make this block it's own master
            offsetX = 0;
            offsetZ = 0;
            size = 1;
            markDirty();
        }
    }

    public void onPlaced() {
        updateMaster();
        setFilled(getFillAmount());
        if (!world.isRemote) {
            MCServerHelper.sendTileUpdate(this, new PacketClearNeighbours(pos));
        }
    }

    @SuppressWarnings("ConstantConditions")
    private BlockPos getNewMaster() {
        for (int x = -2; x <= 2; x++) {
            for (int z = -2; z <= 2; z++) {
                BlockPos offset = pos.add(x, 0, z);
                if (isValidConnection(offset)) {
                    TileFillableConnected connected = ((TileFillableConnected)world.getTileEntity(offset));
                    if (connected.getMaster() == this) {
                        return getPos().add(x, 0, z);
                    }
                }
            }
        }

        return null;
    }

    @SuppressWarnings("ConstantConditions")
    private void setMaster(BlockPos pos) {
        for (int x = -2; x <= 2; x++) {
            for (int z = -2; z <= 2; z++) {
                BlockPos offset = pos.add(x, 0, z);
                if (isValidConnection(offset)) {
                    TileFillableConnected tile = ((TileFillableConnected)world.getTileEntity(offset));
                    if (tile.getMaster() == this) {
                        tile.offsetX = pos.getX() - tile.getPos().getX();
                        tile.offsetZ = pos.getZ() - tile.getPos().getZ();
                        tile.updateMaster(); //Refresh the master status
                        tile.markDirty();
                    }
                }
            }
        }
    }

    public void onRemoved() {
        TileFillableConnected master = getMaster();
        int volume = master.getFillAmount();
        int size = Math.max(0, master.size - 1);
        boolean facingX = master.facingX;
        BlockPos newMaster = null;
        if (master == this) {
            newMaster = getNewMaster();
            if (newMaster != null) {
                setMaster(newMaster);
            }
        }

        //Copy the contents from one tile to the next
        master = newMaster != null ? (TileFillableConnected) world.getTileEntity(newMaster) : master;
        if (master != null) {
            master.size = size;
            master.facingX = facingX;
            master.setFilled(volume); //Update the volume in the new master
            master.markDirty();
            master.resetClientData();
        }

        //Reset everything
        if (!world.isRemote) {
            MCServerHelper.sendTileUpdate(this, new PacketClearNeighbours(pos));
        }
    }

    protected abstract boolean isValidConnection(BlockPos pos);

    public int getSize() {
        return size;
    }

    @Override
    public void readFromNBT(NBTTagCompound nbt) {
        super.readFromNBT(nbt);
        facingX = nbt.getBoolean("FacingX");
        offsetX = nbt.getInteger("OffsetX");
        offsetZ = nbt.getInteger("OffsetZ");
        size = nbt.getByte("Size");
    }

    @Override
    @Nonnull
    public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
        nbt.setBoolean("FacingX", facingX);
        nbt.setInteger("OffsetX", offsetX);
        nbt.setInteger("OffsetZ", offsetZ);
        nbt.setByte("Size", (byte) size);
        return super.writeToNBT(nbt);
    }
}


text:
REM This script replaces the SDK folder with the latest bits from the Azure SDK repository.
REM It removes some files we do not need.  It currently targets the develop branch until fixes are
REM merged into master.

if exist "%~dp0\temp" rd /s /q "%~dp0\temp"
if exist "%~dp0\sdk" rd /s /q "%~dp0\sdk"

mkdir "%~dp0\temp"
mkdir "%~dp0\sdk"

cd /D "%~dp0\temp"

git clone https://github.com/Azure/azure-iot-sdks.git --recursive

cd azure-iot-sdks
echo Upstream HEAD @ > metadata.txt
git rev-parse HEAD >> metadata.txt

cd "%~dp0\temp"

copy "%~dp0\temp\azure-iot-sdks\metadata.txt" "%~dp0\sdk"

copy "%~dp0\temp\azure-iot-sdks\c\iothub_client\src\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\iothub_client\inc\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\serializer\src\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\serializer\inc\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\azure-c-shared-utility\c\src\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\azure-c-shared-utility\c\inc\" "%~dp0\sdk"
copy "%~dp0\temp\azure-iot-sdks\c\azure-c-shared-utility\c\adapters\agenttime.c" "%~dp0\sdk"

del "%~dp0\sdk\iot_logging.h"
del "%~dp0\sdk\iothubtransportamqp.*"
del "%~dp0\sdk\iothubtransportamqp_websockets.*"
del "%~dp0\sdk\iothubtransportmqtt.*"
del "%~dp0\sdk\tickcounter.*"
del "%~dp0\sdk\tlsio*.*"
del "%~dp0\sdk\constbuffer.*"

cd ..

rmdir /S "%~dp0\temp"


text:
<?php
App::uses('AppController', 'Controller');
/**
 * CaudalFinTypes Controller
 *
 */
class CaudalFinTypesController extends AppController {

/**
 * Scaffold
 *
 * @var mixed
 */
	public $scaffold;

}


text:
namespace Simplechat.Data
{
    using Models;

    public class SimplechatData
    {
        private readonly MongoDbContext mongoDbContext;

        public SimplechatData() : this(new MongoDbContext())
        {
        }

        public SimplechatData(MongoDbContext mongoDbContext)
        {
            this.mongoDbContext = mongoDbContext;
        }

        public static string GenerateMessageAsString(Message message)
        {
            var prettyDate = message.PostDate.ToLocalTime().ToString("dd.MM.yyyy hh:mm");
            return $"[{prettyDate}] {message.Text} - posted by {message.PostUser.Name}";
        }
    }
}


text:
<?php

namespace DreamStore\CustomerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BlockController extends Controller
{
    public function indexAction()
    {
        $products = $this->getDoctrine()->getRepository('DreamStoreSellerBundle:Product')->findAll();
        $data["products"] = $products;

        $response = $this->render('DreamStoreCustomerBundle:Block:index.html.twig', $data);
        $response->setSharedMaxAge(600);

        return $response;
    }

    public function cartAction()
    {

        $response = $this->render('DreamStoreCustomerBundle:Block:cart.html.twig');
        $response->setSharedMaxAge(600);

        return $response;
    }

    public function historicalAction()
    {

        $response = $this->render('DreamStoreCustomerBundle:Block:historical.html.twig');
        $response->setSharedMaxAge(600);

        return $response;
    }

    public function sellerProductAction()
    {

        $response = $this->render('DreamStoreCustomerBundle:Block:sellerProduct.html.twig');
        $response->setSharedMaxAge(600);

        return $response;
    }

    public function sellerHistoricalAction()
    {

        $response = $this->render('DreamStoreCustomerBundle:Block:sellerHistorical.html.twig');
        $response->setSharedMaxAge(600);

        return $response;
    }
}


text:
const express = require('express');
const passport = require('passport');
const drones = require('../Controllers/droneCtrl');
const userCtrl = require('../Controllers/userCtrl');
const router = new express.Router();

const authenticate = passport.authenticate('jwt', {session: false});
const authorize = userCtrl.authorizeUser;

router.post('/create', authenticate, authorize(['admin']), function(req, res) {
  const drone = req.body;
  drones.createDrone(drone.name, drone.description,
      drone.flying_time, drone.location, req.user.id, function(response) {
        res.json(response);
      });
});

router.post('/remove/:id', authenticate, authorize(['admin']),
    function(req, res) {
      const drone = req.body;
      // console.log(drone);

      drones.removeDrone(req.params.id, drone.status, function(status) {
        res.json(status);
      });
    });

router.get('/get', function(req, res) {
  drones.getDroneIds(function(ids) {
    res.json({'status': 'OK', 'drones': ids});
  });
});

router.get('/get/:id', function(req, res) {
  drones.getDroneById(req.params.id, function(drone) {
    // console.log(drone);
    res.json(drone);
  });
});

router.post('/update/:id', function(req, res) {
  drones.updateDroneStatus(req.params.id, req.body, function(status) {
    res.json(status);
  });
});

router.post('/takeoff/:id', authenticate, authorize(['admin', 'user']),
    function(req, res) {
      const waypoints = req.body.waypoints;

      drones.takeoffDrone(req.params.id, waypoints, function(status) {
        res.json(status);
      });
    });

router.post('/land/:id', authenticate, authorize(['admin', 'user']),
    function(req, res) {
      const droneId = req.params.id;

      drones.landDrone(droneId, function(status) {
        res.json(status);
      });
    });

router.post('/update/waypoints/:id', authenticate, authorize(['admin', 'user']),
    function(req, res) {
      const droneId = req.params.id;
      const waypoints = req.body.waypoints;

      drones.updateWaypoints(droneId, waypoints, function(status) {
        // console.log(status);
        res.json(status);
      });
    });

router.post('/resume/:id', authenticate, authorize(['admin', 'user']),
    function(req, res) {
      const droneId = req.params.id;
      drones.resumeFlight(droneId, function(status) {
        res.json(status);
      });
    });

router.post('/groups/create', authenticate, authorize(['admin']),
    function(req, res) {
      drones.createGroup(req.body.name, req.user.id, function(status) {
        res.json(status);
      });
    });

router.post('/groups/remove/:id', authenticate, authorize(['admin']),
    function(req, res) {
      drones.removeGroup(req.params.id, function(status) {
        res.json(status);
      });
    });

router.get('/groups', authenticate, function(req, res) {
  drones.getGroups(req.user.id, function(status) {
    res.json(status);
  });
});

router.post('/groups/:id/add', authenticate, function(req, res) {
  drones.addToGroup(req.params.id, req.body.drones, function(status) {
    res.json(status);
  });
});

router.post('/groups/:id/remove/:droneId', authenticate, function(req, res) {
  drones.removeFromGroup(req.params.id, req.params.droneId, function(status) {
    res.json(status);
  });
});

module.exports = router;


text:
/**
 * @param {type} <%= moduleName %> module
 * @author <%- author %>
 * @since <%= date %>
 */

(function () {
    define(['./<%= moduleName %>.module'], function (moduleName) {
        'use strict';

        angular.module(moduleName)
            .controller('<%= serviceName %>', <%= serviceName %>);

        <%= serviceName %>.$inject = ['$log'];

        function <%= serviceName %> ($log) {
            var service = {};

            service.method = method;

            function method() {
                // TODO autogenerated method stub...
            }

            return service;
        }
    });
})();


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <corners android:radius="45dp"/>
            <solid android:color="@color/md_red_500_color_code"/>
            <stroke android:width="1dp" android:color="#ffffff"/>
        </shape>
    </item>

    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="45dp"/>
            <solid android:color="@color/md_red_900_color_code"/>
            <stroke android:width="1dp" android:color="#ffffff"/>
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <corners android:radius="45dp"/>
            <solid android:color="@color/md_red_900_color_code"/>
            <stroke android:width="1dp" android:color="#ffffff"/>
        </shape>
    </item>
</selector>


text:
require 'rails_helper'

RSpec.describe SpaceTile, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
<?php

declare(strict_types=1);

namespace Broadway\Serializer;

/**
 * Interface for classes that can serialize arbitrary objects into arrays with
 * scalars (for now).
 */
interface Serializer
{
    /**
     * @throws SerializationException
     *
     * @param mixed $object
     */
    public function serialize($object): array;

    /**
     * @throws SerializationException
     *
     * @return mixed
     */
    public function deserialize(array $serializedObject);
}


text:
package com.b2international.snowowl.snomed.datastore.id.gen;

import static com.google.common.collect.Sets.newHashSetWithExpectedSize;

import java.util.Random;
import java.util.Set;

import com.b2international.snowowl.core.terminology.ComponentCategory;

/**
 * An item identifier generation strategy that assigns item identifiers to components randomly, without
 * using the namespace or component category arguments.
 *
 * @since 4.0
 */
public class RandomItemIdGenerationStrategy implements ItemIdGenerationStrategy {

	@Override
	public Set<String> generateItemIds(String namespace, ComponentCategory category, int quantity, int attempt) {
		// nextInt excludes top value, add 1 to make it inclusive
		final Set<String> generatedItemIds = newHashSetWithExpectedSize(quantity);
		while (quantity > 0) {
			final String itemId = Integer.toString(new Random().nextInt(9999_9999 - 100 + 1) + 100);
			if (generatedItemIds.add(itemId)) {
				quantity--;
			}
		}
		return generatedItemIds;
	}

}


text:
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/wonderful');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log("we're connected!");
});

var userListSchema = mongoose.Schema({
    name: {type: String, unique: true}
    , email: {type: String, unique: true}
    , password: {type: String}
    , salt: {type: String}
    , hash: {type: String}
});

var todoListSchema = mongoose.Schema({
    name: {type: String}
    , tag: {type: String}
    , createDate: {type: Date}
    , endDate: {type: Date}
    , content: {type: String}
    , done: {type: Boolean}
    , remainDay: {type: Number}
});

var userList = mongoose.model('users', userListSchema);
var todoList = mongoose.model('todoList', todoListSchema);
exports.userList = userList;
exports.todoList = todoList;

exports.CheckSameName = function (req,res,next) {
    userList.count({name: req.body.name}, function (err, doc) {
        if (doc) {
            req.session.error = '存在相同用户名';
            res.redirect('back');
        } else {
            next();
        }
    });
};

exports.CheckSameEmail = function (req,res,next) {
    userList.count({email: req.body.email}, function (err, doc) {
        if (doc) {
            req.session.error = '存在相同邮箱';
            res.redirect('back');
        } else {
            next();
        }
    });
};

exports.updateUser = function (req,res,next) {
    userList.update({name:req.session.user}, {$set: req.user}, options, callback);
    next();
};

exports.loadUser = function (res,req,next){
    userList.findOne({name: req.session.user},function (err,doc){
        if (err) next(new error('获取用户失败'));
        req.user = doc;
        next();
    })
};


text:
import { info } from "../toast/toast";
import { semverCompare, SemverResult, MinVersionOverride } from "../util";
import { Content } from "../constants";
import { Dictionary } from "lodash";

const IDEAL_VERSION =
  globalConfig.FBOS_END_OF_LIFE_VERSION || MinVersionOverride.ALWAYS;

/** Returns a function that, when given a version string, (possibly) warns the
 * user to upgrade FBOS versions before it hits end of life. */
export function createReminderFn() {
  /** FBOS Version can change during the app lifecycle. We only want one
   * reminder per FBOS version change. */
  const alreadyChecked: Dictionary<boolean | undefined> = {
    // Dont bother when the user is offline.
    [MinVersionOverride.ALWAYS]: true
  };

  return function reminder(version: string) {

    // Did we check this particular version yet?
    !alreadyChecked[version]
      // Is it up to date?
      && semverCompare(version, IDEAL_VERSION) === SemverResult.RIGHT_IS_GREATER
      && info(Content.OLD_FBOS_REC_UPGRADE);

    alreadyChecked[version] = true; // Turn off checks for this version now.
  };
}


text:
* oh-my-zsh

## Installation

```sh
git clone https://github.com/fstehle/dotfiles.git
cd dotfiles
script/bootstrap
```

### iTerm2 Configuration

 * Open iTerm2.
 * Go to the Preferences (⌘,)
 * In the General tab, check `Load preferences from a custom folder or URL`.
 * Fill in the text field to point to `/Users/your_name/.dotfiles/iterm2`.
 * Restart iTerm2.

### Oh My Zsh Configuration

Put this to the end of `~/.zshrc`
```
if [[ -a ~/.zshrc_custom ]]
then
  source ~/.zshrc_custom
fi
```

## Thanks

* https://github.com/holman/dotfiles

## License

MIT License. © 2015 Fabian Stehle


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('djangobench_webui.webui.views',
    (r'^$', 'results'),
    (r'^data/(?P<benchmark>\w+)/$', 'benchmark_data'),
)


text:
var
    util = require('util'),
    redis = require('./../redis.js');

var KEY = {
    TOKEN: 'refreshToken:%s'
};

module.exports.KEY = KEY;

module.exports.getUserId = function(refreshToken) {
    return refreshToken.userId;
};

module.exports.save = function(token, userId, clientId, scope, cb) {
    var obj = {token: token, userId: userId, clientId: clientId, scope: scope};
    redis.set(util.format(KEY.TOKEN, token), JSON.stringify(obj), function(err) {
        if (err) cb(err);
        else cb(null, obj);
    });
};

module.exports.fetchByToken = function(token, cb) {
    redis.get(util.format(KEY.TOKEN, token), function(err, stringified) {
        if (err) cb(err);
        else if (!stringified) cb();
        else {
            try {
                var obj = JSON.parse(stringified);
                cb(null, obj);
            } catch (e) {
                cb();
            }
        }
    });
};

// @todo: remove old refreshTokens
module.exports.removeByUserIdClientId = function(userId, clientId, cb) {
    cb();
};


text:
#include "multiBlock/reductiveMultiDataProcessorWrapper3D.h"
#include "multiBlock/reductiveMultiDataProcessorWrapper3D.hh"

namespace plb {

/* *************** Boxed Data Processor functionals ****************** */

template
void applyProcessingFunctional<PRECOMP_T> (
        ReductiveBoxProcessingFunctional3D_N<PRECOMP_T>& functional,
        Box3D domain, MultiNTensorField3D<PRECOMP_T>& field );

template
void applyProcessingFunctional<PRECOMP_T> (
        ReductiveBoxProcessingFunctional3D_S<PRECOMP_T>& functional,
        Box3D domain, MultiScalarField3D<PRECOMP_T>& field );

template
void applyProcessingFunctional<PRECOMP_T> (
        MaskedReductiveBoxProcessingFunctional3D_N<PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field,
        MultiNTensorField3D<int>& mask );

template
void applyProcessingFunctional<PRECOMP_T,PRECOMP_T> (
        ReductiveBoxProcessingFunctional3D_NN<PRECOMP_T,PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field1,
        MultiNTensorField3D<PRECOMP_T>& field2 );

template
void applyProcessingFunctional<PRECOMP_T,PRECOMP_T> (
        ReductiveBoxProcessingFunctional3D_SS<PRECOMP_T,PRECOMP_T>& functional,
        Box3D domain,
        MultiScalarField3D<PRECOMP_T>& field1,
        MultiScalarField3D<PRECOMP_T>& field2 );

template
void applyProcessingFunctional<PRECOMP_T,PRECOMP_T> (
        MaskedReductiveBoxProcessingFunctional3D_NN<PRECOMP_T,PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field1,
        MultiNTensorField3D<PRECOMP_T>& field2,
        MultiNTensorField3D<int>& mask );

template
void applyProcessingFunctional<PRECOMP_T> (
        ReductiveNTensorFieldBoxProcessingFunctional3D<PRECOMP_T>& functional,
        Box3D domain, std::vector<MultiNTensorField3D<PRECOMP_T>*> fields );

template
void applyProcessingFunctional<PRECOMP_T> (
        ReductiveScalarFieldBoxProcessingFunctional3D<PRECOMP_T>& functional,
        Box3D domain, std::vector<MultiScalarField3D<PRECOMP_T>*> fields );

/* *************** Bounded Boxed Data Processor functionals ****************** */

template
void applyProcessingFunctional<PRECOMP_T> (
        BoundedReductiveBoxProcessingFunctional3D_N<PRECOMP_T>& functional,
        Box3D domain, MultiNTensorField3D<PRECOMP_T>& field, plint boundaryWidth );

template
void applyProcessingFunctional<PRECOMP_T> (
        BoundedMaskedReductiveBoxProcessingFunctional3D_N<PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field,
        MultiNTensorField3D<int>& mask,
        plint boundaryWidth );

template
void applyProcessingFunctional<PRECOMP_T,PRECOMP_T> (
        BoundedReductiveBoxProcessingFunctional3D_NN<PRECOMP_T,PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field1,
        MultiNTensorField3D<PRECOMP_T>& field2,
        plint boundaryWidth );

template
void applyProcessingFunctional<PRECOMP_T,PRECOMP_T> (
        BoundedMaskedReductiveBoxProcessingFunctional3D_NN<PRECOMP_T,PRECOMP_T>& functional,
        Box3D domain,
        MultiNTensorField3D<PRECOMP_T>& field1,
        MultiNTensorField3D<PRECOMP_T>& field2,
        MultiNTensorField3D<int>& mask,
        plint boundaryWidth );

}  // namespace plb


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace WindowsPhone.Views
{
    public partial class ResultPage : PhoneApplicationPage
    {
        public ResultPage()
        {
            InitializeComponent();
            Loaded += Page_Loaded;
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.IsVisible = true;
        }
    }
}


text:
<?php

namespace Mobile;

abstract class Feed {
	// Properties
	protected $url;
	protected $data;

	// Abstract functions
	abstract protected function get_source_data();
	abstract protected function parse_data();

	/**
	 * Constructor
	 * @param string $url A string containing the url of the feed source
	 */
	public function __construct($url) {
		// Set the initial properties
		$this->url = $url;
		$this->data = array();

	} // End __construct

	/**
	 * Method to get the feeds data and parse it into a normalized/standardized format
	 */
	final public function get_normalized_data() {
		// Let's get the source data, parse it, and return it as a normalized source
		$this->get_source_data();
		return $this->parse_data();

	} // End get_normalized_data

	/**
	 * Compare timestamps for sorting
	 * @param array $a An array with a 'timestamp' key
	 * @param array $b An array with a 'timestamp' key
	 */
	public static function compare_array_timestamp($a, $b) {
		return $a['timestamp'] < $b['timestamp'];
	} // End compare_array_timestamp

	/**
	 * Method to grab JSON data from a feed source URL and return it as an array
	 * @param string $url A string containing the url of the feed source
	 */
	public function get_json_source($url) {
		// Set up the feed_data array
		$feed_data = array();

		// PSU::curl throws an exception if the document doesn't return a perfect 200 error
		try {
			// Get the JSON data with a CURL request to the url
			$feed_data = \PSU::curl($url, \PSU::FILE_GET_CONTENTS);

			// Return the JSON decoded as an array
			return json_decode($feed_data, true);
		}
		catch (\PSUToolsException $e) {
			// For now, lets just grab the exception and put it into the session
			$_SESSION['errors'][] = $e->getMessage();
		}

		return $feed_data;
	} // End get_json_source

	/**
	 * Method to grab RSS data as an array of PSU Zend Feed objects
	 * @param string $url A string containing the url of the feed source
	 */
	public function get_rss_source($url) {
		// \PSU\Feed::import can throw many exceptions due to the Zend underpinnings. We don't need to handle them individually, so let's just catch them all
		// Possible exceptions seen so far:
		// Zend_Feed_Exception
		// Zend_Http_Client_Exception
		// Zend_Http_Client_Adapter_Exception
		try {
			// Get the feed data
			$feed_data = \PSU\Feed::import($url);
		}
		catch (\Exception $e) {
			// For now, lets just grab the exception and put it into the session
			$_SESSION['errors'][] = $e->getMessage();
		}

		return $feed_data;
	} // Ebd get_rss_source
} // End class Feed


text:
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'sample_project.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^', include(admin.site.urls)),
)


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Jun 27, 2012
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  VHAISWWERFEJ
  Description:

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.imaging.pathology;

import java.util.Date;

/**
 * @author VHAISWWERFEJ
 *
 */
public class PathologyCaseSupplementalReport
{
	private final Date supplementalReportDate;
	private final boolean verified;
	private final String verifiedProvider;
	private final String [] values;

	public PathologyCaseSupplementalReport(Date supplementalReportDate,
			boolean verified, String verifiedProvider, String[] values)
	{
		super();
		this.supplementalReportDate = supplementalReportDate;
		this.verified = verified;
		this.verifiedProvider = verifiedProvider;
		this.values = values;
	}

	public Date getSupplementalReportDate()
	{
		return supplementalReportDate;
	}

	public boolean isVerified()
	{
		return verified;
	}

	public String getVerifiedProvider()
	{
		return verifiedProvider;
	}

	public String[] getValues()
	{
		return values;
	}
}


text:
class Person {
	constructor(name) {
		this.name = name;
	}

	hi() {
		return this.name;
	}
}

class Man extends Person {
	constructor(name) {
		super(name);
	}

	hi() {
		return 'I am a man and my name is ' + super();
	}
}

var name = 'john';
var man = new Man(name);
var msg = man.hi();

console.log(name);
console.log(man);
console.log(msg);


text:
description: 'Stops running containers without removing them. '
keywords: fig, composition, compose, docker, orchestration, cli, stop
title: docker-compose stop
---

```
Usage: stop [options] [SERVICE...]

Options:
-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds (default: 10).
```

Stops running containers without removing them. They can be started again with
`docker-compose start`.


text:
<?php

namespace Sirius\FormRenderer\Utils;

use Sirius\Input\Element;
use Sirius\Input\InputFilter;

class TreeBuilder
{

    /**
     * @var InputFilter
     */
    protected $form;

    public function __construct(InputFilter $form, Element $root = null)
    {
        if (!$root) {
            $root = $form;
        }
        $this->form = $form;
        $this->root = $root;
    }

    public function getTree()
    {
        return $this->createNode($this->root);
    }

    protected function createNode($element, $name = null)
    {
        $node = [
            '_form' => $this->form,
            '_name' => $name,
            '_element' => $element,
            '_children' => (method_exists($element, 'getElements')) ? $this->getChildrenTree($element->getElements()) : null
        ];

        return $node;
    }

    protected function getChildrenTree($elements)
    {
        $parents = [];
        foreach ($elements as $name => $element) {
            $group = ($element === $this->root || !$element->getGroup()) ? '____root' : $element->getGroup();
            $parents[$group][] = $this->createNode($element, $name);
        }

        return $this->createBranch($parents, $parents['____root']);;
    }

    protected function createBranch(&$parents, $children)
    {
        $tree = array();
        foreach ($children as $child) {
            $childName = $child['_name'];
            if (isset($parents[$childName])) {
                $child['_children'] = $this->createBranch($parents, $parents[$childName]);
            }
            $tree[$childName] = $child;
        }

        return $tree;
    }

}


text:
/* traceInfo.h was originally generated by the autoSql program, which also
 * generated traceInfo.c and traceInfo.sql.  This header links the database and
 * the RAM representation of objects. */

#ifndef TRACEINFO_H
#define TRACEINFO_H

struct traceInfo
/* subset of the sequencing trace ancillary information, see http://www.ncbi.nlm.nih.gov/Traces/TraceArchiveRFC.html */
    {
    struct traceInfo *next;  /* Next in singly linked list. */
    char *ti;	/* Trace identifier */
    char *templateId;	/* Name of the template */
    unsigned size;	/* Size of read */
    };

void traceInfoStaticLoad(char **row, struct traceInfo *ret);
/* Load a row from traceInfo table into ret.  The contents of ret will
 * be replaced at the next call to this function. */

struct traceInfo *traceInfoLoad(char **row);
/* Load a traceInfo from row fetched with select * from traceInfo
 * from database.  Dispose of this with traceInfoFree(). */

struct traceInfo *traceInfoLoadAll(char *fileName);
/* Load all traceInfo from a tab-separated file.
 * Dispose of this with traceInfoFreeList(). */

struct traceInfo *traceInfoCommaIn(char **pS, struct traceInfo *ret);
/* Create a traceInfo out of a comma separated string.
 * This will fill in ret if non-null, otherwise will
 * return a new traceInfo */

void traceInfoFree(struct traceInfo **pEl);
/* Free a single dynamically allocated traceInfo such as created
 * with traceInfoLoad(). */

void traceInfoFreeList(struct traceInfo **pList);
/* Free a list of dynamically allocated traceInfo's */

void traceInfoOutput(struct traceInfo *el, FILE *f, char sep, char lastSep);
/* Print out traceInfo.  Separate fields with sep. Follow last field with lastSep. */

#define traceInfoTabOut(el,f) traceInfoOutput(el,f,'\t','\n');
/* Print out traceInfo as a line in a tab-separated file. */

#define traceInfoCommaOut(el,f) traceInfoOutput(el,f,',',',');
/* Print out traceInfo as a comma separated list including final comma. */

#endif /* TRACEINFO_H */


text:
#include "gcp/util/Exception.h"
#include "gcp/util/FileHandler.h"

#include <sstream>
#include <fstream>

using namespace std;
using namespace gcp::util;

/**.......................................................................
 * Constructor.
 */
FileHandler::FileHandler() {}

/**.......................................................................
 * Destructor.
 */
FileHandler::~FileHandler() {}

bool FileHandler::fileExists(std::string name)
{
  std::ifstream fin;
  fin.open(name.c_str(), ios::in);

  if(fin) {
    fin.close();
    return true;
  } else {
    return false;
  }
}


text:
namespace base {
class Pickle;
}

namespace nacl {

class NaClValidationCache {
 public:
  NaClValidationCache();
  ~NaClValidationCache();

  // Get the key used for HMACing validation signatures.  This should be a
  // string of cryptographically secure random bytes.
  const std::string& GetValidationCacheKey() const {
    return validation_cache_key_;
  }

  // Is the validation signature in the database?
  bool QueryKnownToValidate(const std::string& signature, bool reorder);

  // Put the validation signature in the database.
  void SetKnownToValidate(const std::string& signature);

  void Reset();
  void Serialize(base::Pickle* pickle) const;
  bool Deserialize(const base::Pickle* pickle);

  // Testing functions
  size_t size() const {
    return validation_cache_.size();
  }
  void SetValidationCacheKey(std::string& key) {
    validation_cache_key_ = key;
  }
  std::vector<std::string> GetContents() const {
    std::vector<std::string> contents;
    ValidationCacheType::const_iterator iter = validation_cache_.begin();
    for (iter = validation_cache_.begin();
         iter != validation_cache_.end();
         iter++) {
      contents.push_back(iter->first);
    }
    return contents;
  }

 private:
  bool DeserializeImpl(const base::Pickle* pickle);

  typedef base::HashingMRUCache<std::string, bool> ValidationCacheType;
  ValidationCacheType validation_cache_;

  std::string validation_cache_key_;

  DISALLOW_COPY_AND_ASSIGN(NaClValidationCache);
};

} // namespace nacl

#endif  // COMPONENTS_NACL_BROWSER_NACL_VALIDATION_CACHE_H_


text:
try:
    from .harness import Harness
except SystemError:
    from python.harness import Harness


text:
import { Component, ViewChild } from '@angular/core';
import { TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { IgxButtonDirective } from './button.directive';

import { configureTestSuite } from '../../test-utils/configure-suite';
import { IgxIconComponent, IgxIconService } from '../../icon/public_api';
import { DisplayDensity } from '../../core/density';

const BUTTON_COMFORTABLE = 'igx-button';
const BUTTON_COSY = 'igx-button--cosy';
const BUTTON_COMPACT = 'igx-button--compact';

describe('IgxButton', () => {
    configureTestSuite();

    const baseClass = BUTTON_COMFORTABLE;
    const classes = {
        flat: `${baseClass}--flat`,
        raised: `${baseClass}--raised`,
        outlined: `${baseClass}--outlined`,
        fab: `${baseClass}--fab`,
        icon: `${baseClass}--icon`
    };

    beforeAll(waitForAsync(() => {
        TestBed.configureTestingModule({
            declarations: [
                InitButtonComponent,
                ButtonWithAttribsComponent,
                ButtonsWithDisplayDensityComponent,
                IgxButtonDirective,
                IgxIconComponent
            ],
            providers: [IgxIconService]
        })
            .compileComponents();
    }));

    it('Initializes a button', () => {
        const fixture = TestBed.createComponent(InitButtonComponent);
        fixture.detectChanges();

        expect(fixture.debugElement.query(By.css('span.igx-button--flat'))).toBeTruthy();
        expect(fixture.debugElement.query(By.css('i.material-icons'))).toBeTruthy();
    });

    it('Button with properties', () => {
        const fixture = TestBed.createComponent(ButtonWithAttribsComponent);
        fixture.detectChanges();

        const button = fixture.debugElement.query(By.css('span')).nativeElement;

        expect(button).toBeTruthy();
        expect(button.classList.contains('igx-button--raised')).toBe(true);
        expect(button.classList.contains('igx-button--disabled')).toBe(true);

        fixture.componentInstance.disabled = false;
        fixture.detectChanges();

        expect(button.classList.contains('igx-button--disabled')).toBe(false);
        expect(button.style.color).toEqual('white');
        expect(button.style.background).toEqual('black');

        fixture.componentInstance.foreground = 'yellow';
        fixture.componentInstance.background = 'green';
        fixture.detectChanges();

        expect(button.style.color).toEqual('yellow');
        expect(button.style.background).toEqual('green');
    });

    it('Should apply display density to respective buttons correctly', () => {
        const fixture = TestBed.createComponent(ButtonsWithDisplayDensityComponent);
        fixture.detectChanges();

        // Get flat button
        const flatButton = fixture.componentInstance.flatButton;
        const flatButtonDOM = fixture.debugElement.query(By.css('.flatBtn'));
        // Get raised button
        const raisedButton = fixture.componentInstance.raisedButton;
        const raisedButtonDOM = fixture.debugElement.query(By.css('.raisedBtn'));
        // Get outlined button
        const outlinedButton = fixture.componentInstance.outlinedButton;
        const outlinedButtonDOM = fixture.debugElement.query(By.css('.outlinedBtn'));
        // Get fab button
        const fabButton = fixture.componentInstance.fabButton;
        const fabButtonDOM = fixture.debugElement.query(By.css('.fabBtn'));
        // Get icon button
        const iconButton = fixture.componentInstance.iconButton;
        const iconButtonDOM = fixture.debugElement.query(By.css('.iconBtn'));

        verifyDisplayDensity(flatButton, flatButtonDOM, 'flat', DisplayDensity.comfortable);
        verifyDisplayDensity(raisedButton, raisedButtonDOM, 'raised', DisplayDensity.comfortable);
        verifyDisplayDensity(outlinedButton, outlinedButtonDOM, 'outlined', DisplayDensity.comfortable);
        verifyDisplayDensity(fabButton, fabButtonDOM, 'fab', DisplayDensity.comfortable);
        verifyDisplayDensity(iconButton, iconButtonDOM, 'icon', DisplayDensity.comfortable);

        fixture.componentInstance.density = DisplayDensity.compact;
        fixture.detectChanges();

        verifyDisplayDensity(flatButton, flatButtonDOM, 'flat', DisplayDensity.compact);
        verifyDisplayDensity(raisedButton, raisedButtonDOM, 'raised', DisplayDensity.compact);
        verifyDisplayDensity(outlinedButton, outlinedButtonDOM, 'outlined', DisplayDensity.compact);
        verifyDisplayDensity(fabButton, fabButtonDOM, 'fab', DisplayDensity.compact);
        verifyDisplayDensity(iconButton, iconButtonDOM, 'icon', DisplayDensity.compact);

        fixture.componentInstance.density = DisplayDensity.cosy;
        fixture.detectChanges();

        verifyDisplayDensity(flatButton, flatButtonDOM, 'flat', DisplayDensity.cosy);
        verifyDisplayDensity(raisedButton, raisedButtonDOM, 'raised', DisplayDensity.cosy);
        verifyDisplayDensity(outlinedButton, outlinedButtonDOM, 'outlined', DisplayDensity.cosy);
        verifyDisplayDensity(fabButton, fabButtonDOM, 'fab', DisplayDensity.cosy);
        verifyDisplayDensity(iconButton, iconButtonDOM, 'icon', DisplayDensity.cosy);
    });

    it('Should set the correct CSS class on the element using the "type" input', () => {
        const fixture = TestBed.createComponent(InitButtonComponent);
        fixture.detectChanges();
        const theButton = fixture.componentInstance.button;
        const theButtonNativeEl = theButton.nativeElement;
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.flat);

        theButton.type = 'raised';
        fixture.detectChanges();
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.raised);

        theButton.type = 'outlined';
        fixture.detectChanges();
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.outlined);

        theButton.type = 'fab';
        fixture.detectChanges();
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.fab);

        theButton.type = 'icon';
        fixture.detectChanges();
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.icon);

        theButton.type = 'flat';
        fixture.detectChanges();
        expect(theButtonNativeEl.classList.length).toEqual(2);
        expect(theButtonNativeEl.classList).toContain(classes.flat);
    });
});

@Component({
    template:
        `
        add
    `
})
class InitButtonComponent {
    @ViewChild(IgxButtonDirective, { read: IgxButtonDirective, static: true })
    button: IgxButtonDirective;
}

@Component({
    template:
        `Test`
})
class ButtonWithAttribsComponent {
    public disabled = true;
    public foreground = 'white';
    public background = 'black';
}

@Component({
    template:
        `
    <button #flat class="flatBtn" igxButton="flat" [displayDensity]="density">Flat</button>
    <button #raised class="raisedBtn" igxButton="raised" [displayDensity]="density">Raised</button>
    <button #outlined class="outlinedBtn" igxButton="outlined" [displayDensity]="density">Outlined</button>
    <button #fab class="fabBtn" igxButton="fab" [displayDensity]="density">
        <igx-icon>favorite</igx-icon>
    </button>
    <button #icon class="iconBtn" igxButton="icon" [displayDensity]="density">
        <igx-icon>search</igx-icon>
    </button>
    `
})
class ButtonsWithDisplayDensityComponent {
    @ViewChild('flat', { read: IgxButtonDirective, static: true }) flatButton: IgxButtonDirective;
    @ViewChild('raised', { read: IgxButtonDirective, static: true }) raisedButton: IgxButtonDirective;
    @ViewChild('outlined', { read: IgxButtonDirective, static: true }) outlinedButton: IgxButtonDirective;
    @ViewChild('fab', { read: IgxButtonDirective, static: true }) fabButton: IgxButtonDirective;
    @ViewChild('icon', { read: IgxButtonDirective, static: true }) iconButton: IgxButtonDirective;

    public density: DisplayDensity = DisplayDensity.comfortable;
}

/**
 * Verifies the display density of the igxButton based on its type.
 */
const verifyDisplayDensity = (buttonDirective, buttonDebugEl, buttonType, expectedDisplayDensity: DisplayDensity) => {
    let expectedButtonDensityClass = '';

    switch (expectedDisplayDensity) {
        case DisplayDensity.compact:
            expectedButtonDensityClass = BUTTON_COMPACT;
            break;
        case DisplayDensity.cosy:
            expectedButtonDensityClass = BUTTON_COSY;
            break;
        default:
            expectedButtonDensityClass = BUTTON_COMFORTABLE;
    }

    const buttonNativeElement = buttonDebugEl.nativeElement;
    if (expectedDisplayDensity === DisplayDensity.comfortable) {
        // For 'comfortable', the buttons should have no additional CSS classes added.
        expect(buttonNativeElement.classList.length).toBe(3);
        expect(buttonNativeElement.classList.contains(expectedButtonDensityClass)).toBe(true, 'Contains density class!');
    } else {
        // For 'compact' and 'cosy', the buttons should have an additional CSS class added.
        expect(buttonNativeElement.classList.length).toBe(4);
        expect(buttonNativeElement.classList.contains(expectedButtonDensityClass)).toBe(true, 'Missing density class!');
    }
    expect(buttonDirective.displayDensity).toBe(expectedDisplayDensity);
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.data.tables.implementation.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The TableServiceErrorOdataError model. */
@Fluent
public final class TableServiceErrorOdataError {
    /*
     * The service error code.
     */
    @JsonProperty(value = "code")
    private String code;

    /*
     * The service error message.
     */
    @JsonProperty(value = "message")
    private TableServiceErrorOdataErrorMessage message;

    /**
     * Get the code property: The service error code.
     *
     * @return the code value.
     */
    public String getCode() {
        return this.code;
    }

    /**
     * Set the code property: The service error code.
     *
     * @param code the code value to set.
     * @return the TableServiceErrorOdataError object itself.
     */
    public TableServiceErrorOdataError setCode(String code) {
        this.code = code;
        return this;
    }

    /**
     * Get the message property: The service error message.
     *
     * @return the message value.
     */
    public TableServiceErrorOdataErrorMessage getMessage() {
        return this.message;
    }

    /**
     * Set the message property: The service error message.
     *
     * @param message the message value to set.
     * @return the TableServiceErrorOdataError object itself.
     */
    public TableServiceErrorOdataError setMessage(TableServiceErrorOdataErrorMessage message) {
        this.message = message;
        return this;
    }
}


text:
<!doctype html>

<meta charset="<?php bloginfo('charset'); ?>">

<?php if(of_get_option('enable_responsive') == '1') { ?>

<meta name="viewport" content="width=device-width">
<?php } ?>

<title><?php wp_title( '|', true, 'right' ); ?><?php bloginfo('blogname'); ?> | <?php bloginfo('description'); ?></title>
<link rel="Shortcut Icon" href="<?php bloginfo('template_url'); ?>/images/favicon.ico" type="image/x-icon">

<?php get_template_part( 'style', 'options' ); ?>

<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php echo esc_url( bloginfo('pingback_url') ); ?>">

<?php wp_head(); ?>

<body <?php body_class(); ?>>

			<?php if (is_home() || is_front_page() ) { ?>
				<?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) { ?>

<a href="<?php echo get_option('home'); ?>/" title="Home"><img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php bloginfo('name'); ?>" /><?php bloginfo( 'name' ); ?>

				<?php } else { ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

				<?php } ?>
			<?php } else { ?>
				<?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) { ?>

<a href="<?php echo get_option('home'); ?>/" title="Home"><img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php bloginfo('name'); ?>" /><?php bloginfo( 'name' ); ?>

				<?php } else { ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

				<?php } ?>
			<?php } ?>

			<?php if(of_get_option('display_search') == '1') { ?>

			        <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
				        <input type="text" class="inputbox" value="<?php _e('Search', 'organicthemes'); ?>" onfocus="if (this.value == '<?php _e("Search", 'organicthemes'); ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _e('Search', 'organicthemes'); ?>';}" name="s" id="s" />
				        <input type="submit" id="searchsubmit" value="<?php _e("Go", 'organicthemes'); ?>" />
			        </form>

			<?php } ?>

<?php _e( 'Menu', 'organicthemes' ); ?>

				<?php if ( has_nav_menu( 'header-menu' ) ) {
					wp_nav_menu( array(
						'theme_location' => 'header-menu',
						'title_li' => '',
						'depth' => 4,
						'container_class' => '',
						'menu_class'      => 'menu'
						)
					);
				} else { ?>

<?php wp_list_pages('title_li=&depth=4'); ?>

				<?php } ?>


text:
<?php

namespace Openl10n\Cli\File;

class Pattern
{
    protected $pattern;

    public function __construct($pattern)
    {
        $this->pattern = $pattern;
    }

    public function toString(array $attributes = array())
    {
        $placeholders = array_map(function ($attribute) {
            return "<$attribute>";
        }, array_keys($attributes));

        return str_replace($placeholders, $attributes, $this->pattern);
    }

    public function __toString()
    {
        return $this->toString();
    }
}