text:
package com.google.android.exoplayer2.upstream.cache;

import static com.google.android.exoplayer2.upstream.cache.CacheAsserts.assertCacheEmpty;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import android.net.Uri;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.FakeDataSet.FakeData;
import com.google.android.exoplayer2.testutil.FakeDataSource;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.util.Util;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.NavigableSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;

/**
 * Unit tests for {@link CacheDataSource}.
 */
@RunWith(RobolectricTestRunner.class)
public final class CacheDataSourceTest {

  private static final byte[] TEST_DATA = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  private static final int MAX_CACHE_FILE_SIZE = 3;
  private static final String CACHE_KEY_PREFIX = "myCacheKeyFactoryPrefix";

  private Uri testDataUri;
  private String fixedCacheKey;
  private String expectedCacheKey;
  private File tempFolder;
  private SimpleCache cache;
  private CacheKeyFactory cacheKeyFactory;

  @Before
  public void setUp() throws Exception {
    testDataUri = Uri.parse("test_data");
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey = fixedCacheKey;
    cacheKeyFactory =
        new CacheKeyFactory() {
          @Override
          public String buildCacheKey(DataSpec dataSpec) {
            return CACHE_KEY_PREFIX + "." + CacheUtil.generateKey(dataSpec.uri);
          }
        };
    tempFolder = Util.createTempDirectory(RuntimeEnvironment.application, "ExoPlayerTest");
    cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
  }

  @After
  public void tearDown() throws Exception {
    Util.recursiveDelete(tempFolder);
  }

  @Test
  public void testMaxCacheFileSize() throws Exception {
    CacheDataSource cacheDataSource = createCacheDataSource(false, false);
    assertReadDataContentLength(cacheDataSource, false, false);
    for (String key : cache.getKeys()) {
      for (CacheSpan cacheSpan : cache.getCachedSpans(key)) {
        assertThat(cacheSpan.length <= MAX_CACHE_FILE_SIZE).isTrue();
        assertThat(cacheSpan.file.length() <= MAX_CACHE_FILE_SIZE).isTrue();
      }
    }
  }

  @Test
  public void testCacheAndReadUnboundedRequest() throws Exception {
    assertCacheAndRead(/* unboundedRequest= */ true, /* simulateUnknownLength= */ false);
  }

  @Test
  public void testCacheAndReadUnknownLength() throws Exception {
    assertCacheAndRead(/* unboundedRequest= */ false, /* simulateUnknownLength= */ true);
  }

  @Test
  public void testCacheAndReadUnboundedRequestUnknownLength() throws Exception {
    assertCacheAndRead(/* unboundedRequest= */ true, /* simulateUnknownLength= */ true);
  }

  @Test
  public void testCacheAndRead() throws Exception {
    assertCacheAndRead(/* unboundedRequest= */ false, /* simulateUnknownLength= */ false);
  }

  @Test
  public void testUnsatisfiableRange() throws Exception {
    // Bounded request but the content length is unknown. This forces all data to be cached but not
    // the length
    assertCacheAndRead(/* unboundedRequest= */ false, /* simulateUnknownLength= */ true);

    // Now do an unbounded request. This will read all of the data from cache and then try to read
    // more from upstream which will cause to a 416 so CDS will store the length.
    CacheDataSource cacheDataSource =
        createCacheDataSource(/* setReadException= */ true, /* simulateUnknownLength= */ true);
    assertReadDataContentLength(
        cacheDataSource, /* unboundedRequest= */ true, /* unknownLength= */ true);

    // If the user try to access off range then it should throw an IOException
    try {
      cacheDataSource =
          createCacheDataSource(/* setReadException= */ false, /* simulateUnknownLength= */ false);
      cacheDataSource.open(new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));
      fail();
    } catch (IOException e) {
      // success
    }
  }

  @Test
  public void testCacheAndReadUnboundedRequestWithCacheKeyFactoryWithNullDataSpecCacheKey()
      throws Exception {
    fixedCacheKey = null;
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, /* key= */ null));

    assertCacheAndRead(
        /* unboundedRequest= */ true, /* simulateUnknownLength= */ false, cacheKeyFactory);
  }

  @Test
  public void testCacheAndReadUnknownLengthWithCacheKeyFactoryOverridingWithNullDataSpecCacheKey()
      throws Exception {
    fixedCacheKey = null;
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, /* key= */ null));

    assertCacheAndRead(
        /* unboundedRequest= */ false, /* simulateUnknownLength= */ true, cacheKeyFactory);
  }

  @Test
  public void
      testCacheAndReadUnboundedRequestUnknownLengthWithCacheKeyFactoryWithNullDataSpecCacheKey()
          throws Exception {
    fixedCacheKey = null;
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, /* key= */ null));

    assertCacheAndRead(
        /* unboundedRequest= */ true, /* simulateUnknownLength= */ true, cacheKeyFactory);
  }

  @Test
  public void testCacheAndReadWithCacheKeyFactoryWithNullDataSpecCacheKey() throws Exception {
    fixedCacheKey = null;
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, /* key= */ null));

    assertCacheAndRead(
        /* unboundedRequest= */ false, /* simulateUnknownLength= */ false, cacheKeyFactory);
  }

  @Test
  public void testUnsatisfiableRangeWithCacheKeyFactoryNullDataSpecCacheKey() throws Exception {
    fixedCacheKey = null;
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, /* key= */ null));

    // Bounded request but the content length is unknown. This forces all data to be cached but not
    // the length
    assertCacheAndRead(
        /* unboundedRequest= */ false, /* simulateUnknownLength= */ true, cacheKeyFactory);

    // Now do an unbounded request. This will read all of the data from cache and then try to read
    // more from upstream which will cause to a 416 so CDS will store the length.
    CacheDataSource cacheDataSource =
        createCacheDataSource(
            /* setReadException= */ true, /* simulateUnknownLength= */ true, cacheKeyFactory);
    assertReadDataContentLength(
        cacheDataSource, /* unboundedRequest= */ true, /* unknownLength= */ true);

    // If the user try to access off range then it should throw an IOException
    try {
      cacheDataSource =
          createCacheDataSource(
              /* setReadException= */ false, /* simulateUnknownLength= */ false, cacheKeyFactory);
      cacheDataSource.open(new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));
      fail();
    } catch (IOException e) {
      // success
    }
  }

  @Test
  public void testCacheAndReadUnboundedRequestWithCacheKeyFactoryOverridingDataSpecCacheKey()
      throws Exception {
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));

    assertCacheAndRead(true, false, cacheKeyFactory);
  }

  @Test
  public void testCacheAndReadUnknownLengthWithCacheKeyFactoryOverridingDataSpecCacheKey()
      throws Exception {
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));

    assertCacheAndRead(false, true, cacheKeyFactory);
  }

  @Test
  public void
      testCacheAndReadUnboundedRequestUnknownLengthWithCacheKeyFactoryOverridingDataSpecCacheKey()
          throws Exception {
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));

    assertCacheAndRead(
        /* unboundedRequest= */ true, /* simulateUnknownLength= */ true, cacheKeyFactory);
  }

  @Test
  public void testCacheAndReadWithCacheKeyFactoryOverridingDataSpecCacheKey() throws Exception {
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));

    assertCacheAndRead(
        /* unboundedRequest= */ false, /* simulateUnknownLength= */ false, cacheKeyFactory);
  }

  @Test
  public void testUnsatisfiableRangeWithCacheKeyFactoryOverridingDataSpecCacheKey()
      throws Exception {
    fixedCacheKey = CacheUtil.generateKey(testDataUri);
    expectedCacheKey =
        cacheKeyFactory.buildCacheKey(
            new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));

    // Bounded request but the content length is unknown. This forces all data to be cached but not
    // the length
    assertCacheAndRead(
        /* unboundedRequest= */ false, /* simulateUnknownLength= */ true, cacheKeyFactory);

    // Now do an unbounded request. This will read all of the data from cache and then try to read
    // more from upstream which will cause to a 416 so CDS will store the length.
    CacheDataSource cacheDataSource =
        createCacheDataSource(
            /* setReadException= */ true, /* simulateUnknownLength= */ true, cacheKeyFactory);
    assertReadDataContentLength(
        cacheDataSource, /* unboundedRequest= */ true, /* unknownLength= */ true);

    // If the user try to access off range then it should throw an IOException
    try {
      cacheDataSource =
          createCacheDataSource(
              /* setReadException= */ false, /* simulateUnknownLength= */ false, cacheKeyFactory);
      cacheDataSource.open(new DataSpec(testDataUri, TEST_DATA.length, 5, fixedCacheKey));
      fail();
    } catch (IOException e) {
      // success
    }
  }

  @Test
  public void testContentLengthEdgeCases() throws Exception {
    // Read partial at EOS but don't cross it so length is unknown
    CacheDataSource cacheDataSource = createCacheDataSource(false, true);
    assertReadData(cacheDataSource, true, TEST_DATA.length - 2, 2);
    assertThat(cache.getContentLength(expectedCacheKey)).isEqualTo(C.LENGTH_UNSET);

    // Now do an unbounded request for whole data. This will cause a bounded request from upstream.
    // End of data from upstream shouldn't be mixed up with EOS and cause length set wrong.
    cacheDataSource = createCacheDataSource(false, true);
    assertReadDataContentLength(cacheDataSource, true, true);

    // Now the length set correctly do an unbounded request with offset
    assertThat(
            cacheDataSource.open(
                new DataSpec(testDataUri, TEST_DATA.length - 2, C.LENGTH_UNSET, expectedCacheKey)))
        .isEqualTo(2);

    // An unbounded request with offset for not cached content
    assertThat(
            cacheDataSource.open(
                new DataSpec(
                    Uri.parse("notCachedUri"), TEST_DATA.length - 2, C.LENGTH_UNSET, null)))
        .isEqualTo(C.LENGTH_UNSET);
  }

  @Test
  public void testUnknownLengthContentReadInOneConnectionAndLengthIsResolved() throws Exception {
    FakeDataSource upstream = new FakeDataSource();
    upstream
        .getDataSet()
        .newData(testDataUri)
        .appendReadData(TEST_DATA)
        .setSimulateUnknownLength(true);
    CacheDataSource cacheDataSource = new CacheDataSource(cache, upstream, 0);

    int flags = DataSpec.FLAG_ALLOW_CACHING_UNKNOWN_LENGTH;
    cacheDataSource.open(new DataSpec(testDataUri, 0, C.LENGTH_UNSET, expectedCacheKey, flags));
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();

    assertThat(upstream.getAndClearOpenedDataSpecs()).hasLength(1);
    assertThat(cache.getContentLength(expectedCacheKey)).isEqualTo(TEST_DATA.length);
  }

  @Test
  public void testIgnoreCacheForUnsetLengthRequests() throws Exception {
    FakeDataSource upstream = new FakeDataSource();
    upstream.getDataSet().setData(testDataUri, TEST_DATA);
    CacheDataSource cacheDataSource =
        new CacheDataSource(
            cache, upstream, CacheDataSource.FLAG_IGNORE_CACHE_FOR_UNSET_LENGTH_REQUESTS);

    cacheDataSource.open(new DataSpec(testDataUri, 0, C.LENGTH_UNSET, expectedCacheKey));
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();

    assertThat(cache.getKeys()).isEmpty();
  }

  @Test
  public void testReadOnlyCache() throws Exception {
    CacheDataSource cacheDataSource = createCacheDataSource(false, false, 0, null);
    assertReadDataContentLength(cacheDataSource, false, false);
    assertCacheEmpty(cache);
  }

  @Test
  public void testSwitchToCacheSourceWithReadOnlyCacheDataSource() throws Exception {
    // Create a fake data source with a 1 MB default data.
    FakeDataSource upstream = new FakeDataSource();
    FakeData fakeData = upstream.getDataSet().newDefaultData().appendReadData(1024 * 1024 - 1);
    // Insert an action just before the end of the data to fail the test if reading from upstream
    // reaches end of the data.
    fakeData
        .appendReadAction(
            new Runnable() {
              @Override
              public void run() {
                fail("Read from upstream shouldn't reach to the end of the data.");
              }
            })
        .appendReadData(1);
    // Create cache read-only CacheDataSource.
    CacheDataSource cacheDataSource =
        new CacheDataSource(cache, upstream, new FileDataSource(), null, 0, null);

    // Open source and read some data from upstream as the data hasn't cached yet.
    DataSpec dataSpec = new DataSpec(testDataUri, 0, C.LENGTH_UNSET, fixedCacheKey);
    cacheDataSource.open(dataSpec);
    byte[] buffer = new byte[1024];
    cacheDataSource.read(buffer, 0, buffer.length);

    // Cache the data.
    // Although we use another FakeDataSource instance, it shouldn't matter.
    FakeDataSource upstream2 =
        new FakeDataSource(
            new FakeDataSource()
                .getDataSet()
                .newDefaultData()
                .appendReadData(1024 * 1024)
                .endData());
    CacheUtil.cache(dataSpec, cache, upstream2, /* counters= */ null, /* isCanceled= */ null);

    // Read the rest of the data.
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();
  }

  @Test
  public void testSwitchToCacheSourceWithNonBlockingCacheDataSource() throws Exception {
    // Create a fake data source with a 1 MB default data.
    FakeDataSource upstream = new FakeDataSource();
    FakeData fakeData = upstream.getDataSet().newDefaultData().appendReadData(1024 * 1024 - 1);
    // Insert an action just before the end of the data to fail the test if reading from upstream
    // reaches end of the data.
    fakeData
        .appendReadAction(
            new Runnable() {
              @Override
              public void run() {
                fail("Read from upstream shouldn't reach to the end of the data.");
              }
            })
        .appendReadData(1);

    // Lock the content on the cache.
    SimpleCacheSpan cacheSpan = cache.startReadWriteNonBlocking(expectedCacheKey, 0);
    assertThat(cacheSpan).isNotNull();
    assertThat(cacheSpan.isHoleSpan()).isTrue();

    // Create non blocking CacheDataSource.
    CacheDataSource cacheDataSource = new CacheDataSource(cache, upstream, 0);

    // Open source and read some data from upstream without writing to cache as the data is locked.
    DataSpec dataSpec = new DataSpec(testDataUri, 0, C.LENGTH_UNSET, fixedCacheKey);
    cacheDataSource.open(dataSpec);
    byte[] buffer = new byte[1024];
    cacheDataSource.read(buffer, 0, buffer.length);

    // Unlock the span.
    cache.releaseHoleSpan(cacheSpan);
    assertCacheEmpty(cache);

    // Cache the data.
    // Although we use another FakeDataSource instance, it shouldn't matter.
    FakeDataSource upstream2 =
        new FakeDataSource(
            new FakeDataSource()
                .getDataSet()
                .newDefaultData()
                .appendReadData(1024 * 1024)
                .endData());
    CacheUtil.cache(dataSpec, cache, upstream2, /* counters= */ null, /* isCanceled= */ null);

    // Read the rest of the data.
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();
  }

  @Test
  public void testDeleteCachedWhileReadingFromUpstreamWithReadOnlyCacheDataSourceDoesNotCrash()
      throws Exception {
    // Create a fake data source with a 1 KB default data.
    FakeDataSource upstream = new FakeDataSource();
    upstream.getDataSet().newDefaultData().appendReadData(1024).endData();

    // Cache the latter half of the data.
    DataSpec dataSpec = new DataSpec(testDataUri, 512, C.LENGTH_UNSET, fixedCacheKey);
    CacheUtil.cache(dataSpec, cache, upstream, /* counters= */ null, /* isCanceled= */ null);

    // Create cache read-only CacheDataSource.
    CacheDataSource cacheDataSource =
        new CacheDataSource(cache, upstream, new FileDataSource(), null, 0, null);

    // Open source and read some data from upstream as the data hasn't cached yet.
    dataSpec = new DataSpec(testDataUri, 0, C.LENGTH_UNSET, fixedCacheKey);
    cacheDataSource.open(dataSpec);
    TestUtil.readExactly(cacheDataSource, 100);

    // Delete cached data.
    CacheUtil.remove(cache, expectedCacheKey);
    assertCacheEmpty(cache);

    // Read the rest of the data.
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();
  }

  @Test
  public void testDeleteCachedWhileReadingFromUpstreamWithBlockingCacheDataSourceDoesNotBlock()
      throws Exception {
    // Create a fake data source with a 1 KB default data.
    FakeDataSource upstream = new FakeDataSource();
    int dataLength = 1024;
    upstream.getDataSet().newDefaultData().appendReadData(dataLength).endData();

    // Cache the latter half of the data.
    int halfDataLength = 512;
    DataSpec dataSpec = new DataSpec(testDataUri, halfDataLength, C.LENGTH_UNSET, fixedCacheKey);
    CacheUtil.cache(dataSpec, cache, upstream, /* counters= */ null, /* isCanceled= */ null);

    // Create blocking CacheDataSource.
    CacheDataSource cacheDataSource =
        new CacheDataSource(cache, upstream, CacheDataSource.FLAG_BLOCK_ON_CACHE);

    dataSpec = new DataSpec(testDataUri, 0, C.LENGTH_UNSET, fixedCacheKey);
    cacheDataSource.open(dataSpec);

    // Read the first half from upstream as it hasn't cached yet.
    TestUtil.readExactly(cacheDataSource, halfDataLength);

    // Delete the cached latter half.
    NavigableSet<CacheSpan> cachedSpans = cache.getCachedSpans(expectedCacheKey);
    for (CacheSpan cachedSpan : cachedSpans) {
      if (cachedSpan.position >= halfDataLength) {
        try {
          cache.removeSpan(cachedSpan);
        } catch (Cache.CacheException e) {
          // do nothing
        }
      }
    }

    // Read the rest of the data.
    TestUtil.readToEnd(cacheDataSource);
    cacheDataSource.close();
  }

  private void assertCacheAndRead(boolean unboundedRequest, boolean simulateUnknownLength)
      throws IOException {
    // Read all data from upstream and write to cache
    CacheDataSource cacheDataSource = createCacheDataSource(false, simulateUnknownLength);
    assertReadDataContentLength(cacheDataSource, unboundedRequest, simulateUnknownLength);

    // Just read from cache
    cacheDataSource = createCacheDataSource(true, simulateUnknownLength);
    assertReadDataContentLength(
        cacheDataSource,
        unboundedRequest,
        // Length is already cached.
        /* unknownLength= */ false);
  }

  private void assertCacheAndRead(
      boolean unboundedRequest, boolean simulateUnknownLength, CacheKeyFactory cacheKeyFactory)
      throws IOException {
    // Read all data from upstream and write to cache
    CacheDataSource cacheDataSource =
        createCacheDataSource(
            /* setReadException= */ false, simulateUnknownLength, cacheKeyFactory);
    assertReadDataContentLength(cacheDataSource, unboundedRequest, simulateUnknownLength);

    // Just read from cache
    cacheDataSource =
        createCacheDataSource(/* setReadException= */ true, simulateUnknownLength, cacheKeyFactory);
    assertReadDataContentLength(
        cacheDataSource,
        unboundedRequest,
        // Length is already cached.
        /* unknownLength= */ false);
  }

  /**
   * Reads data until EOI and compares it to {@link #TEST_DATA}. Also checks content length returned
   * from open() call and the cached content length.
   */
  private void assertReadDataContentLength(CacheDataSource cacheDataSource,
      boolean unboundedRequest, boolean unknownLength) throws IOException {
    int length = unboundedRequest ? C.LENGTH_UNSET : TEST_DATA.length;
    assertReadData(cacheDataSource, unknownLength, 0, length);
    // If !unboundedRequest, CacheDataSource doesn't reach EOS so shouldn't cache content length
    assertThat(cache.getContentLength(expectedCacheKey))
        .isEqualTo(!unboundedRequest ? C.LENGTH_UNSET : TEST_DATA.length);
  }

  private void assertReadData(CacheDataSource cacheDataSource, boolean unknownLength, int position,
      int length) throws IOException {
    int testDataLength = TEST_DATA.length - position;
    if (length != C.LENGTH_UNSET) {
      testDataLength = Math.min(testDataLength, length);
    }
    DataSpec dataSpec =
        new DataSpec(
            testDataUri,
            position,
            length,
            fixedCacheKey,
            DataSpec.FLAG_ALLOW_CACHING_UNKNOWN_LENGTH);
    assertThat(cacheDataSource.open(dataSpec)).isEqualTo(unknownLength ? length : testDataLength);
    cacheDataSource.close();

    byte[] expected = Arrays.copyOfRange(TEST_DATA, position, position + testDataLength);
    CacheAsserts.assertReadData(
        cacheDataSource, dataSpec, expected, "Cached data doesn't match the original data");
  }

  private CacheDataSource createCacheDataSource(boolean setReadException,
      boolean simulateUnknownLength) {
    return createCacheDataSource(setReadException, simulateUnknownLength,
        CacheDataSource.FLAG_BLOCK_ON_CACHE);
  }

  private CacheDataSource createCacheDataSource(
      boolean setReadException, boolean simulateUnknownLength, CacheKeyFactory cacheKeyFactory) {
    return createCacheDataSource(
        setReadException,
        simulateUnknownLength,
        CacheDataSource.FLAG_BLOCK_ON_CACHE,
        new CacheDataSink(cache, MAX_CACHE_FILE_SIZE),
        cacheKeyFactory);
  }

  private CacheDataSource createCacheDataSource(boolean setReadException,
      boolean simulateUnknownLength, @CacheDataSource.Flags int flags) {
    return createCacheDataSource(setReadException, simulateUnknownLength, flags,
        new CacheDataSink(cache, MAX_CACHE_FILE_SIZE));
  }

  private CacheDataSource createCacheDataSource(boolean setReadException,
      boolean simulateUnknownLength, @CacheDataSource.Flags int flags,
      CacheDataSink cacheWriteDataSink) {
    return createCacheDataSource(
        setReadException,
        simulateUnknownLength,
        flags,
        cacheWriteDataSink,
        /* cacheKeyFactory= */ null);
  }

  private CacheDataSource createCacheDataSource(
      boolean setReadException,
      boolean simulateUnknownLength,
      @CacheDataSource.Flags int flags,
      CacheDataSink cacheWriteDataSink,
      CacheKeyFactory cacheKeyFactory) {
    FakeDataSource upstream = new FakeDataSource();
    FakeData fakeData = upstream.getDataSet().newDefaultData()
        .setSimulateUnknownLength(simulateUnknownLength).appendReadData(TEST_DATA);
    if (setReadException) {
      fakeData.appendReadError(new IOException("Shouldn't read from upstream"));
    }
    return new CacheDataSource(
        cache,
        upstream,
        new FileDataSource(),
        cacheWriteDataSink,
        flags,
        /* eventListener= */ null,
        cacheKeyFactory);
  }

}


text:
tinysou-node
============

[![Build Status](https://travis-ci.org/tinysou/tinysou-node.svg?branch=master)](https://travis-ci.org/tinysou/tinysou-node)

Tinysou node client

### Installation

```npm install tinysou```

### Usage

```javascript
var Tinysou = require('tinysou')
var tinysou = new Tinysou('your_token')
```

#### Engine

List:

```javascript
tinysou.engines.list(function(err, res) {
  console.log(res);
});
```

Create:

```javascript
tinysou.engines.create({
  name: 'blog',
  display_name: 'Blog'
}, function(err, res) {
  console.log(res);
});
```

Get:

```javascript
tinysou.engines.get('blog', function(err, res) {
  console.log(res);
});
```

Update:

```javascript
tinysou.engines.update('blog', {
  display_name: 'My Blog'
}, function(err, res) {
  console.log(res);
});
```

Delete:

```javascript
tinysou.engines.delete('blog', function(err, res) {
  console.log(res);
});
```

#### Collection

List

```javascript
tinysou.collections.list('blog', function(err, res) {
  console.log(res);
});
```

Create

```javascript
tinysou.collections.create('blog', {
  name: 'posts',
  field_types: {
    title: 'string',
    tags: 'string',
    author: 'enum',
    date: 'date',
    body: 'text'
  }
}, function(err, res) {
  console.log(res);
});
```

Get

```javascript
tinysou.collections.get('blog', 'posts', function(err, rest) {
  console.log(res);
});
```

Delete

```javascript
tinysou.collections.delete('blog', 'posts', function(err, res) {
  console.log(res);
});
```

#### Document

List

```javascript
tinysou.documents.list('blog', 'posts', function(err, res) {
  console.log(res);
});
```

Create

```javascript
tinysou.documents.create('blog', 'posts', {
  title: 'My First Post',
  tags: ['news'],
  author: 'Author',
  date: '2014-08-16T00:00:00Z',
  body: 'Tinysou start online today!'
}, function(err, res) {
  console.log(res);
});
```

Get

```javascript
tinysou.documents.get('blog', 'posts', documentId, function(err, res) {
  console.log(res);
});
```

Update

```javascript
tinysou.documents.update('blog', 'posts', documentId, {
  title: 'My First Post',
  tags: ['news'],
  author: 'Author',
  date: '2014-08-16T00:00:00Z',
  body: 'Tinysou start online today!'
}, fucntion(err, res) {
  console.log(res);
});
```

Delete

```javascript
tinysou.documents.delete('blog', 'posts', documentId, function(err, res) {
  console.log(res);
});
```

#### Search

Search in collections

```javascript
tinysou.search('blog', {
  q: 'tinysou',
  c: 'posts'
  page: 0,
  per_parge: 10,
  filter: {
    range: {
      field: "date",
      from: "2014-07-01T00:00:00Z",
      to: "2014-08-01T00:00:00Z"
    }
  },
  sort:{
    field: "date",
    order: "asc",
    mode: "avg"
  }
}, function(err, res) {
  console.log(res);
});
```

#### Autocomplete

Autocomplete in collections

```javascript
tinysou.autocomplete('blog', {
  q: 'tinys',
  c: 'posts'
  page: 0,
  per_parge: 10,
  filter: {
    range: {
      field: "date",
      from: "2014-07-01T00:00:00Z",
      to: "2014-08-01T00:00:00Z"
    }
  },
  sort: {
    field: "date",
    order: "asc",
    mode: "avg"
  }
}, function(err, res) {
  console.log(res);
});
```

### Examples

See [examples](https://github.com/tinysou/tinysou-node/tree/master/examples)

## Contributing

1. Fork it ( https://github.com/tinysou/tinysou-node/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

redpajama_set_name: RedPajamaGithub


text:
@interface AdoptProfileViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *MainImage;
@property (weak, nonatomic) IBOutlet UILabel *Name;
@property (weak, nonatomic) IBOutlet UILabel *Address;
@property(weak, nonatomic) NSDictionary *Orphan;
@end


text:
define(function(require) {
    'use strict';

    var ColumnManagerFilterView;
    var _ = require('underscore');
    var BaseView = require('oroui/js/app/views/base/view');

    ColumnManagerFilterView = BaseView.extend({
        template: require('tpl!orodatagrid/templates/column-manager/column-manager-filter.html'),
        autoRender: true,
        events: {
            'keyup [data-role="column-manager-search"]': 'onSearch',
            'change [data-role="column-manager-search"]': 'onSearch',
            'paste [data-role="column-manager-search"]': 'onSearch',
            'click [data-role="column-manager-clear-search"]': 'onClearSearch',
            'click [data-role="column-manager-show-all"]': 'onShowAll',
            'click [data-role="column-manager-show-selected"]': 'onShowSelected'
        },

        listen: {
            'change model': 'updateView'
        },

        /**
         * @inheritDoc
         */
        initialize: function(options) {
            this.onSearch = _.debounce(this.onSearch, 100);
            ColumnManagerFilterView.__super__.initialize.apply(this, arguments);
        },

        updateView: function() {
            var search = this.model.get('search');
            var renderable = Boolean(this.model.get('renderable'));
            this.$('[data-role="column-manager-search"]').val(search);
            this.$('.column-manager-search').toggleClass('empty', search.length === 0);
            this.$('[data-role="column-manager-show-all"]').toggleClass('active', !renderable);
            this.$('[data-role="column-manager-show-selected"]').toggleClass('active', renderable);
        },

        onSearch: function(e) {
            this.model.set('search', e.currentTarget.value);
        },

        onClearSearch: function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.$('[data-role="column-manager-search"]').focus();
            this.model.set('search', '');
        },

        onShowAll: function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.model.set('renderable', false);
        },

        onShowSelected: function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.model.set('renderable', true);
        }
    });

    return ColumnManagerFilterView;
});


text:
package main

import (
  "io"
  "os"
  "fmt"
  "flag"
  "errors"
  "strings"
  "path/filepath"
)
var verbose bool

//walk through the directories and generate a list of absolute paths of all files.
func fileLister(dirPath string, fileListPtr *[]string) error {
  fileList := *fileListPtr
  curLocation := func(path string, locInfo os.FileInfo, err error) error {
    if err!=nil {
      return err
    }
    if !locInfo.IsDir() {
      fileList = append(fileList, path)
    }
    return err
  }
  err := filepath.Walk(dirPath, curLocation)
  *fileListPtr = fileList
  return err
}

// Check pre-requesited and initiate copy
func fileCopy(src, dest string) (err error) {
  srcFileInfo, err := os.Stat(src)
  if err==nil {
    if !srcFileInfo.Mode().IsRegular() {
      return fmt.Errorf("[COPY ERROR] %s is not a regular file, mode: (%q)", srcFileInfo.Name(), srcFileInfo.Mode().String())
    }
  } else {return}
  if _, err = os.Stat(dest); err==nil {
    return fmt.Errorf("[COPY ERROR] File %s already exists at %s, copy aborted.", src, filepath.Dir(dest))
  }
  err = doFileCopy(src, dest)
  return
}

//Actually copy file content to destination folder
func doFileCopy(src, dest string) (err error) {
  inFile, err := os.Open(src)
  if err!=nil {return}
  defer inFile.Close()

  outFile, err := os.Create(dest)
  if err!=nil {return}
  defer outFile.Close()

  if _, err = io.Copy(outFile, inFile); err!=nil {return}
  err = outFile.Sync()
  if verbose && err==nil {fmt.Println("[COPIED] ", src)}
  return
}

func flatten(dirPath string) (err error) {
  fileList := []string{}
  err = fileLister(dirPath, &fileList)
  if err!=nil {
    return
  }
  for _, aFileLoc := range fileList {
    _, aFileName := filepath.Split(aFileLoc)
    if filepath.Clean(filepath.Dir(aFileLoc))==dirPath {
      continue
    }
    cerr := fileCopy(aFileLoc, filepath.Clean(dirPath + string(os.PathSeparator) + aFileName))
    if cerr!=nil{
      existingErr := ""
      if err!=nil{
        existingErr = err.Error() + "\n"
      }
      err = errors.New(existingErr + cerr.Error())
    }
  }
  return
}

func main() {

  deleteDirsPtr := flag.Bool("delete", false, "Enables deletion of directories after flatten. Use cautiously.")
  verbosePtr := flag.Bool("verbose", false, "Verbose, duh!")
  flag.Parse()
  dirPath := strings.TrimSpace(flag.Arg(0))
  verbose = *verbosePtr

  cmdLineError := func(errMsg string) {
    fmt.Println("Error: " + errMsg)
    fmt.Println("Usage: flatten [-delete] [-verbose] <Directory to flatten>")
    os.Exit(1)
  }

  if dirPath == "" || len(flag.Args())>1 {
    cmdLineError("Invalid number of arguments.")
  }

  dirPath = filepath.Clean(dirPath)

  if dirPathInfo, err:= os.Stat(dirPath); err!=nil || !dirPathInfo.IsDir() {
    cmdLineError("Directory path provided is not a directory.")
  }
  fmt.Println("Copying files to base directory... ")
  err := flatten(dirPath)
  if err!=nil {
    fmt.Println(err)
  }
  fmt.Println("Done!")
  if *deleteDirsPtr {
    if err!=nil{
      fmt.Println("\nEncountered copy errors, review errors before proceeding with delete.")
    }
    var resp string
    fmt.Printf("\nDelete all sub-directories? (yes/NO)> ")
    _, err := fmt.Scanln(&resp)
    if err==nil && strings.ToLower(resp)=="yes" {
      fmt.Println("Deleting all sub-directories...")
      dirPathFD, _ := os.Open(dirPath)
      if err != nil {
        fmt.Println("[DELETE ERROR] Unable to open ", dirPath)
        os.Exit(1)
      }
      items, _ := dirPathFD.Readdirnames(0)
      for _, item := range items {
          itemPath := filepath.Clean(dirPath + string(os.PathSeparator) + item)
        if itemPathInfo, err:= os.Stat(itemPath); err==nil && itemPathInfo.IsDir() {
          err := os.RemoveAll(itemPath)
          if err!=nil {
            fmt.Println("[DELETE ERROR] Unable to detele ", itemPath)
          }
          if verbose && err==nil {fmt.Println("[DELETED] ", itemPath)}
        }
      }
      fmt.Println("Done!")
    } else{
      fmt.Println("Skipping delete.")
    }
  }
}


text:
package org.jetbrains.plugins.scala.lang.psi.impl.toplevel
package typedef

import com.intellij.lang.ASTNode
import com.intellij.openapi.progress.{ProcessCanceledException, ProgressManager}
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.tree.IElementType
import com.intellij.psi.{PsiElement, PsiNamedElement, ResolveState}
import org.jetbrains.plugins.scala.caches.ModTracker
import org.jetbrains.plugins.scala.extensions.{Model, ObjectExt, StringsExt}
import org.jetbrains.plugins.scala.icons.Icons
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenType
import org.jetbrains.plugins.scala.lang.parser.ScalaElementType.PARAM_CLAUSES
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.{ScParameter, ScParameters}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScNamedElement
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScGivenDefinition, ScMember}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.ScalaPsiElementCreationException
import org.jetbrains.plugins.scala.lang.psi.impl.base.ScNamedBeginImpl
import org.jetbrains.plugins.scala.lang.psi.stubs.ScTemplateDefinitionStub
import org.jetbrains.plugins.scala.lang.psi.stubs.elements.ScTemplateDefinitionElementType
import org.jetbrains.plugins.scala.macroAnnotations.{Cached, CachedInUserData}

import javax.swing.Icon

class ScGivenDefinitionImpl(
  stub:      ScTemplateDefinitionStub[ScGivenDefinition],
  nodeType:  ScTemplateDefinitionElementType[ScGivenDefinition],
  node:      ASTNode,
  debugName: String
) extends ScTypeDefinitionImpl(stub, nodeType, node, debugName)
    with ScGivenImpl
    with ScGivenDefinition
    with ScNamedBeginImpl {

  override protected def baseIcon: Icon = Icons.CLASS // todo: better icon ?

  override protected def targetTokenType: ScalaTokenType = ScalaTokenType.GivenKeyword

  override def declaredElements: Seq[PsiNamedElement] = Seq(this)

  override def isObject: Boolean = typeParametersClause.isEmpty && parameters.isEmpty

  override def nameId: PsiElement = nameElement.getOrElse(extendsBlock)

  override def nameInner: String = {
    val explicitName = nameElement.map(_.getText)
    val typeElements = extendsBlock.templateParents.toSeq.flatMap(_.typeElements)

    explicitName
      .getOrElse(ScalaPsiUtil.generateGivenOrExtensionName(typeElements: _*))
  }

  @Cached(ModTracker.anyScalaPsiChange, this)
  override def clauses: Option[ScParameters] =
    getStubOrPsiChild(PARAM_CLAUSES).toOption

  override def parameters: Seq[ScParameter] =
    clauses.fold(Seq.empty[ScParameter])(_.params)

  @CachedInUserData(this, ModTracker.libraryAware(this))
  override def desugaredDefinitions: Seq[ScMember] =
    try {
      val supersText = extendsBlock.templateParents.fold("")(_.supersText)

      if (isObject) {
        val text = s"implicit object $name extends $supersText"
        val obj  = ScalaPsiElementFactory.createTypeDefinitionWithContext(text, this.getContext, this)
        obj.originalGivenElement       = this
        obj.syntheticNavigationElement = this
        Seq(obj)
      } else {
        val typeParametersDeclText = typeParametersClause.fold("")(_.getTextByStub)

        val typeParametersText =
          if (typeParameters.isEmpty) ""
          else                        typeParameters.map(_.name).commaSeparated(Model.SquareBrackets)

        val parametersText = clauses.fold("")(_.getText)

        val clsText            = s"class $name$typeParametersDeclText$parametersText extends $supersText"
        val implicitMethodText = s"implicit def $name$typeParametersDeclText$parametersText: $name$typeParametersText = ???"

        val cls = ScalaPsiElementFactory.createTypeDefinitionWithContext(clsText, this.getContext, this)
        cls.originalGivenElement       = this
        cls.syntheticNavigationElement = this

        val implicitMethod = ScalaPsiElementFactory.createDefinitionWithContext(implicitMethodText, this.getContext, this)
        implicitMethod.originalGivenElement       = this
        implicitMethod.syntheticNavigationElement = this

        Seq(cls, implicitMethod)
      }
    } catch {
      case p: ProcessCanceledException         => throw p
      case _: ScalaPsiElementCreationException => Seq.empty
    }

  override def processDeclarations(
    processor:  PsiScopeProcessor,
    state:      ResolveState,
    lastParent: PsiElement,
    place:      PsiElement
  ): Boolean = {
    for {
      clause <- effectiveParameterClauses
      param  <- clause.effectiveParameters
    } {
      ProgressManager.checkCanceled()
      if (!processor.execute(param, state)) return false
    }

    super.processDeclarations(processor, state, lastParent, place)
  }

  override protected def keywordTokenType: IElementType = ScalaTokenType.GivenKeyword

  // TODO Why ScGiven is a subtype of ScNamedElement it there might be no name?
  override def namedTag: Option[ScNamedElement] = if (nameElement.isDefined) Some(this) else None

  override protected def endParent: Option[PsiElement] = extendsBlock.templateBody
}


text:
<?php

namespace NetSuite\Classes;

class BaseRef {
    public $name;
    static $paramtypesmap = array(
        "name" => "string",
    );
}


text:
package org.apache.streams.twitter.provider;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import org.apache.streams.core.StreamsDatum;
import org.apache.streams.jackson.StreamsJacksonMapper;
import org.apache.streams.twitter.pojo.Follow;
import org.apache.streams.twitter.pojo.User;
import org.apache.streams.util.ComponentUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.PagableResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterObjectFactory;

import java.io.IOException;

/**
 *  Retrieve recent posts for a single user id.
 */
public class TwitterFollowingProviderTask implements Runnable {

    private final static Logger LOGGER = LoggerFactory.getLogger(TwitterFollowingProviderTask.class);

    private final static ObjectMapper mapper = StreamsJacksonMapper.getInstance();

    protected TwitterFollowingProvider provider;
    protected Twitter client;
    protected Long id;
    protected String screenName;
    protected String endpoint;

    private int max_per_page = 200;

    public TwitterFollowingProviderTask(TwitterFollowingProvider provider, Twitter twitter, Long id, String endpoint) {
        this.provider = provider;
        this.client = twitter;
        this.id = id;
        this.endpoint = endpoint;
    }

    public TwitterFollowingProviderTask(TwitterFollowingProvider provider, Twitter twitter, String screenName, String endpoint) {
        this.provider = provider;
        this.client = twitter;
        this.screenName = screenName;
        this.endpoint = endpoint;
    }

    @Override
    public void run() {

        Preconditions.checkArgument(id != null || screenName != null);

        if( id != null )
            getFollowing(id);
        else if( screenName != null)
            getFollowing(screenName);

        LOGGER.info(id != null ? id.toString() : screenName + " Thread Finished");

    }

    protected void getFollowing(Long id) {

        Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers"));

        int keepTrying = 0;

        long curser = -1;

        do
        {
            try
            {
                twitter4j.User followee4j;
                String followeeJson;
                try {
                    followee4j = client.users().showUser(id);
                    followeeJson = TwitterObjectFactory.getRawJSON(followee4j);
                } catch (TwitterException e) {
                    LOGGER.error("Failure looking up " + id);
                    break;
                }

                PagableResponseList<twitter4j.User> list = null;
                if( endpoint.equals("followers") )
                    list = client.friendsFollowers().getFollowersList(id.longValue(), curser, max_per_page);
                else if( endpoint.equals("friends") )
                    list = client.friendsFollowers().getFriendsList(id.longValue(), curser, max_per_page);

                Preconditions.checkNotNull(list);
                Preconditions.checkArgument(list.size() > 0);

                for (twitter4j.User follower4j : list) {

                    String followerJson = TwitterObjectFactory.getRawJSON(follower4j);

                    try {
                        Follow follow = new Follow()
                                .withFollowee(mapper.readValue(followeeJson, User.class))
                                .withFollower(mapper.readValue(followerJson, User.class));

                        ComponentUtils.offerUntilSuccess(new StreamsDatum(follow), provider.providerQueue);
                    } catch (JsonParseException e) {
                        LOGGER.warn(e.getMessage());
                    } catch (JsonMappingException e) {
                        LOGGER.warn(e.getMessage());
                    } catch (IOException e) {
                        LOGGER.warn(e.getMessage());
                    }
                }
                if( list.size() == max_per_page )
                    curser = list.getNextCursor();
                else break;
            }
            catch(TwitterException twitterException) {
                keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException);
            }
            catch(Exception e) {
                keepTrying += TwitterErrorHandler.handleTwitterError(client, e);
            }
        } while (curser != 0 && keepTrying < 10);
    }

    protected void getFollowing(String screenName) {

        twitter4j.User user = null;
        try {
            user = client.users().showUser(screenName);
        } catch (TwitterException e) {
            LOGGER.error("Failure looking up " + id);
        }
        Preconditions.checkNotNull(user);
        getFollowing(user.getId());
    }

}


text:
import { combineReducers } from "redux";
import routeReducer from "./route/route_reducer";

export interface StateType {
    route : string;
}

const reducer = combineReducers({
    route: routeReducer
});

export default reducer;


text:
package org.seasar.doma.internal.apt.dao;

import java.util.List;

import org.seasar.doma.Dao;
import org.seasar.doma.Select;
import org.seasar.doma.internal.apt.entity.Emp;

/**
 * @author taedium
 *
 */
@Dao(config = MyConfig.class)
public interface ElementOfParamListWildcardTypeDao {

    @Select
    List<Emp> select(List<?> param);
}


text:
<?php

error_reporting(E_ALL | E_STRICT);

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
define('APPLICATION_ENV', 'testing');

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path()
)));

/** Zend_Application */
require_once 'Zend/Application.php';
/** Zend_Controller_Test_Case */
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
/** Include Helper Class */
require_once 'Helpers.php';
/** Parent test case classes */
require_once 'ModelTestCase.php';
require_once 'ControllerTestCase.php';
require_once 'AbstractManagerBase.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

clearstatcache();


text:
<!doctype html>

	<meta charset="UTF-8">

<form action="/shohousen" method="POST" id="form">
	<input type="hidden" name="json-data" id="data" />
</form>


text:
using System;
using System.IO;
using System.Collections;
using System.Diagnostics;

namespace SpiffLib {
	public class PdbPacker {
		static int s_cbRecordMax = 32000;
		static int s_cbFilenameMax = 29;
		ArrayList m_alsFiles = new ArrayList();

		public class File {
			public string str;
			public byte[] ab;
			public bool fCompress;
			int m_cbCompressed;

			public File() {
			}

			public File(string strT, byte[] abT, bool fCompressT, int cbCompressed) {
				str = strT;
				ab = abT;
				fCompress = fCompressT;
				m_cbCompressed = cbCompressed;
			}

			public File(string strT, byte[] abT, bool fCompressT) {
				str = strT;
				ab = abT;
				fCompress = fCompressT;
			}

			public File(string strT, byte[] abT) {
				str = strT;
				ab = abT;
				fCompress = true;
			}

			public int GetCompressedSize() {
				return m_cbCompressed;
			}
		}

		public PdbPacker() {
		}

		public PdbPacker(string strFile) {
			Load(strFile);
		}

		public int Count {
			get {
				return m_alsFiles.Count;
			}
		}

		public void Add(File file) {
			m_alsFiles.Add(file);
		}

		public File this[string strFile] {
			get {
				foreach (File file in m_alsFiles) {
					if (file.str.ToLower() == strFile.ToLower())
						return file;
				}
				return null;
			}
		}

		public File this[int iFile] {
			get {
				return (File)m_alsFiles[iFile];
			}
		}

		struct DirEntry {
			public string strFile;
			public byte crec;
			public ushort irec;
		};

		public void Load(string strFile) {
			// Open palm database

			PalmDatabase pdb = new PalmDatabase();
			pdb.Load(strFile);

			// Load directory entries

			ArrayList alsRecordData = pdb.GetRecordData();
			CompressionHeader coh;
			DirEntry[] ade = ParseDirectoryRecord(UnpackRecord((byte[])alsRecordData[0], out coh));

			// Read in the file data

			m_alsFiles.Clear();
			foreach (DirEntry de in ade) {
				// Decompress and write out bytes

				ArrayList alsFileBytes = new ArrayList();
				for (int i = 0; i < de.crec; i++) {
					byte[] ab = UnpackRecord((byte[])alsRecordData[i + de.irec], out coh);
					alsFileBytes.AddRange(ab);
				}

				File file = new File(de.strFile, (byte[])alsFileBytes.ToArray(typeof(byte)), coh.fCompressed, coh.cbCompressed);
				m_alsFiles.Add(file);
			}
		}

		// Straight ascii order comparer, since at runtime we use a strcmp based binary search

		public class FilenameComparer : IComparer {
			public int Compare(object objA, object objB) {
				string strA = (string)objA;
				string strB = (string)objB;
				int cch = Math.Min(strA.Length, strB.Length);
				for (int ich = 0; ich < cch; ich++) {
					if (strA[ich] < strB[ich])
						return -1;
					if (strA[ich] > strB[ich])
						return 1;
				}

				if (strA.Length < strB.Length)
					return -1;
				if (strA.Length > strB.Length)
					return 1;

				return 0;
			}
		}

		public void Save(string strFilePdb, string strCreatorId, string strTypeId) {
			// First sort all the files by name

			string[] astrFileNames = new string[m_alsFiles.Count];
			for (int iFile = 0; iFile < m_alsFiles.Count; iFile++) {
				File file = (File)m_alsFiles[iFile];
				astrFileNames[iFile] = file.str.ToLower();
			}
			File[] afile = (File[])m_alsFiles.ToArray(typeof(File));
			Array.Sort(astrFileNames, afile, new FilenameComparer());

			// Create the record bytes

			ArrayList alsDirEntries = new ArrayList();
			ArrayList alsRecords = new ArrayList();
			ushort irec = 1;
			foreach (File file in afile) {
				// Get filename only, check length

				string strFile = file.str.ToLower();
				if (strFile.Length >= s_cbFilenameMax)
					throw new Exception("The file " + strFile + " is too long. Must be " + (s_cbFilenameMax - 1) + "chars max.");

				// Read the file into chunks

				BinaryReader brdr = new BinaryReader(new MemoryStream(file.ab));
				byte crec = 0;
				while (brdr.BaseStream.Position < brdr.BaseStream.Length) {
					int cbLeft = (int)(brdr.BaseStream.Length - brdr.BaseStream.Position);
					int cbRead = cbLeft < s_cbRecordMax ? cbLeft : s_cbRecordMax;
					byte[] abChunk = brdr.ReadBytes(cbRead);
					alsRecords.Add(PackRecord(abChunk, file.fCompress));
					crec++;
				}
				brdr.Close();

				// Make a directory entry for this file

				DirEntry de = new DirEntry();
				de.strFile = strFile;
				de.irec = irec;
				de.crec = crec;
				alsDirEntries.Add(de);
				irec += de.crec;

#if false
				Console.WriteLine(de.strFile + ", " + de.crec + " recs");
#endif
			}

			// Insert the record for the directory entries

			alsRecords.Insert(0, PackRecord(MakeDirectoryRecord(alsDirEntries), false));

			// Create and save a .pdb around these records

			PalmDatabase pdb = new PalmDatabase();
			pdb.SetRecordData(alsRecords);
			pdb.Name = Path.GetFileName(Path.GetFullPath(strFilePdb));
			pdb.CreatorId = IdFromString(strCreatorId);
			pdb.TypeId = IdFromString(strTypeId);
			pdb.Save(strFilePdb);
		}

		static byte[] PackRecord(byte[] abChunk, bool fCompress) {
			ArrayList alsRecordBytes = new ArrayList();
			byte[] abCompressed = null;
			if (fCompress) {
				abCompressed = Compressor.CompressChunk(abChunk);
				if (abCompressed.Length >= abChunk.Length)
					abCompressed = null;
			}
			if (abCompressed != null) {
				alsRecordBytes.Add((byte)0);
				alsRecordBytes.Add((byte)1);
				alsRecordBytes.Add((byte)((abChunk.Length >> 8) & 0xff));
				alsRecordBytes.Add((byte)(abChunk.Length & 0xff));
				alsRecordBytes.Add((byte)((abCompressed.Length >> 8) & 0xff));
				alsRecordBytes.Add((byte)(abCompressed.Length & 0xff));
				alsRecordBytes.AddRange(abCompressed);
			} else {
				alsRecordBytes.Add((byte)0);
				alsRecordBytes.Add((byte)0);
				alsRecordBytes.Add((byte)((abChunk.Length >> 8) & 0xff));
				alsRecordBytes.Add((byte)(abChunk.Length & 0xff));
				alsRecordBytes.Add((byte)((abChunk.Length >> 8) & 0xff));
				alsRecordBytes.Add((byte)(abChunk.Length & 0xff));
				alsRecordBytes.AddRange(abChunk);
			}
			return (byte[])alsRecordBytes.ToArray(typeof(byte));
		}

		struct CompressionHeader {
			public bool fCompressed;
			public ushort cbUncompressed;
			public ushort cbCompressed;
		}

		static byte[] UnpackRecord(byte[] ab, out CompressionHeader coh) {
			coh.fCompressed = (ab[1] == 1);
			coh.cbUncompressed = (ushort)((ab[2] << 8) + ab[3]);
			coh.cbCompressed = (ushort)((ab[4] << 8) + ab[5]);

			byte[] abT = new byte[ab.Length - 6];
			Array.Copy(ab, 6, abT, 0, abT.Length);
			if (coh.fCompressed) {
				ab = Compressor.DecompressChunk(abT);
			} else {
				ab = abT;
			}

			return ab;
		}

		static uint IdFromString(string str) {
			str.PadLeft(4, ' ');
			uint ui = 0;
			for (int i = 0; i < 4; i++) {
				ui <<= 8;
				ui |= (uint)str[i];
			}
			return ui;
		}

		static byte[] MakeDirectoryRecord(ArrayList alsDirEntries) {
			// Each entry is 32 bytes. Serialize into a byte array.
			//
			// struct DirEntry {
			//	char szFn[kcbFilename];
			//	byte crec;
			//	word irec;
			// };

			ArrayList alsPdbDirEntries = new ArrayList();
			foreach (DirEntry de in alsDirEntries) {
				byte[] abFilename = new byte[s_cbFilenameMax];
				for (int ich = 0; ich < de.strFile.Length; ich++)
					abFilename[ich] = (byte)de.strFile[ich];
				alsPdbDirEntries.AddRange(abFilename);
				alsPdbDirEntries.Add((byte)de.crec);
				alsPdbDirEntries.Add((byte)((de.irec >> 8) & 0xff));
				alsPdbDirEntries.Add((byte)(de.irec & 0xff));
			}
			return (byte[])alsPdbDirEntries.ToArray(typeof(byte));
		}

		static DirEntry[] ParseDirectoryRecord(byte[] ab) {
			ArrayList alsPdbDirEntries = new ArrayList();
			for (int ib = 0; ib < ab.Length; ib += 32) {
				DirEntry de;
				de.strFile = "";
				for (int ich = 0; ich < s_cbFilenameMax; ich++) {
					char ch = (char)ab[ib + ich];
					if (ch == 0)
						break;
					de.strFile += ch;
				}
				de.crec = (byte)ab[ib + s_cbFilenameMax];
				de.irec = (ushort)((ab[ib + s_cbFilenameMax + 1] << 8) + ab[ib + s_cbFilenameMax + 2]);
				alsPdbDirEntries.Add(de);
			}
			return (DirEntry[])alsPdbDirEntries.ToArray(typeof(DirEntry));
		}

		public static void MergePdbs(PalmDatabase pdb, PalmDatabase [] apdb)
		{
			// Create directory entry.

			int irec = pdb.Count + 1; // plus one for directory

			ArrayList alsPdbDirEntries = new ArrayList();
			for (int ipdb = 0; ipdb < apdb.Length; ipdb++) {

				byte [] abFilename = new byte[28];
				for (int ich = 0; ich < apdb[ipdb].Name.Length; ich++)
					abFilename[ich] = (byte)apdb[ipdb].Name[ich];

				alsPdbDirEntries.AddRange(abFilename);
				alsPdbDirEntries.Add((byte)((irec >> 8) & 0xff));
				alsPdbDirEntries.Add((byte)(irec & 0xff));
				alsPdbDirEntries.Add((byte)((apdb[ipdb].Count >> 8) & 0xff));
				alsPdbDirEntries.Add((byte)(apdb[ipdb].Count & 0xff));

				irec += apdb[ipdb].Count;
			}

			alsPdbDirEntries.Add((byte)0); // end of directory marker

			uint uiType = 0x5041434b; // PACK

			irec = 0;
			pdb.Add((byte[])alsPdbDirEntries.ToArray(typeof(byte)), (ushort)irec, uiType);

			for (int ipdb = 0; ipdb < apdb.Length; ipdb++) {
				for (int irecAdd = 0; irecAdd < apdb[ipdb].Count; irecAdd++) {
					irec += 1;
					pdb.Add(apdb[ipdb][irecAdd].Data, (ushort)irec, uiType);
				}
			}
		}
	}
}


text:
<?php

namespace Omnipay\Fatzebra;

use Omnipay\Tests\GatewayTestCase;
use Omnipay\Common\CreditCard;

class GatewayTest extends GatewayTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->gateway = new FatzebraGateway($this->getHttpClient(), $this->getHttpRequest());

        $this->card = new CreditCard(array(
            'firstName' => 'Example',
            'lastName' => 'User',
            'number' => '4111111111111111',
            'expiryMonth' => '12',
            'expiryYear' => '2020',
            'cvv' => '123',
        ));
        $this->options = array(
            'amount' => '10.00',
            'transactionId' => '123412341234',
            'card' => $this->card,
        );
    }

    public function testPurchase()
    {
        $this->setMockHttpResponse('PurchaseSuccess.txt');

        $response = $this->gateway->purchase($this->options)->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-P-S2Y05UQ9', $response->getTransactionReference());
        $this->assertEquals('Approved', $response->getMessage());
    }

    public function testFetchTransaction()
    {
        $request = $this->gateway->fetchTransaction(array('transactionReference' => '525-P-S2Y05UQ9'));

        $this->assertInstanceOf('\Omnipay\Fatzebra\Message\FetchTransactionRequest', $request);
        $this->assertSame('525-P-S2Y05UQ9', $request->getTransactionReference());
    }

    public function testRefund()
    {
        $this->setMockHttpResponse('RefundSuccess.txt');

        $response = $this->gateway->refund(array(
            'transactionReference'  => "525-P-S2Y05UQ9",
            'amount'                => 10.00,
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-R-XIVU3L9U', $response->getTransactionReference());
        $this->assertEquals('Approved', $response->getMessage());
    }

    public function testCreateCard()
    {
        $this->setMockHttpResponse('CreateCardSuccess.txt');

        $response = $this->gateway->createCard(array(
            'card'      => $this->card,
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('hmx8o839', $response->getTransactionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testCreatePlan()
    {
        $this->setMockHttpResponse('CreatePlanSuccess.txt');

        $response = $this->gateway->createPlan(array(
            "name"                  => "Gold Membership",
            "amount"                => 100.00,
            "transactionReference"  => "Gold-1",
            "description"           => "Gold level membership",
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-PL-IN37ICBK', $response->getTransactionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testFetchAllPlans()
    {
        $this->setMockHttpResponse('FetchAllPlansSuccess.txt');

        $response = $this->gateway->fetchAllPlans()->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEmpty($response->getMessage());
    }

    public function testFetchPlan()
    {
        $this->setMockHttpResponse('FetchPlanSuccess.txt');

        $response = $this->gateway->fetchPlan(array(
           'transactionReference'  => '525-PL-IN37ICBK',
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-PL-IN37ICBK', $response->getTransactionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testCreateCustomer()
    {
        $this->setMockHttpResponse('CreateCustomerSuccess.txt');

        // Create a credit card object
        // This card can be used for testing.
        $card = new CreditCard(array(
                    'firstName'             => 'Example',
                    'lastName'              => 'Customer',
                    'number'                => '4005550000000001',
                    'expiryMonth'           => '05',
                    'expiryYear'            => '2020',
                    'cvv'                   => '987',
                    'billingAddress1'       => '1 Lower Creek Road',
                    'billingCountry'        => 'AU',
                    'billingCity'           => 'Scrubby Creek',
                    'billingPostcode'       => '4999',
                    'billingState'          => 'QLD',
                    'email'                 => 'testcust@example.com',
        ));

        // Do a create customer transaction on the gateway
        $response = $this->gateway->createCustomer(array(
            'transactionReference'     => 'TestCust1234',
            'clientIp'                 => '127.0.0.1',
            'card'                     => $card,
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-C-G1ZKF1Y3', $response->getCustomerReference());
        $this->assertEquals('daers4x6', $response->getCardReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testFetchCustomer()
    {
        $this->setMockHttpResponse('FetchCustomerSuccess.txt');

        $response = $this->gateway->fetchCustomer(array(
           'transactionReference'  => '525-C-G1ZKF1Y3',
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-C-G1ZKF1Y3', $response->getTransactionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testCreateSubscription()
    {
        $this->setMockHttpResponse('CreateSubscriptionSuccess.txt');

        $gateway = $this->gateway;

        $response = $this->gateway->createSubscription(array(
            'customerReference'            => '525-C-G1ZKF1Y3',
            'planReference'                => '525-PL-IN37ICBK',
            'frequency'                => $gateway::FREQUENCY_WEEKLY,
            'startDate'                => new \DateTime('tomorrow'),
            'transactionReference'     => 'TestSubscription123456',
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-PL-HT6AMO6J', $response->getPlanReference());
        $this->assertEquals('525-S-DYVABJ3L', $response->getSubscriptionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testDeleteCustomer()
    {
        $this->setMockHttpResponse('DeleteCustomerSuccess.txt');

        $response = $this->gateway->deleteCustomer(array(
           'transactionReference'  => '525-C-G1ZKF1Y3',
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-C-G1ZKF1Y3', $response->getTransactionReference());
        $this->assertEmpty($response->getMessage());
    }

    public function testFetchSubscription()
    {
        $this->setMockHttpResponse('FetchSubscriptionSuccess.txt');

        $response = $this->gateway->fetchSubscription(array(
           'transactionReference'  => '525-S-UQZHEXAT',
        ))->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('525-S-UQZHEXAT', $response->getSubscriptionReference());
        $this->assertEquals('525-PL-HT6AMO6J', $response->getPlanReference());
        $this->assertEquals('525-C-6CSDKGME', $response->getCustomerReference());
        $this->assertEmpty($response->getMessage());
    }
}


text:
package org.onosproject.drivers.gnmi;

import io.grpc.StatusRuntimeException;
import org.onosproject.gnmi.api.GnmiClient;
import org.onosproject.gnmi.api.GnmiClientKey;
import org.onosproject.gnmi.api.GnmiController;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Abstract implementation of a behaviour handler for a gNMI device.
 */
public class AbstractGnmiHandlerBehaviour extends AbstractHandlerBehaviour {

    // Default timeout in seconds for device operations.
    private static final String DEVICE_REQ_TIMEOUT = "deviceRequestTimeout";
    private static final int DEFAULT_DEVICE_REQ_TIMEOUT = 60;

    private static final String GNMI_SERVER_ADDR_KEY = "gnmi_ip";
    private static final String GNMI_SERVER_PORT_KEY = "gnmi_port";

    protected final Logger log = LoggerFactory.getLogger(getClass());
    protected DeviceId deviceId;
    protected DeviceService deviceService;
    protected Device device;
    protected GnmiController controller;
    protected GnmiClient client;

    protected boolean setupBehaviour() {
        deviceId = handler().data().deviceId();
        deviceService = handler().get(DeviceService.class);
        controller = handler().get(GnmiController.class);
        client = controller.getClient(deviceId);

        if (client == null) {
            log.warn("Unable to find client for {}, aborting operation", deviceId);
            return false;
        }

        return true;
    }

    GnmiClient createClient() {
        deviceId = handler().data().deviceId();
        controller = handler().get(GnmiController.class);

        final String serverAddr = this.data().value(GNMI_SERVER_ADDR_KEY);
        final String serverPortString = this.data().value(GNMI_SERVER_PORT_KEY);

        if (serverAddr == null || serverPortString == null) {
            log.warn("Unable to create client for {}, missing driver data key (required is {} and {})",
                    deviceId, GNMI_SERVER_ADDR_KEY, GNMI_SERVER_PORT_KEY);
            return null;
        }

        final int serverPort;
        try {
            serverPort = Integer.parseUnsignedInt(serverPortString);
        } catch (NumberFormatException e) {
            log.error("{} is not a valid port number", serverPortString);
            return null;
        }
        GnmiClientKey clientKey = new GnmiClientKey(deviceId, serverAddr, serverPort);
        if (!controller.createClient(clientKey)) {
            log.warn("Unable to create client for {}, aborting operation", deviceId);
            return null;
        }
        return controller.getClient(deviceId);
    }

    /**
     * Returns the device request timeout driver property, or a default value
     * if the property is not present or cannot be parsed.
     *
     * @return timeout value
     */
    private int getDeviceRequestTimeout() {
        final String timeout = handler().driver()
                .getProperty(DEVICE_REQ_TIMEOUT);
        if (timeout == null) {
            return DEFAULT_DEVICE_REQ_TIMEOUT;
        } else {
            try {
                return Integer.parseInt(timeout);
            } catch (NumberFormatException e) {
                log.error("{} driver property '{}' is not a number, using default value {}",
                        DEVICE_REQ_TIMEOUT, timeout, DEFAULT_DEVICE_REQ_TIMEOUT);
                return DEFAULT_DEVICE_REQ_TIMEOUT;
            }
        }
    }

    /**
     * Convenience method to get the result of a completable future while
     * setting a timeout and checking for exceptions.
     *
     * @param future        completable future
     * @param opDescription operation description to use in log messages. Should
     *                      be a sentence starting with a verb ending in -ing,
     *                      e.g. "reading...", "writing...", etc.
     * @param defaultValue  value to return if operation fails
     * @param <U>           type of returned value
     * @return future result or default value
     */
    <U> U getFutureWithDeadline(CompletableFuture<U> future, String opDescription,
                                U defaultValue) {
        try {
            return future.get(getDeviceRequestTimeout(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("Exception while {} on {}", opDescription, deviceId);
        } catch (ExecutionException e) {
            final Throwable cause = e.getCause();
            if (cause instanceof StatusRuntimeException) {
                final StatusRuntimeException grpcError = (StatusRuntimeException) cause;
                log.warn("Error while {} on {}: {}", opDescription, deviceId, grpcError.getMessage());
            } else {
                log.error("Exception while {} on {}", opDescription, deviceId, e.getCause());
            }
        } catch (TimeoutException e) {
            log.error("Operation TIMEOUT while {} on {}", opDescription, deviceId);
        }
        return defaultValue;
    }
}


text:
[![Build Status](https://travis-ci.org/frbk/frbk.github.io.svg)](https://travis-ci.org/frbk/frbk.github.io)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/b401d2cced3c42f9b1b656db47710217)](https://www.codacy.com/app/frbk/frbk-github-io?utm_source=github.com&utm_medium=referral&utm_content=frbk/frbk.github.io&utm_campaign=Badge_Grade)

So far I post about stuff I care. In the future I am planing to make it into portfolio website.

## License

The following directories and their contents are Copyright Fedor Barannik. You may not reuse anything therein without my permission:

```
_posts/
assets/img/
```

All other directories and files are MIT Licensed (where applicable).


text:
import * as React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'

import { Resolver } from 'react-resolver'

import * as Koa from 'koa'

import { debug } from '../lib/logging'

import { getAlice } from '../components'
import { Container } from '../components/Router'

const match = (url: string) => url === '/'

export const createRouter = (): Koa.Middleware => async (ctx, next) => {
  const { url }: Koa.Context & { cookie: any } = (ctx as any)

  debug('url:', url)
  if (match(url)) {
    const Alice = await getAlice(React, ctx.state.auth)

    if (Alice) {
      await Resolver.resolve(
        () => <Alice/>
      )
      .then(
        ({ Resolved, data }: any): any => {
          const toRenderStatic = (
            <Container data={data}>
              <div
                id="Alice"
                dangerouslySetInnerHTML={{ __html: renderToString(<Resolved/>) }}
              />
            </Container>
          )

          const body = toRenderStatic && renderToStaticMarkup(toRenderStatic)

          if (body) {
            ctx.body = body
          }
        }
      )
    }
  } else {
    await next()
  }
}


text:
<?php

namespace Gremio\AbmBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Gremio\AbmBundle\Entity\Baja;
use Gremio\AbmBundle\Entity\TipoSocio;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Gremio\AbmBundle\Entity\Socio
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Table(name="socio")
 * @ORM\Entity(repositoryClass="Gremio\AbmBundle\Entity\SocioRepository")
 */
class Socio implements UserInterface, \Serializable
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var bigint $Legajo
     *
     * @ORM\Column(name="Legajo", type="bigint",unique="true")
     */
    protected $Legajo;

    /**
     * @var bigint $Num_Documento
     *
     * @ORM\Column(name="Num_Documento", type="string")
     */
    protected $Num_Documento;

    /**
     * @var bigint $Cuit
     *
     * @ORM\Column(name="Cuit", type="string", nullable="true")
     */
    protected $Cuit;

    /**
     * @var string $Apellido
     * @ORM\Column(name="Apellido", type="string")
     */
    protected $Apellido;

    /**
     * @var string $Nombres
     *
     * @ORM\Column(name="Nombres", type="string")
     */
    protected $Nombres;

    /**
     * @var string $Domicilio
     *
     * @ORM\Column(name="Domicilio_Laboral", type="string")
     */
    protected $Domicilio_Laboral;

    /**
     * @var string $Telefono
     *
     * @ORM\Column(name="Telefono_Laboral", type="string", nullable="true")
     */
    protected $Telefono_Laboral;

    /**
     * @var integer $Numero_Mesa
     *
     * @ORM\Column(name="Numero_Mesa", type="integer", nullable="true")
     */
    protected $Numero_Mesa;

    /**
     * @var datetime $Ingreso_Justicia
     *
     * @ORM\Column(name="Ingreso_Justicia", type="datetime", nullable="true")
     */
    protected $Ingreso_Justicia;

    /**
     * @var bigint $Cbu
     *
     * @ORM\Column(name="Cbu", type="string", nullable="true")
     */
    protected $Cbu;

    /**
     * @var string $Domicilio_Particular
     *
     * @ORM\Column(name="Domicilio_Particular", type="string", nullable="true")
     */
    protected $Domicilio_Particular;

    /**
     * @var string $Telefono_Particular
     *
     * @ORM\Column(name="Telefono_Particular", type="string")
     */
    protected $Telefono_Particular;

    /**
     * @var string $Email
     *
     * @ORM\Column(name="Email", type="string", length=30, nullable="false", unique="true")
     */
    protected $Email;

    /**
     * @var datetime $Fecha_Nacimiento
     *
     * @ORM\Column(name="Fecha_Nacimiento", type="datetime", nullable="true")
     */
    protected $Fecha_Nacimiento;

    /**
     *
     *
     * @ORM\Column(name="margen", type="integer")
     */
    protected $margen;

    /**
     * @ORM\ManyToOne(targetEntity="TipoSocio")
     * @ORM\JoinColumn(name="tipo_socio_id", referencedColumnName="id")
     */

    protected $tipo_socio;

    /**
     * @ORM\ManyToOne(targetEntity="Seccion")
     * @ORM\JoinColumn(name="seccion_id", referencedColumnName="id")
     */

    protected $seccion;

    /**
     * @ORM\ManyToOne(targetEntity="Reparticion")
     * @ORM\JoinColumn(name="reparticion_id", referencedColumnName="id")
     */
    protected $reparticion;

    /**
     * @ORM\ManyToOne(targetEntity="Localidad", inversedBy="socios")
     * @ORM\JoinColumn(name="localidad_id", referencedColumnName="id")
     */

    protected $localidad;

    /**
     *
     *
     * @ORM\Column(name="sexo", type="string")
     */
    protected $sexo;

    /**
     * @ORM\OneToMany(targetEntity="Gremio\SociosBundle\Entity\Emision", mappedBy="socio")
     *
     */
    protected $emisiones;

    /**
     * @ORM\OneToMany(targetEntity="Baja", mappedBy="socio")
     *
     */
    protected $bajas;

    /* #####################################################
     * Propiedades Relacionadas con la Auditoria del Sistema
     * #####################################################
     */

    /**
     * @ORM\Column(type="string", length="50", nullable="true")
     *
     */

    protected $user_last_modif;

    public function setUserLastModif($user_last_modif)
    {
        $this->user_last_modif = $user_last_modif;
    }

    public function getUserLastModif()
    {
        return $this->user_last_modif;
    }

    /**
     * @ORM\Column(type="datetime", nullable="true")
     *
     */

    protected $last_modif_date;

    public function setLastModifDate($last_modif_date)
    {
        $this->last_modif_date=$last_modif_date;
    }

    public function getLastModifDate()
    {
        return $this->last_modif_date;
    }
    /* ###############################################################
     * Propiedades Relacionadas con el rol de Usuario de la Aplicacion
     * ###############################################################
     */

    /**
     * @ORM\Column(type="string", length="255", unique=true)
     *
     * @var string username
     */
    protected $username;

    /**
     * @ORM\Column(type="string", length="255")
     *
     * @var string password
     */
    protected $password;

    /**
     * @ORM\Column(type="string", length="255")
     *
     * @var string salt
     */
    protected $salt;

    /**
     * @ORM\Column(type="datetime", name="created_at")
     *
     * @var DateTime $createdAt
     */
    protected $createdAt;

    /**
     * @ORM\OneToMany(targetEntity="Baja", mappedBy="socio")
     *
     */

    public function getId()
    {
        return $this->id;
    }

    /**
     * Set Legajo
     *
     * @param bigint $legajo
     */
    public function setLegajo($legajo)
    {
        $this->Legajo = $legajo;
    }

    /**
     * Get Legajo
     *
     * @return bigint
     */
    public function getLegajo()
    {
        return $this->Legajo;
    }

    /**
     * Set Num_Documento
     *
     * @param bigint $numDocumento
     */
    public function setNumDocumento($numDocumento)
    {
        $this->Num_Documento = $numDocumento;
    }

    /**
     * Get Num_Documento
     *
     * @return bigint
     */
    public function getNumDocumento()
    {
        return $this->Num_Documento;
    }

    /**
     * Set Cuit
     *
     * @param bigint $cuit
     */
    public function setCuit($cuit)
    {
        $this->Cuit = $cuit;
    }

    /**
     * Get Cuit
     *
     * @return bigint
     */
    public function getCuit()
    {
        return $this->Cuit;
    }

    /**
     * Set Apellido
     *
     * @param string $apellido
     */
    public function setApellido($apellido)
    {
        $this->Apellido = $apellido;
    }

    /**
     * Get Apellido
     *
     * @return string
     */
    public function getApellido()
    {
        return $this->Apellido;
    }

    /**
     * Set Nombres
     *
     * @param string $nombres
     */
    public function setNombres($nombres)
    {
        $this->Nombres = $nombres;
    }

    /**
     * Get Nombres
     *
     * @return string
     */
    public function getNombres()
    {
        return $this->Nombres;
    }

    /**
     * Set Domicilio
     *
     * @param string $domicilio
     */
    public function setDomicilio($domicilio)
    {
        $this->Domicilio = $domicilio;
    }

    /**
     * Get Domicilio
     *
     * @return string
     */
    public function getDomicilio()
    {
        return $this->Domicilio;
    }

    /**
     * Set Telefono
     *
     * @param string $telefono
     */
    public function setTelefono($telefono)
    {
        $this->Telefono = $telefono;
    }

    /**
     * Get Telefono
     *
     * @return string
     */
    public function getTelefono()
    {
        return $this->Telefono;
    }

    /**
     * Set Sexo
     *
     * @param string $sexo
     */

    /**
     * Set Numero_Mesa
     *
     * @param integer $numeroMesa
     */
    public function setNumeroMesa($numeroMesa)
    {
        $this->Numero_Mesa = $numeroMesa;
    }

    /**
     * Get Numero_Mesa
     *
     * @return integer
     */
    public function getNumeroMesa()
    {
        return $this->Numero_Mesa;
    }

    /**
     * Set Ingreso_Justicia
     *
     * @param datetime $ingresoJusticia
     */
    public function setIngresoJusticia($ingresoJusticia)
    {
        $this->Ingreso_Justicia = $ingresoJusticia;
    }

    /**
     * Get Ingreso_Justicia
     *
     * @return datetime
     */
    public function getIngresoJusticia()
    {
        return $this->Ingreso_Justicia;
    }

    /**
     * Set Cbu
     *
     * @param bigint $cbu
     */
    public function setCbu($cbu)
    {
        $this->Cbu = $cbu;
    }

    /**
     * Get Cbu
     *
     * @return bigint
     */
    public function getCbu()
    {
        return $this->Cbu;
    }

    /**
     * Set Domicilio_Particular
     *
     * @param string $domicilioParticular
     */
    public function setDomicilioParticular($domicilioParticular)
    {
        $this->Domicilio_Particular = $domicilioParticular;
    }

    /**
     * Get Domicilio_Particular
     *
     * @return string
     */
    public function getDomicilioParticular()
    {
        return $this->Domicilio_Particular;
    }

    /**
     * Set Telefono_Particular
     *
     * @param string $telefonoParticular
     */
    public function setTelefonoParticular($telefonoParticular)
    {
        $this->Telefono_Particular = $telefonoParticular;
    }

    /**
     * Get Telefono_Particular
     *
     * @return string
     */
    public function getTelefonoParticular()
    {
        return $this->Telefono_Particular;
    }

    /**
     * Set Email
     *
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->Email = $email;
    }

    /**
     * Get Email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->Email;
    }

    /**
     * Set Fecha_Nacimiento
     *
     * @param datetime $fechaNacimiento
     */
    public function setFechaNacimiento($fechaNacimiento)
    {
        $this->Fecha_Nacimiento = $fechaNacimiento;
    }

    /**
     * Get Fecha_Nacimiento
     *
     * @return datetime
     */
    public function getFechaNacimiento()
    {
        return $this->Fecha_Nacimiento;
    }

    /**
     * Set Domicilio_Laboral
     *
     * @param string $domicilioLaboral
     */
    public function setDomicilioLaboral($domicilioLaboral)
    {
        $this->Domicilio_Laboral = $domicilioLaboral;
    }

    /**
     * Get Domicilio_Laboral
     *
     * @return string
     */
    public function getDomicilioLaboral()
    {
        return $this->Domicilio_Laboral;
    }

    /**
     * Set Telefono_Laboral
     *
     * @param string $telefonoLaboral
     */
    public function setTelefonoLaboral($telefonoLaboral)
    {
        $this->Telefono_Laboral = $telefonoLaboral;
    }

    /**
     * Get Telefono_Laboral
     *
     * @return string
     */
    public function getTelefonoLaboral()
    {
        return $this->Telefono_Laboral;
    }

    /**
     * Set localidad
     *
     * @param Gremio\AbmBundle\Entity\Localidad $localidad
     */
    public function setLocalidad(\Gremio\AbmBundle\Entity\Localidad $localidad)
    {
        $this->localidad = $localidad;
    }

    /**
     * Get localidad
     *
     * @return Gremio\AbmBundle\Entity\Localidad
     */
    public function getLocalidad()
    {
        return $this->localidad;
    }

    /**
     * Set sexo
     *
     * @param Gremio\AbmBundle\Entity\Sexo $sexo
     */
    public function setSexo($sexo)
    {
        $this->sexo = $sexo;
    }

    /**
     * Get sexo
     *
     * @return Gremio\AbmBundle\Entity\Sexo
     */
    public function getSexo()
    {
        return $this->sexo;
    }

    /***********************************/

    /**
     * Gets the username.
     *
     * @return string The username.
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Sets the username.
     *
     * @param string $value The username.
     */
    public function setUsername($value)
    {
        $this->username = $value;
    }

    /**
     * Gets the complete username.
     *
     * @return string The username.
     */
    public function getCompleteName()
    {
        return $this->getApellido() .' ' .$this->getNombres();
    }

    /**
     * Gets the user password.
     *
     * @return string The password.
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Sets the user password.
     *
     * @param string $value The password.
     */
    public function setPassword($value)
    {
        $this->password = $value;
    }

    /**
     * Gets the user salt.
     *
     * @return string The salt.
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * Sets the user salt.
     *
     * @param string $value The salt.
     */
    public function setSalt($value)
    {
        $this->salt = $value;
    }

    /**
     * Gets an object representing the date and time the user was created.
     *
     * @return DateTime A DateTime object
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Constructs a new instance of User
     */
    public function __construct()
    {

        $this->createdAt = new \DateTime();
    }

    /**
     * Gets the full name of the user.
     *
     * @return string The full name
     */
    public function getFullName()
    {
        return sprintf('%s %s', $this->Apellido, $this->Nombres);
    }

    /**
     * Erases the user credentials.
     */
    public function eraseCredentials()
    {

    }

    /**
     * Gets an array of roles.
     *
     * @return array An array of Role objects
     */
    public function getRoles()
    {
        if ($this->getFechaBaja())
            return array('ROLE_BAJA');
        else
            return array('ROLE_SOCIO');
    }

    /**
     * Compares this user to another to determine if they are the same.
     *
     * @param UserInterface $user The user
     * @return boolean True if equal, false othwerwise.
     */
    public function equals(UserInterface $user)
    {
        return md5($this->getUsername()) == md5($user->getUsername());
    }

    /**
     * Set createdAt
     *
     * @param datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @ORM\prePersist
     */
    public function setUserPass()
    {
        $this->setUsername(strtolower(substr($this->getNombres(),0,1)) . strtolower($this->getApellido()));
        $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
        $this->setSalt(md5(time()));
        $this->setPassword($encoder->encodePassword('socio', $this->getSalt()));

    }

    public function serialize()
{
return serialize(array(
$this->id,
$this->password,
$this->username
));
}

public function unserialize($serialized)
{
list(
$this->id,
$this->password,
$this->username
) = unserialize($serialized);
}

    /**
     * Set tipo_socio
     *
     * @param Gremio\AbmBundle\Entity\TipoSocio $tipoSocio
     */
    public function setTipoSocio(\Gremio\AbmBundle\Entity\TipoSocio $tipoSocio)
    {
        $this->tipo_socio = $tipoSocio;
    }

    /**
     * Get tipo_socio
     *
     * @return Gremio\AbmBundle\Entity\TipoSocio
     */
    public function getTipoSocio()
    {
        return $this->tipo_socio;
    }

    /**
     * Set seccion
     *
     * @param Gremio\AbmBundle\Entity\Seccion $seccion
     */
    public function setSeccion(\Gremio\AbmBundle\Entity\Seccion $seccion)
    {
        $this->seccion = $seccion;
    }

    /**
     * Get seccion
     *
     * @return Gremio\AbmBundle\Entity\Seccion
     */
    public function getSeccion()
    {
        return $this->seccion;
    }

    /**
     * Set reparticion
     *
     * @param Gremio\AbmBundle\Entity\Reparticion $reparticion
     */
    public function setReparticion(\Gremio\AbmBundle\Entity\Reparticion $reparticion)
    {
        $this->reparticion = $reparticion;
    }

    /**
     * Get reparticion
     *
     * @return Gremio\AbmBundle\Entity\Reparticion
     */
    public function getReparticion()
    {
        return $this->reparticion;
    }

    /**
     * Set margen
     *
     * @param integer $margen
     */
    public function setMargen($margen)
    {
        $this->margen = $margen;
    }

    /**
     * Get margen
     *
     * @return integer
     */
    public function getMargen()
    {
        return $this->margen;
    }

    /**
     * Add emisiones
     *
     * @param Gremio\SociosBundle\Entity\Emision $emisiones
     */
    public function addEmision(\Gremio\SociosBundle\Entity\Emision $emisiones)
    {
        $this->emisiones[] = $emisiones;
    }

    /**
     * Get emisiones
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getEmisiones()
    {
        return $this->emisiones;
    }

    /**
     * Get fecha_baja
     *
     * @return datetime
     */
    public function getFechaBaja()
    {
        foreach ($this->getBajas() as $baja)
        {
            if ($baja->getFechaCancelaBaja()==null)
                return $baja->getFechaBaja();
        }
    }

    /**
     * Add bajas_socio
     *
     * @param Gremio\AbmBundle\Entity\Baja $bajasSocio
     */
    public function addBaja(\Gremio\AbmBundle\Entity\Baja $baja)
    {
        $this->bajas[] = $baja;
    }

    /**
     * Get bajas_socio
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getBajas()
    {
        return $this->bajas;
    }

    public function __toString()
    {
        return $this->getApellido().' '.$this->getNombres();
    }

}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>News - Summary Extraction</title>
		<link rel="stylesheet" href="css/bootstrap.css">
		<link rel="stylesheet" href="css/news.css">

		Is My Startup Burn Rate Normal?

		medium.com

			Self-examination for Seed and Series A startups

		SunshinePHP 2015 - Call to Speakers

		calltospeakers.com

			Call to Speakers is a list of open applications for conference talks. Get notified of new opportunities via a weekly newsletter, Twitter account, or ...

		Practical Lessons in Peer Code Review

		blog.salsitasoft.com

			Millions of years ago, apes descended from the trees, evolved opposable thumbs and—eventually—turned into human beings.

		The Complete iOS Game Course - Build a Flappy Bird Clone at bitfountain

		bitfountain.io

			We built an immersive game development course that teaches you all of the fundamentals so you can build your own games on iPhones and iPads. We ...

		The Greatest Lie

		olivierlacan.com

			Unfettered thoughts of Olivier Lacan.

		OWASP AppSecUSA 2014 - Keynote: Gary McGraw - BSIMM: A Decade of Software ...

		www.youtube.com

			Live from AppSecUSA 2014 in Denver http://2014.appsecusa.org/ Keynote: Gary McGraw - Bug Parades, Zombies, and the BSIMM: A Decade of Software ...

		Shellshock Unix Bash Bug by MarkusLindberg

		www.redbubble.com

			Available as T-Shirts & Hoodies, Stickers, iPhone Cases, Samsung Galaxy Cases, Home Decors, Tote Bags, Prints, Cards, and iPad Cases

		Bash specially-crafted environment variables code injection attack

		securityblog.redhat.com

			Update 2014-09-25 16:00 UTC Red Hat is aware that the patch for CVE-2014-6271 is incomplete. An attacker can provide specially-crafted environment ...

		Laravel Forge - PHP Hosting For Artisans

		forge.laravel.com

		Call for Papers | ConFoo.ca

		confoo.ca

			Web technologies conference from February 18-20, 2015 in Montreal, Canada.

		JavaScript hacks explained • Myths of the Near Future

		blog.mdnbar.com

			There are several JavaScript tricks that are used widely by experienced programmers. Many of them may not be instantly obvious, especially for ...

		LASCON 2014 Schedule

		lascon2014.sched.org

			Check out the schedule for LASCON 2014

		Security advisories for contributed projects | Drupal.org

		www.drupal.org

			Security advisories for third-party projects that are not part of Drupal core - this includes all modules, themes, and installation profiles that ...

		Uncovering WordPress Vulnerabilities with Ease

		www.sitepoint.com

			When it comes to securing yours systems, there are a few tools than scan for WordPress vulnerabilities which can help you spot errors before they get ...

		Tuts+ Free Code Tutorials

		code.tutsplus.com

			Tuts+ teaches creative and technical skills across many topics to millions of people worldwide. We offer tutorials, articles, news and insights that ...

		Amazon.com : Logitech Wireless Presenter R400 : Presentation Remotes : ...

		www.amazon.com

			Amazon.com : Logitech Wireless Presenter R400 : Presentation Remotes : Office Products

		In Defense Of Passwords

		www.darkreading.com

			Long live the password (as long as you use it correctly along with something else).

		BrazilJS Conf 2014 - YouTube

		www.youtube.com

			Sign in now to see your channels and recommendations!

		Web Security Testing Cookbook

		shop.oreilly.com

			Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in ...

		Tips on Speaking

		rosstuck.com

			Some tips on speaking and my experiences in the PHP community

		Introducing Laravel Liferaft

		laracasts.com

			Laravel Liferaft provides a simple, painless way to submit bug reports to the Laravel framework. Liferaft automates the creation of Laravel forks and ...

		Online Collaboration Software for Remote and Virtual Teams | Sqwiggle

		www.sqwiggle.com

			Sqwiggle is an always-on online workplace for your remote team to work together throughout the day and feel more connected.

		Subscribe to Nomad PHP - Nomad PHP

		nomadphp.com

			Continuous Learning Nomad PHP is the best way for PHP developers to stay at the top of their game. Each month we have expert speakers from around the ...

		Developer Conference—Thunder Plains

		thunderplainsconf.com

			Thunder Plains Developer Conference

		Today's top skill sets in security -- and why they're in demand

		www.csoonline.com

			The threat landscape is ever-changing, and so are the skills that are needed to mitigate them. Here, experts weigh in on some of the most in-demand ...

		The Pragmatic Bookshelf | The Nature of Software Development

		pragprog.com

			title: The Nature of Software Development: Keep It Simple, Make It Valuable, Build It Piece by Piece, by: Ron Jeffries, isbn: 9781941222379, date: ...

		Calling All Papers

		callingallpapers.com

			We know that one of the hardest parts about wanting to speak and share your knowledge is finding out where you can present. It's hard to keep up with ...

		CoderFaire Nashville September 20-21, 2014 | Two days of learning, on ...

		tennessee.coderfaire.com

			One of the core values we set forth when forming CoderFaire has been to elevate local developers by giving them a stage, or 4, to stand on and ...

		Coursera

		www.coursera.org

			Take free online classes from 80+ top universities and organizations. Coursera is a social entrepreneurship company partnering with Stanford ...

		Norse - IPViking Live

		map.ipviking.com

			Every second, Norse collects and analyzes live threat intelligence from darknets in hundreds of locations in over 40 countries. The attacks shown are ...


text:
package com.code2bits.hackerrank.algorithms.warmup.staircase;

import java.util.Scanner;

/**
 * This class contains the solution for the HackerRank challenge called Staircase
 * which forms part of the Algorithm WarmUp challenges. To see more information
 * about the challenge, follow the link below and paste this code inside the submit section.
 *
 * @see		https://www.hackerrank.com/challenges/staircase
 *
 * @author	André Maré
 */
public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        for(int count = n; count > 0; count--) {
            for(int index=0; index < count-1; index++)
                System.out.print(" ");

            for(int hash=n; hash > count-1; hash--)
                System.out.print("#");

            System.out.println();
        }

        in.close();
    }

}