text:
package com.opengamma.web.bundle;

import java.net.URI;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

/**
 * RESTful resource for a CSS/Javascript bundle in development mode.
 */
@Path("/bundles/dev/{bundleId}")
public class WebDevBundleResource extends AbstractWebBundleResource {

  /**
   * Creates the resource.
   *
   * @param parent  the parent resource, not null
   */
  public WebDevBundleResource(final AbstractWebBundleResource parent) {
    super(parent);
  }

  //-------------------------------------------------------------------------
  @GET
  @Produces("text/css")
  public Response get(@PathParam("bundleId") final String idStr) {
    return Response.ok(getCssImports(idStr)).build();
  }

  private String getCssImports(final String bundleId) {
    final BundleManager bundleManager = data().getDevBundleManager();
    final Bundle bundle = bundleManager.getBundle(bundleId);
    return BundleUtils.buildImports(bundle, new WebBundlesUris(data()));
  }

  //-------------------------------------------------------------------------
  /**
   * Builds a URI for this resource.
   *
   * @param data  the data, not null
   * @param bundleId  the bundleId, not null
   * @return the URI, not null
   */
  public static URI uri(final WebBundlesData data, final String bundleId) {
    return data.getUriInfo().getBaseUriBuilder().path(WebDevBundleResource.class).build(bundleId);
  }

}


text:
require('./angular-locale_es-bz');
module.exports = 'ngLocale';

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @category   Payment Gateway
 * @package    Adyen_Payment
 * @author     Adyen
 * @property   Adyen B.V
 * @copyright  Copyright (c) 2014 Adyen BV (http://www.adyen.com)
 */
class Adyen_Payment_Model_Adyen_Data_ModificationRequest extends Adyen_Payment_Model_Adyen_Data_Abstract
{

    public $anyType2anyTypeMap;
    public $authorisationCode;
    public $merchantAccount;
    public $merchantReference;
    public $modificationAmount;
    public $originalReference;
    public $applicationInfo;

    public function create(Varien_Object $payment, $amount, $merchantAccount, $pspReference = null)
    {
        $order = $payment->getOrder();
        $currency = $order->getOrderCurrencyCode();
        $incrementId = $order->getIncrementId();

        $this->anyType2anyTypeMap = null;
        $this->authorisationCode = null;
        $this->merchantAccount = $merchantAccount;
        $this->reference = $incrementId;
        if ($amount) {
            $this->modificationAmount = new Adyen_Payment_Model_Adyen_Data_Amount();
            $this->modificationAmount->value = Mage::helper('adyen')->formatAmount($amount, $currency);
            $this->modificationAmount->currency = $currency;
        }

        $this->originalReference = $pspReference;
        $this->applicationInfo = new Adyen_Payment_Model_Adyen_Data_ApplicationInfo();

        return $this;
    }

}


text:
require_relative 'CultistPlayer'
require_relative 'Card'

class Cultist
    include Card
    def initialize(name, gainedLevels)
        @name = name
        @gainedLevels = gainedLevels
    end

    def getBasicValue
        @gainedLevels
    end

    def getSpecialValue
        @gainedLevels * CultistPlayer.getTotalCultistPlayers
    end
end


text:
/**
 * Created by olivererxleben on 04.12.13.
 */
mysql = require('mysql');

function Query() {

}

/**
 *
 * @param qstr
 * @param callback
 */
Query.prototype.execute = function(qstr, callback) {

    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'mmk2014',
        database : 'hipsterbility'
    });

    connection.query(qstr, function( err, rows) {
        if (err) {
            console.log(err); // TODO better
        } else {

            callback(rows);

        }

        connection.end();
    });

};

module.exports = Query;


text:
namespace NPOI.SS.Formula.Functions
{
    using System;
    using NPOI.SS.Formula.Eval;
    using NPOI.SS.Formula;

    public interface Accumulator
    {
        double Accumulate(double x, double y);
    }
    /**
     * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
     *
     */
    public abstract class XYNumericFunction : Fixed2ArgFunction
    {
        protected static int X = 0;
        protected static int Y = 1;

        private abstract class ValueArray : ValueVector
        {
            private int _size;
            protected ValueArray(int size)
            {
                _size = size;
            }
            public ValueEval GetItem(int index)
            {
                if (index < 0 || index > _size)
                {
                    throw new ArgumentException("Specified index " + index
                            + " is outside range (0.." + (_size - 1) + ")");
                }
                return GetItemInternal(index);
            }
            protected abstract ValueEval GetItemInternal(int index);
            public int Size
            {
                get
                {
                    return _size;
                }
            }
        }

        private class SingleCellValueArray : ValueArray
        {
            private ValueEval _value;
            public SingleCellValueArray(ValueEval value)
                : base(1)
            {

                _value = value;
            }
            protected override ValueEval GetItemInternal(int index)
            {
                return _value;
            }
        }
        private class RefValueArray : ValueArray
        {
            private RefEval _ref;
            private int _width;

            public RefValueArray(RefEval ref1)
                : base(ref1.NumberOfSheets)
            {
                _ref = ref1;
                _width = ref1.NumberOfSheets;
            }
            protected override ValueEval GetItemInternal(int index)
            {
                int sIx = (index % _width) + _ref.FirstSheetIndex;
                return _ref.GetInnerValueEval(sIx);
            }
        }
        private class AreaValueArray : ValueArray
        {
            private TwoDEval _ae;
            private int _width;

            public AreaValueArray(TwoDEval ae)
                : base(ae.Width * ae.Height)
            {
                _ae = ae;
                _width = ae.Width;
            }
            protected override ValueEval GetItemInternal(int index)
            {
                int rowIx = index / _width;
                int colIx = index % _width;
                return _ae.GetValue(rowIx, colIx);
            }
        }
        protected class DoubleArrayPair
        {

            private double[] _xArray;
            private double[] _yArray;

            public DoubleArrayPair(double[] xArray, double[] yArray)
            {
                _xArray = xArray;
                _yArray = yArray;
            }
            public double[] GetXArray()
            {
                return _xArray;
            }
            public double[] GetYArray()
            {
                return _yArray;
            }
        }

        public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1)
        {
            double result;
            try
            {
                ValueVector vvX = CreateValueVector(arg0);
                ValueVector vvY = CreateValueVector(arg1);
                int size = vvX.Size;
                if (size == 0 || vvY.Size != size)
                {
                    return ErrorEval.NA;
                }
                result = EvaluateInternal(vvX, vvY, size);
            }
            catch (EvaluationException e)
            {
                return e.GetErrorEval();
            }
            if (Double.IsNaN(result) || Double.IsInfinity(result))
            {
                return ErrorEval.NUM_ERROR;
            }
            return new NumberEval(result);
        }
        /**
 * Constructs a new instance of the Accumulator used to calculated this function
 */
        public abstract Accumulator CreateAccumulator();

        private double EvaluateInternal(ValueVector x, ValueVector y, int size)
        {
            Accumulator acc = CreateAccumulator();

            // error handling is as if the x is fully evaluated before y
            ErrorEval firstXerr = null;
            ErrorEval firstYerr = null;
            bool accumlatedSome = false;
            double result = 0.0;

            for (int i = 0; i < size; i++)
            {
                ValueEval vx = x.GetItem(i);
                ValueEval vy = y.GetItem(i);
                if (vx is ErrorEval)
                {
                    if (firstXerr == null)
                    {
                        firstXerr = (ErrorEval)vx;
                        continue;
                    }
                }
                if (vy is ErrorEval)
                {
                    if (firstYerr == null)
                    {
                        firstYerr = (ErrorEval)vy;
                        continue;
                    }
                }
                // only count pairs if both elements are numbers
                if (vx is NumberEval && vy is NumberEval)
                {
                    accumlatedSome = true;
                    NumberEval nx = (NumberEval)vx;
                    NumberEval ny = (NumberEval)vy;
                    result += acc.Accumulate(nx.NumberValue, ny.NumberValue);
                }
                else
                {
                    // all other combinations of value types are silently ignored
                }
            }
            if (firstXerr != null)
            {
                throw new EvaluationException(firstXerr);
            }
            if (firstYerr != null)
            {
                throw new EvaluationException(firstYerr);
            }
            if (!accumlatedSome)
            {
                throw new EvaluationException(ErrorEval.DIV_ZERO);
            }
            return result;
        }

        private static double[] TrimToSize(double[] arr, int len)
        {
            double[] tarr = arr;
            if (arr.Length > len)
            {
                tarr = new double[len];
                Array.Copy(arr, 0, tarr, 0, len);
            }
            return tarr;
        }

        private static bool IsNumberEval(Eval eval)
        {
            //bool retval = false;

            //if (eval is NumberEval)
            //{
            //    retval = true;
            //}
            //else if (eval is RefEval)
            //{
            //    RefEval re = (RefEval)eval;
            //    ValueEval ve = re.InnerValueEval;
            //    retval = (ve is NumberEval);
            //}

            //return retval;
            throw new InvalidOperationException("not found in poi");
        }

        private static double GetDoubleValue(Eval eval)
        {
            //double retval = 0;
            //if (eval is NumberEval)
            //{
            //    NumberEval ne = (NumberEval)eval;
            //    retval = ne.NumberValue;
            //}
            //else if (eval is RefEval)
            //{
            //    RefEval re = (RefEval)eval;
            //    ValueEval ve = re.InnerValueEval;
            //    retval = (ve is NumberEval)
            //        ? ((NumberEval)ve).NumberValue
            //        : double.NaN;
            //}
            //else if (eval is ErrorEval)
            //{
            //    retval = double.NaN;
            //}
            //return retval;
            throw new InvalidOperationException("not found in poi");
        }
        private static ValueVector CreateValueVector(ValueEval arg)
        {
            if (arg is ErrorEval)
            {
                throw new EvaluationException((ErrorEval)arg);
            }
            if (arg is TwoDEval)
            {
                return new AreaValueArray((TwoDEval)arg);
            }
            if (arg is RefEval)
            {
                return new RefValueArray((RefEval)arg);
            }
            return new SingleCellValueArray(arg);
        }
    }
}


text:
package OptimizationTests.NonTemporalMove.VolatileInt_001;

// 2 non-temporal moves expected. Assign volatile variable to tab[i]

public class Main {
    final int iterations = 133000*200;
    private volatile int jack = 0;

    public int $noinline$checkSum(int[] tab, int n) {
        int s = 0;
        for (int i = 0; i < n ; i++) {
            s = s + tab[i];
        }
        return s;
    }

    public boolean $noinline$testLoop(int[] tab) {
        new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < iterations; ++i) {
                    jack = 1;
                }
            }
        }).start();

        int count = 0;
        for(int i = 0; i < iterations; ++i) {
            int k = jack;
            tab[i] = k;

            if (k == 1) {
                count++;
                jack = 0;
            }
        }

        return $noinline$checkSum(tab, iterations) == count;
    }

    public void $noinline$test()
    {
        int[] tab = new int[iterations];

        if ($noinline$testLoop(tab) == true)
            System.out.println("ok");
        else
            System.out.println("not ok");
    }

    public static void main(String[] args)
    {
        new Main().$noinline$test();
    }

}


text:
import settings from '../../src/common/settings';
import buildConfig from '../../src/common/config/buildConfig';
import defaultPreferences from '../../src/common/config/defaultPreferences';
import pastDefaultPreferences from '../../src/common/config/pastDefaultPreferences';

describe('common/settings.js', () => {
  it('should upgrade v0 config file', () => {
    const v0Config = {
      url: 'https://example.com/team',
    };
    const config = settings.upgrade(v0Config);
    config.teams.length.should.equal(1);
    config.teams[0].url.should.equal(v0Config.url);
    config.version.should.equal(settings.version);
  });

  it('should merge teams with buildConfig.defaultTeams', () => {
    const teams = [
      {
        name: 'test',
        url: 'https://example.com',
      },
    ];

    const mergedTeams = settings.mergeDefaultTeams(teams);
    mergedTeams.should.deep.equal([
      {
        name: 'test',
        url: 'https://example.com',
      },
      ...buildConfig.defaultTeams,
    ]);
  });
});

describe('common/config/', () => {
  it('pastDefaultPreferences should have each past version of defaultPreferences', () => {
    for (let version = 0; version <= defaultPreferences.version; version++) {
      pastDefaultPreferences[`${version}`].should.exist; // eslint-disable-line no-unused-expressions
    }
  });

  it('defaultPreferences equal to one of pastDefaultPreferences', () => {
    const pastPreferences = pastDefaultPreferences[`${defaultPreferences.version}`];
    pastPreferences.should.deep.equal(defaultPreferences);
  });
});


text:
<?php

require 'db.php';

$query = $dbh->query('SELECT * from users order by id');

$user = json_decode(file_get_contents('php://input')); //get user from json headers

if($user->email == 'admin' && $user->pass == 'admin'):
    print 'login success';
else:
    print 'login not success';
endif;

?>


text:
Creative portfolio based on Material Design.

Created By
Colaborators on GitHub


text:
package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/gu-io/gu/assets"
	"github.com/gu-io/gu/assets/packers"
	"github.com/influx6/moz/gen"
)

func main() {
	aspacker := assets.New(packers.RawPacker{})

	aspacker.Register(".js", packers.JSPacker{})
	aspacker.Register(".css", packers.CSSPacker{CleanCSS: true})
	aspacker.Register(".static.html", packers.StaticMarkupPacker{
		PackageName:     "snippet",
		DestinationFile: ".//snippet_static_bundle.go",
	})

	writer, statics, err := aspacker.Compile("./", false)
	if err != nil {
		panic(err)
	}

	pipeGen := gen.Block(
		gen.Package(
			gen.Name("snippet"),
			writer,
		),
	)

	currentDir, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	if err := writeToFile(pipeGen, fmt.Sprintf("%s_bundle.go", "snippet"), "./", currentDir); err != nil {
		panic(err)
	}

	for _, directives := range statics {
		for _, directive := range directives {
			if directive.Static == nil {
				continue
			}

			if err := writeToFile(directive.Writer, directive.Static.FileName, directive.Static.DirName, currentDir); err != nil {
				panic(err)
			}
		}
	}

	fmt.Println("Bundling completed for 'snippet'")
}

// writeToFile writes the giving content from the WriterTo instance to the file of
// the giving file.
func writeToFile(w io.WriterTo, fileName string, dirName string, currentDir string) error {
	coDir := filepath.Join(currentDir, dirName)

	if dirName != "" {
		if _, err := os.Stat(coDir); err != nil {
			if err := os.MkdirAll(coDir, 0700); err != nil && err != os.ErrExist {
				return err
			}

			fmt.Printf("- Created package directory: %q\n", coDir)
		}
	}

	coFile := filepath.Join(coDir, fileName)
	file, err := os.Create(coFile)
	if err != nil {
		return err
	}

	defer file.Close()

	if _, err := w.WriteTo(file); err != nil {
		return err
	}

	fmt.Printf("- Created directory file: %q\n", filepath.Join(dirName, fileName))
	return nil
}


text:
package gateways

import (
	"fmt"
	"testing"

	"github.com/ghmeier/bloodlines/config"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/stretchr/testify/assert"
)

func TestNewSQLSuccess(t *testing.T) {
	assert := assert.New(t)

	sql, err := NewSQL(config.MySQL{
		User:     "test",
		Password: "test",
		Host:     "1.1.1.1",
		Port:     "1111",
		Database: "test",
	})

	assert.NoError(err)
	assert.NotNil(sql)
}

func TestSQLModifySuccess(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectPrepare("INSERT INTO test").
		ExpectExec().
		WithArgs(1).
		WillReturnResult(sqlmock.NewResult(1, 1))

	err := sql.Modify("INSERT INTO test SET id=?", 1)

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.NoError(err)
}

func TestSQLModifyFail(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectPrepare("INSERT INTO test").
		ExpectExec().
		WithArgs(1).
		WillReturnError(fmt.Errorf("some error"))

	err := sql.Modify("INSERT INTO test SET id=?", 1)

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.Error(err)

}

func TestSQLModifyPrepareFail(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectPrepare("INSERT INTO test").
		WillReturnError(fmt.Errorf("some error"))

	err := sql.Modify("INSERT INTO test SET id=?", 1)

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.Error(err)
}

func TestSQLSelectSuccess(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectQuery("SELECT name FROM testing").
		WillReturnRows(sqlmock.NewRows([]string{"name"}))

	_, err := sql.Select("SELECT name FROM testing")

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.NoError(err)
}

func TestSQLSelectMultiArgsSuccess(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectQuery("SELECT name FROM testing").
		WithArgs(2, 2).
		WillReturnRows(sqlmock.NewRows([]string{"name"}))

	_, err := sql.Select("SELECT name FROM testing", 2, 2)

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.NoError(err)
}

func TestSQLSelectFail(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectQuery("SELECT id FROM testing").
		WithArgs(2, 2).
		WillReturnError(fmt.Errorf("some error"))

	_, err := sql.Select("SELECT id FROM testing", 2, 2)

	assert.Equal(mock.ExpectationsWereMet(), nil)
	assert.Error(err)
}

func TestSQLDestroy(t *testing.T) {
	assert := assert.New(t)

	s, mock, _ := sqlmock.New()
	sql := &MySQL{DB: s}

	mock.ExpectClose()

	sql.Destroy()

	assert.Equal(mock.ExpectationsWereMet(), nil)
}


text:
package au.gov.amsa.ais.rx;

import java.io.File;
import java.nio.charset.StandardCharsets;

import org.apache.commons.csv.CSVFormat;

import com.github.davidmoten.bigsorter.Serializer;
import com.github.davidmoten.shi.Index;

public class CsvHilbertIndexCreatorMain {

    public static void main(String[] args) {
        File input = new File(
                System.getProperty("user.home") + "/Downloads/2018-11-27-positions.csv");
        Index //
                .serializer(Serializer.csv(CSVFormat.DEFAULT.withRecordSeparator('\n'),
                        StandardCharsets.UTF_8)) //
                .pointMapper(r -> {
                    try {
                        long time = Long.parseLong(r.get(2));
                        double lat = Double.parseDouble(r.get(3));
                        double lon = Double.parseDouble(r.get(4));
                        return new double[] { lat, lon, time };
                    } catch (Throwable e) {
                        System.out.println(r);
                        throw new RuntimeException(e);
                    }
                }) //
                .input(input) //
                .output(new File("target/2018-11-27-positions-sorted.csv")) //
                .bits(10) //
                .dimensions(3) //
                .numIndexEntries(50000) //
                .createIndex("target/2018-11-27-positions-sorted.csv.idx");
    }

}


text:
from robot.api.deco import keyword

@keyword('${x} in library')
def x_in_library(x):
    assert x == 'x'

@keyword('${x} and ${y} in library')
def x_and_y_in_library(x, y):
    assert x == 'x'
    assert y == 'y'

@keyword('${y:y} in library')
def y_in_library(y):
    assert False

@keyword('${match} in ${both} libraries')
def match_in_both_libraries(match, both):
    assert False

@keyword('Best ${match} in ${one of} libraries')
def best_match_in_one_of_libraries(match, one_of):
    assert match == 'match'
    assert one_of == 'one of'


text:
#include "config.h"
#include "WebKitSourceBuffer.h"

#if ENABLE(MEDIA_SOURCE)

#include "SourceBufferPrivate.h"
#include "TimeRanges.h"
#include "WebKitMediaSource.h"
#include <runtime/Uint8Array.h>

namespace WebCore {

PassRefPtr<WebKitSourceBuffer> WebKitSourceBuffer::create(PassOwnPtr<SourceBufferPrivate> sourceBufferPrivate, PassRefPtr<WebKitMediaSource> source)
{
    return adoptRef(new WebKitSourceBuffer(sourceBufferPrivate, source));
}

WebKitSourceBuffer::WebKitSourceBuffer(PassOwnPtr<SourceBufferPrivate> sourceBufferPrivate, PassRefPtr<WebKitMediaSource> source)
    : m_private(sourceBufferPrivate)
    , m_source(source)
    , m_timestampOffset(0)
{
    ASSERT(m_private);
    ASSERT(m_source);
}

WebKitSourceBuffer::~WebKitSourceBuffer()
{
}

PassRefPtr<TimeRanges> WebKitSourceBuffer::buffered(ExceptionCode& ec) const
{
    // Section 3.1 buffered attribute steps.
    // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an
    //    INVALID_STATE_ERR exception and abort these steps.
    if (isRemoved()) {
        ec = INVALID_STATE_ERR;
        return 0;
    }

    // 2. Return a new static normalized TimeRanges object for the media segments buffered.
    return m_private->buffered();
}

double WebKitSourceBuffer::timestampOffset() const
{
    return m_timestampOffset;
}

void WebKitSourceBuffer::setTimestampOffset(double offset, ExceptionCode& ec)
{
    // Section 3.1 timestampOffset attribute setter steps.
    // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an
    //    INVALID_STATE_ERR exception and abort these steps.
    if (isRemoved()) {
        ec = INVALID_STATE_ERR;
        return;
    }

    // 4. If the readyState attribute of the parent media source is in the "ended" state then run the following steps:
    // 4.1 Set the readyState attribute of the parent media source to "open"
    // 4.2 Queue a task to fire a simple event named sourceopen at the parent media source.
    m_source->openIfInEndedState();

    // 5. If this object is waiting for the end of a media segment to be appended, then throw an INVALID_STATE_ERR
    // and abort these steps.
    if (!m_private->setTimestampOffset(offset)) {
        ec = INVALID_STATE_ERR;
        return;
    }

    // 6. Update the attribute to the new value.
    m_timestampOffset = offset;
}

void WebKitSourceBuffer::append(PassRefPtr<Uint8Array> data, ExceptionCode& ec)
{
    // SourceBuffer.append() steps from October 1st version of the Media Source Extensions spec.
    // https://dvcs.w3.org/hg/html-media/raw-file/7bab66368f2c/media-source/media-source.html#dom-append

    // 2. If data is null then throw an INVALID_ACCESS_ERR exception and abort these steps.
    if (!data) {
        ec = INVALID_ACCESS_ERR;
        return;
    }

    // 3. If this object has been removed from the sourceBuffers attribute of media source then throw
    //    an INVALID_STATE_ERR exception and abort these steps.
    if (isRemoved()) {
        ec = INVALID_STATE_ERR;
        return;
    }

    // 5. If the readyState attribute of media source is in the "ended" state then run the following steps:
    // 5.1. Set the readyState attribute of media source to "open"
    // 5.2. Queue a task to fire a simple event named sourceopen at media source.
    m_source->openIfInEndedState();

    // Steps 6 & beyond are handled by the private implementation.
    m_private->append(data->data(), data->length());
}

void WebKitSourceBuffer::abort(ExceptionCode& ec)
{
    // Section 3.2 abort() method steps.
    // 1. If this object has been removed from the sourceBuffers attribute of the parent media source
    //    then throw an INVALID_STATE_ERR exception and abort these steps.
    // 2. If the readyState attribute of the parent media source is not in the "open" state
    //    then throw an INVALID_STATE_ERR exception and abort these steps.
    if (isRemoved() || !m_source->isOpen()) {
        ec = INVALID_STATE_ERR;
        return;
    }

    // 4. Run the reset parser state algorithm.
    m_private->abort();
}

void WebKitSourceBuffer::removedFromMediaSource()
{
    if (isRemoved())
        return;

    m_private->removedFromMediaSource();
    m_source.clear();
}

bool WebKitSourceBuffer::isRemoved() const
{
    return !m_source;
}

} // namespace WebCore

#endif


text:
"use strict";

/**
 * Extends multiple objects from 1..n object sources.
 * The resulting object is a deep clone of all objects provided.
 *
 * e.g.
 * var source1 = { a:1, b:1};
 * var source2 = { b:2, c:2};
 * var source3 = { b:3, d:3};
 * var result = extend (source1, source2, source3);
 * result = {a:1, b:3, c:2, d:3};
 *
 * @param  {Object} source1..sourceN
 * @return {Object}
 */
function extend() {
	var
		i,
		src,
		dest = {};

	for (i in arguments) {
		src = arguments[i];
		if (src && typeof src === 'object') {
			(Object.getOwnPropertyNames(src)).forEach(function(key){
				if (src[key] !== null && typeof(src[key]) === 'object' && !(src[key] instanceof Array)) {
					dest[key] = extend({}, src[key]);
				}
				else {
					var descriptor = Object.getOwnPropertyDescriptor(src, key);
					Object.defineProperty(dest, key, descriptor);
				}
			}); // jshint ignore:line
		}
	}
	return dest;
};

/**
 * Merges multiple objects from 1..n object sources.
 * The resulting object is a deep clone of all objects provided.
 * null objects do not merged into an already existing object.
 *
 * e.g.
 * var source1 = { a: { a:1, b:1 } } ;
 * var source2 = { a: { c: { a: true } }, b: { b:2, c:2 } };
 * var source3 = { a: { b:3, d:3 } };
 * var result = merge (source1, source2, source3);
 * result = { a: { a: 1, c: { a: true }, b: 3, d: 3 }, b: { b: 2, c: 2 } };
 *
 * @param  {Object} source1 .. sourceN
 * @return {Object}
 */
function merge() {
	var i;
	var src;
	var dest = {};

	for (i in arguments) {
		src = arguments[i];
		if (src && typeof src === 'object') {
			(Object.getOwnPropertyNames(src)).forEach(function(key){
				var descriptor;

				if (src[key] !== null && typeof(src[key]) === 'object') {
					if (Array.isArray(src[key])) {
						if (! dest[key]) {
							dest[key] = [];
						}
						for (var k = 0; k < src[key].length; k += 1) {
							dest[key].push(src[key][k]);
						}
					}
					else {
						if (isCircular(src[key])) {
							dest[key] = src[key]; // assign circularity
						}
						else {
							dest[key] = merge(dest[key], src[key]);
						}
					}
				}
				else if (src[key] === null && dest[key]) {
					dest[key] = null;
				}
				else {
					descriptor = Object.getOwnPropertyDescriptor(src, key);
					Object.defineProperty(dest, key, descriptor);
				}
			}); // jshint ignore:line
		}
	}
	return dest;
};

/**
 * Pulled from http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html.
 * One line added to detect where the cycle is.
 */
function isCircular (obj) {
	var seenObjects = [];

	function detect (obj) {
		if (obj && typeof obj === 'object') {
			if (seenObjects.indexOf(obj) !== -1) {
				return true;
			}
			seenObjects.push(obj);
			for (var key in obj) {
				if (obj.hasOwnProperty(key) && detect(obj[key])) {
					//~ console.log(obj, 'cycle at ' + key);
					return true;
				}
			}
		}
		return false;
	}

	return detect(obj);
};

module.exports = {
	extend: extend,
	merge: merge,
	isCircular: isCircular
};


text:
layout: post
microblog: true
date: 2017-05-03 23:33 +0300
guid: http://desparoz.micro.blog/2017/05/03/203321.html
---
[Apps for Freedivers](http://www.thefreedivingclub.com/freediving/freedivers-ios-apps).


text:
package com.evolveum.midpoint.web.component.menu;

import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;

import org.apache.wicket.model.IModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Viliam Repan (lazyman)
 */
public class MainMenuItem extends BaseMenuItem {
	private static final long serialVersionUID = 1L;

	public static final String F_ITEMS = "items";
    public static final String F_ICON_CLASS = "iconClass";
    public static final String F_BUBBLE_LABEL = "bubbleLabel";

    private boolean insertDefaultBackBreadcrumb = true;
    private String iconClass;
    private List<MenuItem> items;

    public MainMenuItem(String iconClass, IModel<String> name) {
        this(iconClass, name, null, null);
    }

    public MainMenuItem(String iconClass, IModel<String> name, Class<? extends PageBase> page) {
        this(iconClass, name, page, null);
    }

    public MainMenuItem(String iconClass, IModel<String> name, Class<? extends PageBase> page,
                        List<MenuItem> items) {
        this(iconClass, name, page, items, null);
    }

    public MainMenuItem(String iconClass, IModel<String> name, Class<? extends PageBase> page,
                        List<MenuItem> items, VisibleEnableBehaviour visibleEnable) {
        super(name, page, null, visibleEnable);
        this.iconClass = iconClass;
        this.items = items;
    }

    public String getIconClass() {
        return iconClass;
    }

    public List<MenuItem> getItems() {
        if (items == null) {
            items = new ArrayList<>();
        }
        return items;
    }

    public String getBubbleLabel() {
    	return null;
    }

    public boolean isInsertDefaultBackBreadcrumb() {
        return insertDefaultBackBreadcrumb;
    }

    public void setInsertDefaultBackBreadcrumb(boolean insertDefaultBackBreadcrumb) {
        this.insertDefaultBackBreadcrumb = insertDefaultBackBreadcrumb;
    }
}


text:
package com.list.dao;

import java.util.List;

import com.list.model.Tm_Owner_Integral;
import com.list.model.Tm_custOmer;

public interface OwnerIntegralDao {
	/**获取查询结果的总数*/
	public long getCountAll(String keyWord) throws Exception;

	public List<Tm_Owner_Integral> findByLike(String keyWord, int start , int end) throws Exception;

	public List<Tm_Owner_Integral> findByTel(String telephone, int end) throws Exception;
	public Tm_Owner_Integral findByTel(String PHONE, String DELIVERER_MOBILE
			,String contactor_mobile, String CONTACTOR_PHONE) throws Exception;

	public List<Tm_Owner_Integral> findByVIN(String VIN, int end) throws Exception;

	public List<Tm_Owner_Integral> findByLike(String keyWord,int start , int end, String sort) throws Exception;

	public void findFastInsert(MyDBDao mydbdao) throws Exception;

	public List<Tm_Owner_Integral> findTelORVIN(String telephone, String vin) throws Exception;

	public long getCountKey(String keyWord) throws Exception;

	public Tm_Owner_Integral findByTel(String fieldName, String phone, String deliverer_mobile
			,String contactor_mobile, String contactor_phone) throws Exception;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright 2014 Nick Dimiduk

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

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

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.n10k</groupId>
    <artifactId>hbase-1.0-api-examples</artifactId>
    <version>0.1.0-SNAPSHOT</version>

    <!-- HBase 0.94.x dependencies -->
    <!--
    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase</artifactId>
            <version>0.94.6</version>
        </dependency>
    </dependencies>
    -->

    <!-- HBase 1.0.x dependencies -->
    <repositories>
        <repository>
            <id>dev-preview</id>
            <url>https://repository.apache.org/content/repositories/orgapachehbase-1043/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>0.99.1</version>
        </dependency>
    </dependencies>

</project>


text:
var sass = require('gulp-ruby-sass');
var prefixer = require('gulp-autoprefixer');
var gulp         = require('gulp');
var notify       = require('gulp-notify');
var handleErrors = require('../util/handleErrors');

// Where do you store your Sass files?
var sassDir = 'src/scss';

// Which directory should Sass compile to?
var targetCSSDir = 'css';

//Styles
gulp.task('styles', function(){
    return gulp.src(sassDir + '/style.scss')
        .pipe(sass({ style: 'extended' }).on('error', handleErrors))
        .pipe(prefixer('last 10 version'))
        .pipe(gulp.dest(targetCSSDir));
});


text:
package org.apache.hadoop.yarn.server.resourcemanager.reservation;

import org.apache.hadoop.yarn.api.records.ReservationDefinition;

/**
 * A Plan represents the central data structure of a reservation system that
 * maintains the "agenda" for the cluster. In particular, it maintains
 * information on how a set of {@link ReservationDefinition} that have been
 * previously accepted will be honored.
 *
 * {@link ReservationDefinition} submitted by the users through the RM public
 * APIs are passed to appropriate {@code ReservationAgent}s, which in turn will
 * consult the Plan (via the {@link PlanView} interface) and try to determine
 * whether there are sufficient resources available in this Plan to satisfy the
 * temporal and resource constraints of a {@link ReservationDefinition}. If a
 * valid allocation is found the agent will try to store it in the plan (via the
 * {@link PlanEdit} interface). Upon success the system return to the user a
 * positive acknowledgment, and a reservation identifier to be later used to
 * access the reserved resources.
 *
 * A {@link PlanFollower} will continuously read from the Plan and will
 * affect the instantaneous allocation of resources among jobs running by
 * publishing the "current" slice of the Plan to the underlying scheduler. I.e.,
 * the configuration of queues/weights of the scheduler are modified to reflect
 * the allocations in the Plan.
 *
 * As this interface have several methods we decompose them into three groups:
 * {@link PlanContext}: containing configuration type information,
 * {@link PlanView} read-only access to the plan state, and {@link PlanEdit}
 * write access to the plan state.
 */
public interface Plan extends PlanContext, PlanView, PlanEdit {

}


text:
        <input type="checkbox"
               ng-model="item.owned"
               ng-class="{hide: item.consumed}">

      {{item.name}}
      {{item.weight}}kg


text:
package com.example.android.bluetoothchat;

/**
 * Created by Jacob on 4/29/2015.
 */
import android.app.Application;

public class MyApplication extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        // Initialize the singletons so their instances
        // are bound to the application process.
        initSingletons();
    }

    protected void initSingletons()
    {
        // Initialize the instance of MySingleton
        CommonStuff.initInstance();
    }

}


text:
/*****************************************************************************
 *                          USBLCD Kernel Driver                             *
 *                            Version 1.05                                   *
 *             (C) 2005 Georges Toth <g.toth@e-biz.lu>                       *
 *                                                                           *
 *     This file is licensed under the GPL. See COPYING in the package.      *
 * Based on usb-skeleton.c 2.0 by Greg Kroah-Hartman (greg@kroah.com)        *
 *                                                                           *
 *                                                                           *
 * 28.02.05 Complete rewrite of the original usblcd.c driver,                *
 *          based on usb_skeleton.c.                                         *
 *          This new driver allows more than one USB-LCD to be connected     *
 *          and controlled, at once                                          *
 *****************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/usb.h>

#define DRIVER_VERSION "USBLCD Driver Version 1.05"

#define USBLCD_MINOR		144

#define IOCTL_GET_HARD_VERSION	1
#define IOCTL_GET_DRV_VERSION	2

static struct usb_device_id id_table [] = {
	{ .idVendor = 0x10D2, .match_flags = USB_DEVICE_ID_MATCH_VENDOR, },
	{ },
};
MODULE_DEVICE_TABLE (usb, id_table);

struct usb_lcd {
	struct usb_device *	udev;			/* init: probe_lcd */
	struct usb_interface *  interface;		/* the interface for this device */
	unsigned char *         bulk_in_buffer;		/* the buffer to receive data */
	size_t			bulk_in_size;		/* the size of the receive buffer */
	__u8			bulk_in_endpointAddr;	/* the address of the bulk in endpoint */
	__u8			bulk_out_endpointAddr;	/* the address of the bulk out endpoint */
	struct kref             kref;
};
#define to_lcd_dev(d) container_of(d, struct usb_lcd, kref)

static struct usb_driver lcd_driver;

static void lcd_delete(struct kref *kref)
{
	struct usb_lcd *dev = to_lcd_dev(kref);

	usb_put_dev(dev->udev);
	kfree (dev->bulk_in_buffer);
	kfree (dev);
}

static int lcd_open(struct inode *inode, struct file *file)
{
	struct usb_lcd *dev;
	struct usb_interface *interface;
	int subminor;
	int retval = 0;

	subminor = iminor(inode);

	interface = usb_find_interface(&lcd_driver, subminor);
	if (!interface) {
		err ("USBLCD: %s - error, can't find device for minor %d",
		     __FUNCTION__, subminor);
		retval = -ENODEV;
		goto exit;
	}

	dev = usb_get_intfdata(interface);
	if (!dev) {
		retval = -ENODEV;
		goto exit;
	}

	/* increment our usage count for the device */
	kref_get(&dev->kref);

	/* save our object in the file's private structure */
	file->private_data = dev;

exit:
	return retval;
}

static int lcd_release(struct inode *inode, struct file *file)
{
	struct usb_lcd *dev;

	dev = (struct usb_lcd *)file->private_data;
	if (dev == NULL)
		return -ENODEV;

	/* decrement the count on our device */
	kref_put(&dev->kref, lcd_delete);
	return 0;
}

static ssize_t lcd_read(struct file *file, char __user * buffer, size_t count, loff_t *ppos)
{
	struct usb_lcd *dev;
	int retval = 0;
	int bytes_read;

	dev = (struct usb_lcd *)file->private_data;

	/* do a blocking bulk read to get data from the device */
	retval = usb_bulk_msg(dev->udev,
			      usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr),
			      dev->bulk_in_buffer,
			      min(dev->bulk_in_size, count),
			      &bytes_read, 10000);

	/* if the read was successful, copy the data to userspace */
	if (!retval) {
		if (copy_to_user(buffer, dev->bulk_in_buffer, bytes_read))
			retval = -EFAULT;
		else
			retval = bytes_read;
	}

	return retval;
}

static int lcd_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	struct usb_lcd *dev;
	u16 bcdDevice;
	char buf[30];

	dev = (struct usb_lcd *)file->private_data;
	if (dev == NULL)
		return -ENODEV;

	switch (cmd) {
	case IOCTL_GET_HARD_VERSION:
		bcdDevice = le16_to_cpu((dev->udev)->descriptor.bcdDevice);
		sprintf(buf,"%1d%1d.%1d%1d",
			(bcdDevice & 0xF000)>>12,
			(bcdDevice & 0xF00)>>8,
			(bcdDevice & 0xF0)>>4,
			(bcdDevice & 0xF));
		if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
			return -EFAULT;
		break;
	case IOCTL_GET_DRV_VERSION:
		sprintf(buf,DRIVER_VERSION);
		if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
			return -EFAULT;
		break;
	default:
		return -ENOTTY;
		break;
	}

	return 0;
}

static void lcd_write_bulk_callback(struct urb *urb)
{
	struct usb_lcd *dev;

	dev = (struct usb_lcd *)urb->context;

	/* sync/async unlink faults aren't errors */
	if (urb->status &&
	    !(urb->status == -ENOENT ||
	      urb->status == -ECONNRESET ||
              urb->status == -ESHUTDOWN)) {
		dbg("USBLCD: %s - nonzero write bulk status received: %d",
		    __FUNCTION__, urb->status);
	}

	/* free up our allocated buffer */
	usb_buffer_free(urb->dev, urb->transfer_buffer_length,
			urb->transfer_buffer, urb->transfer_dma);
}

static ssize_t lcd_write(struct file *file, const char __user * user_buffer, size_t count, loff_t *ppos)
{
	struct usb_lcd *dev;
        int retval = 0;
	struct urb *urb = NULL;
	char *buf = NULL;

	dev = (struct usb_lcd *)file->private_data;

	/* verify that we actually have some data to write */
	if (count == 0)
		goto exit;

	/* create a urb, and a buffer for it, and copy the data to the urb */
	urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!urb)
		return -ENOMEM;

	buf = usb_buffer_alloc(dev->udev, count, GFP_KERNEL, &urb->transfer_dma);
	if (!buf) {
		retval = -ENOMEM;
		goto error;
	}

	if (copy_from_user(buf, user_buffer, count)) {
		retval = -EFAULT;
		goto error;
	}

	/* initialize the urb properly */
	usb_fill_bulk_urb(urb, dev->udev,
			  usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
			  buf, count, lcd_write_bulk_callback, dev);
	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;

	/* send the data out the bulk port */
	retval = usb_submit_urb(urb, GFP_KERNEL);
	if (retval) {
		err("USBLCD: %s - failed submitting write urb, error %d", __FUNCTION__, retval);
		goto error;
	}

	/* release our reference to this urb, the USB core will eventually free it entirely */
	usb_free_urb(urb);

exit:
	return count;

error:
	usb_buffer_free(dev->udev, count, buf, urb->transfer_dma);
	usb_free_urb(urb);
	return retval;
}

static const struct file_operations lcd_fops = {
        .owner =        THIS_MODULE,
        .read =         lcd_read,
        .write =        lcd_write,
        .open =         lcd_open,
	.ioctl =        lcd_ioctl,
        .release =      lcd_release,
};

/*
 * usb class driver info in order to get a minor number from the usb core,
 * and to have the device registered with the driver core
 */
static struct usb_class_driver lcd_class = {
        .name =         "lcd%d",
        .fops =         &lcd_fops,
        .minor_base =   USBLCD_MINOR,
};

static int lcd_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
	struct usb_lcd *dev = NULL;
	struct usb_host_interface *iface_desc;
	struct usb_endpoint_descriptor *endpoint;
	size_t buffer_size;
	int i;
	int retval = -ENOMEM;

	/* allocate memory for our device state and initialize it */
	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL) {
		err("Out of memory");
		goto error;
	}
	kref_init(&dev->kref);

	dev->udev = usb_get_dev(interface_to_usbdev(interface));
	dev->interface = interface;

	if (le16_to_cpu(dev->udev->descriptor.idProduct) != 0x0001) {
		warn(KERN_INFO "USBLCD model not supported.");
		return -ENODEV;
	}

	/* set up the endpoint information */
	/* use only the first bulk-in and bulk-out endpoints */
	iface_desc = interface->cur_altsetting;
	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
		endpoint = &iface_desc->endpoint[i].desc;

		if (!dev->bulk_in_endpointAddr &&
		    usb_endpoint_is_bulk_in(endpoint)) {
			/* we found a bulk in endpoint */
			buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
			dev->bulk_in_size = buffer_size;
			dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
			dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
			if (!dev->bulk_in_buffer) {
				err("Could not allocate bulk_in_buffer");
				goto error;
			}
		}

		if (!dev->bulk_out_endpointAddr &&
		    usb_endpoint_is_bulk_out(endpoint)) {
			/* we found a bulk out endpoint */
			dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
		}
	}
	if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
		err("Could not find both bulk-in and bulk-out endpoints");
		goto error;
	}

	/* save our data pointer in this interface device */
	usb_set_intfdata(interface, dev);

	/* we can register the device now, as it is ready */
	retval = usb_register_dev(interface, &lcd_class);
	if (retval) {
		/* something prevented us from registering this driver */
		err("Not able to get a minor for this device.");
		usb_set_intfdata(interface, NULL);
		goto error;
	}

	i = le16_to_cpu(dev->udev->descriptor.bcdDevice);

	info("USBLCD Version %1d%1d.%1d%1d found at address %d",
		(i & 0xF000)>>12,(i & 0xF00)>>8,(i & 0xF0)>>4,(i & 0xF),
		dev->udev->devnum);

	/* let the user know what node this device is now attached to */
	info("USB LCD device now attached to USBLCD-%d", interface->minor);
	return 0;

error:
	if (dev)
		kref_put(&dev->kref, lcd_delete);
	return retval;
}

static void lcd_disconnect(struct usb_interface *interface)
{
	struct usb_lcd *dev;
        int minor = interface->minor;

        /* prevent skel_open() from racing skel_disconnect() */
        lock_kernel();

        dev = usb_get_intfdata(interface);
        usb_set_intfdata(interface, NULL);

        /* give back our minor */
        usb_deregister_dev(interface, &lcd_class);

	unlock_kernel();

	/* decrement our usage count */
	kref_put(&dev->kref, lcd_delete);

	info("USB LCD #%d now disconnected", minor);
}

static struct usb_driver lcd_driver = {
	.name =		"usblcd",
	.probe =	lcd_probe,
	.disconnect =	lcd_disconnect,
	.id_table =	id_table,
};

static int __init usb_lcd_init(void)
{
	int result;

	result = usb_register(&lcd_driver);
	if (result)
		err("usb_register failed. Error number %d", result);

	return result;
}

static void __exit usb_lcd_exit(void)
{
	usb_deregister(&lcd_driver);
}

module_init(usb_lcd_init);
module_exit(usb_lcd_exit);

MODULE_AUTHOR("Georges Toth <g.toth@e-biz.lu>");
MODULE_DESCRIPTION(DRIVER_VERSION);
MODULE_LICENSE("GPL");


text:
<?php

ini_set ('display_errors', 1);
error_reporting (E_ALL);

require_once('CMBase.php');

//-----------------------------INPUT PARAMS---------------------------------------

$apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$listid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

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

	$cm = new CampaignMonitor( $apikey );

	//Optional statement to include debugging information in the result
	$cm->debug_level = 1;

	//This is the actual call to the method
	$result = $cm->listGetDetail( $listid );

	echo '

';
	print_r($result);

?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="Examples">
  <process id="testJsonVarInExpression" name="Test Json Var In Expression" isExecutable="true">
    <startEvent id="theStart"></startEvent>
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="userTask"></sequenceFlow>
    <userTask id="userTask"></userTask>
    <endEvent id="theEndSuccess"></endEvent>
    <userTask id="usertask1" name="User Task" activiti:assignee="${userMap.assignee}" activiti:candidateUsers="${userMap.mapInMap.user}" activiti:category="${userMap.category}"></userTask>
    <sequenceFlow id="flow2" sourceRef="userTask" targetRef="usertask1"></sequenceFlow>
    <sequenceFlow id="flow3" sourceRef="usertask1" targetRef="theEndSuccess"></sequenceFlow>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_testJsonVarInExpression">
    <bpmndi:BPMNPlane bpmnElement="testJsonVarInExpression" id="BPMNPlane_testJsonVarInExpression">
      <bpmndi:BPMNShape bpmnElement="theStart" id="BPMNShape_theStart">
        <omgdc:Bounds height="35.0" width="35.0" x="70.0" y="95.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="userTask" id="BPMNShape_userTask">
        <omgdc:Bounds height="60.0" width="100.0" x="170.0" y="83.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="theEndSuccess" id="BPMNShape_theEndSuccess">
        <omgdc:Bounds height="35.0" width="35.0" x="490.0" y="95.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="usertask1" id="BPMNShape_usertask1">
        <omgdc:Bounds height="55.0" width="105.0" x="310.0" y="85.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="flow1" id="BPMNEdge_flow1">
        <omgdi:waypoint x="105.0" y="112.0"></omgdi:waypoint>
        <omgdi:waypoint x="170.0" y="113.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow2" id="BPMNEdge_flow2">
        <omgdi:waypoint x="270.0" y="113.0"></omgdi:waypoint>
        <omgdi:waypoint x="310.0" y="112.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow3" id="BPMNEdge_flow3">
        <omgdi:waypoint x="415.0" y="112.0"></omgdi:waypoint>
        <omgdi:waypoint x="490.0" y="112.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>


text:
<?php declare(strict_types=1);

namespace SebastianBergmann\GlobalState\TestFixture;

class SnapshotClassTyped
{
    private static bool $bool = true;

    private static string $string;

    public static function init(): void
    {
        self::$string = 'string';
    }
}


text:
This inspection reports on comparison operations with constant values on their right-hand side. Some coding conventions
specify that constants should be on the left-hand side of comparisons.

Powered by InspectionGadgets


text:
author: slowe
categories: Personal
comments: true
date: 2011-09-07T09:19:35Z
slug: the-move-to-colorado-day-3
tags:
- Travel
- Personal
title: 'The Move to Colorado: Day 3'
url: /2011/09/07/the-move-to-colorado-day-3/
wordpress_id: 2399
---

Day 3 of our road trip to Colorado completes our trip and puts us in Denver. The trip today was pretty straightforward. We left Kansas City this morning and just followed I-70 across Kansas into Colorado. When it was all said and done, it took about 9 hours of driving to go from Kansas City to Denver.

Now that we've arrived in Denver, we're in a hotel for the next few days until our house in Castle Pines North is ready for us to move in. In the meantime, I'll be handling all the various move-related issues that need to be addressed---change of address forms, insurance, driver's licenses, etc. That also includes buying some furniture, a task we got started on tonight with a quick trip to the new Ikea store here in Denver.

I have a couple of blog posts in the works that I'll try to get published over the next few days, but with all the move-related tasks that need to be handled I'm not sure I'll actually be able to get them finished and posted. I'll do my best!


text:
package com.naiive.zhihudaily.utils;

import android.util.Log;

/**
 * Created by wangzhe on 16/6/2.
 */
public class LogUtil {

    public static boolean DEBUG = true;
    private static final String TAG = "Logger";

    public static void info(String string){
        if (DEBUG){
            Log.d(TAG,string);
        }
    }

}


text:
namespace media_router {

struct CastSinkExtraData;

class MirroringActivity : public CastActivity,
                          public mirroring::mojom::SessionObserver,
                          public mirroring::mojom::CastMessageChannel {
 public:
  using OnStopCallback = base::OnceClosure;

  enum class MirroringType {
    kTab,           // Mirror a single tab.
    kDesktop,       // Mirror the whole desktop.
    kOffscreenTab,  // Used for Presentation API 1UA mode.
    kMaxValue = kOffscreenTab,
  };

  MirroringActivity(const MediaRoute& route,
                    const std::string& app_id,
                    cast_channel::CastMessageHandler* message_handler,
                    CastSessionTracker* session_tracker,
                    int frame_tree_node_id,
                    const CastSinkExtraData& cast_data,
                    OnStopCallback callback);
  ~MirroringActivity() override;

  virtual void CreateMojoBindings(mojom::MediaRouter* media_router);

  // SessionObserver implementation
  void OnError(mirroring::mojom::SessionError error) override;
  void DidStart() override;
  void DidStop() override;
  void LogInfoMessage(const std::string& message) override;
  void LogErrorMessage(const std::string& message) override;

  // CastMessageChannel implementation
  void Send(mirroring::mojom::CastMessagePtr message) override;

  // CastActivity implementation
  void OnAppMessage(const cast::channel::CastMessage& message) override;
  void OnInternalMessage(const cast_channel::InternalMessage& message) override;

 protected:
  void OnSessionSet(const CastSession& session) override;
  void CreateMediaController(
      mojo::PendingReceiver<mojom::MediaController> media_controller,
      mojo::PendingRemote<mojom::MediaStatusObserver> observer) override;
  std::string GetRouteDescription(const CastSession& session) const override;

 private:
  FRIEND_TEST_ALL_PREFIXES(MirroringActivityTest, GetScrubbedLogMessage);

  void HandleParseJsonResult(const std::string& route_id,
                             data_decoder::DataDecoder::ValueOrError result);

  void StopMirroring();

  // Scrubs AES related data in messages with type "OFFER".
  static std::string GetScrubbedLogMessage(const base::Value& message);

  mojo::Remote<mirroring::mojom::MirroringServiceHost> host_;

  // Sends Cast messages from the mirroring receiver to the mirroring service.
  mojo::Remote<mirroring::mojom::CastMessageChannel> channel_to_service_;

  // Only used to store pending CastMessageChannel receiver while waiting for
  // OnSessionSet() to be called.
  mojo::PendingReceiver<mirroring::mojom::CastMessageChannel>
      channel_to_service_receiver_;

  // Remote to the logger owned by the Media Router. Used to log WebRTC messages
  // sent between the mirroring service and mirroring receiver.
  // |logger_| should be bound before the CastMessageChannel message pipe is
  // created.
  mojo::Remote<mojom::Logger> logger_;

  mojo::Receiver<mirroring::mojom::SessionObserver> observer_receiver_{this};

  // To handle Cast messages from the mirroring service to the mirroring
  // receiver.
  mojo::Receiver<mirroring::mojom::CastMessageChannel> channel_receiver_{this};

  // Set before and after a mirroring session is established, for metrics.
  absl::optional<base::Time> will_start_mirroring_timestamp_;
  absl::optional<base::Time> did_start_mirroring_timestamp_;

  const absl::optional<MirroringType> mirroring_type_;

  // The FrameTreeNode ID to retrieve the WebContents of the tab to mirror.
  const int frame_tree_node_id_;
  const CastSinkExtraData cast_data_;
  OnStopCallback on_stop_;
  base::WeakPtrFactory<MirroringActivity> weak_ptr_factory_{this};
};

}  // namespace media_router

#endif  // CHROME_BROWSER_MEDIA_ROUTER_PROVIDERS_CAST_MIRRORING_ACTIVITY_H_


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include "textfile.h"

///////////////////////////////////////////////
// déclaration des macros et defines globaux //
///////////////////////////////////////////////

#ifndef M_PI
#define M_PI 3.1415926535897932385
#endif
#define DEG2RAD(a) ( a / 180.0f ) * ( M_PI );

/////////////////////////////////////////
// déclaration des constantes globales //
/////////////////////////////////////////

const GLfloat gl_separate_specular_color = GL_SEPARATE_SPECULAR_COLOR;  // constante de paramètre

const float freqRotX     = 0.15;             // la fréquence de rotation en X du modèle
const float freqRotY     = 0.1;              // la fréquence de rotation en Y du modèle
const float freqRotZ     = 0.2;              // la fréquence de rotation en Z du modèle

const float frameRate    = 50.0;             // le framerate cible de l'application graphique.

const float modelSize    = 15.0;             // la grandeur du modèle
const float axeScaleFact = 15.0;             // le facteur multiplicatif des axes unitaires dessinés dans la scène
const GLfloat fogColor[] = {0.0, 0.0, 0.0};  // la couleur du FOG dans l'application

bool rotAutoModele       = false;            // la rotation automatique du modèle ou non

///////////////////////////////////////
// déclaration des variables globales //
////////////////////////////////////////
int g_nWindowID;                 // le ID de la fenêtre graphique GLUT
const int g_nWidth = 640;        // la largeur initiale de la fenêtre GLUT
const int g_nHeight = 480;       // la hauteur initiale de la fenêtre GLUT
int currentW, currentH;          // Largeur et hauteur courantes de la fenêtre graphique (viewport)
bool isPerspective = true;       // indique si on est en mode Perspective (true) ou glOrtho (false)

double theta = DEG2RAD(270.0f);  // angle de rotation de la caméra en theta (coord. sphériques)
double phi = DEG2RAD(90.0f);     // angle de rotation de la caméra en phi (coord. sphériques)
double rho = 30.0;               // angle de rotation de la caméra en rho (coord. sphériques)
float  x, y, z;					   // la position de la camera

float angleRotX = 0.0f;          // angle courant de rotation en X du modèle
float angleRotY = 0.0f;          // angle courant de rotation en Y du modèle
float angleRotZ = 0.0f;          // angle courant de rotation en Z du modèle

bool premierMouvement = true;    // indique si la souris fut bougée déjà
int dernierX = 0;                // la dernière valeur en X de position lue de la souris
int dernierY = 0;                // la derniere valeur en Y de position lus de la souris

bool spotLightAllumee  = true;   // indique si on désire activer la lumière Spot
bool dirLightAllumee   = true;   // indique si on désire activer la lumière Directionnelle
bool pointLightAllumee = true;   // indique si on désire activer la lumière Ponctuelle
bool SHADER_ON         = false;  // indique si l'on veut utiliser le nuanceur

#define QUAD_LIST 1              // déclaration de la liste d'affichage du modèle
#define CUBE_LIST 2              // déclaration de la liste d'affichage d'un cube

GLuint texture0;	               // les noms de textures
GLuint texture1;	               // les noms de textures
GLuint texture2;	               // les noms de textures

GLuint noShaderProg = 0 ;        // Un "nuanceur" NUL ==> représentant la fonctionalité fixe d'OPENGL (=0)
GLuint fixedPipelineShaderProg;	// Votre programme de nuanceur émulant la fonctionnalité fixe.

// Définition des lumières openGL
// Les lumières sont et restent définies dans la PARTIE OPENGL, même lorsque
// l'on utilise les nuanceurs. Alors ici, pour obtenir l'effet désiré dans ShaderGen,
// on doit créer les mêmes trois (3) lumières openGL que dans ShaderGen et les
// positionner aux mêmes endroits.

// POINT LIGHT
GLfloat light_position0[] = { 20.0, 10.0, 3.0, 1.0 };
GLfloat light_ambient0[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse0[] = { 1.0, 0.5, 1.0, 1.0 };
GLfloat light_specular0[] = { 1.0, 0.5, 1.0, 1.0 };
GLfloat light_emission0[] = { 1.0, 1.0, 1.0, 1.0 };

// SPOT LIGHT
GLfloat light_position1[] = { 0.0,  0.0,  0.0,  1.0 };
GLfloat light_ambient1[] =  { 0.0,  0.0,  0.0,  1.0 };
GLfloat light_diffuse1[] =  { 1.0,  1.0,  1.0,  1.0 };
GLfloat light_specular1[] = { 1.0,  1.0,  1.0,  1.0 };
GLfloat light_emission1[] = { 1.0, 1.0, 1.0, 1.0 };

// DIRECTIONNAL LIGHT
GLfloat light_position2[] = {  -60.0, 0.0, 3.0, 0.0 };
GLfloat light_ambient2[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse2[] = { 0.86, 0.69, 0.04, 1.0 };
GLfloat light_specular2[] = { 0.91, 0.93, 0.0, 1.0 };
GLfloat light_emission2[] = { 1.0, 1.0, 1.0, 1.0 };

// définition du matériau utilisé.
GLfloat mat_ambiant_model[]  = { 0.0, 0.0, 0.0, 1.0 };
GLfloat mat_diffuse_model[]  = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_specular_model[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_emission_model[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat mat_shininess_model[] = { 100.0 };

// Structure qui représente une image RGB
struct SImage
{
    GLuint    width;
    GLuint    height;
    GLubyte*  data;

    SImage( int Width, int Height )
        : width ( Width  )
        , height( Height )
        , data  ( NULL   )
    {
        data = new GLubyte[ width * height * 3 ];
    }

    ~SImage( void )
    {
        if( data )
            delete [] data;
    }
};

// PROTOTYPES DES FONCTIONS
void initialisation (void);
void dessinerScene();
void affichage(void);
void attente(void);
void clavier(unsigned char touche, int x, int y);
void clavierSpecial(int touche, int x, int y);
void redimensionnement(GLsizei w, GLsizei h);

void rafraichirCamera();
void compileGrilleQuads(int listID, float size, int nbRows, int nbColums, bool outsideNormal);
void compileCube(int listID, float size, int nbRows, int nbColums, bool outsideNormal);
void dessinerGrilleQuads(float size, int nbRows, int nbColums, bool outsideNormal);
void rafraichirEclairage();
void rafraichirProjection();
void initialiserNuanceurs() ;
void afficherShaderInfoLog(GLuint obj);
void afficherProgramInfoLog(GLuint obj);
void appliquerTextures();
SImage* LoadBMP(char* Filename);
void init2DTexture(GLint texName, GLint texWidth, GLint texHeight, GLubyte *texPtr);
void chargerTextures();
void desactiverTextures();

// initialisation d'openGL
void initialisation (void) {

   // modèle de rendu
   glShadeModel(GL_SMOOTH);

   /*  couleur de l'arrière-plan   */
   glClearColor (0.2, 0.2, 0.2, 1.0);

   // activer les etats openGL
   glEnable(GL_NORMALIZE);
   glEnable(GL_LIGHTING);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_FOG);

   // fonction de profondeur
   glDepthFunc(GL_LEQUAL);

   // amélioration de la perspective
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

   glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE );
   glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE );     // two-side mode in openGL
   glEnable( GL_VERTEX_PROGRAM_TWO_SIDE );                // two-side mode in GLSL
   // ajouter ici le mode de calcul séparé de la couleur spéculaire
   glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);

   // charger les textures
   chargerTextures();

   // compiler les listes d'affichage
   compileGrilleQuads(QUAD_LIST, modelSize, 30, 30, true);
   compileCube(CUBE_LIST, modelSize, 30, 30, true);
}

void dessinerScene()
{

   // ajuster le fog dynamiquement selon la distance de l'observateur
   // vous devez ici l'améliorer... pour que les paramètres
   // GL_FOG_START et GL_FOG_END soient ajustés automatiquement
   // en fonction du zoom.

	glFogi (GL_FOG_MODE,    GL_LINEAR);
	glFogf (GL_FOG_START,   rho - 6);
	glFogf (GL_FOG_END,     rho + 4);
	glFogfv(GL_FOG_COLOR,   fogColor);
	glFogf (GL_FOG_DENSITY, 0.0);

   if (SHADER_ON)
      glUseProgram(fixedPipelineShaderProg);
   else
      glUseProgram(noShaderProg);

   // Dessiner le modèle
	glPushMatrix(); {
		// appliquer le matériau du cube
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambiant_model);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse_model);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular_model);
		glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emission_model);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess_model);

		// dessiner le cube tournant, si désiré
      if (rotAutoModele) {
		   angleRotX += 360.0 * (freqRotX / frameRate);
		   angleRotY += 360.0 * (freqRotY / frameRate);
		   angleRotZ += 360.0 * (freqRotZ / frameRate);

         if (angleRotX >= 360.0)
			   angleRotX -= 360.0;
		   if (angleRotY >= 360.0)
			   angleRotY -= 360.0;
		   if (angleRotZ >= 360.0)
			   angleRotZ -= 360.0;
      }

		glRotated(180.0, 1.0, 0.0, 0.0);
		glRotated(angleRotX, 1.0, 0.0, 0.0);
      glRotated(angleRotY, 0.0, 1.0, 0.0);
      glRotated(angleRotZ, 0.0, 0.0, 1.0);

      glCallList(QUAD_LIST);
      desactiverTextures();
   }
   glPopMatrix();

   glUseProgram(noShaderProg);

	// Dessiner les axes pour se retrouver
	glPushMatrix(); {
      glDisable(GL_TEXTURE_2D);
      glDisable(GL_LIGHTING);
      glDisable(GL_FOG);

		glLineWidth(3.0);

		glBegin(GL_LINES);{
			// l'axe des x en Rouge
			glColor4f(1.0, 0.0, 0.0, 1.0);
			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(1.0*axeScaleFact, 0.0, 0.0);

			// l'axe des y en Vert
			glColor4f(0.0, 1.0, 0.0, 1.0);
			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(0.0, 1.0*axeScaleFact, 0.0);

			// l'axe des z en Bleu
			glColor4f(0.0, 0.0, 1.0, 1.0);
			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(0.0, 0.0, 1.0*axeScaleFact);
		}
		glEnd();

		glEnable(GL_FOG);
	   glEnable(GL_LIGHTING);
      glEnable(GL_TEXTURE_2D);
	}
	glPopMatrix();

   if (SHADER_ON)
      glUseProgram(fixedPipelineShaderProg);
   else
      glUseProgram(noShaderProg);

    // flush les derniers vertex du pipeline graphique
	glFlush();
}

// fonction d'affichage
void affichage(void)
{
    // effacement de l'ecran et du tampon de profondeur
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    // charger matrice de modélisation
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // mettre à jour la caméra openGL
    rafraichirCamera();  // ne pas permettre pour l'instant de déplacer la caméra...

    // mettre à jour l'éclairage
    rafraichirEclairage();

    // dessiner la scène
    dessinerScene();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    // mettre à jour la projection
    rafraichirProjection();

    // utiliser le "double-buffering"
    glutSwapBuffers();
}

// fonction appelee lorsque l'application ne fait rien
void attente(void)
{
	// une variable pour memoriser le temps a attendre
	static int nWaitUntil = glutGet(GLUT_ELAPSED_TIME);

	// on recupere le temps présent
	int nTimer = glutGet(GLUT_ELAPSED_TIME);
	// et on le compare a l'instant qu'il faut attendre
	if(nTimer >= nWaitUntil)
	{
		// pour rafraichir l'affichage
		glutPostRedisplay();
		// 5 fois pa5 seconde
		nWaitUntil = nTimer + (1000 / frameRate);
	}
}

// fonction de gestion du clavier
void clavier(unsigned char touche, int x, int y)
{
	// traitement des touches q et echap
   switch(touche) {
      case 'q' :
		// destruction de la fenetre GLUT
		glutDestroyWindow(g_nWindowID);
		// on quitte notre programme
		exit(EXIT_SUCCESS);
      break;

      case 'p' :
         if (isPerspective)
            isPerspective = false;
         else
            isPerspective = true;
         affichage();
      break;

      // permutation du "spot light"
      case 's' :
         if (spotLightAllumee)
            spotLightAllumee = false;
         else
            spotLightAllumee = true;
         glutPostRedisplay();
      break;

      // permutation du "dirLight"
      case 'd' :
         if (dirLightAllumee)
            dirLightAllumee = false;
         else
            dirLightAllumee = true;
         glutPostRedisplay();
      break;

      // permutation du "point light"
      case 'a' :
         if (pointLightAllumee)
            pointLightAllumee = false;
         else
            pointLightAllumee = true;
         glutPostRedisplay();
      break;

      // permutation de l'activation des shaders
      case 'x' :
         if (SHADER_ON)
            SHADER_ON = false;
         else
            SHADER_ON = true;
         glutPostRedisplay();
      break;

      case '-' :
         // la caméra recule
         rho += 2.0f;
         affichage();
      break;

      case '=' :
         // la caméra avance
         rho -= 2.0f;
         if (rho <= 1.0)
            rho = 1.0f;
         affichage();
      break;

      case ' ' :
         // permuter la rotation automatique du modèle
         rotAutoModele ? rotAutoModele = false : rotAutoModele = true;
         affichage();
      break;

	}
}

// fonction de gestion du clavier spécial
void clavierSpecial(int touche, int x, int y)
{
	// traitement des touches q et echap
   switch(touche) {
      case GLUT_KEY_RIGHT :
		   // effectuer une rotation vers la droite autour du cube
         theta += DEG2RAD(2.0f);
         affichage();
      break;

      case GLUT_KEY_LEFT :
		   // effectuer une rotation vers la droite autour du cube
         theta -= DEG2RAD(2.0f);
         affichage();
      break;

      case GLUT_KEY_UP :
		   // effectuer une rotation vers la droite autour du cube
         phi -= DEG2RAD(2.0f);
         affichage();
      break;

      case GLUT_KEY_DOWN :
		   // effectuer une rotation vers la droite autour du cube
         phi += DEG2RAD(2.0f);
         affichage();
      break;
	}
}

// fonction de redimensionnement de la fenêtre graphique
void redimensionnement(GLsizei w, GLsizei h)
{
   currentW = w;
   currentH = h;
   glViewport(0, 0, w, h);
   affichage();
}

// fonction callback lorsque la souris est cliquee
void sourisClickee(int button, int state, int x, int y)
{
   if (state == GLUT_DOWN) {
      // on vient de presser la souris
      dernierX = x;
      dernierY = y;
   } else {
      // on vient de relacher la souris

   }
}

// fonction de redimensionnement de la fenêtre graphique
void mouvementSouris(int x, int y)
{
   angleRotX += y - dernierY;
   angleRotZ -= x - dernierX;

   dernierX = x;
   dernierY = y;
}

// le main
int main(int argc,char *argv[])
{
	// initialisation de GLUT
	glutInit(&argc, argv);
	// parametrage de l'affichage
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	// taille de la fenetre
	glutInitWindowSize(800, 800);
	// creation de la fenetre
	g_nWindowID = glutCreateWindow("Exemple");

	// referencement de la fonction d'affichage
	glutDisplayFunc(affichage);
	// referencement de la fonction d'attente
	glutIdleFunc(attente);
	// referencement de la fonction de gestion des touches
	glutKeyboardFunc(clavier);
	// referencement de la fonction de gestion spéciale des touches extended
	glutSpecialFunc(clavierSpecial);
	// referencement de la fonction de redimensionnement
	glutReshapeFunc (redimensionnement);
	// référencement de la fonction de mouvement de la souris
	glutMotionFunc (mouvementSouris);
	// référencement de la fonction de click de la souris
	glutMouseFunc (sourisClickee);

	// vérification de la présence des extensions
	// ou de la version 2.0 d'openGL
	glewInit();
	if (glewIsSupported("GL_VERSION_2_0"))
		printf("Ready for OpenGL 2.0\n");
	else {
		printf("OpenGL 2.0 not supported\n");
		exit(1);
	}

	// compiler et linker les nuanceurs
	initialiserNuanceurs();

	// initialisation de variables d'état openGL et création des listes
	initialisation();

	// boucle principale de gestion des evenements
	glutMainLoop();

	// le programme n'arrivera jamais jusqu'ici
	return EXIT_SUCCESS;
}

//////////////////////////////////////////////////////////
////////////  FONCTIONS POUR LA CAMÉRA ///////////////////
//////////////////////////////////////////////////////////
void rafraichirCamera()
{
   x = rho*cos(theta)*sin(phi);
   y = rho*sin(theta)*sin(phi);
   z = rho*cos(phi);

   gluLookAt(x, y, z, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
}

//////////////////////////////////////////////////////////
//////  FONCTIONS POUR LES LISTES D'AFFICHAGE ////////////
//////////////////////////////////////////////////////////
void compileCube(int listID, float size, int nbRows, int nbColums, bool outsideNormal) {
   // dessiner la pièce
   glNewList(listID , GL_COMPILE);

      // face du fond
      glPushMatrix();
         glTranslatef(0.0f, size/2.0f, 0.0f);
         glCallList(QUAD_LIST);
      glPopMatrix();

      // face de derrière
      glPushMatrix();
         glTranslatef(0.0f, -size/2.0f, 0.0f);
         glRotatef(180.0, 0.0, 0.0, 1.0);
         glCallList(QUAD_LIST);
      glPopMatrix();

      // face de gauche
      glPushMatrix();
         glTranslatef(-size/2.0f, 0.0f, 0.0f);
         glRotatef(90.0, 0.0, 0.0, 1.0);
         glCallList(QUAD_LIST);
      glPopMatrix();

      // face de droite
      glPushMatrix();
         glTranslatef(size/2.0f, 0.0f, 0.0f);
         glRotatef(-90.0, 0.0, 0.0, 1.0);
         glCallList(QUAD_LIST);
      glPopMatrix();

      // face du bas
      glPushMatrix();
         glTranslatef(0.0f, 0.0f, size/2.0f);
         glRotatef(90.0, 1.0, 0.0, 0.0);
         glCallList(QUAD_LIST);
      glPopMatrix();

      // face du haut
      glPushMatrix();
         glTranslatef(0.0f, 0.0f, -size/2.0f);
         glRotatef(-90.0, 1.0, 0.0, 0.0);
         glCallList(QUAD_LIST);
      glPopMatrix();

   glEndList();
}

void compileGrilleQuads(int listID, float size, int nbRows, int nbColums, bool outsideNormal)
{

   glNewList(listID, GL_COMPILE);
      appliquerTextures();
      dessinerGrilleQuads(size, nbRows, nbColums, outsideNormal);
   glEndList();
}

void dessinerGrilleQuads(float size, int nbRows, int nbColums, bool outsideNormal) {

   int normFact = outsideNormal ? 1 : -1;

   float startX = -size/2.0f;
   float startY = 0.0f;
   float startZ = size/2.0f;
   float s1, t1, s2, t2;

   float incrementX = size / (float)nbColums;
   float incrementZ = size / (float)nbRows;

   glBegin(GL_QUADS);
   glNormal3f(0.0, normFact, 0.0);

   for (int i=0;i<nbColums;i++) {
      for (int k=0;k<nbRows;k++) {

         s1 = (i*incrementX)/size;
         s2 = ((i+1)*incrementX)/size;
         t1 = (k*incrementZ)/size;
         t2 = ((k+1)*incrementZ)/size;

         glMultiTexCoord2f(GL_TEXTURE0, s1, t1);
         glMultiTexCoord2f(GL_TEXTURE1, s1, t1);
         glMultiTexCoord2f(GL_TEXTURE2, s1, t1);
         glVertex3f(startX + i*incrementX, 0.0f, startZ - k*incrementZ);

         glMultiTexCoord2f(GL_TEXTURE0, s2, t1);
         glMultiTexCoord2f(GL_TEXTURE1, s2, t1);
         glMultiTexCoord2f(GL_TEXTURE2, s2, t1);
         glVertex3f((startX + i*incrementX) + incrementX, 0.0f, startZ - k*incrementZ);

         glMultiTexCoord2f(GL_TEXTURE0, s2, t2);
         glMultiTexCoord2f(GL_TEXTURE1, s2, t2);
         glMultiTexCoord2f(GL_TEXTURE2, s2, t2);
         glVertex3f((startX + i*incrementX) + incrementX, 0.0f, (startZ - k*incrementZ) - incrementZ);

         glMultiTexCoord2f(GL_TEXTURE0, s1, t2);
         glMultiTexCoord2f(GL_TEXTURE1, s1, t2);
         glMultiTexCoord2f(GL_TEXTURE2, s1, t2);
         glVertex3f(startX + i*incrementX, 0.0f, (startZ - k*incrementZ) - incrementZ);
      }
   }
   glEnd();
}

//////////////////////////////////////////////////////////
///////////  FONCTIONS POUR L'ÉCLAIRAGE //////////////////
//////////////////////////////////////////////////////////
void rafraichirEclairage()
{
   // inscription des variables de lumière dans le nuanceur

   if (pointLightAllumee) {
      glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient0);
      glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse0);
      glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular0);
      glLightfv(GL_LIGHT0, GL_EMISSION, light_emission0);
      glLightfv(GL_LIGHT0, GL_POSITION, light_position0);

      glEnable(GL_LIGHT0);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "pointLightOn"), 1);
   }
   else {
      glDisable(GL_LIGHT0);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "pointLightOn"), 0);
   }

   if (spotLightAllumee) {
      // variables position et spotDirection pour la "flashLight")
      GLfloat spotPosition[4] =  { x, y, z, 1.0};
      GLfloat spotDirection[3] = {-x,-y,-z};

      glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient1);
      glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1);
      glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1);
      glLightfv(GL_LIGHT1, GL_EMISSION, light_emission1);
      glLightfv(GL_LIGHT1, GL_POSITION, spotPosition);
      glLightf (GL_LIGHT1, GL_SPOT_EXPONENT, 1.0);
      glLightf (GL_LIGHT1, GL_SPOT_CUTOFF, 30.0);
      glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spotDirection);

      glEnable(GL_LIGHT1);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "spotLightOn"), 1);
   }
   else {
      glDisable(GL_LIGHT1);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "spotLightOn"), 0);
   }

   if (dirLightAllumee) {
      glLightfv(GL_LIGHT2, GL_AMBIENT, light_ambient2);
      glLightfv(GL_LIGHT2, GL_DIFFUSE, light_diffuse2);
      glLightfv(GL_LIGHT2, GL_SPECULAR, light_specular2);
      glLightfv(GL_LIGHT2, GL_EMISSION, light_emission2);
      glLightfv(GL_LIGHT2, GL_POSITION, light_position2);

      glEnable(GL_LIGHT2);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "dirLightOn"), 1);
   }
   else {
      glDisable(GL_LIGHT2);
      glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "dirLightOn"), 0);
   }
}

//////////////////////////////////////////////////////////
//////////  FONCTIONS POUR LA PROJECTION /////////////////
//////////////////////////////////////////////////////////
void rafraichirProjection()
{
   if (isPerspective) {
       gluPerspective(60.0, (GLfloat)currentW / (GLfloat) currentH, 0.1, 300.0);
   } else {
       if (currentW <= currentH)
           glOrtho (-10.0, 10.0, -10.0*(GLfloat)currentH/(GLfloat)currentW,
               10.0*(GLfloat)currentH/(GLfloat)currentW, 0.01, 300.0);
       else
           glOrtho (-10.0*(GLfloat)currentW/(GLfloat)currentH,
               10.0*(GLfloat)currentW/(GLfloat)currentH, -10.0, 10.0, 0.01, 300.0);
   }
}

//////////////////////////////////////////////////////////
//////////  FONCTIONS POUR LES NUANCEURS /////////////////
//////////////////////////////////////////////////////////
void afficherShaderInfoLog(GLuint obj, char* message)
{
	int infologLength = 0;
	int charsWritten  = 0;
	char *infoLog;

   // afficher le message d'en-tête
   printf("%s\n", message);

   // afficher le message d'erreur, le cas échéant
	glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength);

	if (infologLength > 1)
	{
		infoLog = (char *)malloc(infologLength);
		glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
		printf("%s\n",infoLog);
		free(infoLog);
	}
   else
   {
      printf("Aucune erreur :-)\n\n");
   }
}

void afficherProgramInfoLog(GLuint obj, char* message)
{
	int infologLength = 0;
	int charsWritten  = 0;
	char *infoLog;

   // afficher le message d'en-tête
   printf("%s\n", message);

   // afficher le message d'erreur, le cas échéant
	glGetProgramiv(obj, GL_INFO_LOG_LENGTH,&infologLength);

	if (infologLength > 0)
	{
		infoLog = (char *)malloc(infologLength);
		glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
		printf("%s\n",infoLog);
		free(infoLog);
	}
   else
   {
      printf("Aucune erreur :-)\n\n");
   }
}

void initialiserNuanceurs()
{
	// définition des nuanceurs à créer ci-bas...
   GLuint nuanceurSommets;
   GLuint nuanceurFragments;

   // déclaration des chaînes qui devront recevoir le code des nuanceurs
	char *ns = NULL;
	char *nf = NULL;

	// création des nuanceurs
	nuanceurSommets = glCreateShader(GL_VERTEX_SHADER);
	nuanceurFragments = glCreateShader(GL_FRAGMENT_SHADER);

	// lecture du code des nuanceurs
	ns = textFileRead("nuanceurs/nuanceurSommets.glsl");
	nf = textFileRead("nuanceurs/nuanceurFragments.glsl");

	// créer des pointeurs sur le texte du code des nuanceurs
	const char * ns_ptr = ns;
	const char * nf_ptr = nf;

	// sourcer les nuanceurs
	glShaderSource(nuanceurSommets, 1, &ns_ptr, NULL);
	glShaderSource(nuanceurFragments, 1, &nf_ptr, NULL);

	// libérer la mémoire des codes source
	free(ns);
	free(nf);

   // compiler les nuanceurs et vérifier les erreurs
   glCompileShader(nuanceurSommets);
   glCompileShader(nuanceurFragments);

   // Afficher les erreurs de compilation !!
   afficherShaderInfoLog(nuanceurSommets, "ERREURS DE COMPILATION DU NUANCEUR DE SOMMETS : ");
   afficherShaderInfoLog(nuanceurFragments, "ERREURS DE COMPILATION DU NUANCEUR DE FRAGMENTS : ");

	// créer le programme des nuanceurs et lier
	fixedPipelineShaderProg = glCreateProgram();
	glAttachShader(fixedPipelineShaderProg,nuanceurSommets);
	glAttachShader(fixedPipelineShaderProg,nuanceurFragments);
	glLinkProgram(fixedPipelineShaderProg);

	// afficher les erreurs de compilation et de linkage du programme
   afficherProgramInfoLog(fixedPipelineShaderProg, "ERREURS DE L'EDITION DES LIENS : ");

   glUseProgram(fixedPipelineShaderProg);
}

//////////////////////////////////////////////////////////
//////////  FONCTIONS POUR LES TEXTURES //////////////////
//////////////////////////////////////////////////////////
void appliquerTextures()
{
	// ETAGE 0 (texture de mur)
	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture0);
	glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "texUnit0"), 0);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	// ETAGE 1 (texture de rust)
	float white[] = { 1.0, 1.0, 1.0, 1.0 };
	glActiveTexture(GL_TEXTURE1);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture1);
	glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "texUnit1"), 1);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
	glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, white);
	glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
	glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS);
	glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE);
	glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_CONSTANT);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
	glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
	glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE , 2.0);
	// ETAGE 2 (texture "paint job")
	glActiveTexture(GL_TEXTURE2);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture2);
	glUniform1i(glGetUniformLocation(fixedPipelineShaderProg, "texUnit2"), 2);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);   //Modulate RGB with RGB*/
}

SImage* LoadBMP( char *Filename )
{
    if( !Filename )
        return NULL;

    FILE *file;
    unsigned int  width;
    unsigned int  height;
	unsigned long i;
	unsigned short int planes; // planes in image (must be 1)
	unsigned short int bpp;    // bits per pixel (must be 24)

	// make sure the file is there.
	if( ( file = fopen( Filename, "rb" ) ) == NULL )
    {
		printf( "File Not Found : %s\n", Filename );
		return NULL;
	}

	// seek through the bmp header, up to the width/height:
	fseek( file, 18, SEEK_CUR );

	// read the width
	if( ( i = ( unsigned long )fread( &width, 4, 1, file ) ) != 1 )
    {
		printf( "Error reading width from %s.\n", Filename );
		return NULL;
	}

	// read the height
	if( ( i = ( unsigned long )fread( &height, 4, 1, file ) ) != 1 )
    {
		printf( "Error reading height from %s.\n", Filename );
		return NULL;
	}

	// read the planes
	if( ( ( unsigned long )fread( &planes, 2, 1, file ) ) != 1 )
    {
		printf( "Error reading planes from %s.\n", Filename );
		return NULL;
	}

	if( planes != 1 )
    {
		printf( "Planes from %s is not 1: %u\n", Filename, planes );
		return NULL;
	}

	// read the bpp
	if( ( i = ( unsigned long )fread( &bpp, 2, 1, file ) ) != 1 )
    {
		printf("Error reading bpp from %s.\n", Filename );
		return NULL;
	}

	if( bpp != 24 )
    {
		printf( "Bpp from %s is not 24: %u\n", Filename, bpp );
		return NULL;
	}

	// seek past the rest of the bitmap header.
	fseek( file, 24, SEEK_CUR );

	// read the data.
    SImage* Image = new SImage( width, height );

	if( ( i = ( unsigned long )fread( Image->data, width * height * 3, 1, file ) ) != 1 )
    {
		printf("Error reading image data from %s.\n", Filename );
		delete Image;
		return NULL;
	}

	return Image;
}

void init2DTexture(GLint texName, GLint texWidth, GLint texHeight, GLubyte *texPtr)
{
   glBindTexture(GL_TEXTURE_2D, texName);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 1.0);
   glTexImage2D(GL_TEXTURE_2D, 0, 3, texWidth, texHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, texPtr);
}

void chargerTextures()
{
   SImage* Image = NULL;

   if( Image = LoadBMP("textures/stonewalldiffuse.bmp" ) )
   {
      glGenTextures( 1, &texture0 );
      init2DTexture( texture0, Image->width, Image->height, Image->data );
      delete Image;
   }

   if( Image = LoadBMP( "textures/rust.bmp" ) )
   {
      glGenTextures( 1, &texture1 );
      init2DTexture( texture1, Image->width, Image->height, Image->data );
      delete Image;
   }

   if( Image = LoadBMP( "textures/3dlabs.bmp" ) )
   {
      glGenTextures( 1, &texture2 );
      init2DTexture( texture2, Image->width, Image->height, Image->data );
      delete Image;
   }
}

void desactiverTextures()
{
   glActiveTexture(GL_TEXTURE0);
   glDisable(GL_TEXTURE_2D);
   glActiveTexture(GL_TEXTURE1);
   glDisable(GL_TEXTURE_2D);
   glActiveTexture(GL_TEXTURE2);
   glDisable(GL_TEXTURE_2D);
}


text:
namespace Spire
{
	namespace Compiler
	{
		using namespace CoreLib::Basic;

        struct TokenList
        {
            Token* begin() const;
            Token* end() const;

            List<Token> mTokens;
        };

        struct TokenSpan
        {
            TokenSpan();
            TokenSpan(
                TokenList const& tokenList)
                : mBegin(tokenList.begin())
                , mEnd  (tokenList.end  ())
            {}

            Token* begin() const { return mBegin; }
            Token* end  () const { return mEnd  ; }

            int GetCount() { return (int)(mEnd - mBegin); }

            Token* mBegin;
            Token* mEnd;
        };

        struct TokenReader
        {
            TokenReader();
            explicit TokenReader(TokenSpan const& tokens)
                : mCursor(tokens.begin())
                , mEnd   (tokens.end  ())
            {}
            explicit TokenReader(TokenList const& tokens)
                : mCursor(tokens.begin())
                , mEnd   (tokens.end  ())
            {}

            bool IsAtEnd() const { return mCursor == mEnd; }
            Token PeekToken() const;
            CoreLib::Text::TokenType PeekTokenType() const;
            CodePosition PeekLoc() const;

            Token AdvanceToken();

            int GetCount() { return (int)(mEnd - mCursor); }

            Token* mCursor;
            Token* mEnd;
        };

		class Lexer
		{
		public:
			TokenList Parse(const String & fileName, const String & str, DiagnosticSink * sink);
		};
	}
}

#endif