text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.ComponentModel;
using System.Threading;

namespace System.Reactive.PlatformServices
{
    /// <summary>
    /// (Infrastructure) Provides access to the host's lifecycle management services.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class HostLifecycleService
    {
        private static Lazy<IHostLifecycleNotifications> s_notifications = new Lazy<IHostLifecycleNotifications>(InitializeNotifications);

        private static int _refCount;

        /// <summary>
        /// Event that gets raised when the host suspends the application.
        /// </summary>
        public static event EventHandler<HostSuspendingEventArgs> Suspending;

        /// <summary>
        /// Event that gets raised when the host resumes the application.
        /// </summary>
        public static event EventHandler<HostResumingEventArgs> Resuming;

        /// <summary>
        /// Adds a reference to the host lifecycle manager, causing it to be sending notifications.
        /// </summary>
        public static void AddRef()
        {
            if (Interlocked.Increment(ref _refCount) == 1)
            {
                var notifications = s_notifications.Value;
                if (notifications != null)
                {
                    notifications.Suspending += OnSuspending;
                    notifications.Resuming += OnResuming;
                }
            }
        }

        /// <summary>
        /// Removes a reference to the host lifecycle manager, causing it to stop sending notifications
        /// if the removed reference was the last one.
        /// </summary>
        public static void Release()
        {
            if (Interlocked.Decrement(ref _refCount) == 0)
            {
                var notifications = s_notifications.Value;
                if (notifications != null)
                {
                    notifications.Suspending -= OnSuspending;
                    notifications.Resuming -= OnResuming;
                }
            }
        }

        private static void OnSuspending(object sender, HostSuspendingEventArgs e)
        {
            var suspending = Suspending;
            if (suspending != null)
                suspending(sender, e);
        }

        private static void OnResuming(object sender, HostResumingEventArgs e)
        {
            var resuming = Resuming;
            if (resuming != null)
                resuming(sender, e);
        }

        private static IHostLifecycleNotifications InitializeNotifications()
        {
            return PlatformEnlightenmentProvider.Current.GetService<IHostLifecycleNotifications>();
        }
    }

    /// <summary>
    /// (Infrastructure) Provides notifications about the host's lifecycle events.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public interface IHostLifecycleNotifications
    {
        /// <summary>
        /// Event that gets raised when the host suspends.
        /// </summary>
        event EventHandler<HostSuspendingEventArgs> Suspending;

        /// <summary>
        /// Event that gets raised when the host resumes.
        /// </summary>
        event EventHandler<HostResumingEventArgs> Resuming;
    }

    /// <summary>
    /// (Infrastructure) Event arguments for host suspension events.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class HostSuspendingEventArgs : EventArgs
    {
    }

    /// <summary>
    /// (Infrastructure) Event arguments for host resumption events.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class HostResumingEventArgs : EventArgs
    {
    }
}


text:
Creates NFS share.

## SYNTAX

```
New-UnityNFSShare [-session <Object>] [-Filesystem] <String[]> -Path <String> -Name <String>
 [-description <String>] [-isReadOnly <Boolean>] [-defaultAccess <NFSShareDefaultAccessEnum>]
 [-minSecurity <NFSShareSecurityEnum>] [-noAccessHosts <String[]>] [-readOnlyHosts <String[]>]
 [-readWriteHosts <String[]>] [-rootAccessHosts <String[]>] [-WhatIf] [-Confirm]
```

## DESCRIPTION
Creates NFS share.
You need to have an active session with the array.

## EXAMPLES

### -------------------------- EXAMPLE 1 --------------------------
```
New-UnityNFSShare -Filesystem fs_17 -Path / -Name 'NFSSHARE01' -rootAccessHosts Host_20
```

Create a new NFS Share named 'NFSSHARE01'

## PARAMETERS

### -session
Specify an UnitySession Object.

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true})
Accept pipeline input: False
Accept wildcard characters: False
```

### -Filesystem
Specify Filesystem ID

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```

### -Path
Local path to a location within a file system.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Name of the NFS share unique to NAS server

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -description
NFS share description

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -isReadOnly
Indicates whether the NFS share is read-only.
Values are:
- true - NFS share is read-only.
- false - NFS share is read-write.

```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -defaultAccess
Default access level for all hosts accessing the NFS share.

```yaml
Type: NFSShareDefaultAccessEnum
Parameter Sets: (All)
Aliases:
Accepted values: NoAccess, ReadOnly, ReadWrite, Root

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -minSecurity
Minimal security level that must be provided by a client to mount the NFS share.

```yaml
Type: NFSShareSecurityEnum
Parameter Sets: (All)
Aliases:
Accepted values: Sys, Kerberos, KerberosWithIntegrity, KerberosWithEncryption

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -noAccessHosts
Hosts with no access to the NFS share or its snapshots, as defined by the host resource type.

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -readOnlyHosts
Hosts with read-only access to the NFS share and its snapshots, as defined by the host resource type.

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -readWriteHosts
Hosts with read-write access to the NFS share and its snapshots, as defined by the host resource type.

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -rootAccessHosts
Hosts with root access to the NFS share and its snapshots, as defined by the host resource type.

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

## INPUTS

## OUTPUTS

## NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE

## RELATED LINKS

[https://github.com/equelin/Unity-Powershell](https://github.com/equelin/Unity-Powershell)

redpajama_set_name: RedPajamaGithub


text:
`use strict`

process.env.NODE_ENV = 'test'

const chai = require('chai')
const should = chai.should()
const chaiHttp = require('chai-http')
const server = require('../app')
const { knex } = require('../db/database')
const localAuth = require('../auth/local');
chai.use(chaiHttp)

// tests for user auth
describe('auth : local', () => {
  // test for encoding token
  describe('encodeToken()', () => {
    it('should return a token', (done) => {
      const results = localAuth.encodeToken({id: 2})
      should.exist(results)
      results.should.be.a('string')
      done()
    })
  })

  describe('decodeToken()', () => {
    // test for decoding token
    it('should return a payload', (done) => {
      const token = localAuth.encodeToken({id: 2})
      should.exist(token)
      token.should.be.a('string')
      localAuth.decodeToken(token, (err, res) => {
        should.not.exist(err)
        res.sub.should.equal(2)
        done()
      })
    })
  })
})

// tests for routes
describe('abc routes', ()=>{
  // does a rollback on test db and then migration and seed before each test run so we know what is in db
  beforeEach(() =>{
    return knex.migrate.rollback()
      .then (()=>{
        return knex.migrate.latest()
      })
      .then (()=>{
        return knex.seed.run()
      })
  });

  // test for getting the api root
  describe('get root route', ()=>{
    it('should have all routes',() =>{
      return chai.request(server)
        .get('/api/v1/')
        .then((res) => {
          res.should.have.status(200)
          res.should.be.json
          res.should.be.a.object
          // checks for ALL route keys - will exit test if missing any
          res.body.should.have.key(['getAllgames','getGamesForLoggedInUser', 'register', 'login', 'getLoggedInUser', 'getFriendsForLoggedInUser', 'getWordsForSpecifiedGame', 'getWord', 'addWord', 'addGame', 'updateGame'])
        })
    })
  });

  // tests register route
  describe('POST /auth/register', () => {
    it('should register a new user', (done) => {
      chai.request(server)
      .post('/api/v1/auth/register')
      .send({
        username: 'geronimo',
        password: 'password'
      })
      .end((err, res) => {
        should.not.exist(err);
        res.redirects.length.should.eql(0);
        res.status.should.eql(200);
        res.type.should.eql('application/json');
        res.body.should.include.keys('status', 'token');
        res.body.status.should.eql('success');
        done();
      });
    });
  });

  // tests login route
  describe('POST /auth/login', () => {
    it('should login a user', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((err, res) => {
        should.not.exist(err);
        res.redirects.length.should.eql(0);
        res.status.should.eql(200);
        res.type.should.eql('application/json');
        res.body.should.include.keys('status', 'token');
        res.body.status.should.eql('success');
        should.exist(res.body.token);
        done();
      });
    });
    it('should not login an unregistered user', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'sid',
        password: 'viscous'
      })
      .end((err, res) => {
        should.exist(err);
        res.status.should.eql(500);
        res.type.should.eql('application/json');
        res.body.status.should.eql('error');
        done();
      });
    });
  });

  // tests user endpoint
  describe('GET /auth/user', () => {
    it('should return a success', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get('/api/v1/auth/user')
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          res.body.status.should.eql('success')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests get all games
  describe('GET /games', () => {
    it('should return all game if a user is logged in', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get('/api/v1/games')
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          res.body.games.should.be.a.array
          res.body.games[0].number_correct.should.be.eql(4)
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests getting all games for logged in user
  describe('GET /api/v1/user/games', () => {
    it('should return all games specifically for logged in user', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get(`/api/v1/user/games`)
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.body.games.should.be.a.array
          res.body.games[0].number_correct.should.equal(4)
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests user friends
  describe('GET /user/friends', () => {
    it('should return a all friends unlocked by logged in user', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get('/api/v1/user/friends')
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          res.body.friends[0].name.should.eql('Ant')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests route for getting words used in games
  describe('GET /games/words', () => {
    it('should return a all words used in a specified game', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get('/api/v1/games/words?gameId=1')
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          res.body.words[0].correct_word.should.eql('ant')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests route for getting single word
  describe('GET /word/:<correct_word>', () => {
    it('should return a single word if a user is logged in', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .get('/api/v1/word/ant')
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          res.body.correct_word.should.eql('ant')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests route for adding word to words table
  describe('POST /word/:<correct_word>', () => {
    it('should add a word if a user is logged in', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .post('/api/v1/words/new')
        .send({correct_word: 'husky'})
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(201)
          chai.request(server)
          .get('/api/v1/word/husky')
          .set('authorization', 'Bearer ' + response.body.token)
          .end((err, res) => {
            should.not.exist(err)
            res.status.should.eql(200)
            res.type.should.eql('application/json')
            res.body.correct_word.should.eql('husky')
            // console.log('word just added:', res.body.correct_word)
            done()
          })
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests route for adding a game to games table and users_games table
  describe('POST /games/new', () => {
    it('should add a game to the game table and the users_games table', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .post('/api/v1/games/new')
        .send({number_asked: 1})
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(201)
          // res.type.should.eql('application/json')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

  // tests route for updating a game
  describe('PATCH /games/:<id>', () => {
    it('should update a game if a user is logged in', (done) => {
      chai.request(server)
      .post('/api/v1/auth/login')
      .send({
        username: 'jufe',
        password: 'password'
      })
      .end((error, response) => {
        should.not.exist(error)
        chai.request(server)
        .patch('/api/v1/games/1')
        .send({number_asked: 8, number_correct: 5})
        .set('authorization', 'Bearer ' + response.body.token)
        .end((err, res) => {
          should.not.exist(err)
          res.status.should.eql(200)
          res.type.should.eql('application/json')
          done()
        })
      })
    })
    it('should throw an error if a user is not logged in', (done) => {
      chai.request(server)
      .get('/api/v1/auth/user')
      .end((err, res) => {
        should.exist(err)
        res.status.should.eql(400)
        res.type.should.eql('application/json')
        res.body.status.should.eql('Please log in')
        done()
      })
    })
  })

})


text:
package org.incode.module.document.dom.impl.docs;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import javax.activation.DataSource;

import org.apache.commons.io.output.NullOutputStream;

import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.services.factory.FactoryService;
import org.apache.isis.applib.value.Blob;
import org.apache.isis.applib.value.Clob;

import org.incode.module.document.dom.impl.docs.minio.Document_downloadExternalUrlAsBlob;
import org.incode.module.document.dom.impl.docs.minio.Document_downloadExternalUrlAsClob;

public enum DocumentSort {
    /**
     * Stored as a BLOB
     */
    EMPTY(DocumentNature.BYTES, DocumentStorage.INTERNAL) {
        @Override
        public DataSource asDataSource(DocumentAbstract<?> document) {
            throw new IllegalStateException("Document not yet rendered");
        }
    },
    /**
     * Stored as a BLOB
     */
    BLOB(DocumentNature.BYTES, DocumentStorage.INTERNAL) {
        @Override
        public DataSource asDataSource(final DocumentAbstract<?> document) {
            return new ByteDataSource(document, asBytes(document));
        }

        @Override
        public byte[] asBytes(final DocumentAbstract<?> document) {
            return document.getBlobBytes();
        }
    },
    /**
     * Stored as a CLOB
     */
    CLOB(DocumentNature.CHARACTERS, DocumentStorage.INTERNAL) {
        @Override
        public DataSource asDataSource(final DocumentAbstract<?> document) {
            return new CharDataSource(document, asChars(document));
        }

        @Override
        public String asChars(final DocumentAbstract<?> document) {
            return document.getClobChars();
        }
    },
    /**
     * Stored in-situ (as a LONGVARCHAR)
     */
    TEXT(DocumentNature.CHARACTERS, DocumentStorage.INTERNAL) {
        @Override
        public DataSource asDataSource(final DocumentAbstract<?> document) {
            return new CharDataSource(document, asChars(document));
        }

        @Override
        public String asChars(final DocumentAbstract<?> document) {
            return document.getText();
        }
    },
    /**
     * Stored externally as blob (holds a hyperlink to access)
     *
     * Only {@link Document}s can be stored externally (not {@link DocumentTemplate}).
     */
    EXTERNAL_BLOB(DocumentNature.BYTES, DocumentStorage.EXTERNAL) {
        @Override
        public DataSource asDataSource(final DocumentAbstract<?> document) {
            return new ByteDataSource(document,
                    // TODO: could probably instead just call Document#asBytes();
                    //   being conversative for now to minimize retesting effort as this is a prod fix
                    document.getBlobBytes() != null ? document.getBlobBytes() : asBytes(document));
        }

        @Override
        public byte[] asBytes(final DocumentAbstract<?> document) {
            final FactoryService factoryService = document.factoryService;
            final Blob blob = factoryService.mixin(Document_downloadExternalUrlAsBlob.class, document).act();
            return blob != null ? blob.getBytes() : null;
        }
    },
    /**
     * Stored externally as clob (holds a hyperlink to access).
     *
     * Only {@link Document}s can be stored externally (not {@link DocumentTemplate}).
     */
    EXTERNAL_CLOB(DocumentNature.BYTES, DocumentStorage.EXTERNAL) {
        @Override
        public DataSource asDataSource(final DocumentAbstract<?> document) {
            return new CharDataSource(document,
                    // TODO: could probably instead just call Document#asChars();
                    //   being conversative for now to minimize retesting effort as this is a prod fix
                    document.getClobChars() != null ? document.getClobChars() : asChars(document));
        }

        @Override
        public String asChars(final DocumentAbstract<?> document) {
            final FactoryService factoryService = document.factoryService;
            final Clob clob = factoryService.mixin(Document_downloadExternalUrlAsClob.class, document).act();
            final CharSequence chars = clob.getChars();
            return chars instanceof String ? (String) chars : chars.toString();
        }
    };

    private final DocumentNature nature;
    private final DocumentStorage storage;

    private DocumentSort(DocumentNature nature, DocumentStorage storage) {
        this.nature = nature;
        this.storage = storage;
    }

    @Programmatic
    public abstract DataSource asDataSource(final DocumentAbstract<?> document);

    @Programmatic
    public String asChars(final DocumentAbstract<?> document) {
        throw new IllegalArgumentException("Cannot convert to characters");
    }

    /**
     * Supported only if {@link #isBytes()}.
     */
    @Programmatic
    public byte[] asBytes(final DocumentAbstract<?> document) {
        throw new IllegalArgumentException("Cannot convert to bytes");
    }

    @Programmatic
    public DocumentSort asExternal() {
        if(this == BLOB) { return EXTERNAL_BLOB; }
        if(this == CLOB || this == TEXT) { return EXTERNAL_CLOB; }
        return this;
    }

    @Programmatic
    public boolean isBytes() {
        return nature == DocumentNature.BYTES;
    }

    @Programmatic
    public boolean isCharacters() {
        return nature == DocumentNature.CHARACTERS;
    }

    @Programmatic
    public boolean isExternal() {
        return storage == DocumentStorage.EXTERNAL;
    }

    private static abstract class DocumentDataSource implements DataSource {

        final DocumentAbstract<?> document;
        public DocumentDataSource(final DocumentAbstract<?> document) {
            this.document = document;
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return new NullOutputStream();
        }

        @Override
        public String getContentType() {
            return document.getMimeType();
        }

        @Override
        public String getName() {
            return document.getName();
        }
    }

    private static class ByteDataSource extends DocumentDataSource {

        private static final Charset CHARSET = StandardCharsets.UTF_8;

        private final byte[] bytes;

        public ByteDataSource(final DocumentAbstract<?> document, final byte[] bytes) {
            super(document);
            this.bytes = bytes;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }

    private static class CharDataSource extends DocumentDataSource {

        private static final Charset CHARSET = StandardCharsets.UTF_8;

        private final String chars;

        public CharDataSource(final DocumentAbstract<?> document, final String chars) {
            super(document);
            this.chars = chars;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(chars.getBytes(CHARSET));
        }
    }

}


text:
<?php

/* BWFVideosBundle:Videos:addVideo.html.twig */
class __TwigTemplate_cc41df01a57d6c39e685d3463b33435fda030aa7a4124792ea3494f88dfe1b09 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'content' => array($this, 'block_content'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 12
        echo "
";
        // line 13
        $this->displayBlock('content', $context, $blocks);
    }

    public function block_content($context, array $blocks = array())
    {
        // line 14
        echo "
         <form action=\"";
        // line 15
        echo $this->env->getExtension('routing')->getPath("bwf_formations_add", array("id" => "new"));
        echo "\" method=\"post\" >
            ";
        // line 16
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "

<input type=\"submit\" />

        </form>

    ";
    }

    public function getTemplateName()
    {
        return "BWFVideosBundle:Videos:addVideo.html.twig";
    }

    public function getDebugInfo()
    {
        return array (  36 => 16,  32 => 15,  29 => 14,  23 => 13,  20 => 12,);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using AutoMapper;

namespace BTC.Shared.Automapper
{
    public static class AutoMapperExtensions
    {
        public static TU MapTo<T, TU>(this T from, TU toEntity)
        {
            Mapper.Map(from, toEntity);
            return toEntity;
        }

        public static IEnumerable<TU> Select<T, TU>(this IEnumerable<T> from, TU obj)
            where TU : new()
        {
            return from.Select(n => MapTo(n, new TU()));
        }
    }
}


text:
import Node from './'

test('Node is a constructor', () => {
  expect(typeof Node.prototype.constructor).toBe('function')
})

test('Node can insert correctly', () => {
  const node = new Node(10)
  node.insert(5)
  node.insert(15)
  node.insert(17)

  expect(node.left.data).toBe(5)
  expect(node.right.data).toBe(15)
  expect(node.right.right.data).toBe(17)
})

test('Contains returns node with the same data', () => {
  const node = new Node(10)
  node.insert(5)
  node.insert(15)
  node.insert(20)
  node.insert(0)
  node.insert(-5)
  node.insert(3)

  const three = node.left.left.right
  expect(node.contains(3)).toEqual(three)
})

test('Contains returns null if value not found', () => {
  const node = new Node(10);
  node.insert(5);
  node.insert(15);
  node.insert(20);
  node.insert(0);
  node.insert(-5);
  node.insert(3);

  expect(node.contains(9999)).toEqual(null);
})


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Brittonia 24:292. 1972

#### Original name
null

### Remarks
null


text:
[jvm]
Content
open override fun [toImmutable](to-immutable.md)(): [Instructions](../-instructions/index.md)
More info

Creates a immutable [Instructions](../-instructions/index.md) with elements of this [Instructions](../-instructions/index.md).


text:
package com.java.laiy.controller;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.*;

public class GameStarterTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
        System.setErr(null);
    }

    @Test
    public void testDefaultStartOutput() throws Exception {
        GameStarter.defaultStart();
        assertEquals("PLAYER X: X\n" +
                     "PLAYER O: O\n",outContent.toString());

    }
    @Test
    public void testDefaultStart() throws Exception {
        final String gameName = "XO";
        final String playerOneName = "PLAYER X";
        final String playerTwoName = "PLAYER O";
        final int boardSize = 3;
        assertEquals(boardSize,GameStarter.defaultStart().getGameController().getBoard().getFiguresArray().length);
        assertEquals(gameName,GameStarter.defaultStart().getGameController().getGameName());
        assertEquals(playerOneName,GameStarter.defaultStart().getGameController().getPlayers()[0].getName());
        assertEquals(playerTwoName,GameStarter.defaultStart().getGameController().getPlayers()[1].getName());
    }

    @Test
    public void testCustomStart() throws Exception {
        final int boardSize = 4;
        final String gameName = "XOxo";
        final String playerOneName = "PLAYER XxXx";
        final String playerTwoName = "PLAYER OoOo";
        final Game newGame = GameStarter.customStart(boardSize,playerOneName,playerTwoName,gameName);
        assertEquals(boardSize,newGame.getGameController().getBoard().getFiguresArray().length);
        assertEquals(gameName, newGame.getGameController().getGameName());
        assertEquals(playerOneName, newGame.getGameController().getPlayers()[0].getName());
        assertEquals(playerTwoName, newGame.getGameController().getPlayers()[1].getName());
    }

    @Test
    public void testCustomStartIncorrectInput() throws Exception {
        final int boardSize = -4;
        final String gameName = "XOxo";
        final String playerOneName = "PLAYER XxXx";
        final String playerTwoName = "PLAYER OoOo";
        final Game newGame = GameStarter.customStart(boardSize,playerOneName,playerTwoName,gameName);
        assertNull(newGame.getGameController().getBoard());
    }
}


text:
'use strict';

var dependencies = require('../test.dependencies');

var objectToTest = 'CoreService';

describe(objectToTest, function () {
    var service;

    dependencies.configureDepencencies();

    beforeEach(inject(function (CoreService) {
        service = CoreService;
    }));

    it('can get an instance of my factory', function() {
        expect(service).toBeDefined();
    });

    it('can get a correct value from getDummyText', function() {
        expect(service.getDummyText()).toBe('dummyText');
    });
});


text: default['delivery']['config']['delivery-bag']['data-bag-repo-path'] = ""


text:
CSV River Plugin for ElasticSearch
==================================

The CSV River plugin allows index CSV files in folder.

In order to install the plugin, simply run:
```bin/plugin -install river-csv -url https://github.com/AgileWorksOrg/elasticsearch-river-csv/releases/download/2.2.1/elasticsearch-river-csv-2.2.1.zip```.

If it doesn't work, clone git repository and build plugin manually.

    -------------------------------------
    | CSV Plugin     | ElasticSearch    |
    -------------------------------------
    | master         | 1.7.x -> master  |
    -------------------------------------
    | 2.2.1          | 1.7.x -> master  |
    -------------------------------------
    | 2.2.0          | 1.5.x -> master  |
    -------------------------------------
    | 2.1.2          | 1.4.x -> master  |
    -------------------------------------
    | 2.0.2          | 1.0.x -> 1.2.x   |
    -------------------------------------
    | 2.0.1          | 1.0.x -> 1.2.x   |
    -------------------------------------
    | 2.0.0          | 1.0.0            |
    -------------------------------------
    | 1.0.1          | 0.19.x           |
    -------------------------------------
    | 1.0.0          | 0.19.x           |
    -------------------------------------

The CSV river import data from CSV files and index it.

##Changelog

###2.2.2-SNAPSHOT

* no changes yet

###2.2.1

* updated groovy version to support ES 1.7.x

###2.2.0

* updated dependencies to latest versions

###2.1.2

* fixed - After import, the file remained open, preventing a rename to .imported.
* added the ability to run bash, powershell and "Windows script host"

###2.1.1

* added support for custom charset
* added support for generating an import timestamp in all imported documents
* made list of files to be imported / which have been imported visible to the before/after listener scripts

###2.1.0

* Works with ElasticSearch 1.2.x - 1.3.x

###2.0.2

* Minor enhancements

###2.0.1

* Replaced custom upload logic with BulkProcessor. Inspired from pullrequest by https://github.com/aritratony . Thanks!
* Added error handling - if something went wrong during line or file processing it is logged, skipped and import continues
* Added callback feature - custom shell scripts can be called on events: before import, before file processing start, after file is processed and after all files are processed

###2.0.0

* Updated to ES 1.0.0
* Fixed - when input file was smaller than batch it didn't saved to ES
* Added - id column name, documents with ID column can be updated
* Added - ability to parse first row as header, must be enabled by property

##Creating the CSV river can be done using:

###Minimal curl

	curl -XPUT localhost:9200/_river/my_csv_river/_meta -d '
    {
        "type" : "csv",
        "csv_file" : {
            "folder" : "/tmp",
            "first_line_is_header":"true"
        }
    }'

###Full request

    curl -XPUT localhost:9200/_river/my_csv_river/_meta -d '
	{
	    "type" : "csv",
	    "csv_file" : {
	        "folder" : "/tmp",
	        "filename_pattern" : ".*\\.csv$",
	        "poll":"5m",
	        "fields" : [
	            "column1",
	            "column2",
	            "column3",
	            "column4"
	        ],
            "first_line_is_header" : "false",
	        "field_separator" : ",",
	        "escape_character" : ";",
	        "quote_character" : "'",
            "field_id" : "id",
            "field_id_include" : "false",
            "field_timestamp" : "imported_at",
            "concurrent_requests" : "1",
            "charset" : "UTF-8",
            "script_before_all": "/path/to/before_all.sh",
            "script_after_all": "/path/to/after_all.sh",
            "script_before_file": "/path/to/before_file.sh",
            "script_after_file": "/path/to/after_file.sh"
	    },
	    "index" : {
	        "index" : "my_csv_data",
	        "type" : "csv_type",
	        "bulk_size" : 100,
	        "bulk_threshold" : 10
	    }
	}'

* takes list of all file paths as arguments

	    "script_before_all": "/path/to/before_all.sh"
    	"script_after_all": "/path/to/after_all.sh"

* file path is argument

        "script_before_file": "/path/to/before_file.sh",
        "script_after_file": "/path/to/after_file.sh"

####Examples how the files look like

        #!/bin/sh
        echo "greetings from shell before all, will process $*"

        #!/bin/bash
        echo "greetings from shell before file $1"

        #!/bin/bash
        echo "greetings from shell after file $1"

        #!/bin/bash
        echo "greetings from shell after all, processed $*"

###Optional parameters:

fields = empty - MUST BE SET or first_line_is_header must be set to true

    ----------------------------------------
    | Name              | Default value    |
    ----------------------------------------
    | first_line_is_header   | false       |
    ----------------------------------------
    | filename_pattern   | .*\\.csv$       |
    ----------------------------------------
    | poll              |   60 minutes     |
    ----------------------------------------
    | field_separator   | ,   (for tab separator use ```\t```     |
    ----------------------------------------
    | charset           | UTF-8            |
    ----------------------------------------
    | escape_character  | \                |
    ----------------------------------------
    | quote_character   | "                |
    ----------------------------------------
    | bulk_size         | 100              |
    ----------------------------------------
    | bulk_threshold    | 10               |
    ----------------------------------------
    | concurrent_requests | 1              |
    ----------------------------------------

####Charset

Default charset is "UTF-8". If you need different, consider to use one of:

* US-ASCII	Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
* ISO-8859-1  	ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
* UTF-8	    Eight-bit UCS Transformation Format
* UTF-16BE	Sixteen-bit UCS Transformation Format, big-endian byte order
* UTF-16LE	Sixteen-bit UCS Transformation Format, little-endian byte order
* UTF-16 	Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

 More details about charsets are available at http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html

License
-------

    This software is licensed under the Apache 2 license, quoted below.

    Copyright 2012-2013 Martin Bednar, Vitek Tajzich

    Licensed under the Apache License, Version 2.0 (the "License"); you may not
    use this file except in compliance with the License. You may obtain a copy of
    the License at

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

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


text:
__author__ = 'Samuel'

#
# WRONG (SLOW)
#

primes = []
last = 0
primes.insert(last, 2)

def NextPrime():
    global last, primes

    number = primes[last]
    found = False

    while not found:
        number += 1

        found = True
        for x in range(2, number - 1):
            if (number % x == 0):
                found = False

    last += 1
    primes.insert(last, number)

def GetPrime(location):
    global last, primes

    if (last < location):
        for i in range (last, location):
            NextPrime()

    return primes[location]

goal = 600851475143

print(GetPrime(1000))


text:
'use strict';

import Browser = require('vs/base/browser/browser');
import Types = require('vs/base/common/types');
import Emitter = require('vs/base/common/eventEmitter');
import Lifecycle = require('vs/base/common/lifecycle');
import mouseEvent = require('vs/base/browser/mouseEvent');
import keyboardEvent = require('vs/base/browser/keyboardEvent');
import errors = require('vs/base/common/errors');
import browserService = require('vs/base/browser/browserService');

export type IKeyboardEvent = keyboardEvent.IKeyboardEvent;
export type IMouseEvent = mouseEvent.IMouseEvent;

export function clearNode (node:HTMLElement) {
	while (node.firstChild) {
		node.removeChild(node.firstChild);
	}
}

/**
 * Calls JSON.Stringify with a replacer to break apart any circular references.
 * This prevents JSON.stringify from throwing the exception
 *  "Uncaught TypeError: Converting circular structure to JSON"
 */
export function safeStringifyDOMAware(obj: any):string {
	var seen:any[] = [];
	return JSON.stringify(obj, (key, value) => {

		// HTML elements are never going to serialize nicely
		if(value instanceof Element) {
			return '[Element]';
		}

		if(Types.isObject(value) || Array.isArray(value)) {
			if(seen.indexOf(value) !== -1) {
				return '[Circular]';
			} else {
				seen.push(value);
			}
		}
		return value;
	});
}

export function isInDOM(node:Node):boolean {
	while (node) {
		if (node === document.body) {
			return true;
		}
		node = node.parentNode;
	}
	return false;
}

var _blank = ' '.charCodeAt(0);
var lastStart:number, lastEnd:number;

function _findClassName(node:HTMLElement, className:string): void {

	var classes = node.className;
	if(!classes) {
		lastStart = -1;
		return;
	}

	className = className.trim();

	var classesLen = classes.length,
		classLen = className.length;

	if(classLen === 0) {
		lastStart = -1;
		return;
	}

	if(classesLen < classLen) {
		lastStart = -1;
		return;
	}

	if(classes === className) {
		lastStart = 0;
		lastEnd = classesLen;
		return;
	}

	var idx = -1,
		idxEnd:number;

	while ((idx = classes.indexOf(className, idx + 1)) >= 0) {

		idxEnd = idx + classLen;

		// a class that is followed by another class
		if((idx === 0 || classes.charCodeAt(idx - 1) === _blank) && classes.charCodeAt(idxEnd) === _blank) {
			lastStart = idx;
			lastEnd = idxEnd + 1;
			return;
		}

		// last class
		if(idx > 0 && classes.charCodeAt(idx - 1) === _blank && idxEnd === classesLen) {
			lastStart = idx - 1;
			lastEnd = idxEnd;
			return;
		}

		// equal - duplicate of cmp above
		if(idx === 0 && idxEnd === classesLen) {
			lastStart = 0;
			lastEnd = idxEnd;
			return;
		}
	}

	lastStart = -1;
}

/**
 * @param node a dom node
 * @param className a class name
 * @return true if the className attribute of the provided node contains the provided className
 */
export function hasClass(node:HTMLElement, className:string): boolean {
	_findClassName(node, className);
	return lastStart !== -1;
}

/**
 * Adds the provided className to the provided node. This is a no-op
 * if the class is already set.
 * @param node a dom node
 * @param className a class name
 */
export function addClass(node:HTMLElement, className:string): void {
	if(!node.className) { // doesn't have it for sure
		node.className = className;
	} else {
		_findClassName(node, className); // see if it's already there
		if(lastStart === -1) {
			node.className = node.className + ' ' + className;
		}
	}
}

/**
 * Removes the className for the provided node. This is a no-op
 * if the class isn't present.
 * @param node a dom node
 * @param className a class name
 */
export function removeClass(node:HTMLElement, className:string): void {
	_findClassName(node, className);
	if (lastStart === -1) {
		return; // Prevent styles invalidation if not necessary
	} else {
		node.className = node.className.substring(0, lastStart) + node.className.substring(lastEnd);
	}
}

/**
 * @param node a dom node
 * @param className a class name
 * @param shouldHaveIt
 */
export function toggleClass(node:HTMLElement, className:string, shouldHaveIt?:boolean): void {
	_findClassName(node, className);
	if(lastStart !== -1 && !shouldHaveIt) {
		removeClass(node, className);
	}
	if(lastStart === -1 && shouldHaveIt) {
		addClass(node, className);
	}
}

export var StyleMutator = {
	setMaxWidth: (domNode:HTMLElement, maxWidth:number) => {
		var desiredValue = maxWidth + 'px';
		if (domNode.style.maxWidth !== desiredValue) {
			domNode.style.maxWidth = desiredValue;
		}
	},
	setWidth: (domNode:HTMLElement, width:number) => {
		var desiredValue = width + 'px';
		if (domNode.style.width !== desiredValue) {
			domNode.style.width = desiredValue;
		}
	},
	setHeight: (domNode:HTMLElement, height:number) => {
		var desiredValue = height + 'px';
		if (domNode.style.height !== desiredValue) {
			domNode.style.height = desiredValue;
		}
	},
	setTop: (domNode:HTMLElement, top:number) => {
		var desiredValue = top + 'px';
		if (domNode.style.top !== desiredValue) {
			domNode.style.top = desiredValue;
		}
	},
	setLeft: (domNode:HTMLElement, left:number) => {
		var desiredValue = left + 'px';
		if (domNode.style.left !== desiredValue) {
			domNode.style.left = desiredValue;
		}
	},
	setBottom: (domNode:HTMLElement, bottom:number) => {
		var desiredValue = bottom + 'px';
		if (domNode.style.bottom !== desiredValue) {
			domNode.style.bottom = desiredValue;
		}
	},
	setRight: (domNode:HTMLElement, right:number) => {
		var desiredValue = right + 'px';
		if (domNode.style.right !== desiredValue) {
			domNode.style.right = desiredValue;
		}
	},
	setFontSize: (domNode:HTMLElement, fontSize:number) => {
		var desiredValue = fontSize + 'px';
		if (domNode.style.fontSize !== desiredValue) {
			domNode.style.fontSize = desiredValue;
		}
	},
	setLineHeight: (domNode:HTMLElement, lineHeight:number) => {
		var desiredValue = lineHeight + 'px';
		if (domNode.style.lineHeight !== desiredValue) {
			domNode.style.lineHeight = desiredValue;
		}
	},
	setTransform: null,
	setDisplay: (domNode:HTMLElement, desiredValue:string) => {
		if (domNode.style.display !== desiredValue) {
			domNode.style.display = desiredValue;
		}
	},
	setVisibility: (domNode:HTMLElement, desiredValue:string) => {
		if (domNode.style.visibility !== desiredValue) {
			domNode.style.visibility = desiredValue;
		}
	},
};

// Define setTransform
function setWebkitTransform(domNode: HTMLElement, desiredValue: string): void {
	if (domNode.getAttribute('data-transform') !== desiredValue) {
		domNode.setAttribute('data-transform', desiredValue);
		(<any>domNode.style).webkitTransform = desiredValue;
	}
}
function setTransform(domNode: HTMLElement, desiredValue: string): void {
	if (domNode.getAttribute('data-transform') !== desiredValue) {
		domNode.setAttribute('data-transform', desiredValue);
		domNode.style.transform = desiredValue;
	}
}
(function () {
	var testDomNode = document.createElement('div');
	if (typeof (<any>testDomNode.style).webkitTransform !== 'undefined') {
		StyleMutator.setTransform = setWebkitTransform;
	} else {
		StyleMutator.setTransform = setTransform;
	}
})();

export function addListener(node:Element, type:string, handler:(event:any)=>void, useCapture?:boolean):()=>void;
export function addListener(node:Window, type:string, handler:(event:any)=>void, useCapture?:boolean):()=>void;
export function addListener(node:Document, type:string, handler:(event:any)=>void, useCapture?:boolean):()=>void;
export function addListener(node:any, type:string, handler:(event:any)=>void, useCapture?:boolean):()=>void {
	var wrapHandler = function (e):void {
		e = e || window.event;
		handler(e);
	};

	if (Types.isFunction(node.addEventListener)) {
		node.addEventListener(type, wrapHandler, useCapture || false);
		return function () {
			if (!wrapHandler) {
				// Already removed
				return;
			}
			node.removeEventListener(type, wrapHandler, useCapture || false);

			// Prevent leakers from holding on to the dom node or handler func
			wrapHandler = null;
			node = null;
			handler = null;
		};
	}

	node.attachEvent('on' + type, wrapHandler);
	return function () { node.detachEvent('on' + type, wrapHandler); };
}

export function addDisposableListener(node:Element, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable;
export function addDisposableListener(node:Window, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable;
export function addDisposableListener(node:Document, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable;
export function addDisposableListener(node:any, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable {
	var dispose = addListener(node, type, handler, useCapture);
	return {
		dispose: dispose
	};
}

export interface IAddStandardDisposableListenerSignature {
	(node:HTMLElement, type:'click', handler:(event:IMouseEvent)=>void, useCapture?:boolean): Lifecycle.IDisposable;
	(node:HTMLElement, type:'keydown', handler:(event:IKeyboardEvent)=>void, useCapture?:boolean): Lifecycle.IDisposable;
	(node:HTMLElement, type:'keypress', handler:(event:IKeyboardEvent)=>void, useCapture?:boolean): Lifecycle.IDisposable;
	(node:HTMLElement, type:'keyup', handler:(event:IKeyboardEvent)=>void, useCapture?:boolean): Lifecycle.IDisposable;
	(node:HTMLElement, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable;
}
function _wrapAsStandardMouseEvent(handler:(e:IMouseEvent)=>void): (e:MouseEvent) => void {
	return function (e:MouseEvent) {
		return handler(new mouseEvent.StandardMouseEvent(e));
	};
}
function _wrapAsStandardKeyboardEvent(handler:(e:IKeyboardEvent)=>void): (e:KeyboardEvent) => void {
	return function (e:KeyboardEvent) {
		return handler(new keyboardEvent.StandardKeyboardEvent(e));
	};
}
export var addStandardDisposableListener:IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node:HTMLElement, type:string, handler:(event:any)=>void, useCapture?:boolean): Lifecycle.IDisposable {
	var wrapHandler = handler;

	if (type === 'click') {
		wrapHandler = _wrapAsStandardMouseEvent(handler);
	} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
		wrapHandler = _wrapAsStandardKeyboardEvent(handler);
	}

	node.addEventListener(type, wrapHandler, useCapture || false);
	return {
		dispose: function () {
			if (!wrapHandler) {
				// Already removed
				return;
			}
			node.removeEventListener(type, wrapHandler, useCapture || false);

			// Prevent leakers from holding on to the dom node or handler func
			wrapHandler = null;
			node = null;
			handler = null;
		}
	};
};

export function addNonBubblingMouseOutListener(node:Element, handler:(event:any)=>void):()=>void {
	return addListener(node, 'mouseout', (e:MouseEvent) => {
		// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
		var toElement = <Node>(e.relatedTarget || e.toElement);
		while (toElement && toElement !== node) {
			toElement = toElement.parentNode;
		}
		if (toElement === node) {
			return;
		}

		handler(e);
	});
}
export function addDisposableNonBubblingMouseOutListener(node:Element, handler:(event:MouseEvent)=>void): Lifecycle.IDisposable {
	var dispose = addNonBubblingMouseOutListener(node, handler);
	return {
		dispose: dispose
	};
}

var _animationFrame = (function() {
	var emulatedRequestAnimationFrame = (callback:(time:number)=>void):number => {
		return setTimeout(() => callback(new Date().getTime()), 0);
	};
	var nativeRequestAnimationFrame:(callback:(time:number)=>void)=>number =
			self.requestAnimationFrame
			|| (<any>self).msRequestAnimationFrame
			|| (<any>self).webkitRequestAnimationFrame
			|| (<any>self).mozRequestAnimationFrame
			|| (<any>self).oRequestAnimationFrame;

	var emulatedCancelAnimationFrame = (id:number) => {};
	var nativeCancelAnimationFrame:(id:number)=>void =
			self.cancelAnimationFrame || (<any>self).cancelRequestAnimationFrame
			|| (<any>self).msCancelAnimationFrame || (<any>self).msCancelRequestAnimationFrame
			|| (<any>self).webkitCancelAnimationFrame || (<any>self).webkitCancelRequestAnimationFrame
			|| (<any>self).mozCancelAnimationFrame || (<any>self).mozCancelRequestAnimationFrame
			|| (<any>self).oCancelAnimationFrame || (<any>self).oCancelRequestAnimationFrame;

	var isNative = !!nativeRequestAnimationFrame;
	var request = nativeRequestAnimationFrame || emulatedRequestAnimationFrame;
	var cancel = nativeCancelAnimationFrame || nativeCancelAnimationFrame;

	return {
		isNative: isNative,
		request: (callback:(time:number)=>void): number => {
			return request(callback);
		},
		cancel: (id:number) => {
			return cancel(id);
		}
	};
})();

/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed immediately.
 * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
 */
export var runAtThisOrScheduleAtNextAnimationFrame:(runner:()=>void, priority?:number)=>Lifecycle.IDisposable;
/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed at the next animation frame.
 * @return token that can be used to cancel the scheduled runner.
 */
export var scheduleAtNextAnimationFrame:(runner:()=>void, priority?:number)=>Lifecycle.IDisposable;

class AnimationFrameQueueItem implements Lifecycle.IDisposable {

	private _runner: () => void;
	public priority: number;
	private _canceled: boolean;

	constructor(runner: () => void, priority: number) {
		this._runner = runner;
		this.priority = priority;
		this._canceled = false;
	}

	public dispose(): void {
		this._canceled = true;
	}

	public execute(): void {
		if (this._canceled) {
			return;
		}

		try {
			this._runner();
		} catch (e) {
			errors.onUnexpectedError(e);
		}
	}

	// Sort by priority (largest to lowest)
	public static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
		return b.priority - a.priority;
	}
}

(function() {
	/**
	 * The runners scheduled at the next animation frame
	 */
	var NEXT_QUEUE: AnimationFrameQueueItem[] = [];
	/**
	 * The runners scheduled at the current animation frame
	 */
	var CURRENT_QUEUE: AnimationFrameQueueItem[] = null;
	/**
	 * A flag to keep track if the native requestAnimationFrame was already called
	 */
	var animFrameRequested = false;
	/**
	 * A flag to indicate if currently handling a native requestAnimationFrame callback
	 */
	var inAnimationFrameRunner = false;

	var animationFrameRunner = () => {
		animFrameRequested = false;

		CURRENT_QUEUE = NEXT_QUEUE;
		NEXT_QUEUE = [];

		inAnimationFrameRunner = true;
		while (CURRENT_QUEUE.length > 0) {
			CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
			var top = CURRENT_QUEUE.shift();
			top.execute();
		}
		inAnimationFrameRunner = false;
	};

	scheduleAtNextAnimationFrame = (runner:()=>void, priority:number = 0) => {
		var item = new AnimationFrameQueueItem(runner, priority);
		NEXT_QUEUE.push(item);

		if (!animFrameRequested) {
			animFrameRequested = true;

			// TODO@Alex: also check if it is electron
			if (Browser.isChrome) {
				var handle:number;
				_animationFrame.request(function () {
					clearTimeout(handle);
					animationFrameRunner();
				});
				// This is a fallback in-case chrome dropped
				// the request for an animation frame. This
				// is sick but was spotted in the wild
				handle = setTimeout(animationFrameRunner, 1000);
			} else {
				_animationFrame.request(animationFrameRunner);
			}
		}

		return item;
	};

	runAtThisOrScheduleAtNextAnimationFrame = (runner:()=>void, priority?:number) => {
		if (inAnimationFrameRunner) {
			var item = new AnimationFrameQueueItem(runner, priority);
			CURRENT_QUEUE.push(item);
			return item;
		} else {
			return scheduleAtNextAnimationFrame(runner, priority);
		}
	};
})();

/// <summary>
/// Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
/// </summary>
export interface IEventMerger<R> {
	(lastEvent:R, currentEvent:Event):R;
}

var MINIMUM_TIME_MS = 16;
var DEFAULT_EVENT_MERGER:IEventMerger<Event> = function (lastEvent:Event, currentEvent:Event) {
	return currentEvent;
};

function timeoutThrottledListener<R>(node:any, type:string, handler:(event:R)=>void, eventMerger:IEventMerger<R> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs:number = MINIMUM_TIME_MS):()=>void {
	var lastEvent:R = null, lastHandlerTime = 0, timeout = -1;

	function invokeHandler(): void {
		timeout = -1;
		lastHandlerTime = (new Date()).getTime();
		handler(lastEvent);
		lastEvent = null;
	};

	var unbinder = addListener(node, type, function (e) {
		lastEvent = eventMerger(lastEvent, e);
		var elapsedTime = (new Date()).getTime() - lastHandlerTime;

		if (elapsedTime >= minimumTimeMs) {
			if (timeout !== -1) {
				window.clearTimeout(timeout);
			}
			invokeHandler();
		} else {
			if (timeout === -1) {
				timeout = window.setTimeout(invokeHandler, minimumTimeMs - elapsedTime);
			}
		}
	});

	return function () {
		if (timeout !== -1) {
			window.clearTimeout(timeout);
		}
		unbinder();
	};
}

export function addThrottledListener<R>(node:any, type:string, handler:(event:R)=>void, eventMerger?:IEventMerger<R>, minimumTimeMs?:number):()=>void {
	return timeoutThrottledListener(node, type, handler, eventMerger, minimumTimeMs);
}

export function addDisposableThrottledListener<R>(node:any, type:string, handler:(event:R)=>void, eventMerger?:IEventMerger<R>, minimumTimeMs?:number):Lifecycle.IDisposable {
	var dispose = addThrottledListener(node, type, handler, eventMerger, minimumTimeMs);
	return {
		dispose: dispose
	};
}

export function getComputedStyle(el:HTMLElement):CSSStyleDeclaration {
	return document.defaultView.getComputedStyle(el, null);
}

// Adapted from WinJS
// Converts a CSS positioning string for the specified element to pixels.
var convertToPixels:(element:HTMLElement, value:string)=>number = (function() {
	var pixelsRE = /^-?\d+(\.\d+)?(px)?$/i;
	var numberRE = /^-?\d+(\.\d+)?/i;
	return function(element:HTMLElement, value:string):number {
		return parseFloat(value) || 0;
	};
})();

function getDimension(element:HTMLElement, cssPropertyName:string, jsPropertyName:string):number {
	var computedStyle:CSSStyleDeclaration = getComputedStyle(element);
	var value = '0';
	if (computedStyle) {
		if (computedStyle.getPropertyValue) {
			value = computedStyle.getPropertyValue(cssPropertyName);
		} else {
			// IE8
			value = (<any>computedStyle).getAttribute(jsPropertyName);
		}
	}
	return convertToPixels(element, value);
}

var sizeUtils = {

	getBorderLeftWidth: function (element:HTMLElement):number {
		return getDimension(element, 'border-left-width', 'borderLeftWidth');
	},
	getBorderTopWidth: function (element:HTMLElement):number {
		return getDimension(element, 'border-top-width', 'borderTopWidth');
	},
	getBorderRightWidth: function (element:HTMLElement):number {
		return getDimension(element, 'border-right-width', 'borderRightWidth');
	},
	getBorderBottomWidth: function (element:HTMLElement):number {
		return getDimension(element, 'border-bottom-width', 'borderBottomWidth');
	},

	getPaddingLeft: function (element:HTMLElement):number {
		return getDimension(element, 'padding-left', 'paddingLeft');
	},
	getPaddingTop: function (element:HTMLElement):number {
		return getDimension(element, 'padding-top', 'paddingTop');
	},
	getPaddingRight: function (element:HTMLElement):number {
		return getDimension(element, 'padding-right', 'paddingRight');
	},
	getPaddingBottom: function (element:HTMLElement):number {
		return getDimension(element, 'padding-bottom', 'paddingBottom');
	},

	getMarginLeft: function (element:HTMLElement):number {
		return getDimension(element, 'margin-left', 'marginLeft');
	},
	getMarginTop: function (element:HTMLElement):number {
		return getDimension(element, 'margin-top', 'marginTop');
	},
	getMarginRight: function (element:HTMLElement):number {
		return getDimension(element, 'margin-right', 'marginRight');
	},
	getMarginBottom: function (element:HTMLElement):number {
		return getDimension(element, 'margin-bottom', 'marginBottom');
	},
	__commaSentinel: false
};

// ----------------------------------------------------------------------------------------
// Position & Dimension

export function getTopLeftOffset (element:HTMLElement):{left:number; top:number;} {
	// Adapted from WinJS.Utilities.getPosition
	// and added borders to the mix

	var offsetParent = element.offsetParent, top = element.offsetTop, left = element.offsetLeft;

	while ((element = <HTMLElement>element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
		top -= element.scrollTop;
		var c = getComputedStyle(element);
		if (c) {
			left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
		}

		if (element === offsetParent) {
			left += sizeUtils.getBorderLeftWidth(element);
			top += sizeUtils.getBorderTopWidth(element);
			top += element.offsetTop;
			left += element.offsetLeft;
			offsetParent = element.offsetParent;
		}
	}

	return {
		left: left,
		top: top
	};
}

export interface IDomNodePosition {
	left:number;
	top:number;
	width:number;
	height:number;
}

export function getDomNodePosition (domNode:HTMLElement):IDomNodePosition {
	var r = getTopLeftOffset(domNode);
	return {
		left: r.left,
		top: r.top,
		width: domNode.clientWidth,
		height: domNode.clientHeight
	};
}

// Adapted from WinJS
// Gets the width of the content of the specified element. The content width does not include borders or padding.
export function getContentWidth(element:HTMLElement):number {
	var border = sizeUtils.getBorderLeftWidth(element) + sizeUtils.getBorderRightWidth(element);
	var padding = sizeUtils.getPaddingLeft(element) + sizeUtils.getPaddingRight(element);
	return element.offsetWidth - border - padding;
}

// Adapted from WinJS
// Gets the width of the element, including margins.
export function getTotalWidth(element:HTMLElement):number {
	var margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
	return element.offsetWidth + margin;
}

// Adapted from WinJS
// Gets the height of the content of the specified element. The content height does not include borders or padding.
export function getContentHeight(element:HTMLElement):number {
	var border = sizeUtils.getBorderTopWidth(element) + sizeUtils.getBorderBottomWidth(element);
	var padding = sizeUtils.getPaddingTop(element) + sizeUtils.getPaddingBottom(element);
	return element.offsetHeight - border - padding;
}

// Adapted from WinJS
// Gets the height of the element, including its margins.
export function getTotalHeight(element:HTMLElement):number {
	var margin = sizeUtils.getMarginTop(element) + sizeUtils.getMarginBottom(element);
	return element.offsetHeight + margin;
}

// Adapted from WinJS
// Gets the left coordinate of the specified element relative to the specified parent.
export function getRelativeLeft(element:HTMLElement, parent:HTMLElement):number {
	if (element === null) {
		return 0;
	}

	var left = element.offsetLeft;
	var e = <HTMLElement>element.parentNode;
	while (e !== null) {
		left -= e.offsetLeft;

		if (e === parent) {
			break;
		}
		e = <HTMLElement>e.parentNode;
	}

	return left;
}

// Adapted from WinJS
// Gets the top coordinate of the element relative to the specified parent.
export function getRelativeTop(element:HTMLElement, parent:HTMLElement):number {
	if (element === null) {
		return 0;
	}

	var top = element.offsetTop;
	var e = <HTMLElement>element.parentNode;
	while (e !== null) {
		top -= e.offsetTop;

		if (e === parent) {
			break;
		}
		e = <HTMLElement>e.parentNode;
	}

	return top;
}

// ----------------------------------------------------------------------------------------

export function isAncestor (testChild:Node, testAncestor:Node):boolean {
	while(testChild) {
		if (testChild === testAncestor) {
			return true;
		}
		testChild = testChild.parentNode;
	}

	return false;
}

export function findParentWithClass (node:HTMLElement, clazz:string, stopAtClazz?:string):HTMLElement {
	while (node) {
		if (hasClass(node, clazz)) {
			return node;
		}

		if (stopAtClazz && hasClass(node, stopAtClazz)) {
			return null;
		}

		node = <HTMLElement>node.parentNode;
	}

	return null;
}

export function createStyleSheet(): HTMLStyleElement {
	var style = document.createElement('style');
	style.type = 'text/css';
	style.media = 'screen';
	document.getElementsByTagName('head')[0].appendChild(style);
	return style;
}

var sharedStyle = <any>createStyleSheet();

function getDynamicStyleSheetRules(style:any) {
	if (style && style.sheet && style.sheet.rules) {
		// Chrome, IE
		return style.sheet.rules;
	}
	if (style && style.sheet && style.sheet.cssRules) {
		// FF
		return style.sheet.cssRules;
	}
	return [];
}

export function createCSSRule(selector:string, cssText:string, style:HTMLStyleElement=sharedStyle): void {
	if (!style || !cssText) {
		return;
	}

	(<any>style.sheet).insertRule(selector + '{' + cssText + '}', 0);
}

export function getCSSRule(selector:string, style:HTMLStyleElement=sharedStyle): any {
	if (!style) {
		return null;
	}

	var rules = getDynamicStyleSheetRules(style);
	for (var i = 0; i < rules.length; i++) {
		var rule = rules[i];
		var normalizedSelectorText = rule.selectorText.replace(/::/gi, ':');
		if (normalizedSelectorText === selector) {
			return rule;
		}
	}

	return null;
}

export function removeCSSRulesWithPrefix(ruleName:string, style=sharedStyle): void {
	if (!style) {
		return;
	}

	var rules = getDynamicStyleSheetRules(style);
	var toDelete: number[] = [];
	for (var i = 0; i < rules.length; i++) {
		var rule = rules[i];
		var normalizedSelectorText = rule.selectorText.replace(/::/gi, ':');
		if (normalizedSelectorText.indexOf(ruleName) === 0) {
			toDelete.push(i);
		}
	}

	for (var i = toDelete.length - 1; i >= 0; i--) {
		style.sheet.deleteRule(toDelete[i]);
	}
}

export function isHTMLElement(o:any): o is HTMLElement {
	return browserService.getService().isHTMLElement(o);
}

export var EventType = {
	// Mouse
	CLICK: 'click',
	DBLCLICK: 'dblclick',
	MOUSE_UP: 'mouseup',
	MOUSE_DOWN: 'mousedown',
	MOUSE_OVER: 'mouseover',
	MOUSE_MOVE: 'mousemove',
	MOUSE_OUT: 'mouseout',
	CONTEXT_MENU: 'contextmenu',
	// Keyboard
	KEY_DOWN: 'keydown',
	KEY_PRESS: 'keypress',
	KEY_UP: 'keyup',
	// HTML Document
	LOAD: 'load',
	UNLOAD: 'unload',
	ABORT: 'abort',
	ERROR: 'error',
	RESIZE: 'resize',
	SCROLL: 'scroll',
	// Form
	SELECT: 'select',
	CHANGE: 'change',
	SUBMIT: 'submit',
	RESET: 'reset',
	FOCUS: 'focus',
	BLUR: 'blur',
	INPUT: 'input',
	// Local Storage
	STORAGE: 'storage',
	// Drag
	DRAG_START: 'dragstart',
	DRAG: 'drag',
	DRAG_ENTER: 'dragenter',
	DRAG_LEAVE: 'dragleave',
	DRAG_OVER: 'dragover',
	DROP: 'drop',
	DRAG_END: 'dragend',
	// Animation
	ANIMATION_START: Browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
	ANIMATION_END: Browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
	ANIMATION_ITERATION: Browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
};

export var EventHelper = {
	stop: function (e:Event, cancelBubble?:boolean) {
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			// IE8
			(<any>e).returnValue = false;
		}

		if (cancelBubble) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				// IE8
				e.cancelBubble = true;
			}
		}
	}
};

export interface IFocusTracker {
	addBlurListener(fn):()=>void;
	addFocusListener(fn):()=>void;
	dispose():void;
}

export function selectTextInInputElement(textArea:HTMLTextAreaElement): void {
	// F12 has detected in their automated tests that selecting throws sometimes,
	// the root cause remains a mistery. Bug #378257 filled against IE.
	try {
		var scrollState:number[] = saveParentsScrollTop(textArea);
		textArea.select();
		if (textArea.setSelectionRange) {
			// on iOS Safari, .select() moves caret to the end of the text instead of selecting
			// see http://stackoverflow.com/questions/3272089/programmatically-selecting-text-in-an-input-field-on-ios-devices-mobile-safari
			textArea.setSelectionRange(0, 9999);
		}
		restoreParentsScrollTop(textArea, scrollState);
	} catch (e) {
		// no-op
	}
}

export function saveParentsScrollTop(node:Element): number[] {
	var r:number[] = [];
	for (var i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
		r[i] = node.scrollTop;
		node = <Element>node.parentNode;
	}
	return r;
}

export function restoreParentsScrollTop(node:Element, state:number[]): void {
	for (var i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
		if (node.scrollTop !== state[i]) {
			node.scrollTop = state[i];
		}
		node = <Element>node.parentNode;
	}
}

export function trackFocus(element:HTMLElement):IFocusTracker {

	var hasFocus:boolean = false, loosingFocus = false;
	var eventEmitter = new Emitter.EventEmitter(), unbind = [], result:IFocusTracker = null;

	// fill result
	result = {
		addFocusListener: function(fn) {
			var h = eventEmitter.addListener('focus', fn);
			unbind.push(h);
			return h;
		},
		addBlurListener: function(fn) {
			var h = eventEmitter.addListener('blur', fn);
			unbind.push(h);
			return h;
		},
		dispose: function() {
			while(unbind.length > 0) {
				unbind.pop()();
			}
		}
	};

	var onFocus = function(event) {
		loosingFocus = false;
		if(!hasFocus) {
			hasFocus = true;
			eventEmitter.emit('focus', {});
		}
	};

	var onBlur = function(event) {
		if(hasFocus) {
			loosingFocus = true;
			window.setTimeout(function() {
				if(loosingFocus) {
					loosingFocus = false;
					hasFocus = false;
					eventEmitter.emit('blur', {});
				}
			}, 0);
		}
	};

	// bind
	unbind.push(addListener(element, EventType.FOCUS, onFocus, true));
	unbind.push(addListener(element, EventType.BLUR, onBlur, true));

	return result;
}

export function removeScriptTags(html:string):string {
	var div = document.createElement('div');
	div.innerHTML = html;

	var scripts = div.getElementsByTagName('script');
	var i = scripts.length;

	while (i--) {
		scripts[i].parentNode.removeChild(scripts[i]);
	}

	return div.innerHTML;
};

export function append<T extends Node>(parent: HTMLElement, child: T): T {
	parent.appendChild(child);
	return child;
}

var SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;

// Similar to builder, but much more lightweight
export function emmet(description: string):HTMLElement {
	var match = SELECTOR_REGEX.exec(description);

	if (!match) {
		throw new Error('Bad use of emmet');
	}

	var result = document.createElement(match[1] || 'div');
	match[3] && (result.id = match[3]);
	match[4] && (result.className = match[4].replace(/\./g, ' ').trim());

	return result;
};

export function show(element: HTMLElement): void {
	element.style.display = null;
}

export function hide(element: HTMLElement): void {
	element.style.display = 'none';
}


text:
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class ConfigService {

    get configuration(): any {
        return environment.configuration;
    }

    get corsProxy(): string {
        return environment.corsProxy;
    }
}


text:
{% extends 'arpegio-core/base.html' %}

{% block head %}
  {% with title=category %}
    {{ block.super }}
  {% endwith %}
{% endblock %}

{% block content %}

Category Archives: {{ category }}

{% endblock %}


text:
@implementation MadvertiseSDKSampleAppDelegate_iPhone

#pragma mark -
#pragma mark

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

@end


text:
@interface SCViewController : UIViewController

@property (nonatomic, strong) RequestManager *requestManager;
@property (nonatomic, strong) UIActivityIndicatorView *loadingSpinner;

- (void)showLoadingSpinner;
- (void)hideLoadingSpinner;

@end


text:
/*
 * module to include the modules
 */

config_require(ip-mib/ipAddressTable);
config_require(ip-mib/inetNetToMediaTable);
config_require(ip-mib/ipSystemStatsTable);
config_require(ip-mib/ip_scalars);
config_add_mib(IP-MIB)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.CodeDom.Compiler;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Automapping;
using FluentNHibernate.Mapping;
using T4FluentNH.Metadata;
using NHibernate;
using NHibernate.Collection;
using NHibernate.Util;
using System.Threading.Tasks;
//<EntityProjectItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><EntityFullName>T4FluentNH.Tests.OneToMany.O2MPerson</EntityFullName><EntityFilePaths><string>OneToMany\O2MPerson.cs</string></EntityFilePaths><OverrideFilePaths><string>OneToMany\O2MPerson.cs</string></OverrideFilePaths><GeneratedFilePath>O2MPerson.generated.cs</GeneratedFilePath></EntityProjectItem>
namespace T4FluentNH.Tests.OneToMany
{
    [GeneratedCode("T4Template", "1.0")]
    public partial class O2MPerson
    {

        #region RelationsMetadata
        #pragma warning disable

        public new static readonly Dictionary<string, RelationMetadata> RelationsMetadata =
            new Dictionary<string, RelationMetadata>
            {
                {"Cars", new OneToManyRelationMetadata
                {
                    RelatedModelType = typeof(O2MCar),
                    RelatedModelProperty = typeof(O2MCar).GetProperty("Owner"),
                    RelatedModelIdProperty = typeof(O2MCar).GetProperty("Id"),
                    AssociationType = AssociationType.Bidirectional,
                    Field = typeof(O2MPerson).GetField("_cars", BindingFlags.Instance | BindingFlags.NonPublic),
                    ParameterName = "car",
                    Property = typeof(O2MPerson).GetProperty("Cars"),
                    AddMethod = typeof(O2MPerson).GetMethods().FirstOrDefault(o => o.Name == "AddCar" && o.GetParameters().Length == 1 && o.GetParameters()[0].ParameterType == typeof(O2MCar)),
                    RemoveMethod = typeof(O2MPerson).GetMethods().FirstOrDefault(o => o.Name == "RemoveCar" && o.GetParameters().Length == 1 && o.GetParameters()[0].ParameterType == typeof(O2MCar)),
                    CollectionMapType = CollectionMapType.Unknown,

                }},

            };
        #pragma warning restore
        #endregion

        #region Cars

        private ISet<O2MCar> _cars;

        public virtual void AddCar(O2MCar car)
        {
            this.AddOneToMany(o => o.Cars, car, o => o.Owner, o=> o.RemoveCar);
        }

        public virtual Task AddCarAsync(O2MCar car)
        {
            return this.AddOneToManyAsync(o => o.Cars, car, o => o.Owner, o=> o.RemoveCarAsync);
        }

        public virtual void RemoveCar(O2MCar car)
        {
            this.RemoveOneToMany(o => o.Cars, car, o => o.Owner);
        }

        public virtual Task RemoveCarAsync(O2MCar car)
        {
            return this.RemoveOneToManyAsync(o => o.Cars, car, o => o.Owner);
        }

        #endregion

        private void ResetField<T>(ref T field, T value, ref bool synthIsSetField)
        {
            field = value;
            synthIsSetField = false;
        }
    }
}


text:
package com.haduart.pdftablegenerator.structure;

import java.util.*;

import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;

public class Table {

    // Table attributes
    private String title = null;
    private float margin;
    private float height;
    private PDRectangle pageSize;
    private boolean isLandscape;
    private float rowHeight;

    // font attributes
    private PDFont textFont;
    private float fontSize;

    // Content attributes
    private Integer numberOfRows;
    private List<Column> columns;
    private SortedMap<Integer, LinkedList> dynamicContent;
    private float cellMargin;

    public Table() {
    }

    public Integer getNumberOfColumns() {
        return this.getColumns().size();
    }

    public float getWidth() {
        float tableWidth = 0f;
        for (Column column : columns) {
            tableWidth += column.getWidth();
        }
        return tableWidth;
    }

    public float getMargin() {
        return margin;
    }

    public void setMargin(float margin) {
        this.margin = margin;
    }

    public PDRectangle getPageSize() {
        return pageSize;
    }

    public void setPageSize(PDRectangle pageSize) {
        this.pageSize = pageSize;
    }

    public PDFont getTextFont() {
        return textFont;
    }

    public void setTextFont(PDFont textFont) {
        this.textFont = textFont;
    }

    public float getFontSize() {
        return fontSize;
    }

    public void setFontSize(float fontSize) {
        this.fontSize = fontSize;
    }

    public LinkedList<String> getColumnsNamesAsArray() {
        LinkedList<String> columnNames = new LinkedList<String>();
        Iterator<Column> iter = columns.iterator();
        while (iter.hasNext())
            columnNames.add(iter.next().getName());

        return columnNames;
    }

    public SortedMap<Integer, LinkedList> getDynamicContent() {
        return dynamicContent;
    }

    public void setDynamicContent(SortedMap<Integer, LinkedList> dynamicContent) {
        this.dynamicContent = dynamicContent;
    }

    public List<Column> getColumns() {
        return columns;
    }

    public void setColumns(List<Column> columns) {
        this.columns = columns;
    }

    public Integer getNumberOfRows() {
        return numberOfRows;
    }

    public void setNumberOfRows(Integer numberOfRows) {
        this.numberOfRows = numberOfRows;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public float getRowHeight() {
        return rowHeight;
    }

    public void setRowHeight(float rowHeight) {
        this.rowHeight = rowHeight;
    }

    public float getCellMargin() {
        return cellMargin;
    }

    public void setCellMargin(float cellMargin) {
        this.cellMargin = cellMargin;
    }

    public boolean isLandscape() {
        return isLandscape;
    }

    public void setLandscape(boolean isLandscape) {
        this.isLandscape = isLandscape;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}


text:
class Installation < ActiveRecord::Base
  belongs_to :versioned_product
  belongs_to :office
end


text:
Please select an issue template from
https://github.com/facebookresearch/detectron2/issues/new/choose .

Otherwise your issue will be closed.


text:
@implementation SamuraiCSSObject(NumberVmax)

- (BOOL)isVmax
{
	return NO;
}

@end

#pragma mark -

@implementation SamuraiCSSNumberVmax

+ (instancetype)parseValue:(KatanaValue *)value
{
	if ( NULL == value )
		return nil;

	SamuraiCSSNumberVmax * result = nil;

	if ( KATANA_VALUE_VMAX == value->unit )
	{
		result = [[SamuraiCSSNumberVmax alloc] init];
		result.value = value->fValue;
	}

	return result;
}

#pragma mark -

+ (instancetype)vmax:(CGFloat)value
{
	SamuraiCSSNumberVmax * result = [[SamuraiCSSNumberVmax alloc] init];
	result.value = value;
	return result;
}

#pragma mark -

- (id)init
{
	self = [super init];
	if ( self )
	{
		self.value = 0.0f;
		self.unit = @"vmax";
	}
	return self;
}

- (void)dealloc
{
}

#pragma mark -

- (NSString *)description
{
	return [NSString stringWithFormat:@"Vmax( %.2f )", self.value];
}

- (BOOL)isVmax
{
	return YES;
}

- (BOOL)isAbsolute
{
	return YES;
}

- (CGFloat)computeValue:(CGFloat)value
{
	return self.value;
}

@end

// ----------------------------------
// Unit test
// ----------------------------------

#pragma mark -

#if __SAMURAI_TESTING__

TEST_CASE( WebCore, CSSNumberRad )

DESCRIBE( before )
{
}

DESCRIBE( after )
{
}

TEST_CASE_END

#endif	// #if __SAMURAI_TESTING__

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

#import "_pragma_pop.h"


text:
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  background-image: url(./background.jpg);
}


text:
package org.pentaho.di.repository.pur.provider;

import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.Repository;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class PluginRepositoryProviderTest {

  private RepositoryProvider pluginRepositoryProvider;
  private final String repoPassword = "password";
  private final String repoUsername = "username";

  @Before
  public void setUp() {
    pluginRepositoryProvider = spy( new RepositoryProvider() );
  }

  @Test
  public void testGetRepoUserName() {
    pluginRepositoryProvider.setUsername( repoUsername );

    String instanceRepoUsername = pluginRepositoryProvider.getUsername();

    assertEquals( repoUsername, instanceRepoUsername );
  }

  @Test
  public void testGetPassword() {
    String repoPassword = "password";
    pluginRepositoryProvider.setPassword( repoPassword );

    String instanceRepoPassword = pluginRepositoryProvider.getPassword();

    assertEquals( repoPassword, instanceRepoPassword );
  }

  @Test
  public void testGetRepository() {
    Repository repository = null;
    Repository mockRepository = mock( Repository.class );

    pluginRepositoryProvider.setRepository( mockRepository );
    repository = pluginRepositoryProvider.getRepository();

    assertNotNull( repository );
  }

  @Test
  public void testGetRepositoryShouldReconnectRepositoryOnChangePassword() {
    Repository repository = null;
    Repository mockRepository = mock( Repository.class );
    pluginRepositoryProvider.setPassword( "SomePassword" );

    pluginRepositoryProvider.setRepository( mockRepository );
    repository = pluginRepositoryProvider.getRepository();

    assertNotNull( repository );
    verify( pluginRepositoryProvider, times( 1 ) ).reconnectToRepository();
  }

  @Test
  public void testGetRepositoryShouldReconnectRepositoryOnChangeUsername() {
    Repository repository = null;
    Repository mockRepository = mock( Repository.class );
    pluginRepositoryProvider.setUsername( "SomeUsername" );

    pluginRepositoryProvider.setRepository( mockRepository );
    repository = pluginRepositoryProvider.getRepository();

    assertNotNull( repository );
    verify( pluginRepositoryProvider, times( 1 ) ).reconnectToRepository();
  }

  @Test
  public void testReconnectRepository() {
    Repository mockRepository = mock( Repository.class );
    pluginRepositoryProvider.setRepository( mockRepository );
    when( mockRepository.isConnected() ).thenReturn( true );
    pluginRepositoryProvider.setUsername( repoUsername );
    pluginRepositoryProvider.setPassword( repoPassword );

    pluginRepositoryProvider.reconnectToRepository();

    verify( mockRepository, times( 1 ) ).disconnect();
    try {
      verify( mockRepository, times( 1 ) ).connect( anyString(), anyString() );
    } catch ( KettleException e ) {
      e.printStackTrace();
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?><!-- XML的版本以及编码方式 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"><!-- 添加一个垂直线性布局 -->
	<TextView
	    android:layout_width="fill_parent"   android:layout_height="wrap_content"
	    android:textSize="20px"
	    android:gravity="center"
	    android:text="@string/textView" /><!-- 添加TextView -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:gravity="center"><!-- 添加一个水平布局 -->
    	<ImageButton
    		android:id="@+id/button01"
    		android:layout_width="wrap_content"	android:layout_height="wrap_content"
    		android:focusableInTouchMode="true"
    		android:src="@drawable/png1"/>    <!-- 添加一个ImageButton-->
    	<ImageButton
    		android:id="@+id/button02"
    		android:layout_width="wrap_content"	android:layout_height="wrap_content"
    		android:focusableInTouchMode="true"
    		android:src="@drawable/png2"/>    <!-- 添加一个ImageButton-->
    </LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:gravity="center"><!-- 添加一个水平的线性布局-->
		<ImageButton
    		android:id="@+id/button03"
    		android:layout_width="wrap_content"	android:layout_height="wrap_content"
    		android:focusableInTouchMode="true"
    		android:src="@drawable/png3"/>      <!-- 添加一个ImageButton-->
		<ImageButton
    		android:id="@+id/button04"
    		android:layout_width="wrap_content"	android:layout_height="wrap_content"
    		android:focusableInTouchMode="true"
    		android:src="@drawable/png4"/>    <!-- 添加一个ImageButton-->
    </LinearLayout>
    <TextView
      	android:id="@+id/myTextView"
    	android:textSize="30px"
    	android:layout_width="fill_parent" 	android:layout_height="wrap_content"
    	android:gravity="center"/>	<!-- 添加一个TextView-->
</LinearLayout>


text:
[![Build Status](http://cloud.drone.io/api/badges/drone-plugins/drone-slack/status.svg)](http://cloud.drone.io/drone-plugins/drone-slack)
[![Gitter chat](https://badges.gitter.im/drone/drone.png)](https://gitter.im/drone/drone)
[![Join the discussion at https://discourse.drone.io](https://img.shields.io/badge/discourse-forum-orange.svg)](https://discourse.drone.io)
[![Drone questions at https://stackoverflow.com](https://img.shields.io/badge/drone-stackoverflow-orange.svg)](https://stackoverflow.com/questions/tagged/drone.io)
[![](https://images.microbadger.com/badges/image/plugins/slack.svg)](https://microbadger.com/images/plugins/slack "Get your own image badge on microbadger.com")
[![Go Doc](https://godoc.org/github.com/drone-plugins/drone-slack?status.svg)](http://godoc.org/github.com/drone-plugins/drone-slack)
[![Go Report](https://goreportcard.com/badge/github.com/drone-plugins/drone-slack)](https://goreportcard.com/report/github.com/drone-plugins/drone-slack)

Drone plugin for sending Slack notifications. For the usage information and a listing of the available options please take a look at [the docs](http://plugins.drone.io/drone-plugins/drone-slack/).

## Build

Build the binary with the following commands:

```
go build
```

## Docker

Build the Docker image with the following commands:

```
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -a -tags netgo -o release/linux/amd64/drone-slack
docker build --rm -t plugins/slack .
```

## Usage

Execute from the working directory:

```
docker run --rm \
  -e SLACK_WEBHOOK=https://hooks.slack.com/services/... \
  -e PLUGIN_CHANNEL=foo \
  -e PLUGIN_USERNAME=drone \
  -e DRONE_REPO_OWNER=octocat \
  -e DRONE_REPO_NAME=hello-world \
  -e DRONE_COMMIT_SHA=7fd1a60b01f91b314f59955a4e4d4e80d8edf11d \
  -e DRONE_COMMIT_BRANCH=master \
  -e DRONE_COMMIT_AUTHOR=octocat \
  -e DRONE_COMMIT_AUTHOR_EMAIL=octocat@github.com \
  -e DRONE_COMMIT_AUTHOR_AVATAR="https://avatars0.githubusercontent.com/u/583231?s=460&v=4" \
  -e DRONE_COMMIT_AUTHOR_NAME="The Octocat" \
  -e DRONE_BUILD_NUMBER=1 \
  -e DRONE_BUILD_STATUS=success \
  -e DRONE_BUILD_LINK=http://github.com/octocat/hello-world \
  -e DRONE_TAG=1.0.0 \
  plugins/slack
```

## Release Preparation

Run the changelog generator.

```BASH
docker run -it --rm -v "$(pwd)":/usr/local/src/your-app githubchangeloggenerator/github-changelog-generator -u drone-plugins -p drone-slack -t <secret github token>
```

You can generate a token by logging into your GitHub account and going to Settings -> Personal access tokens.

Next we tag the PR's with the fixes or enhancements labels. If the PR does not fufil the requirements, do not add a label.

**Before moving on make sure to update the version file `version/version.go && version/version_test.go`.**

Run the changelog generator again with the future version according to semver.

```BASH
docker run -it --rm -v "$(pwd)":/usr/local/src/your-app githubchangeloggenerator/github-changelog-generator -u drone-plugins -p drone-slack <secret token> --future-release v1.0.0
```

Create your pull request for the release. Get it merged then tag the release.


text:
package asmble.examples.csimple;

import java.lang.invoke.MethodHandle;

import asmble.generated.CSimple;

class Main {
    public static void main(String[] args) {
        // Doesn't need memory or method table
        CSimple simple = new CSimple(0, new MethodHandle[0]);
        System.out.println("25 + 1 = " + simple.addOne(25));
    }
}


text:
namespace net {

class NET_EXPORT_PRIVATE ReceiveAlgorithmInterface {
 public:
  static ReceiveAlgorithmInterface* Create(const QuicClock* clock,
                                           CongestionFeedbackType type);

  virtual ~ReceiveAlgorithmInterface() {}

  // Returns false if no QuicCongestionFeedbackFrame block is needed.
  // Otherwise fills in feedback and return true.
  virtual bool GenerateCongestionFeedback(
      QuicCongestionFeedbackFrame* feedback) = 0;

  // Should be called for each incoming packet.
  // bytes: is the packet size in bytes including IP headers.
  // sequence_number: is the unique sequence number from the QUIC packet header.
  // timestamp: is the sent timestamp from the QUIC packet header.
  // revived: is set if the packet is lost and then recovered with help of FEC
  // (Forward Error Correction) packet(s).
  virtual void RecordIncomingPacket(QuicByteCount bytes,
                                    QuicPacketSequenceNumber sequence_number,
                                    QuicTime timestamp,
                                    bool revived) = 0;
};

}  // namespace net

#endif  // NET_QUIC_CONGESTION_CONTROL_RECEIVE_ALGORITHM_INTERFACE_H_


text:
'use strict';

var Particle = require('../../../src/physics/bodies/Particle');
var Wall = require('../../../src/physics/bodies/Wall');
var test = require('tape');

test('Wall', function(t) {
    var w = new Wall({direct: Wall.DOWN});

    t.test('should extend Particle', function(t) {
        t.assert(Wall instanceof Function, 'Wall should be a constructor');

        t.assert(w instanceof Wall && w instanceof Particle, 'new boxes should be instances of Particle');

        t.end();
    });

    t.test('mass properties', function(t) {
        t.assert(w.inverseMass === 0, 'walls should have 0 inverse mass');
        var i = w.inverseInertia.get();
        t.assert(i[0] === 0 && i[4] === 0 && i[8] === 0, 'walls should have 0 inverse moments of inertia');

        t.end();
    });

    t.end();
});


text:
<?php

/**
 * Process - Processing parameters to be passed phpcron
 *
 * @author    Dmitry Mamontov <d.slonyara@gmail.com>
 * @copyright 2014 Dmitry Mamontov <d.slonyara@gmail.com>
 * @license   http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @version   Release: @package_version@
 * @link      https://github.com/dmamontov/phpcron/blob/master/src/lib/classes/Command.php
 * @since     Class available since Release 1.0.0
 */
class Process
{
    public static $file = false;
    /*
     * Running Commands
     * @param $arg array - Console argument
     */
    public function run($arg)
    {
        self::$file = strtr('*/../../phpcron.pid', array('*' => dirname(__FILE__)));
        switch ($arg[1]) {
            case "restart":
            case "start":
                if (!isset($arg[2])) {
                    $arg[2] = false;
                }
                self::start($arg[2]);
                break;
            case "stop":
                self::stop();
                break;
            case "status":
                self::status();
                break;
            case "import":
                self::import();
                break;
            case "help":
            default:
                self::help();
                break;
        }
    }

    /*
     * Command start
     */
    public static function start($flag)
    {
        if ($flag == "-f") {
            self::forcedStop();
        } elseif (file_exists(self::$file)) {
            echo strtr("PHPCron * is running\n", array('*' => file_get_contents(self::$file)));
            exit();
        }
    }

    /*
     * Command stop
     */
    public static function stop()
    {
        self::forcedStop();
        exit();
    }

	/*
     * Import crontab
     */
    public static function import()
    {
        exec("crontab -l > /../../tasks/crontab.cron");
    }
    /*
     * Forced stop
     */
    public static function forcedStop()
    {
        if (file_exists(self::$file)) {
            $pid = file_get_contents(self::$file);
            exec(strtr("ps o pid --ppid *", array('*' => $pid)), $out);
            array_push($out, $pid);
            unset($out[0]);
            foreach ($out as $line) {
                posix_kill(trim($line), SIGCHLD);
                posix_kill(trim($line), SIGTERM);
            }
        } else {
            echo "PHPCron is not running\n";
            exit();
        }
    }

    /*
     * Command status
     */
    public static function status()
    {
        if (file_exists(self::$file)) {
            echo strtr("PHPCron * is running\n", array('*' => file_get_contents(self::$file)));
        } else {
            echo "PHPCron is not running\n";
        }
        exit();
    }

    /*
     * Command help
     */
    public static function help()
    {
        echo "Usage example:\n";
        echo "php phpcron.php parameter\n\n";
        echo "Parameters:\n";
        echo "\tstart\t\tStart Daemon\n";
        echo "\tstop\t\tStop Daemon\n";
        echo "\trestart\t\tRestart Daemon\n";
        echo "\tstatus\t\tStatus Daemon\n";
        echo "\timport\t\tImport crontab\n";
        echo "\thelp\t\tHelp\n";
        exit();
    }
}