text:
package org.apache.mesos.elasticsearch.systemtest;

import com.containersol.minimesos.docker.DockerClientFactory;
import com.github.dockerjava.api.DockerClient;
import org.apache.mesos.elasticsearch.systemtest.base.TestBase;
import org.apache.mesos.elasticsearch.systemtest.containers.ElasticsearchSchedulerContainer;
import org.apache.mesos.elasticsearch.systemtest.util.ContainerLifecycleManagement;
import org.apache.mesos.elasticsearch.systemtest.util.DockerUtil;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;

/**
 * Tests CLUSTER state monitoring and reconciliation.
 */
@SuppressWarnings({"PMD.TooManyMethods"})
@Ignore("This test has to be merged into DeploymentSystemTest. See https://github.com/mesos/elasticsearch/issues/591")
public class ReconciliationSystemTest extends TestBase {
    private static final int TIMEOUT = 120;
    private static final ContainerLifecycleManagement CONTAINER_MANAGER = new ContainerLifecycleManagement();
    private static DockerClient dockerClient = DockerClientFactory.build();
    private DockerUtil dockerUtil = new DockerUtil(dockerClient);

    private static ElasticsearchSchedulerContainer startSchedulerContainer() {
        ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(dockerClient, CLUSTER.getZooKeeper().getIpAddress());
        CONTAINER_MANAGER.addAndStart(scheduler, TEST_CONFIG.getClusterTimeout());
        return scheduler;
    }

    @Rule
    public TestWatcher containerWatcher = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            CONTAINER_MANAGER.stopAll();
        }
    };

    @After
    public void killContainers() {
        CONTAINER_MANAGER.stopAll();
    }

    @Test
    public void ifSchedulerLostShouldReconcileExecutors() throws IOException {
        ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
        assertCorrectNumberOfExecutors();

        // Stop and restart container
        CONTAINER_MANAGER.stopContainer(scheduler);
        startSchedulerContainer();
        assertCorrectNumberOfExecutors();
    }

    @Test
    public void ifExecutorIsLostShouldStartAnother() throws IOException {
        startSchedulerContainer();
        assertCorrectNumberOfExecutors();

        dockerUtil.killOneExecutor();

        // Should restart an executor, so there should still be three
        assertCorrectNumberOfExecutors();

    }

    @Test
    public void ifExecutorIsLostWhileSchedulerIsDead() throws IOException {
        ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
        assertCorrectNumberOfExecutors();

        // Kill scheduler
        CONTAINER_MANAGER.stopContainer(scheduler);

        // Kill executor
        dockerUtil.killOneExecutor();

        startSchedulerContainer();
        // Should restart an executor, so there should still be three
        assertCorrectNumberOfExecutors();
    }

    private void assertCorrectNumberOfExecutors() throws IOException {
        assertCorrectNumberOfExecutors(getTestConfig().getElasticsearchNodesCount());
    }

    private void assertCorrectNumberOfExecutors(int expected) throws IOException {
        await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> dockerUtil.getExecutorContainers().size() == expected);
        assertEquals(expected, dockerUtil.getExecutorContainers().size());
    }
}


text:
<?php

namespace Kemistra\MainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TypeMaterielType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom', null, array('label' => 'Nom : '))
            ->add('description', null, array('label' => 'Description : '))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Kemistra\MainBundle\Entity\TypeMateriel'
        ));
    }

    public function getName()
    {
        return 'kemistra_mainbundle_typematerieltype';
    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as ts from "typescript";
import {DBTypes, DefaultDBType} from "./decorator";
import * as _ from "lodash";
import {InterfaceMap, ParsedInfo, PropertyOption, Interface,
        RelationshipType, Relationship} from "./types";
import {tsTypeToString} from "./util";

function getDecoratorName(decorator: ts.Decorator): string {

    switch (decorator.expression.kind) {
        case ts.SyntaxKind.Identifier:
            {
                const id = (decorator.expression as ts.Identifier);
                return id.text;
            }
        case ts.SyntaxKind.CallExpression:
            {
                const call = (decorator.expression as ts.CallExpression);
                return (call.expression as ts.Identifier).text;
            }
    }
    return null;
}

function getDecoratorArgs(decorator: ts.Decorator): ts.Expression[] {
    if (decorator.expression.kind === ts.SyntaxKind.CallExpression) {
        const call = (decorator.expression as ts.CallExpression);
        return call.arguments.map<ts.Expression>((v) => { return v; });
    }
    return [];
}

export function parse(fileName: string): ParsedInfo {
    let program = ts.createProgram([fileName], {
        target: ts.ScriptTarget.ES2015
    });
    var source = program.getSourceFile(fileName); //ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES5, true);
    var typeChecker = program.getTypeChecker();
    var interfaces : InterfaceMap = {};

    var imports: {[key:string]:string} = {};
    var usedImports: {[key:string]:string[]} = {};
    var usedDeclaration: {
        name: string;
        begin: number;
        end: number;
    }[] = [];
    ts.forEachChild(source, visit);

    function visit(node: ts.Node) {
        if (node.kind !== ts.SyntaxKind.ClassDeclaration) {
            if (node.kind === ts.SyntaxKind.ImportDeclaration) {
                let importDecl = <ts.ImportDeclaration>node;
                let moduleName = (<ts.StringLiteral>importDecl.moduleSpecifier).text;
                for (var namedBinding of (<ts.NamedImports>importDecl.importClause.namedBindings).elements) {
                    imports[namedBinding.name.text] = moduleName;
                }
            }
            return;
        }

        // only model exports
        if (node.decorators == null ||
            _.findIndex(node.decorators,
                (d: ts.Decorator) => getDecoratorName(d) === "model") === -1) {
            return;
        }

        let t = typeChecker.getTypeAtLocation(node);
        let name = t.getSymbol().getName();
        let newInterface: Interface = {
            name: name,
            properties: [],
            createdAt: "createdAt",
            deletedAt: null,
            updatedAt: "updatedAt",
            hasPrimaryKey: false,
            relationships: [],
            indexes: {}
        };
        for (let prop of typeChecker.getPropertiesOfType(t)) {
            const propName = prop.name;
            const info = parseProperty(prop.getDeclarations()[0] as ts.PropertyDeclaration);
            if (info == null) {
                continue;
            }

            info[0].associated = info[2];
            const [option, tsType] = info;
            newInterface.properties.push({
                name: propName,
                tsType,
                option
            });
            if (info[0].primaryKey) {
                newInterface.hasPrimaryKey = true;
            }
            if (info[2] != null) {
                info[2].name = propName;
                newInterface.relationships.push(info[2]);
            }
            if (info[3] !== null) {
                let index = newInterface.indexes[info[3]];
                if (index == null) {
                    index = newInterface.indexes[info[3]] = {unique: false, fields: []};
                }
                index.fields.push(propName);
            }
        }

        interfaces[name] = newInterface;
    }

    function parseDecorators(decorators: ts.NodeArray<ts.Decorator>): PropertyOption {
        let ret: PropertyOption = {
            concreteType: null,
            embeded: null,
            internal: false,
            primaryKey: false,
            arrayJoinedWith: null,
            associated: null
        };

        if (decorators === undefined) {
            return ret;
        }
        for (var decorator of decorators) {
            let name: string = getDecoratorName(decorator);
            const args = getDecoratorArgs(decorator);
            switch (name) {
            case "internal":
                ret.internal = true;
                break;
            case "concreteType":
                ret.concreteType = DBTypes[(args[0] as ts.PropertyAccessExpression).name.text as keyof typeof DBTypes];
                break;
            case "embededField":
                ret.embeded = [];
                break;
            case "primaryKey":
                ret.primaryKey = true;
                break;
            case "arrayJoinedWith":
                ret.arrayJoinedWith = (<ts.StringLiteral>args[0]).text;
                break;
            }
        }
        return ret;
    }

    function parseProperty(decl: ts.PropertyDeclaration): [PropertyOption, ts.Type, Relationship, string] {
        let ret: PropertyOption = {
            concreteType: null,
            embeded: null,
            internal: false,
            primaryKey: false,
            arrayJoinedWith: null,
            associated: null
        };
        if (decl.kind != ts.SyntaxKind.PropertyDeclaration) {
            return;
        }
        var decorators = decl.decorators;
        let propType = typeChecker.getTypeAtLocation(decl.type);
        let tsType: string = tsTypeToString(propType);
        let baseType: string = tsType.replace("[]", "");
        let typeDecl: ts.Declaration = null;
        let relationship: Relationship = null;
        let index: string = null;
        let isArray: boolean = false;
        if (propType.symbol) {
            if (propType.symbol.name === "Array") {
                isArray = true;
                if ((propType as ts.GenericType).typeArguments[0].symbol) {
                    typeDecl = (propType as ts.GenericType).typeArguments[0].symbol.declarations[0];
                }
            }
            else {
                typeDecl = propType.symbol.declarations[0];
            }
        }

        const indexInfo = _.find(decorators, (dec) => getDecoratorName(dec) === "Index");
        if (indexInfo !== undefined) {
            const args = getDecoratorArgs(indexInfo);
            index = (args[0] as ts.StringLiteral).text;
        }
        // import
        if (typeDecl) {
            let moduleName = imports[baseType];
            let typeDecoratorNames = _.map(typeDecl.decorators, getDecoratorName);
            if (_.includes(typeDecoratorNames, "model")) {
                // model - relation
                relationship = {
                    type: isArray?RelationshipType.OneToMany:RelationshipType.ManyToOne,
                    name : null,
                    targetName: baseType,
                    targetModule: moduleName
                };
            }
            else if (baseType in imports) {
                if (!(moduleName in usedImports)) {
                    usedImports[moduleName] = [];
                }
                usedImports[moduleName].push(baseType);
            }
            else if (typeDecl.getSourceFile() === source) {
                usedDeclaration.push({
                    name: tsType,
                    begin: typeDecl.pos,
                    end: typeDecl.end
                });
            }
        }
        // declared in same file or default
        else if (!isNodeType(tsType)) {
            console.log(decl);
            if (decl.getSourceFile() === source) {
                usedDeclaration.push({
                    name: tsType,
                    begin: typeDecl.pos,
                    end: typeDecl.end
                });
            }
        }
        _.assign(ret, parseDecorators(decorators));

        // fill concreteType
        if (ret.concreteType == null) {
            if (DefaultDBType.has(tsType)) {
                ret.concreteType = DefaultDBType.get(tsType);
            }
            else if (ret.embeded != null) {
                for (var embededProp of typeChecker.getPropertiesOfType(propType)) {
                    let name = embededProp.getName();
                    let info = parseProperty(<ts.PropertyDeclaration>embededProp.getDeclarations()[0]);
                    if (info == null) {
                        continue;
                    }
                    ret.embeded.push({
                        name: name,
                        option: info[0],
                        tsType: info[1]
                    });
                }
            } else if (propType.flags & ts.TypeFlags.Enum || propType.flags & ts.TypeFlags.EnumLiteral) {
                ret.concreteType = DBTypes.Int;
            }
        }
        return [ret, propType, relationship, index];
    }

    function isNodeType(typename: string): boolean {
        return _.includes(["string", "number", "boolean", "Date"],
                          typename.replace("[]",""));
    }

    const declarations: {[key:string]:string} = {};
    _.forEach(usedDeclaration, (declInfo) => {
        if (interfaces[declInfo.name]) {
            return;
        }
        var code = source.text.slice(declInfo.begin, declInfo.end).trim();
        if (!code.startsWith("export")) {
            code = `export ${code}`;
        }
        declarations[declInfo.name] = code;
    });

    return {
        interfaces: interfaces,
        declarations: declarations,
        imports: usedImports
    };
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title> R / V</title>

	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="X-Frame-Options" content="sameorigin">

	<link rel="stylesheet" href="/css/main.css">

	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

	<link rel="canonical" href="https://richyvk.github.io//blog/page3/">

	<link rel="alternate" type="application/atom+xml" title="R / V" href="https://richyvk.github.io//feed.xml" />

	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

	<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">

			R / V

					About

					Posts

  <div class="call-out"

My name is Richard Vankoningsveld. I'm a law librarian.

I write about learning to write code. My focus is web development and data analysis, mostly using Python.

            Creating an RSS feed for Australian Commonwealth Bill changes with Python

          October 8, 2015

The story of my first real attempt at making something useful with Python.

          Continue reading

            On learning to code (it's a bloody long road)

          August 28, 2015

I've been attempting to learn to code for a few years now on and off. To a degree this is for work reasons (I'm a librarian, with systems librarian tendancies, and some opportunities to write code as part of my job). It's also because I aspire to write code full time for a living.

          Continue reading

            Readifying AustLii

          February 14, 2015

I love AustLii. Everyone I know that works in a law library loves AustLii (well, if not the actual site itself, then at least the idea of it). For some time now though, I've found myself increasingly frustrated with it. Specifially, since I've actually had to start reading court decisions in some detail using it, I've concluded that AustLii's current format does not provide for enjoyable, or efficient reading. In short, it sucks for reading!

          Continue reading

            Programming for Everybody (Python) notes

          January 14, 2015

I recently did most of Dr Chuck's Python course on Coursera, and documented most of what I'd learnt. Here are my notes, and few comments on the experience.

          Continue reading

            MOOCs, python, first step into a larger world

          September 25, 2014

I've had a change of direction since I resurrected my blogging efforts. I have found 24 things to be pretty uninspiring I'm afraid. I'm sure many people get a lot out of it, but it's not for me.

          Continue reading

      Prev

      Next

Powered by Jekyll with a customised version of Type Theme


text:
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

const artists = Ember.A([
  Ember.Object.create({ id: 1, name: "Eddie Vedder" }),
  Ember.Object.create({ id: 2, name: "Dave Grohl" }),
  Ember.Object.create({ id: 3, name: "John Paul Jones" }),
  Ember.Object.create({ id: 4, name: "Jimmy Page" })
]);

function typeInInput(text) {
  this.$('.auto-complete-input')
    .prop('value', text)
    .trigger('input');
}

moduleForComponent('auto-complete', 'Integration | Component | auto-complete', {
  integration: true
});

test('it works', function(assert) {
  assert.expect(4);

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });
  this.set('selectedArtist', null);
  this.set('matchingArtists', artists);
  this.actions = {
    selectArtist(artist) {
      this.set('selectedArtist', artist);
    },
    filterArtists(searchTerm) {
      const matchingArtists = artists.filter(function(artist) {
        searchTerm = searchTerm.toLowerCase();
        return artist.get('name').toLowerCase().indexOf(searchTerm) === 0;
      });
      this.set('matchingArtists', Ember.A(matchingArtists));
    }
  };

  this.render(hbs`
    {{#auto-complete
        on-select=(action "selectArtist")
        on-input=(action "filterArtists")
        items=matchingArtists
        displayProperty="name"
        as |params|}}
        {{auto-complete-input
            class="auto-complete-input"
            value=params.inputValue
            on-change=params.onInput
            type="text"}}
        {{#auto-complete-list isVisible=params.isOpen}}
          {{#each params.options as |option|}}
            {{#auto-complete-option
                class="auto-complete-option"
                index=option.index
                on-click=params.onSelect
                isFocused=(eq params.focusedIndex option.index)
                isSelected=(eq params.selectedIndex option.index)}}
              {{option.value}}
            {{/auto-complete-option}}
          {{else}}

No results.

          {{/each}}
        {{/auto-complete-list}}
        {{#auto-complete-dropdown-toggle on-click=params.toggleDropdown}}

        {{/auto-complete-dropdown-toggle}}
    {{/auto-complete}}
  `);

  function assertSelectedArtist(name) {
    assert.equal(this.get('selectedArtist.name'), name);
  }

  function assertOptionCount(count, message) {
    assert.equal(this.$('.auto-complete-option').length, count, message);
  }

  this.$('.auto-complete-option:first').click();
  assertSelectedArtist.call(this, 'Eddie Vedder');

  this.$('.auto-complete-option:last').click();
  assertSelectedArtist.call(this, 'Jimmy Page');

  typeInInput.call(this, 'J');
  assertOptionCount.call(this, 2, "The filtered artists are shown");

  typeInInput.call(this, 'Jo');
  assertSelectedArtist.call(this, 'John Paul Jones');

  typeInInput.call(this, '');
});


text:
// .NAME vtkLabeledDataMapper - draw text labels at dataset points
// .SECTION Description
// vtkLabeledDataMapper is a mapper that renders text at dataset
// points. Various items can be labeled including point ids, scalars,
// vectors, normals, texture coordinates, tensors, and field data components.
//
// The format with which the label is drawn is specified using a
// printf style format string. The font attributes of the text can
// be set through the vtkTextProperty associated to this mapper.
//
// By default, all the components of multi-component data such as
// vectors, normals, texture coordinates, tensors, and multi-component
// scalars are labeled. However, you can specify a single component if
// you prefer. (Note: the label format specifies the format to use for
// a single component. The label is creating by looping over all components
// and using the label format to render each component.)

// .SECTION Caveats
// Use this filter in combination with vtkSelectVisiblePoints if you want
// to label only points that are visible. If you want to label cells rather
// than points, use the filter vtkCellCenters to generate points at the
// center of the cells. Also, you can use the class vtkIdFilter to
// generate ids as scalars or field data, which can then be labeled.

// .SECTION See Also
// vtkMapper2D vtkActor2D vtkTextMapper vtkTextProperty vtkSelectVisiblePoints
// vtkIdFilter vtkCellCenters

#ifndef vtkLabeledDataMapper_h
#define vtkLabeledDataMapper_h

#include "vtkRenderingLabelModule.h" // For export macro
#include "vtkMapper2D.h"

#include <cassert> // For assert macro

class vtkDataObject;
class vtkDataSet;
class vtkTextMapper;
class vtkTextProperty;
class vtkTransform;

#define VTK_LABEL_IDS        0
#define VTK_LABEL_SCALARS    1
#define VTK_LABEL_VECTORS    2
#define VTK_LABEL_NORMALS    3
#define VTK_LABEL_TCOORDS    4
#define VTK_LABEL_TENSORS    5
#define VTK_LABEL_FIELD_DATA 6

class VTKRENDERINGLABEL_EXPORT vtkLabeledDataMapper : public vtkMapper2D
{
public:
  // Description:
  // Instantiate object with %%-#6.3g label format. By default, point ids
  // are labeled.
  static vtkLabeledDataMapper *New();

  vtkTypeMacro(vtkLabeledDataMapper,vtkMapper2D);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set/Get the format with which to print the labels.  This should
  // be a printf-style format string.
  //
  // By default, the mapper will try to print each component of the
  // tuple using a sane format: %d for integers, %f for floats, %g for
  // doubles, %ld for longs, et cetera.  If you need a different
  // format, set it here.  You can do things like limit the number of
  // significant digits, add prefixes/suffixes, basically anything
  // that printf can do.  If you only want to print one component of a
  // vector, see the ivar LabeledComponent.
  vtkSetStringMacro(LabelFormat);
  vtkGetStringMacro(LabelFormat);

  // Description:
  // Set/Get the component number to label if the data to print has
  // more than one component. For example, all the components of
  // scalars, vectors, normals, etc. are labeled by default
  // (LabeledComponent=(-1)). However, if this ivar is nonnegative,
  // then only the one component specified is labeled.
  vtkSetMacro(LabeledComponent,int);
  vtkGetMacro(LabeledComponent,int);

  // Description:
  // Set/Get the field data array to label. This instance variable is
  // only applicable if field data is labeled.  This will clear
  // FieldDataName when set.
  void SetFieldDataArray(int arrayIndex);
  vtkGetMacro(FieldDataArray,int);

  // Description:
  // Set/Get the name of the field data array to label.  This instance
  // variable is only applicable if field data is labeled.  This will
  // override FieldDataArray when set.
  void SetFieldDataName(const char *arrayName);
  vtkGetStringMacro(FieldDataName);

  // Description:
  // Set the input dataset to the mapper. This mapper handles any type of data.
  virtual void SetInputData(vtkDataObject*);

  // Description:
  // Use GetInputDataObject() to get the input data object for composite
  // datasets.
  vtkDataSet *GetInput();

  // Description:
  // Specify which data to plot: IDs, scalars, vectors, normals, texture coords,
  // tensors, or field data. If the data has more than one component, use
  // the method SetLabeledComponent to control which components to plot.
  // The default is VTK_LABEL_IDS.
  vtkSetMacro(LabelMode, int);
  vtkGetMacro(LabelMode, int);
  void SetLabelModeToLabelIds() {this->SetLabelMode(VTK_LABEL_IDS);};
  void SetLabelModeToLabelScalars() {this->SetLabelMode(VTK_LABEL_SCALARS);};
  void SetLabelModeToLabelVectors() {this->SetLabelMode(VTK_LABEL_VECTORS);};
  void SetLabelModeToLabelNormals() {this->SetLabelMode(VTK_LABEL_NORMALS);};
  void SetLabelModeToLabelTCoords() {this->SetLabelMode(VTK_LABEL_TCOORDS);};
  void SetLabelModeToLabelTensors() {this->SetLabelMode(VTK_LABEL_TENSORS);};
  void SetLabelModeToLabelFieldData()
            {this->SetLabelMode(VTK_LABEL_FIELD_DATA);};

  // Description:
  // Set/Get the text property.
  // If an integer argument is provided, you may provide different text
  // properties for different label types. The type is determined by an
  // optional type input array.
  virtual void SetLabelTextProperty(vtkTextProperty *p)
    { this->SetLabelTextProperty(p, 0); }
  virtual vtkTextProperty* GetLabelTextProperty()
    { return this->GetLabelTextProperty(0); }
  virtual void SetLabelTextProperty(vtkTextProperty *p, int type);
  virtual vtkTextProperty* GetLabelTextProperty(int type);

  // Description:
  // Draw the text to the screen at each input point.
  void RenderOpaqueGeometry(vtkViewport* viewport, vtkActor2D* actor);
  void RenderOverlay(vtkViewport* viewport, vtkActor2D* actor);

  // Description:
  // Release any graphics resources that are being consumed by this actor.
  virtual void ReleaseGraphicsResources(vtkWindow *);

  // Description:
  // The transform to apply to the labels before mapping to 2D.
  vtkGetObjectMacro(Transform, vtkTransform);
  void SetTransform(vtkTransform* t);

  //BTX
  /// Coordinate systems that output dataset may use.
  enum Coordinates
    {
    WORLD=0,           //!< Output 3-D world-space coordinates for each label anchor.
    DISPLAY=1          //!< Output 2-D display coordinates for each label anchor (3 components but only 2 are significant).
    };
  //ETX

  // Description:
  // Set/get the coordinate system used for output labels.
  // The output datasets may have point coordinates reported in the world space or display space.
  vtkGetMacro(CoordinateSystem,int);
  vtkSetClampMacro(CoordinateSystem,int,WORLD,DISPLAY);
  void CoordinateSystemWorld() { this->SetCoordinateSystem( vtkLabeledDataMapper::WORLD ); }
  void CoordinateSystemDisplay() { this->SetCoordinateSystem( vtkLabeledDataMapper::DISPLAY ); }

  // Description:
  // Return the modified time for this object.
  virtual unsigned long GetMTime();

  // Description:
  // Return the number of labels rendered by the mapper.
  vtkGetMacro(NumberOfLabels, int)

  // Description:
  // Return the position of the requested label.
  void GetLabelPosition(int label, double pos[3])
  {
    assert("label index range" && label >= 0 && label < this->NumberOfLabels);
    pos[0] = this->LabelPositions[3 * label];
    pos[1] = this->LabelPositions[3 * label + 1];
    pos[2] = this->LabelPositions[3 * label + 2];
  }

  // Description:
  // Return the text for the requested label.
  const char *GetLabelText(int label);

protected:
  vtkLabeledDataMapper();
  ~vtkLabeledDataMapper();

  vtkDataSet *Input;

  char  *LabelFormat;
  int   LabelMode;
  int   LabeledComponent;
  int   FieldDataArray;
  char  *FieldDataName;
  int CoordinateSystem;

  vtkTimeStamp BuildTime;

  int NumberOfLabels;
  int NumberOfLabelsAllocated;
  vtkTextMapper **TextMappers;
  double* LabelPositions;
  vtkTransform *Transform;

  virtual int FillInputPortInformation(int, vtkInformation*);

  void AllocateLabels(int numLabels);
  void BuildLabels();
  void BuildLabelsInternal(vtkDataSet*);

  //BTX
  class Internals;
  Internals* Implementation;
  //ETX

private:
  vtkLabeledDataMapper(const vtkLabeledDataMapper&);  // Not implemented.
  void operator=(const vtkLabeledDataMapper&);  // Not implemented.
};

#endif


text:
int main(int argc, char** argv);

// Initialize GLEW.
int initializeGLEW();

//	Initialize GLFW.
int initializeGLFW();

//	Initialize the ECS.
void initializeECS();

//	Render the Cycle.
void enterRenderCycle();

//	Terminate the ECS.
void terminateECS();

//	Key Callback.
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);

//	Pointer to the ECS.
std::shared_ptr<PlanetMakerECS> ecs;

//	Current Frame Time.
float deltaFrameTime, currentFrameTime, lastFrameTime;

// Default initialization for monitor
GLFWmonitor * monitor;
const GLFWvidmode * mode;
GLFWwindow	* window;


text:
using OOM.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace OOM.Web.Controllers
{
    public class RevisionsController : Controller
    {
        private OOMetricsContext _db = new OOMetricsContext();

        // GET: /Revisions/List/5
        public ActionResult List(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var project = _db.Projects.Find(id);
            if (project == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }

            return View(project.Revisions);
        }

        // GET: /Revisions/Details/5
        public ActionResult Details(int id)
        {
            var revision = _db.Revisions.Find(id);
            if (revision == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }

            return View(revision);
        }

        // GET: /Revisions/Explore/?elementType=class&elementId=8
        public JsonResult Explore(ElementType? elementType, int elementId)
        {
            ElementType type = elementType.HasValue ? elementType.Value : 0;
            int group = GetGroupByElementType(type);
            object result = null;
            switch (type)
            {
                case ElementType.Namespace:
                    var ns = _db.Namespaces.Find(elementId);
                    result = AssemblyExplorerStructure(new
                    {
                        id = ns.Id,
                        name = ns.Name,
                        description = ns.FullyQualifiedIdentifier,
                        group = group,
                        parent = new { group = GetGroupByElementType(null), id = ns.RevisionId }
                    }, ns.Classes);
                    break;
                case ElementType.Class:
                    var c = _db.Classes.Find(elementId);
                    result = AssemblyExplorerStructure(new
                    {
                        id = c.Id,
                        name = c.Name,
                        description = c.FullyQualifiedIdentifier,
                        group = group,
                        parent = new { group = GetGroupByElementType(ElementType.Namespace), id = c.NamespaceId }
                    }, c.Fields.Cast<IElement>().Concat(c.Methods));
                    break;
                case ElementType.Field:
                    var f = _db.Fields.Find(elementId);
                    result = AssemblyExplorerStructure(new
                    {
                        id = f.Id,
                        name = f.Name,
                        description = f.FullyQualifiedIdentifier,
                        group = group,
                        parent = new { group = GetGroupByElementType(ElementType.Class), id = f.ClassId }
                    }, null);
                    break;
                case ElementType.Method:
                    var m = _db.Methods.Find(elementId);
                    result = AssemblyExplorerStructure(new
                    {
                        id = m.Id,
                        name = m.Name,
                        description = m.FullyQualifiedIdentifier,
                        group = group,
                        parent = new { group = GetGroupByElementType(ElementType.Class), id = m.ClassId }
                    }, null);
                    break;
                default:
                    var r = _db.Revisions.Find(elementId);
                    result = AssemblyExplorerStructure(new
                    {
                        id = r.Id,
                        name = String.Format("Revision #{0}", r.Number),
                        description = String.Format("
{0}

Author: {1}

Date: {2:dd/mm/yyyy}
", r.Message, r.Author, r.CreatedAt),
                        group = group,
                        root = true
                    }, r.Namespaces);
                    break;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        private int GetGroupByElementType(ElementType? elementType)
        {
            ElementType type = elementType.HasValue ? elementType.Value : 0;
            int group = 0;
            switch (type)
            {
                case ElementType.Namespace:
                    group = 2;
                    break;
                case ElementType.Class:
                    group = 3;
                    break;
                case ElementType.Field:
                    group = 4;
                    break;
                case ElementType.Method:
                    group = 5;
                    break;
                default:
                    group = 1;
                    break;
            }

            return group;
        }

        private object AssemblyExplorerStructure(object rootData, IEnumerable<IElement> children)
        {
            var nodes = new List<object>();
            var links = new List<object>();

            var revisionNodeIndex = nodes.Count;
            nodes.Add(rootData);

            if (children != null)
            {
                foreach (var child in children)
                {
                    var nodeIndex = nodes.Count;

                    nodes.Add(new
                    {
                        id = child.Id,
                        name = child.FullyQualifiedIdentifier,
                        group = GetGroupByElementType(child.Type)
                    });

                    links.Add(new
                    {
                        source = revisionNodeIndex,
                        target = nodeIndex
                    });
                }
            }

            return new
            {
                nodes = nodes,
                links = links
            };
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _db.Dispose();
            }

            base.Dispose(disposing);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/importexport/quickSubmit/locale/sr_SR/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * Localization strings for the sr_SR (Serbian) locale.
  *
  -->

<locale name="sr_SR" full_name="Serbian">
	<message key="plugins.importexport.quickSubmit.addToExisting">Dodaj u postojeći broj:</message>
	<message key="plugins.importexport.quickSubmit.chooseDestination">Odredište predaje</message>
	<message key="plugins.importexport.quickSubmit.chooseDestinationDescription">Odredite da li predaja rada ide u postojeći broj ili u uredništvo.</message>
	<message key="plugins.importexport.quickSubmit.displayName">Dodatak za brzu predaju radova</message>
	<message key="plugins.importexport.quickSubmit.description">Dodatak za predaju radova u jednom koraku</message>
	<message key="plugins.importexport.quickSubmit.descriptionLong">Ovaj dodatak omogućuje da brzo predate rad u uredništvo ili direktno u časopis.</message>
	<message key="plugins.importexport.quickSubmit.issueRequired">Morate da odaberete broj da biste dodali članak u njega.</message>
	<message key="plugins.importexport.quickSubmit.leaveUnpublished">Ostavi neobjavljeno</message>
	<message key="plugins.importexport.quickSubmit.saveAndCreateAnother">Sačuvaj i napravi novi</message>
	<message key="plugins.importexport.quickSubmit.submissionData">Datum predaje</message>
	<message key="plugins.importexport.quickSubmit.submissionDescription">Izaberite fajl koji će se koristiti kao krajnji prikaz ovog rada u časopisu.</message>
	<message key="plugins.importexport.quickSubmit.submissionRequired">Morate da dodate fajl uz ovu predaju.</message>
	<message key="plugins.importexport.quickSubmit.success">Članak je dodat</message>
	<message key="plugins.importexport.quickSubmit.successDescription">Pravljenje članka je uspešno završeno</message>
	<message key="plugins.importexport.quickSubmit.successReturn">Vrati se na dodatak</message>
</locale>


text:
package org.apache.drill.exec.store.parquet;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.base.AbstractWriter;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.impl.WriterRecordBatch;
import org.apache.drill.exec.planner.logical.DrillTable;
import org.apache.drill.exec.planner.logical.DynamicDrillTable;
import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.store.RecordWriter;
import org.apache.drill.exec.store.StoragePluginOptimizerRule;
import org.apache.drill.exec.store.dfs.BasicFormatMatcher;
import org.apache.drill.exec.store.dfs.DrillFileSystem;
import org.apache.drill.exec.store.dfs.DrillPathFilter;
import org.apache.drill.exec.store.dfs.FileSelection;
import org.apache.drill.exec.store.dfs.FileSystemConfig;
import org.apache.drill.exec.store.dfs.FileSystemPlugin;
import org.apache.drill.exec.store.dfs.FormatMatcher;
import org.apache.drill.exec.store.dfs.FormatPlugin;
import org.apache.drill.exec.store.dfs.FormatSelection;
import org.apache.drill.exec.store.dfs.MagicString;
import org.apache.drill.exec.store.mock.MockStorageEngine;
import org.apache.drill.exec.store.parquet.Metadata.ParquetFileMetadata;
import org.apache.drill.exec.store.parquet.Metadata.ParquetTableMetadata_v1;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.hadoop.ParquetFileWriter;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class ParquetFormatPlugin implements FormatPlugin{
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MockStorageEngine.class);

  public static final ParquetMetadataConverter parquetMetadataConverter = new ParquetMetadataConverter();

  private static final String DEFAULT_NAME = "parquet";

  private static final List<Pattern> PATTERNS = Lists.newArrayList(
      Pattern.compile(".*\\.parquet$"),
      Pattern.compile(".*/" + ParquetFileWriter.PARQUET_METADATA_FILE));
  private static final List<MagicString> MAGIC_STRINGS = Lists.newArrayList(new MagicString(0, ParquetFileWriter.MAGIC));

  private final DrillbitContext context;
  private final Configuration fsConf;
  private final ParquetFormatMatcher formatMatcher;
  private final ParquetFormatConfig config;
  private final StoragePluginConfig storageConfig;
  private final String name;

  public ParquetFormatPlugin(String name, DrillbitContext context, Configuration fsConf,
      StoragePluginConfig storageConfig){
    this(name, context, fsConf, storageConfig, new ParquetFormatConfig());
  }

  public ParquetFormatPlugin(String name, DrillbitContext context, Configuration fsConf,
      StoragePluginConfig storageConfig, ParquetFormatConfig formatConfig){
    this.context = context;
    this.config = formatConfig;
    this.formatMatcher = new ParquetFormatMatcher(this);
    this.storageConfig = storageConfig;
    this.fsConf = fsConf;
    this.name = name == null ? DEFAULT_NAME : name;
  }

  @Override
  public Configuration getFsConf() {
    return fsConf;
  }

  @Override
  public ParquetFormatConfig getConfig() {
    return config;
  }

  public DrillbitContext getContext() {
    return this.context;
  }

  @Override
  public boolean supportsRead() {
    return true;
  }

  @Override
  public Set<StoragePluginOptimizerRule> getOptimizerRules() {
    return ImmutableSet.of();
  }

  @Override
  public AbstractWriter getWriter(PhysicalOperator child, String location, List<String> partitionColumns) throws IOException {
    return new ParquetWriter(child, location, partitionColumns, this);
  }

  public RecordWriter getRecordWriter(FragmentContext context, ParquetWriter writer) throws IOException, OutOfMemoryException {
    Map<String, String> options = Maps.newHashMap();

    options.put("location", writer.getLocation());

    FragmentHandle handle = context.getHandle();
    String fragmentId = String.format("%d_%d", handle.getMajorFragmentId(), handle.getMinorFragmentId());
    options.put("prefix", fragmentId);

    options.put(FileSystem.FS_DEFAULT_NAME_KEY, ((FileSystemConfig)writer.getStorageConfig()).connection);

    options.put(ExecConstants.PARQUET_BLOCK_SIZE, context.getOptions().getOption(ExecConstants.PARQUET_BLOCK_SIZE).num_val.toString());
    options.put(ExecConstants.PARQUET_PAGE_SIZE, context.getOptions().getOption(ExecConstants.PARQUET_PAGE_SIZE).num_val.toString());
    options.put(ExecConstants.PARQUET_DICT_PAGE_SIZE, context.getOptions().getOption(ExecConstants.PARQUET_DICT_PAGE_SIZE).num_val.toString());

    options.put(ExecConstants.PARQUET_WRITER_COMPRESSION_TYPE,
        context.getOptions().getOption(ExecConstants.PARQUET_WRITER_COMPRESSION_TYPE).string_val);

    options.put(ExecConstants.PARQUET_WRITER_ENABLE_DICTIONARY_ENCODING,
        context.getOptions().getOption(ExecConstants.PARQUET_WRITER_ENABLE_DICTIONARY_ENCODING).bool_val.toString());

    RecordWriter recordWriter = new ParquetRecordWriter(context, writer);
    recordWriter.init(options);

    return recordWriter;
  }

  public WriterRecordBatch getWriterBatch(FragmentContext context, RecordBatch incoming, ParquetWriter writer)
          throws ExecutionSetupException {
    try {
      return new WriterRecordBatch(writer, incoming, context, getRecordWriter(context, writer));
    } catch(IOException e) {
      throw new ExecutionSetupException(String.format("Failed to create the WriterRecordBatch. %s", e.getMessage()), e);
    }
  }

  @Override
  public ParquetGroupScan getGroupScan(String userName, FileSelection selection, List<SchemaPath> columns)
      throws IOException {
    return new ParquetGroupScan(userName, selection, this, selection.selectionRoot, columns);
  }

  @Override
  public StoragePluginConfig getStorageConfig() {
    return storageConfig;
  }

  public String getName(){
    return name;
  }

  @Override
  public boolean supportsWrite() {
    return false;
  }

  @Override
  public boolean supportsAutoPartitioning() {
    return true;
  }

  @Override
  public FormatMatcher getMatcher() {
    return formatMatcher;
  }

  private static class ParquetFormatMatcher extends BasicFormatMatcher{

    public ParquetFormatMatcher(ParquetFormatPlugin plugin) {
      super(plugin, PATTERNS, MAGIC_STRINGS);
    }

    @Override
    public boolean supportDirectoryReads() {
      return true;
    }

    @Override
    public DrillTable isReadable(DrillFileSystem fs, FileSelection selection,
        FileSystemPlugin fsPlugin, String storageEngineName, String userName)
        throws IOException {
      // TODO: we only check the first file for directory reading.  This is because
      if(selection.containsDirectories(fs)){
        if(isDirReadable(fs, selection.getFirstPath(fs))){
          return new DynamicDrillTable(fsPlugin, storageEngineName, userName,
              new FormatSelection(plugin.getConfig(), expandSelection(fs, selection)));
        }
      }
      return super.isReadable(fs, selection, fsPlugin, storageEngineName, userName);
    }

    private FileSelection expandSelection(DrillFileSystem fs, FileSelection selection) throws IOException {
      if (metaDataFileExists(fs, selection.getFirstPath(fs))) {
        FileStatus metaRootDir = selection.getFirstPath(fs);
        Path metaFilePath = getMetadataPath(metaRootDir);

        // get the metadata for the directory by reading the metadata file
        ParquetTableMetadata_v1 metadata  = Metadata.readBlockMeta(fs, metaFilePath.toString());
        List<String> fileNames = Lists.newArrayList();
        for (ParquetFileMetadata file : metadata.files) {
          fileNames.add(file.path);
        }
        // when creating the file selection, set the selection root in the form /a/b instead of
        // file:/a/b.  The reason is that the file names above have been created in the form
        // /a/b/c.parquet and the format of the selection root must match that of the file names
        // otherwise downstream operations such as partition pruning can break.
        final Path metaRootPath = Path.getPathWithoutSchemeAndAuthority(metaRootDir.getPath());
        final FileSelection newSelection = FileSelection.create(null, fileNames, metaRootPath.toString());
        return ParquetFileSelection.create(newSelection, metadata);
      } else {
        // don't expand yet; ParquetGroupScan's metadata gathering operation
        // does that.
        return selection;
      }
    }

    private Path getMetadataPath(FileStatus dir) {
      return new Path(dir.getPath(), Metadata.METADATA_FILENAME);
    }

    private boolean metaDataFileExists(FileSystem fs, FileStatus dir) throws IOException {
      return fs.exists(getMetadataPath(dir));
    }

    boolean isDirReadable(DrillFileSystem fs, FileStatus dir) {
      Path p = new Path(dir.getPath(), ParquetFileWriter.PARQUET_METADATA_FILE);
      try {
        if (fs.exists(p)) {
          return true;
        } else {

          if (metaDataFileExists(fs, dir)) {
            return true;
          }
          PathFilter filter = new DrillPathFilter();

          FileStatus[] files = fs.listStatus(dir.getPath(), filter);
          if (files.length == 0) {
            return false;
          }
          return super.isFileReadable(fs, files[0]);
        }
      } catch (IOException e) {
        logger.info("Failure while attempting to check for Parquet metadata file.", e);
        return false;
      }
    }
  }
}


text:
  <canvas id="base" class="chart-bar"
          chart-data="data" chart-labels="labels" chart-colors="colors"
          chart-options="chartOptions" chart-dataset-override="datasetOverride">
  </canvas>


text:
using System;
using System.Runtime.Serialization;

namespace Lime.Protocol.Security
{
    /// <summary>
    /// Defines a external authentication scheme, that uses third-party validation.
    /// </summary>
    [DataContract(Namespace = "http://limeprotocol.org/2014")]
    public class ExternalAuthentication : Authentication
    {
        public const string TOKEN_KEY = "token";
        public const string ISSUER_KEY = "issuer";

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalAuthentication"/> class.
        /// </summary>
        public ExternalAuthentication()
            : base(AuthenticationScheme.External)
        {
        }

        /// <summary>
        /// Gets or sets the authentication token on base64 representation.
        /// </summary>
        [DataMember(Name = TOKEN_KEY)]
        public string Token { get; set; }

        /// <summary>
        /// Gets or sets the trusted token issuer.
        /// </summary>
        [DataMember(Name = ISSUER_KEY)]
        public string Issuer { get; set; }

        /// <summary>
        /// Set a plain token to a base64 representation
        /// </summary>
        /// <param name="password"></param>
        public void SetToBase64Token(string password)
        {
            Token = string.IsNullOrWhiteSpace(password) ? password : password.ToBase64();
        }

        /// <summary>
        /// Gets the token decoded from the Base64 representation
        /// </summary>
        /// <returns></returns>
        public string GetFromBase64Token()
        {
            return string.IsNullOrWhiteSpace(Token) ? Token : Token.FromBase64();
        }
    }
}


text:
#import "LVAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "LView.h"
#import "LVHeads.h"

@interface LVAudioPlayer ()
@property(nonatomic,assign) BOOL playing;
@end

@implementation LVAudioPlayer{
    AVAudioPlayer* audioPlayer;
}

static void releaseUserDataAudioPlayer(LVUserDataInfo* user){
    if( user && user->object ){
        LVAudioPlayer* palyer = CFBridgingRelease(user->object);
        user->object = NULL;
        if( palyer ){
            [palyer stop];
            palyer.lv_userData = NULL;
            palyer.lv_luaviewCore = nil;
        }
    }
}

-(void) dealloc{
    releaseUserDataAudioPlayer(_lv_userData);
}

-(id) init:(lua_State*) L{
    self = [super init];
    if( self ){
        self.lv_luaviewCore = LV_LUASTATE_VIEW(L);
    }
    return self;
}

-(void) setPlayFileName0:(NSString*) fileName bundle:(LVBundle*) bundle{
    NSString* path = [bundle resourcePathWithName:fileName];
    if( path ) {
        NSURL* url = [[NSURL alloc] initWithString:path];
        NSError* error = nil;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];//使用本地URL创建
        if( error ) {
            NSLog(@"[LuaView][error]%@",error);
        }
    }
    if( self.playing ) {
        [self play];
    }
}

-(void) setPlayFileName:(NSString*) fileName bundle:(LVBundle*) bundle{
    if( fileName ==nil )
        return;
    if( [LVUtil isExternalUrl:fileName] ){
        [LVUtil download:fileName callback:^(NSData *fileData) {
            NSString* suffix = [fileName componentsSeparatedByString:@"."].lastObject;
            NSData* theFileNameData = [fileName dataUsingEncoding:NSUTF8StringEncoding];
            NSString* md5Path = [LVUtil MD5HashFromData:theFileNameData];
            md5Path = [NSString stringWithFormat:@"%@.%@",md5Path,suffix];//Mp3文件一定要加后缀,否则无法播放
            if( [LVUtil saveData:fileData toFile:[LVUtil PathForCachesResource:md5Path]] ) {
                [self setPlayFileName0:md5Path bundle:bundle];
            }
        }];
    } else {
        [self setPlayFileName0:fileName bundle:bundle];
    }
}

-(void) play {
    [audioPlayer play];
    self.playing = YES;
}

-(void) stop {
    [audioPlayer stop];
    self.playing = NO;
}

- (id) lv_nativeObject{
    return audioPlayer;
}

#pragma -mark AudioPlayer

static int lvNewAudioPlayer (lua_State *L) {
    if( lua_gettop(L)>=1 ) {
        Class c = [LVUtil upvalueClass:L defaultClass:[LVAudioPlayer class]];

        LVAudioPlayer* player = [[c alloc] init:L];
        LuaViewCore* lview = LV_LUASTATE_VIEW(L);
        NSString* fileName = lv_paramString(L, 1);
        [player setPlayFileName:fileName bundle:lview.bundle];

        {
            NEW_USERDATA(userData, AudioPlayer);
            userData->object = CFBridgingRetain(player);
            player.lv_userData = userData;

            luaL_getmetatable(L, META_TABLE_AudioPlayer );
            lua_setmetatable(L, -2);
        }
        return 1;
    }
    return 0;
}

static int play (lua_State *L) {
    LVUserDataInfo * user = (LVUserDataInfo *)lua_touserdata(L, 1);

    if( user && LVIsType(user, AudioPlayer) ){
        LVAudioPlayer* player = (__bridge LVAudioPlayer *)(user->object);
        if( player ){
            [player play];
            lua_pushvalue(L,1);
            return 1;
        }
    }
    return 0;
}

static int stop (lua_State *L) {
    LVUserDataInfo * user = (LVUserDataInfo *)lua_touserdata(L, 1);
    if( user ){
        LVAudioPlayer* player = (__bridge LVAudioPlayer *)(user->object);
        if( player ){
            [player stop];
        }
    }
    return 0;
}

static int __gc (lua_State *L) {
    LVUserDataInfo * user = (LVUserDataInfo *)lua_touserdata(L, 1);
    releaseUserDataAudioPlayer(user);
    return 0;
}

static int __tostring (lua_State *L) {
    LVUserDataInfo * user = (LVUserDataInfo *)lua_touserdata(L, 1);
    if( user ){
        LVAudioPlayer* player =  (__bridge LVAudioPlayer *)(user->object);
        NSString* s = [NSString stringWithFormat:@"LVUserDataAudioPlayer: %@", player ];
        lua_pushstring(L, s.UTF8String);
        return 1;
    }
    return 0;
}

+(int) lvClassDefine:(lua_State *)L globalName:(NSString*) globalName{
    [LVUtil reg:L clas:self cfunc:lvNewAudioPlayer globalName:globalName defaultName:@"AudioPlayer"];

    const struct luaL_Reg memberFunctions [] = {
        {"play", play },
        {"stop", stop },
        // pause
        // resume
        // callback { onComplete onError }

        // playing
        // looping
        // pausing

        {"__gc", __gc },
        {"__tostring", __tostring },
        {NULL, NULL}
    };
    lv_createClassMetaTable(L, META_TABLE_AudioPlayer);

    luaL_openlib(L, NULL, memberFunctions, 0);
    return 1;
}

@end