text:
import {
  degToRads,
} from '../common';
import PropertyFactory from '../PropertyFactory';
import TextSelectorProp from './TextSelectorProperty';

function TextAnimatorDataProperty(elem, animatorProps, container) {
  var defaultData = { propType: false };
  var getProp = PropertyFactory.getProp;
  var textAnimatorAnimatables = animatorProps.a;
  this.a = {
    r: textAnimatorAnimatables.r ? getProp(elem, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData,
    rx: textAnimatorAnimatables.rx ? getProp(elem, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData,
    ry: textAnimatorAnimatables.ry ? getProp(elem, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData,
    sk: textAnimatorAnimatables.sk ? getProp(elem, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData,
    sa: textAnimatorAnimatables.sa ? getProp(elem, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData,
    s: textAnimatorAnimatables.s ? getProp(elem, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData,
    a: textAnimatorAnimatables.a ? getProp(elem, textAnimatorAnimatables.a, 1, 0, container) : defaultData,
    o: textAnimatorAnimatables.o ? getProp(elem, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData,
    p: textAnimatorAnimatables.p ? getProp(elem, textAnimatorAnimatables.p, 1, 0, container) : defaultData,
    sw: textAnimatorAnimatables.sw ? getProp(elem, textAnimatorAnimatables.sw, 0, 0, container) : defaultData,
    sc: textAnimatorAnimatables.sc ? getProp(elem, textAnimatorAnimatables.sc, 1, 0, container) : defaultData,
    fc: textAnimatorAnimatables.fc ? getProp(elem, textAnimatorAnimatables.fc, 1, 0, container) : defaultData,
    fh: textAnimatorAnimatables.fh ? getProp(elem, textAnimatorAnimatables.fh, 0, 0, container) : defaultData,
    fs: textAnimatorAnimatables.fs ? getProp(elem, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData,
    fb: textAnimatorAnimatables.fb ? getProp(elem, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData,
    t: textAnimatorAnimatables.t ? getProp(elem, textAnimatorAnimatables.t, 0, 0, container) : defaultData,
  };

  this.s = TextSelectorProp.getTextSelectorProp(elem, animatorProps.s, container);
  this.s.t = animatorProps.s.t;
}

export default TextAnimatorDataProperty;


text:
@interface SimpleScrollView ()<UIScrollViewDelegate,UIGestureRecognizerDelegate>
@property(strong,nonatomic)UIScrollView* scrView;
@property(strong,nonatomic)UIPageControl* pageControl;
@property(strong,nonatomic)UILabel* lblScale;
@end

@implementation SimpleScrollView{
    NSTimer* timer;
}
-(void)killTimer{
    [timer invalidate];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.edgesForExtendedLayout=UIRectEdgeNone;

    CGRect sizeFrame=self.view.frame;
    _scrView=[[UIScrollView alloc] initWithFrame:CGRectMake((sizeFrame.size.width-Photo_width)*0.5, 0, Photo_width, Photo_height)];
    _scrView.contentSize=CGSizeMake(Photo_width*numberPhoto, Photo_height);
    _scrView.pagingEnabled=true;
    _scrView.delegate=self;

    for (int i=1; i<numberPhoto+1; i++) {
        UIImage* img=[UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i]];
        UIImageView *imgView=[[UIImageView alloc] initWithImage:img];
        imgView.frame=CGRectMake(0, 0, Photo_width, Photo_height);

        imgView.userInteractionEnabled=true;
        imgView.multipleTouchEnabled=true;

        UITapGestureRecognizer* singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onSingleTap:)];
        singleTap.numberOfTapsRequired=1;
        singleTap.delegate=self;
        [imgView addGestureRecognizer:singleTap];

        UITapGestureRecognizer* doubleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onDoubleTap:)];
        doubleTap.numberOfTapsRequired=2;
        doubleTap.delegate=self;
        [imgView addGestureRecognizer:doubleTap];

        [singleTap requireGestureRecognizerToFail:doubleTap];

        UIScrollView* scrItem=[[UIScrollView alloc] initWithFrame:CGRectMake(Photo_width*(i-1), 0, Photo_width, Photo_height)];
        scrItem.contentSize=CGSizeMake(Photo_width, Photo_height);
        scrItem.maximumZoomScale=5.0;
        scrItem.minimumZoomScale=0.2;
        scrItem.delegate=self;

        [scrItem addSubview:imgView];
        [_scrView addSubview:scrItem];
    }

    [self.view addSubview:_scrView];

    _pageControl=[[UIPageControl alloc] initWithFrame:CGRectMake(0, sizeFrame.size.height-40-64,sizeFrame.size.width, 40)];
    _pageControl.numberOfPages=numberPhoto;
    _pageControl.backgroundColor=[UIColor grayColor];
    [_pageControl addTarget:self  action:@selector(pageControlChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_pageControl];

    _lblScale=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 25)];
    _lblScale.textAlignment=NSTextAlignmentRight;
    _lblScale.text=[NSString stringWithFormat:@"%2.1f",_scrView.zoomScale];

    UIBarButtonItem* item=[[UIBarButtonItem alloc] initWithCustomView:_lblScale];
    [self.navigationItem setRightBarButtonItem:item];

    timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(runningSlideShow) userInfo:nil repeats:true];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(killTimer) name:@"closeTimer" object:nil];

    UIButton* btnTunoff=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    btnTunoff.backgroundColor=[UIColor redColor];
    btnTunoff.center=CGPointMake(sizeFrame.size.width/2, _scrView.frame.origin.x+_scrView.frame.size.height+20);
    [btnTunoff setTitle:@"Turn off SlideShow" forState:UIControlStateNormal];
    [btnTunoff addTarget:self action:@selector(TurnOff:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnTunoff];
}
-(void)TurnOff:(UIButton*) sender{
    if([sender.titleLabel.text isEqualToString:@"Turn off SlideShow"]){
        [sender setTitle:@"Turn on SlideShow" forState:UIControlStateNormal];
        sender.backgroundColor=[UIColor greenColor];
        [timer invalidate];
    }else{
        [sender setTitle:@"Turn off SlideShow" forState:UIControlStateNormal];
        sender.backgroundColor=[UIColor redColor];
        timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(runningSlideShow) userInfo:nil repeats:true];
    }
}

-(void)runningSlideShow{
    NSLog(@"SimpleScroll running timer!");
    _pageControl.currentPage=arc4random_uniform(6);
     _scrView.contentOffset=CGPointMake(Photo_width*_pageControl.currentPage, 0);
}
-(void)onSingleTap:(UITapGestureRecognizer*)sender{
    int pageIndex=_scrView.contentOffset.x/Photo_width;
    UIScrollView* scrItem=_scrView.subviews[pageIndex];
    UIImageView* imgItem=scrItem.subviews[0];

    CGPoint tapPoint=[sender locationInView:imgItem];
    float newScale=_scrView.zoomScale*Zoom_step;
    [self zoomRectForScale:newScale withCenter:tapPoint];
}
-(void)onDoubleTap:(id)sender{
    int pageIndex=_scrView.contentOffset.x/Photo_width;
    UIScrollView* scrItem=_scrView.subviews[pageIndex];
    UIImageView* imgItem=scrItem.subviews[0];

    CGPoint tapPoint=[sender locationInView:imgItem];
    float newScale=_scrView.zoomScale/Zoom_step;
    [self zoomRectForScale:newScale withCenter:tapPoint];
}
- (void)zoomRectForScale:(float)scale
              withCenter:(CGPoint)center {
    CGRect zoomRect;
    CGSize scrollViewSize = self.scrView.bounds.size;
    int pageIndex=_scrView.contentOffset.x/Photo_width;
    UIScrollView* scrItem=_scrView.subviews[pageIndex];

    zoomRect.size.height = scrollViewSize.height / scale;
    zoomRect.size.width  = scrollViewSize.width  / scale;

    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);

    [scrItem zoomToRect:zoomRect
                       animated:YES];

    self.lblScale.text = [NSString stringWithFormat:@"%2.1f", self.scrView.zoomScale];

}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    int pageIndex=_scrView.contentOffset.x/Photo_width;
    UIScrollView* scrItem=_scrView.subviews[pageIndex];
    UIImageView* imgItem=scrItem.subviews[0];
    return imgItem;
}
-(void)pageControlChange:(UIPageControl*) page{
    _scrView.contentOffset=CGPointMake(Photo_width*page.currentPage, 0);
    self.lblScale.text = [NSString stringWithFormat:@"%2.1f", self.scrView.zoomScale];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _pageControl.currentPage=_scrView.contentOffset.x/Photo_width;
    self.lblScale.text = [NSString stringWithFormat:@"%2.1f", self.scrView.zoomScale];
}
@end

redpajama_set_name: RedPajamaGithub


text:
var bless = require('../');
var should = require('should');
var fs = require('fs');
var path = require('path');
var File = require('gulp-util').File;
var Buffer = require('buffer').Buffer;

describe('gulp-bless', function() {
    describe('bless()', function() {

        it('should do nothing if under the limit', function(done){
            var stream = bless(),
                numberOfNewFiles = 0;

            stream.on('data', function(newFile){
                numberOfNewFiles++;

                should.exist(newFile);
                should.exist(newFile.path);
                should.exist(newFile.relative);
                should.exist(newFile.contents);

                newFile.relative.should.equal('file.css');
                newFile.contents.toString('utf8').should.equal('p {color:red}');
                Buffer.isBuffer(newFile.contents).should.equal(true);
            });

            stream.on('end', function(){
                numberOfNewFiles.should.equal(1);
                done();
            });

            stream.write(new File({
                cwd: "/home/adam/",
                base: "/home/adam/test",
                path: "/home/adam/test/file.css",
                contents: new Buffer("p {color:red}")
            }));
            stream.end();
        });

        it('should split when selector count is over the limit', function(done){
            var stream = bless({imports: false});

            fs.readFile('./test/css/long.css', function(err, data){
                if(err) throw new Error(err);

                var longStylesheet = new File({
                        cwd: "/home/adam/",
                        base: "/home/adam/test",
                        path: "/home/adam/test/long-split.css",
                        contents: new Buffer(data)
                    }),
                    expectedSplits = [];

                fs.readFile('./test/css/long-split.css', function(err, data){
                    if(err) throw new Error(err);

                    expectedSplits.push(new File({
                        cwd: "/home/adam/",
                        base: "/home/adam/test",
                        path: "/home/adam/test/long-split.css",
                        contents: new Buffer(data)
                    }));

                    fs.readFile('./test/css/long-split-blessed1.css', function(err, data){
                        if(err) throw new Error(err);

                        expectedSplits.push(new File({
                            cwd: "/home/adam/",
                            base: "/home/adam/test",
                            path: "/home/adam/test/long-split-blessed1.css",
                            contents: new Buffer(data)
                        }));

                        var index = expectedSplits.length - 1,
                            numberOfNewFiles = 0;

                        stream.on('data', function(newFile){
                            numberOfNewFiles++;

                            should.exist(newFile);
                            should.exist(newFile.path);
                            should.exist(newFile.relative);
                            should.exist(newFile.contents);

                            var expectedSplitFile = expectedSplits[index];
                            newFile.relative.should.equal(path.basename(expectedSplitFile.path));
                            newFile.contents.toString('utf8').should.equal(expectedSplitFile.contents.toString('utf8'));
                            Buffer.isBuffer(newFile.contents).should.equal(true);
                            index--;
                        });

                        stream.on('end', function(){
                            numberOfNewFiles.should.equal(2);
                            done();
                        });

                        stream.write(longStylesheet);
                        stream.end();
                    });
                });
            });
        });

        it('should return empty file if empty files are passed', function(done){
            var stream = bless();

            var stylesheetA = new File({
                cwd: "/home/adam/",
                base: "/home/adam/test",
                path: "/home/adam/test/file.css",
                contents: new Buffer("")
            });

            var stylesheetB = new File({
                cwd: "/home/adam/",
                base: "/home/adam/test",
                path: "/home/adam/test/file.css",
                contents: new Buffer("")
            });

            var numberOfNewFiles = 0;

            stream.on('data', function(newFile){
                numberOfNewFiles++;
                should.exist(newFile);
                should.exist(newFile.path);
                should.exist(newFile.relative);
                should.exist(newFile.contents);

                newFile.relative.should.equal('file.css');
                newFile.contents.toString('utf8').should.equal('');
                Buffer.isBuffer(newFile.contents).should.equal(true);
            });

            stream.on('end', function(){
                numberOfNewFiles.should.equal(2);
                done();
            });

            stream.write(stylesheetA);
            stream.write(stylesheetB);
            stream.end();
        });

        it('should throw an error if stream is passed', function(done){
            var stream = bless();

            stream.on('error', function(err){
                err.plugin.should.equal('gulp-bless');
                err.message.should.equal('Streaming not supported');
                done();
            });

            stream.write(new File({
                path: 'a',
                base: 'a',
                cwd: 'a',
                contents: fs.createReadStream('./test/css/long.css')
            }));
            stream.end();
        });

        it("shouldn't throw error if options are passed", function(done){
            var stream = bless({
                hello: 'world'
            });
            var numberOfErrors = 0;

            stream.on('error', function(){
                numberOfErrors++
            });

            stream.on('end', function(){
               numberOfErrors.should.be.equal(0);
               done();
            });

            stream.write(new File({
                path: 'style.css',
                contents: new Buffer('p {color:red;}')
            }));
            stream.emit('end');
        });

        it("should work if file doesn't end with .css", function(done){
            var stream = bless();
            var fileContents = 'p {color:red}';
            var numberOfFiles = 0;
            var numberOfErrrors = 0;

            stream.on('error', function(){
                numberOfErrrors++;
            });

            stream.on('data', function(file){
                file.contents.toString().should.be.equal(fileContents);
                path.basename(file.path).should.be.equal('style.xml');
                numberOfFiles++;
            });

            stream.on('end', function(){
                numberOfErrrors.should.be.equal(0);
                numberOfFiles.should.be.equal(1);
                done();
            });

            stream.write(new File({
                base: '/test/',
                cwd: '/test/a/',
                path: '/test/a/style.xml',
                contents: new Buffer(fileContents)
            }));
            stream.end();
        });

        it("should work if file doesn't contain an extension", function(done){
            var stream = bless();
            var fileContents = 'p {color:red}';
            var numberOfFiles = 0;
            var numberOfErrrors = 0;

            stream.on('error', function(){
                numberOfErrrors++;
            });

            stream.on('data', function(file){
                file.contents.toString().should.be.equal(fileContents);
                path.basename(file.path).should.be.equal('style');
                numberOfFiles++;
            });

            stream.on('end', function(){
                numberOfErrrors.should.be.equal(0);
                numberOfFiles.should.be.equal(1);
                done();
            });

            stream.write(new File({
                base: '/test/',
                cwd: '/test/a/',
                path: '/test/a/style',
                contents: new Buffer(fileContents)
            }));
            stream.end();
        });

        it("shouldn't concatenate files", function(done){
            var stream = bless();
            var numberOfFiles = 0;
            var numberOfErrrors = 0;

            var fileA = new File({
                base: '/test/',
                cwd: '/test/a/',
                path: '/test/a/abc.css',
                contents: new Buffer('aaa')
            });

            var fileB = new File({
                base: '/test/',
                cwd: '/test/a/',
                path: '/test/a/def.css',
                contents: new Buffer('bbb')
            });

            stream.on('error', function(){
                numberOfErrrors++;
            });

            stream.on('data', function(file){
                if(numberOfFiles){
                    file.contents.toString().should.be.equal(fileB.contents.toString());
                    file.path.should.be.equal(fileB.path);
                }
                else {
                    file.contents.toString().should.be.equal(fileA.contents.toString());
                    file.path.should.be.equal(fileA.path);
                }
                numberOfFiles++;
            });

            stream.on('end', function(){
                numberOfErrrors.should.be.equal(0);
                numberOfFiles.should.be.equal(2);
                done();
            });

            stream.write(fileA);
            stream.write(fileB);
            stream.end();
        });
    });
});


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui"
	xmlns:m="urn:import:gwt.material.design.client.ui">
	<ui:style>

	</ui:style>

			<m:MaterialImage ui:field="studentImg" type="CIRCLE" addStyleNames="studentItem"/>

</ui:UiBinder>


text:
<?php

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;

/**
 * Normalizes an object implementing the {@see \DateTimeInterface} to a date string.
 * Denormalizes a date string to an instance of {@see \DateTime} or {@see \DateTimeImmutable}.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
{
    const FORMAT_KEY = 'datetime_format';

    private $format;

    /**
     * @param string $format
     */
    public function __construct($format = \DateTime::RFC3339)
    {
        $this->format = $format;
    }

    /**
     * {@inheritdoc}
     *
     * @throws InvalidArgumentException
     */
    public function normalize($object, $format = null, array $context = array())
    {
        if (!$object instanceof \DateTimeInterface) {
            throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
        }

        $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;

        return $object->format($format);
    }

    /**
     * {@inheritdoc}
     */
    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof \DateTimeInterface;
    }

    /**
     * {@inheritdoc}
     *
     * @throws UnexpectedValueException
     */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
        $dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;

        if (null !== $dateTimeFormat) {
            $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);

            if (false !== $object) {
                return $object;
            }

            $dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();

            throw new UnexpectedValueException(sprintf(
                'Parsing datetime string "%s" using format "%s" resulted in %d errors:'."\n".'%s',
                $data,
                $dateTimeFormat,
                $dateTimeErrors['error_count'],
                implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))
            ));
        }

        try {
            return \DateTime::class === $class ? new \DateTime($data) : new \DateTimeImmutable($data);
        } catch (\Exception $e) {
            throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null)
    {
        $supportedTypes = array(
            \DateTimeInterface::class => true,
            \DateTimeImmutable::class => true,
            \DateTime::class => true,
        );

        return isset($supportedTypes[$type]);
    }

    /**
     * Formats datetime errors.
     *
     * @return string[]
     */
    private function formatDateTimeErrors(array $errors)
    {
        $formattedErrors = array();

        foreach ($errors as $pos => $message) {
            $formattedErrors[] = sprintf('at position %d: %s', $pos, $message);
        }

        return $formattedErrors;
    }
}


text: export * from './loadPatients';


text:
/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)select.h	8.2 (Berkeley) 1/4/94
 */

#ifndef _SYS_SELECT_H_
#define	_SYS_SELECT_H_

#include <sys/appleapiopts.h>
#include <sys/cdefs.h>
#include <sys/_types.h>

/*
 * [XSI] The <sys/select.h> header shall define the fd_set type as a structure.
 * The timespec structure shall be defined as described in <time.h>
 * The <sys/select.h> header shall define the timeval structure.
 */
#include <sys/_types/_fd_def.h>
#include <sys/_types/_timespec.h>
#include <sys/_types/_timeval.h>

/*
 * The time_t and suseconds_t types shall be defined as described in
 * <sys/types.h>
 * The sigset_t type shall be defined as described in <signal.h>
 */
#include <sys/_types/_time_t.h>
#include <sys/_types/_suseconds_t.h>
#include <sys/_types/_sigset_t.h>

/*
 * [XSI] FD_CLR, FD_ISSET, FD_SET, FD_ZERO may be declared as a function, or
 *	 defined as a macro, or both
 * [XSI] FD_SETSIZE shall be defined as a macro
 */

/*
 * Select uses bit masks of file descriptors in longs.  These macros
 * manipulate such bit fields (the filesystem macros use chars).  The
 * extra protection here is to permit application redefinition above
 * the default size.
 */
#include <sys/_types/_fd_setsize.h>
#include <sys/_types/_fd_set.h>
#include <sys/_types/_fd_clr.h>
#include <sys/_types/_fd_isset.h>
#include <sys/_types/_fd_zero.h>

#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
#include <sys/_types/_fd_copy.h>
#endif	/* (!_POSIX_C_SOURCE || _DARWIN_C_SOURCE) */

#include <sys/kernel_types.h>
#include <kern/waitq.h>
#include <sys/event.h>

/*
 * Used to maintain information about processes that wish to be
 * notified when I/O becomes possible.
 */
struct selinfo;

__BEGIN_DECLS

extern int selwait;
void	selrecord(proc_t selector, struct selinfo *, void *);
void	selwakeup(struct selinfo *);
void	selthreadclear(struct selinfo *);

__END_DECLS

#endif /* !_SYS_SELECT_H_ */


text:
		<error-zone ng-model="error">
		</error-zone>

								{{role.name}}

					<input type="text" ng-model="newRoleName" placeholder="new role" ng-change="onNewRoleInput(newRoleName)"/>
					<button ng-disabled="!canAddNewRole" class="btn btn-primary" ng-click="newRole(newRoleName)" translate="permissions.cmd.newRole"></button>

						<select class="permissions-cbo"
						        ng-model="currentRole"
								ng-options="role as role.name for role in roles"
								ng-change="selectRole(currentRole)">
						</select>

						<select class="permissions-cbo"
								ng-model="currentResource"
								ng-options="resource as resource.name for resource in resources"
								ng-change="selectResource(currentResource)">
						</select>
						<button class="pull-rigth" ng-click="saveCurrentPermission()"
						        translate="permissions.apply">
						</button>

					Permissions for
					 {{currentPermission.title}}

						Horizontal Data Security Profile:
						<select id="hsec"
								class="permissions-cbo"
						        ng-model="currentPermission.horizontalSecurity"
								ng-options="hsec as hsec.label for hsec in horizontalSecurityRules">
						</select>
						{{currentPermission.horizontalSecurity.description}}

						Operations

							Can Execute:
							All |
							None

									{{op.name}}

										<tristate ng-model="op.selected"
												class="tristate-permissions pull-right"
												hide-null-button="true">
										</tristate>

						Field visibility

							Can View:
							All |
							None

									{{field.name}}

										<tristate ng-model="field.selected"
												class="tristate-permissions pull-right"
												hide-null-button="true">
										</tristate>

Security Settings Import/Export

Export

							Export all the security settings (roles and permissions) into a JSON file.

						<button class="btn btn-primary" ng-click="export()" translate="permissions.export">Export</button>

Import

								Import security settings from a JSON file.
								Warning:
								this operations overrides current security settings (roles and permissions).

						<file-selector class="" ng-model="importFile" accept="application/json">
						</file-selector>

						<button class="btn btn-danger" ng-disabled="!importFile" ng-click="import()"
						        translate="permissions.import">Import</button>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Dagger2example</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="clickme">Click me!</string>

</resources>


text:
var TableJobsController = function(jobs, $scope, $state, locationUtils) {

	$scope.jobs = jobs;

	$scope.createJob = function() {
		locationUtils.navigateToPath('/admin/jobs/new');
	};

	$scope.refresh = function() {
		$state.reload(); // reloads all the resolves for the view
	};

	angular.element(document).ready(function () {
		$('#jobsTable').dataTable({
			"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
			"iDisplayLength": 25,
			"aaSorting": []
		});
	});

};

TableJobsController.$inject = ['jobs', '$scope', '$state', 'locationUtils'];
module.exports = TableJobsController;


text:
package org.apache.pulsar.client.api;

import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.Sets;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.broker.authentication.AuthenticationProviderToken;
import org.apache.pulsar.broker.authentication.utils.AuthTokenUtils;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminBuilder;
import org.apache.pulsar.client.impl.auth.AuthenticationToken;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.policies.data.AuthAction;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
import org.awaitility.Awaitility;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.crypto.SecretKey;
import java.time.Duration;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Test(groups = "broker-api")
@Slf4j
public class TokenExpirationProduceConsumerTest extends TlsProducerConsumerBase {
    private final String tenant ="my-tenant";
    private final NamespaceName namespaceName = NamespaceName.get("my-tenant","my-ns");

    @BeforeMethod
    @Override
    protected void setup() throws Exception {
        // TLS configuration for Broker
        internalSetUpForBroker();

        // Start Broker
        super.init();

        admin = getAdmin(ADMIN_TOKEN);
        admin.clusters().createCluster(configClusterName,
                ClusterData.builder()
                        .serviceUrl(brokerUrl.toString())
                        .serviceUrlTls(brokerUrlTls.toString())
                        .brokerServiceUrl(pulsar.getBrokerServiceUrl())
                        .brokerServiceUrlTls(pulsar.getBrokerServiceUrlTls())
                        .build());
        admin.tenants().createTenant(tenant,
                new TenantInfoImpl(Sets.newHashSet("appid1", "appid2"), Sets.newHashSet(configClusterName)));
        admin.namespaces().createNamespace(namespaceName.toString());
    }

    @AfterMethod(alwaysRun = true)
    @Override
    protected void cleanup() throws Exception {
        super.internalCleanup();
    }

    private static final SecretKey SECRET_KEY = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);
    public static final String ADMIN_TOKEN = Jwts.builder().setSubject("admin").signWith(SECRET_KEY).compact();

    public String getExpireToken(String role, Date date) {
        return Jwts.builder().setSubject(role).signWith(SECRET_KEY)
                .setExpiration(date).compact();
    }

    protected void internalSetUpForBroker() {
        conf.setBrokerServicePortTls(Optional.of(0));
        conf.setWebServicePortTls(Optional.of(0));
        conf.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
        conf.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
        conf.setTlsTrustCertsFilePath(TLS_TRUST_CERT_FILE_PATH);
        conf.setClusterName(configClusterName);
        conf.setAuthenticationRefreshCheckSeconds(1);
        conf.setTlsRequireTrustedClientCertOnConnect(false);
        conf.setTlsAllowInsecureConnection(false);
        conf.setAuthenticationEnabled(true);
        conf.setTransactionCoordinatorEnabled(true);
        conf.setSuperUserRoles(Sets.newHashSet("admin"));
        conf.setAuthenticationProviders(Sets.newHashSet(AuthenticationProviderToken.class.getName()));
        conf.setBrokerClientAuthenticationPlugin(AuthenticationToken.class.getName());
        conf.setBrokerClientAuthenticationParameters("token:" + ADMIN_TOKEN);
        conf.getProperties().setProperty("tokenSecretKey", "data:;base64,"
                + Base64.getEncoder().encodeToString(SECRET_KEY.getEncoded()));
    }

    private PulsarClient getClient(String token) throws Exception {
        ClientBuilder clientBuilder = PulsarClient.builder()
                .serviceUrl(pulsar.getBrokerServiceUrlTls())
                .tlsTrustCertsFilePath(TLS_TRUST_CERT_FILE_PATH)
                .enableTls(true)
                .allowTlsInsecureConnection(false)
                .enableTlsHostnameVerification(true)
                .authentication(AuthenticationToken.class.getName(),"token:" +token)
                .operationTimeout(1000, TimeUnit.MILLISECONDS);
        return clientBuilder.build();
    }

    private PulsarAdmin getAdmin(String token) throws Exception {
        PulsarAdminBuilder clientBuilder = PulsarAdmin.builder().serviceHttpUrl(pulsar.getWebServiceAddressTls())
                .tlsTrustCertsFilePath(TLS_TRUST_CERT_FILE_PATH)
                .allowTlsInsecureConnection(false)
                .authentication(AuthenticationToken.class.getName(),"token:" +token)
                .enableTlsHostnameVerification(true);
        return clientBuilder.build();
    }

    @Test
    public void testTokenExpirationProduceConsumer() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 20);
        String role = "test";
        String token = getExpireToken(role, calendar.getTime());
        Date expiredTime = calendar.getTime();

        Set<AuthAction> permissions = new HashSet<>();
        permissions.add(AuthAction.consume);
        permissions.add(AuthAction.produce);
        admin.namespaces().grantPermissionOnNamespace(namespaceName.toString(), role, permissions);

        @Cleanup
        PulsarClient pulsarClient = getClient(token);
        String topic = namespaceName + "/test-token";

        @Cleanup final Consumer<byte[]> consumer = pulsarClient.newConsumer()
                .topic(topic)
                .subscriptionName("test-token")
                .subscribe();
        @Cleanup final Producer<byte[]> producer = pulsarClient.newProducer()
                .topic(topic)
                .create();

        Awaitility.await().timeout(Duration.ofSeconds(60)).pollInterval(3, TimeUnit.SECONDS).untilAsserted(() -> {
            assertThrows(PulsarClientException.TimeoutException.class, () -> {
                producer.send("heart beat".getBytes());
                Message<byte[]> message = consumer.receive();
                consumer.acknowledge(message);
            });
            assertTrue(new Date().compareTo(expiredTime) > 0);
        });
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/myFavourite_image"
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:padding="10dp"
        android:scaleType="fitXY" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:padding="4dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/myFavourite_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:text="@string/my_favourite_default"
            android:textColor="#000"
            android:ellipsize="end"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/myFavourite_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#949494"
            android:ellipsize="end"
            android:textSize="12sp" />
    </LinearLayout>

</LinearLayout>


text:
Triangle_Mesh load_obj_model(const std::string& path, float additional_scale) {
    tinyobj::attrib_t attrib;
    std::vector<tinyobj::shape_t> shapes;
    std::vector<tinyobj::material_t> materials;
    std::string err;

    if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &err, path.c_str()))
        error("failed to load obj model: " + path);

	assert(shapes.size() == 1);
	const tinyobj::mesh_t& obj_mesh = shapes[0].mesh;

	for (uint8_t num_face_vertices : obj_mesh.num_face_vertices)
		assert(num_face_vertices == 3);

	struct Index_Hasher {
		size_t operator()(const tinyobj::index_t& index) const {
			size_t hash = 0;
			hash_combine(hash, index.vertex_index);
			hash_combine(hash, index.normal_index);
			hash_combine(hash, index.texcoord_index);
			return hash;
		}
	};
	struct Index_Comparator {
		bool operator()(const tinyobj::index_t& a, const tinyobj::index_t& b) const {
			return
				a.vertex_index == b.vertex_index &&
				a.normal_index == b.normal_index &&
				a.texcoord_index == b.texcoord_index;
		}
	};
	std::unordered_map<tinyobj::index_t, int, Index_Hasher, Index_Comparator> index_mapping;

	Vector3 mesh_min(Infinity);
	Vector3 mesh_max(-Infinity);

	Triangle_Mesh mesh;
	mesh.indices.reserve(obj_mesh.indices.size());

	for (const tinyobj::index_t& index : obj_mesh.indices) {
		auto it = index_mapping.find(index);
		if (it == index_mapping.end()) {
			it = index_mapping.insert(std::make_pair(index, (int)mesh.vertices.size())).first;

			// add new vertex
			Vertex vertex;
			assert(index.vertex_index != -1);
			vertex.pos = {
				attrib.vertices[3 * index.vertex_index + 0],
				attrib.vertices[3 * index.vertex_index + 1],
				attrib.vertices[3 * index.vertex_index + 2]
			};
			if (index.texcoord_index != -1) {
				vertex.uv = {
					attrib.texcoords[2 * index.texcoord_index + 0],
					1.f - attrib.texcoords[2 * index.texcoord_index + 1]
				};
			}
			mesh.vertices.push_back(vertex);

			// update mesh bounds
			mesh_min.x = std::min(mesh_min.x, vertex.pos.x);
			mesh_min.y = std::min(mesh_min.y, vertex.pos.y);
			mesh_min.z = std::min(mesh_min.z, vertex.pos.z);
			mesh_max.x = std::max(mesh_max.x, vertex.pos.x);
			mesh_max.y = std::max(mesh_max.y, vertex.pos.y);
			mesh_max.z = std::max(mesh_max.z, vertex.pos.z);
		}
		mesh.indices.push_back(it->second);
	}

    // scale and center the mesh
    Vector3 diag = mesh_max - mesh_min;
    float max_size = std::max(diag.x, std::max(diag.y, diag.z));
    float scale = (2.f / max_size) * additional_scale;

    Vector3 center = (mesh_min + mesh_max) * 0.5f;
    for (auto& v : mesh.vertices) {
        v.pos -= center;
        v.pos *= scale;
    }
    return mesh;
}


text:
import React from 'react';
import { connect } from 'react-redux'
import { updateProfile, changePassword, deleteAccount } from '../../actions/auth';
import { link, unlink } from '../../actions/oauth';
import Messages from '../Messages';

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: props.user.email,
      name: props.user.name,
      gender: props.user.gender,
      location: props.user.location,
      website: props.user.website,
      gravatar: props.user.gravatar,
      password: '',
      confirm: ''
    };
  }

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  handleProfileUpdate(event) {
    event.preventDefault();
    this.props.dispatch(updateProfile(this.state, this.props.token));
  }

  handleChangePassword(event) {
    event.preventDefault();
    this.props.dispatch(changePassword(this.state.password, this.state.confirm, this.props.token));
  }

  handleDeleteAccount(event) {
    event.preventDefault();
    this.props.dispatch(deleteAccount(this.props.token));
  }

  handleLink(provider) {
    this.props.dispatch(link(provider))
  }

  handleUnlink(provider) {
    this.props.dispatch(unlink(provider));
  }

  render() {
    const googleLinkedAccount = this.props.user.google ? (
      Unlink your Google account
    ) : (
      Link your Google account
    );
    return (

            <Messages messages={this.props.messages}/>
            <form onSubmit={this.handleProfileUpdate.bind(this)} className="form-horizontal">
              <legend>Profile Information</legend>

                Email

                  <input type="email" name="email" id="email" className="form-control" value={this.state.email} onChange={this.handleChange.bind(this)}/>

                Name

                  <input type="text" name="name" id="name" className="form-control" value={this.state.name} onChange={this.handleChange.bind(this)}/>

                Gender

                    <input type="radio" name="gender" value="male" checked={this.state.gender === 'male'} onChange={this.handleChange.bind(this)}/>Male

                    <input type="radio" name="gender" value="female" checked={this.state.gender === 'female'} onChange={this.handleChange.bind(this)}/>Female

                Location

                  <input type="text" name="location" id="location" className="form-control" value={this.state.location} onChange={this.handleChange.bind(this)}/>

                Website

                  <input type="text" name="website" id="website" className="form-control" value={this.state.website} onChange={this.handleChange.bind(this)}/>

                Gravatar

                  <button type="submit" className="btn btn-success">Update Profile</button>

            </form>

            <form onSubmit={this.handleChangePassword.bind(this)} className="form-horizontal">
              <legend>Change Password</legend>

                New Password

                  <input type="password" name="password" id="password" className="form-control" value={this.state.password} onChange={this.handleChange.bind(this)}/>

                Confirm Password

                  <input type="password" name="confirm" id="confirm" className="form-control" value={this.state.confirm} onChange={this.handleChange.bind(this)}/>

                  <button type="submit" className="btn btn-success">Change Password</button>

            </form>

              <legend>Linked Accounts</legend>

{googleLinkedAccount}

            <form onSubmit={this.handleDeleteAccount.bind(this)} className="form-horizontal">
              <legend>Delete Account</legend>

You can delete your account, but keep in mind this action is irreversible.

                  <button type="submit" className="btn btn-danger">Delete my account</button>

            </form>

    );
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
    user: state.auth.user,
    messages: state.messages
  };
};

export default connect(mapStateToProps)(Profile);


text:
<?xml version='1.0' encoding='UTF-8'?>
<ModifySecurityGroupAttributeResponse>
     <RequestId>CEF72CEB-54B6-4AE8-B225-F876FF7BA984</RequestId>
</ModifySecurityGroupAttributeResponse>


text:
section[data-template="/zoning/zoning"]
{

}


text:
import { StringDictionary } from "../ts-helpers";

type QuasarIconSetType = "positive" | "negative" | "info" | "warning";
type QuasarIconSetArrow = "up" | "right" | "down" | "left" | "dropdown";
type QuasarIconSetChevron = "left" | "right";
type QuasarIconSetColorPicker = "spectrum" | "tune" | "palette";
type QuasarIconSetPullToRefresh = "icon";
type QuasarIconSetCarousel = "left" | "right" | "navigationIcon" | "thumbnails";
type QuasarIconSetChip = "remove" | "selected";
type QuasarIconSetDatetime = "arrowLeft" | "arrowRight" | "now" | "today";
type QuasarIconSetEditor =
  | "bold"
  | "italic"
  | "strikethrough"
  | "underline"
  | "unorderedList"
  | "orderedList"
  | "subscript"
  | "superscript"
  | "hyperlink"
  | "toggleFullscreen"
  | "quote"
  | "left"
  | "center"
  | "right"
  | "justify"
  | "print"
  | "outdent"
  | "indent"
  | "removeFormat"
  | "formatting"
  | "fontSize"
  | "align"
  | "hr"
  | "undo"
  | "redo"
  | "heading"
  | "heading1"
  | "heading2"
  | "heading3"
  | "heading4"
  | "heading5"
  | "heading6"
  | "code"
  | "size"
  | "size1"
  | "size2"
  | "size3"
  | "size4"
  | "size5"
  | "size6"
  | "size7"
  | "font"
  | "viewSource";
type QuasarIconSetExpansionItem = "icon" | "denseIcon";
type QuasarIconSetFab = "icon" | "activeIcon";
type QuasarIconSetField = "clear" | "error";
type QuasarIconSetPagination = "first" | "prev" | "next" | "last";
type QuasarIconSetRating = "icon";
type QuasarIconSetStepper = "done" | "active" | "error";
type QuasarIconSetTabs = "left" | "right" | "up" | "down";
type QuasarIconSetTable = "arrowUp" | "warning" | "prevPage" | "nextPage";
type QuasarIconSetTree = "icon";
type QuasarIconSetUploader =
  | "done"
  | "clear"
  | "add"
  | "upload"
  | "removeQueue"
  | "removeUploaded";

export interface QuasarIconSet {
  name: string;
  type: StringDictionary<QuasarIconSetType>;
  arrow: StringDictionary<QuasarIconSetArrow>;
  chevron: StringDictionary<QuasarIconSetChevron>;
  colorPicker: StringDictionary<QuasarIconSetColorPicker>;
  pullToRefresh: StringDictionary<QuasarIconSetPullToRefresh>;
  carousel: StringDictionary<QuasarIconSetCarousel>;
  chip: StringDictionary<QuasarIconSetChip>;
  datetime: StringDictionary<QuasarIconSetDatetime>;
  editor: StringDictionary<QuasarIconSetEditor>;
  expansionItem: StringDictionary<QuasarIconSetExpansionItem>;
  fab: StringDictionary<QuasarIconSetFab>;
  field: StringDictionary<QuasarIconSetField>;
  pagination: StringDictionary<QuasarIconSetPagination>;
  rating: StringDictionary<QuasarIconSetRating>;
  stepper: StringDictionary<QuasarIconSetStepper>;
  tabs: StringDictionary<QuasarIconSetTabs>;
  table: StringDictionary<QuasarIconSetTable>;
  tree: StringDictionary<QuasarIconSetTree>;
  uploader: StringDictionary<QuasarIconSetUploader>;
}

export type QuasarIconSets =
  | "material-icons"
  | "material-icons-outlined"
  | "material-icons-round"
  | "material-icons-sharp"
  | "mdi-v4"
  | "mdi-v3"
  | "fontawesome-v5"
  | "ionicons-v4"
  | "eva-icons"
  | "themify";


text:
<?php

namespace SlmMail\Factory;

use SlmMail\Factory\Exception\RuntimeException;
use SlmMail\Service\MailgunService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MailgunServiceFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Config');

        if (!isset($config['slm_mail']['mailgun'])) {
            throw new RuntimeException(
                'Config for Mailgun is not set, did you copy config file into your config/autoload folder ?'
            );
        }

        $config  = $config['slm_mail']['mailgun'];
        $service = new MailgunService($config['domain'], $config['key']);

        $client  = $serviceLocator->get('SlmMail\Http\Client');
        $service->setClient($client);

        return $service;
    }
}


text:
package org.cloudfoundry.receptor.commands;

import java.util.HashMap;
import java.util.Map;

import org.cloudfoundry.receptor.support.Route;
import org.springframework.util.ObjectUtils;

/**
 * @author Mark Fisher
 */
public class DesiredLRPUpdateRequest {

	private int instances = 1;

	private Map<String, Route[]> routes = new HashMap<String, Route[]>();

	private String annotation;

	public int getInstances() {
		return instances;
	}

	public void setInstances(int instances) {
		this.instances = instances;
	}

	public Map<String, Route[]> getRoutes() {
		return routes;
	}

	public void setRoutes(Map<String, Route[]> routes) {
		this.routes = routes;
	}

	public void addRoute(int port, String... hostnames) {
		this.routes.put("cf-router", ObjectUtils.addObjectToArray(this.routes.get("cf-router"), new Route(port, hostnames)));
	}

	public void setAnnotation(String annotation) {
		this.annotation = annotation;
	}

	public String getAnnotation() {
		return annotation;
	}
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { LogHistoryService } from './log-history.service';

describe('LogHistoryService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LogHistoryService]
    });
  });

  it('should ...', inject([LogHistoryService], (service: LogHistoryService) => {
    expect(service).toBeTruthy();
  }));
});


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Functions dealing with attributes and meta items

use extra;

use ast;
use ast::{Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList};
use codemap::{Spanned, spanned, dummy_spanned};
use codemap::BytePos;
use diagnostic::span_handler;
use parse::comments::{doc_comment_style, strip_doc_comment_decoration};

use std::hashmap::HashSet;

pub trait AttrMetaMethods {
    // This could be changed to `fn check_name(&self, name: @str) ->
    // bool` which would facilitate a side table recording which
    // attributes/meta items are used/unused.

    /// Retrieve the name of the meta item, e.g. foo in #[foo],
    /// #[foo="bar"] and #[foo(bar)]
    fn name(&self) -> @str;

    /**
     * Gets the string value if self is a MetaNameValue variant
     * containing a string, otherwise None.
     */
    fn value_str(&self) -> Option<@str>;
    /// Gets a list of inner meta items from a list MetaItem type.
    fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]>;

    /**
     * If the meta item is a name-value type with a string value then returns
     * a tuple containing the name and string value, otherwise `None`
     */
    fn name_str_pair(&self) -> Option<(@str, @str)>;
}

impl AttrMetaMethods for Attribute {
    fn name(&self) -> @str { self.meta().name() }
    fn value_str(&self) -> Option<@str> { self.meta().value_str() }
    fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]> {
        self.node.value.meta_item_list()
    }
    fn name_str_pair(&self) -> Option<(@str, @str)> { self.meta().name_str_pair() }
}

impl AttrMetaMethods for MetaItem {
    fn name(&self) -> @str {
        match self.node {
            MetaWord(n) => n,
            MetaNameValue(n, _) => n,
            MetaList(n, _) => n
        }
    }

    fn value_str(&self) -> Option<@str> {
        match self.node {
            MetaNameValue(_, ref v) => {
                match v.node {
                    ast::lit_str(s) => Some(s),
                    _ => None,
                }
            },
            _ => None
        }
    }

    fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]> {
        match self.node {
            MetaList(_, ref l) => Some(l.as_slice()),
            _ => None
        }
    }

    fn name_str_pair(&self) -> Option<(@str, @str)> {
        self.value_str().map_move(|s| (self.name(), s))
    }
}

// Annoying, but required to get test_cfg to work
impl AttrMetaMethods for @MetaItem {
    fn name(&self) -> @str { (**self).name() }
    fn value_str(&self) -> Option<@str> { (**self).value_str() }
    fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]> {
        (**self).meta_item_list()
    }
    fn name_str_pair(&self) -> Option<(@str, @str)> { (**self).name_str_pair() }
}

pub trait AttributeMethods {
    fn meta(&self) -> @MetaItem;
    fn desugar_doc(&self) -> Attribute;
}

impl AttributeMethods for Attribute {
    /// Extract the MetaItem from inside this Attribute.
    fn meta(&self) -> @MetaItem {
        self.node.value
    }

    /// Convert self to a normal #[doc="foo"] comment, if it is a
    /// comment like `///` or `/** */`. (Returns self unchanged for
    /// non-sugared doc attributes.)
    fn desugar_doc(&self) -> Attribute {
        if self.node.is_sugared_doc {
            let comment = self.value_str().unwrap();
            let meta = mk_name_value_item_str(@"doc",
                                              strip_doc_comment_decoration(comment).to_managed());
            mk_attr(meta)
        } else {
            *self
        }
    }
}

/* Constructors */

pub fn mk_name_value_item_str(name: @str, value: @str) -> @MetaItem {
    let value_lit = dummy_spanned(ast::lit_str(value));
    mk_name_value_item(name, value_lit)
}

pub fn mk_name_value_item(name: @str, value: ast::lit) -> @MetaItem {
    @dummy_spanned(MetaNameValue(name, value))
}

pub fn mk_list_item(name: @str, items: ~[@MetaItem]) -> @MetaItem {
    @dummy_spanned(MetaList(name, items))
}

pub fn mk_word_item(name: @str) -> @MetaItem {
    @dummy_spanned(MetaWord(name))
}

pub fn mk_attr(item: @MetaItem) -> Attribute {
    dummy_spanned(Attribute_ {
        style: ast::AttrInner,
        value: item,
        is_sugared_doc: false,
    })
}

pub fn mk_sugared_doc_attr(text: @str, lo: BytePos, hi: BytePos) -> Attribute {
    let style = doc_comment_style(text);
    let lit = spanned(lo, hi, ast::lit_str(text));
    let attr = Attribute_ {
        style: style,
        value: @spanned(lo, hi, MetaNameValue(@"doc", lit)),
        is_sugared_doc: true
    };
    spanned(lo, hi, attr)
}

/* Searching */
/// Check if `needle` occurs in `haystack` by a structural
/// comparison. This is slightly subtle, and relies on ignoring the
/// span included in the `==` comparison a plain MetaItem.
pub fn contains(haystack: &[@ast::MetaItem],
                needle: @ast::MetaItem) -> bool {
    debug!("attr::contains (name=%s)", needle.name());
    do haystack.iter().any |item| {
        debug!("  testing: %s", item.name());
        item.node == needle.node
    }
}

pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
    debug!("attr::contains_name (name=%s)", name);
    do metas.iter().any |item| {
        debug!("  testing: %s", item.name());
        name == item.name()
    }
}

pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
                                 -> Option<@str> {
    attrs.iter()
        .find(|at| name == at.name())
        .and_then(|at| at.value_str())
}

pub fn last_meta_item_value_str_by_name(items: &[@MetaItem], name: &str)
                                     -> Option<@str> {
    items.rev_iter().find(|mi| name == mi.name()).and_then(|i| i.value_str())
}

/* Higher-level applications */

pub fn sort_meta_items(items: &[@MetaItem]) -> ~[@MetaItem] {
    // This is sort of stupid here, but we need to sort by
    // human-readable strings.
    let mut v = items.iter()
        .map(|&mi| (mi.name(), mi))
        .collect::<~[(@str, @MetaItem)]>();

    do extra::sort::quick_sort(v) |&(a, _), &(b, _)| {
        a <= b
    }

    // There doesn't seem to be a more optimal way to do this
    do v.move_iter().map |(_, m)| {
        match m.node {
            MetaList(n, ref mis) => {
                @Spanned {
                    node: MetaList(n, sort_meta_items(*mis)),
                    .. /*bad*/ (*m).clone()
                }
            }
            _ => m
        }
    }.collect()
}

/**
 * From a list of crate attributes get only the meta_items that affect crate
 * linkage
 */
pub fn find_linkage_metas(attrs: &[Attribute]) -> ~[@MetaItem] {
    let mut result = ~[];
    for attr in attrs.iter().filter(|at| "link" == at.name()) {
        match attr.meta().node {
            MetaList(_, ref items) => result.push_all(*items),
            _ => ()
        }
    }
    result
}

#[deriving(Eq)]
pub enum InlineAttr {
    InlineNone,
    InlineHint,
    InlineAlways,
    InlineNever,
}

/// True if something like #[inline] is found in the list of attrs.
pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr {
    // FIXME (#2809)---validate the usage of #[inline] and #[inline]
    do attrs.iter().fold(InlineNone) |ia,attr| {
        match attr.node.value.node {
          MetaWord(n) if "inline" == n => InlineHint,
          MetaList(n, ref items) if "inline" == n => {
            if contains_name(*items, "always") {
                InlineAlways
            } else if contains_name(*items, "never") {
                InlineNever
            } else {
                InlineHint
            }
          }
          _ => ia
        }
    }
}

/// Tests if any `cfg(...)` meta items in `metas` match `cfg`. e.g.
///
/// test_cfg(`[foo="a", bar]`, `[cfg(foo), cfg(bar)]`) == true
/// test_cfg(`[foo="a", bar]`, `[cfg(not(bar))]`) == false
/// test_cfg(`[foo="a", bar]`, `[cfg(bar, foo="a")]`) == true
/// test_cfg(`[foo="a", bar]`, `[cfg(bar, foo="b")]`) == false
pub fn test_cfg<AM: AttrMetaMethods, It: Iterator<AM>>
    (cfg: &[@MetaItem], mut metas: It) -> bool {
    // having no #[cfg(...)] attributes counts as matching.
    let mut no_cfgs = true;

    // this would be much nicer as a chain of iterator adaptors, but
    // this doesn't work.
    let some_cfg_matches = do metas.any |mi| {
        debug!("testing name: %s", mi.name());
        if "cfg" == mi.name() { // it is a #[cfg()] attribute
            debug!("is cfg");
            no_cfgs = false;
             // only #[cfg(...)] ones are understood.
            match mi.meta_item_list() {
                Some(cfg_meta) => {
                    debug!("is cfg(...)");
                    do cfg_meta.iter().all |cfg_mi| {
                        debug!("cfg(%s[...])", cfg_mi.name());
                        match cfg_mi.node {
                            ast::MetaList(s, ref not_cfgs) if "not" == s => {
                                debug!("not!");
                                // inside #[cfg(not(...))], so these need to all
                                // not match.
                                not_cfgs.iter().all(|mi| {
                                    debug!("cfg(not(%s[...]))", mi.name());
                                    !contains(cfg, *mi)
                                })
                            }
                            _ => contains(cfg, *cfg_mi)
                        }
                    }
                }
                None => false
            }
        } else {
            false
        }
    };
    debug!("test_cfg (no_cfgs=%?, some_cfg_matches=%?)", no_cfgs, some_cfg_matches);
    no_cfgs || some_cfg_matches
}

/// Represents the #[deprecated="foo"] (etc) attributes.
pub struct Stability {
    level: StabilityLevel,
    text: Option<@str>
}

/// The available stability levels.
#[deriving(Eq,Ord,Clone)]
pub enum StabilityLevel {
    Deprecated,
    Experimental,
    Unstable,
    Stable,
    Frozen,
    Locked
}

/// Find the first stability attribute. `None` if none exists.
pub fn find_stability<AM: AttrMetaMethods, It: Iterator<AM>>(mut metas: It) -> Option<Stability> {
    for m in metas {
        let level = match m.name().as_slice() {
            "deprecated" => Deprecated,
            "experimental" => Experimental,
            "unstable" => Unstable,
            "stable" => Stable,
            "frozen" => Frozen,
            "locked" => Locked,
            _ => loop // not a stability level
        };

        return Some(Stability {
                level: level,
                text: m.value_str()
            });
    }
    None
}

pub fn require_unique_names(diagnostic: @mut span_handler,
                            metas: &[@MetaItem]) {
    let mut set = HashSet::new();
    for meta in metas.iter() {
        let name = meta.name();

        if !set.insert(name) {
            diagnostic.span_fatal(meta.span,
                                  fmt!("duplicate meta item `%s`", name));
        }
    }
}


text:
set(shell_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/Input.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/Shell.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/ShellFileInterface.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/ShellOpenGL.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/ShellRenderInterfaceExtensions.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/ShellRenderInterfaceOpenGL.h
    ${PROJECT_SOURCE_DIR}/Samples/shell/include/ShellSystemInterface.h
)

set(shell_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/shell/src/Input.cpp
    ${PROJECT_SOURCE_DIR}/Samples/shell/src/Shell.cpp
    ${PROJECT_SOURCE_DIR}/Samples/shell/src/ShellFileInterface.cpp
    ${PROJECT_SOURCE_DIR}/Samples/shell/src/ShellRenderInterfaceOpenGL.cpp
    ${PROJECT_SOURCE_DIR}/Samples/shell/src/ShellSystemInterface.cpp
)

set(customlog_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/customlog/src/SystemInterface.h
)

set(customlog_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/customlog/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/customlog/src/SystemInterface.cpp
)

set(drag_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/drag/src/DragListener.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/drag/src/Inventory.h
)

set(drag_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/drag/src/DragListener.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/drag/src/Inventory.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/drag/src/main.cpp
)

set(loaddocument_HDR_FILES
)

set(loaddocument_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/loaddocument/src/main.cpp
)

set(bitmapfont_HDR_FILES
)

set(bitmapfont_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/bitmapfont/src/main.cpp
)

set(ogre3d_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RenderInterfaceOgre3D.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RocketApplication.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RocketFrameListener.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/SystemInterfaceOgre3D.h
)

set(ogre3d_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RenderInterfaceOgre3D.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RocketApplication.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/RocketFrameListener.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/ogre3d/src/SystemInterfaceOgre3D.cpp
)

set(treeview_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/treeview/src/FileFormatter.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/treeview/src/FileSystem.h
)

set(treeview_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/treeview/src/FileFormatter.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/treeview/src/FileSystem.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/treeview/src/main.cpp
)

set(sdl2_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sdl2/src/RenderInterfaceSDL2.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/sdl2/src/SystemInterfaceSDL2.h
)

set(sdl2_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sdl2/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sdl2/src/RenderInterfaceSDL2.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sdl2/src/SystemInterfaceSDL2.cpp
)

set(sfml_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml/src/RenderInterfaceSFML.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml/src/SystemInterfaceSFML.h
)

set(sfml_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml/src/RenderInterfaceSFML.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml/src/SystemInterfaceSFML.cpp
)

set(sfml2_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml2/src/RenderInterfaceSFML.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml2/src/SystemInterfaceSFML.h
)

set(sfml2_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml2/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml2/src/RenderInterfaceSFML.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/sfml2/src/SystemInterfaceSFML.cpp
)

set(directx_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx/src/RenderInterfaceDirectX.h
)

set(directx_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx/src/RenderInterfaceDirectX.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx/src/ShellRenderInterfaceExtensionsDirectX_Win32.cpp
)

set(directx10_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx10/src/D3D10Effect.h
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx10/src/RenderInterfaceDirectx10.h
)

set(directx10_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx10/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx10/src/RenderInterfaceDirectx10.cpp
    ${PROJECT_SOURCE_DIR}/Samples/basic/directx10/src/ShellRenderInterfaceExtensionsDirectX10_Win32.cpp
)

set(template_HDR_FILES
)

set(template_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/template/src/main.cpp
)

set(datagrid_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/DecoratorDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/DecoratorInstancerDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/HighScores.h
)

set(datagrid_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/DecoratorDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/DecoratorInstancerDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/HighScores.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid/src/main.cpp
)

set(datagrid_tree_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/DecoratorDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/DecoratorInstancerDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/HighScores.h
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/HighScoresShipFormatter.h
)

set(datagrid_tree_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/DecoratorDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/DecoratorInstancerDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/HighScores.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/HighScoresShipFormatter.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/datagrid_tree/src/main.cpp
)

set(tutorial_drag_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/tutorial_drag/src/Inventory.h
)

set(tutorial_drag_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/tutorial_drag/src/Inventory.cpp
    ${PROJECT_SOURCE_DIR}/Samples/tutorial/tutorial_drag/src/main.cpp
)

set(invaders_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorInstancerDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorInstancerStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Defender.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/ElementGame.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Event.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandler.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerHighScore.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerOptions.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerStartGame.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventInstancer.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventManager.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Game.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/GameDetails.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScores.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScoresNameFormatter.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScoresShipFormatter.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Invader.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Mothership.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Shield.h
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Sprite.h
)

set(invaders_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorInstancerDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorInstancerStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/DecoratorStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Defender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/ElementGame.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Event.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandler.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerHighScore.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerOptions.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventHandlerStartGame.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventInstancer.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/EventManager.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Game.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/GameDetails.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScores.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScoresNameFormatter.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/HighScoresShipFormatter.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Invader.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Mothership.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Shield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/invaders/src/Sprite.cpp
)

set(luainvaders_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorInstancerDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorInstancerStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Defender.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/ElementGame.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/ElementGameInstancer.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Game.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/GameDetails.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/HighScores.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Invader.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/LuaInterface.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Mothership.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Shield.h
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Sprite.h
)

set(luainvaders_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorInstancerDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorInstancerStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/DecoratorStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Defender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/ElementGame.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/ElementGameInstancer.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Game.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/GameDetails.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/HighScores.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Invader.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/LuaInterface.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Mothership.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Shield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/luainvaders/src/Sprite.cpp
)

set(pyinvaders_HDR_FILES
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorInstancerDefender.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorInstancerStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorStarfield.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Defender.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/ElementGame.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Game.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/GameDetails.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/HighScores.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Invader.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Mothership.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/PythonInterface.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Shield.h
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Sprite.h
)

set(pyinvaders_SRC_FILES
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorInstancerDefender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorInstancerStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/DecoratorStarfield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Defender.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/ElementGame.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Game.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/GameDetails.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/HighScores.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Invader.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/main.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Mothership.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/PythonInterface.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Shield.cpp
    ${PROJECT_SOURCE_DIR}/Samples/pyinvaders/src/Sprite.cpp
)

# Deal with platform specific sources for sample shell
if(WIN32)
       list(APPEND shell_SRC_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/win32/ShellWin32.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/win32/InputWin32.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/win32/ShellRenderInterfaceExtensionsOpenGL_Win32.cpp
       )
       list(APPEND shell_HDR_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/include/win32/InputWin32.h
       )
elseif(APPLE)
       list(APPEND shell_SRC_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/macosx/ShellMacOSX.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/macosx/InputMacOSX.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/macosx/ShellRenderInterfaceExtensionsOpenGL_MacOSX.cpp
       )
       list(APPEND shell_HDR_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/include/macosx/InputMacOSX.h
       )
else()
       list(APPEND shell_SRC_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/x11/ShellX11.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/x11/InputX11.cpp
               ${PROJECT_SOURCE_DIR}/Samples/shell/src/x11/ShellRenderInterfaceExtensionsOpenGL_X11.cpp
       )
       list(APPEND shell_HDR_FILES
               ${PROJECT_SOURCE_DIR}/Samples/shell/include/x11/InputX11.h
       )
endif()


text:
package nodes

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/GoogleCloudPlatform/heapster/sources/api"
	"github.com/golang/glog"
)

// Provides a list of external cadvisor nodes to monitor.
type externalCadvisorNodes struct {
	// File containing list of hosts to monitor.
	hostsFile string

	// Whether to run in "standalone" mode and only consider localhost.
	standalone bool

	nodes *NodeList
}

// While updating this, also update deploy/docker/Dockerfile.
var hostsFile = flag.String("external_hosts_file", "/var/run/heapster/hosts", "A file that heapster refers to get a list of nodes to monitor.")
var standaloneMode = flag.Bool("standalone", false, "Whether to run Heapster in \"standalone\" mode where it only targets the current node.")

func (self *externalCadvisorNodes) List() (*NodeList, error) {
	// Standalone means only localhost.
	if self.standalone {
		self.nodes = newNodeList()
		const localhostIP = "127.0.0.1"
		self.nodes.Items["localhost"] = Info{
			PublicIP:   localhostIP,
			InternalIP: localhostIP,
		}
		return self.nodes, nil
	}

	fi, err := os.Stat(self.hostsFile)
	if err != nil {
		return nil, fmt.Errorf("cannot stat file %q: %s", self.hostsFile, err)
	}
	if fi.Size() == 0 {
		return &NodeList{}, nil
	}
	contents, err := ioutil.ReadFile(self.hostsFile)
	if err != nil {
		return nil, err
	}
	var externalNodes api.ExternalNodeList
	err = json.Unmarshal(contents, &externalNodes)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal contents of file %s. Error: %s", self.hostsFile, err)
	}
	nodes := newNodeList()
	for _, node := range externalNodes.Items {
		nodes.Items[Host(node.Name)] = Info{PublicIP: node.IP, InternalIP: node.IP}
	}
	glog.V(5).Infof("Using cAdvisor hosts %+v", nodes)
	self.nodes = nodes
	return nodes, nil
}

func (self *externalCadvisorNodes) DebugInfo() string {
	output := "External Nodes plugin:"
	if self.standalone {
		output = fmt.Sprintf(" Running in standalone mode.\n")
	}
	if self.nodes != nil {
		output = fmt.Sprintf("%s hosts are\n %v", output, self.nodes.Items)
	}
	return output
}

func NewExternalNodes() (NodesApi, error) {
	if *standaloneMode {
		glog.Infof("Running in standalone mode, external nodes source will only use localhost")
	} else {
		_, err := os.Stat(*hostsFile)
		if err != nil {
			return nil, fmt.Errorf("cannot stat file %q: %s", *hostsFile, err)
		}
	}

	return &externalCadvisorNodes{
		hostsFile:  *hostsFile,
		standalone: *standaloneMode,
		nodes:      nil,
	}, nil
}