text:
class Sound < ActiveRecord::Base
  attr_accessible :access_token

  APP_CLIENT = Soundcloud.new({:client_id => ENV['SC_CLIENT_ID'], :client_secret => ENV['SC_CLIENT_SECRET'], :redirect_uri => "http://www.backlyne.com/sounds/connected"})

  def client
    Soundcloud.new(:access_token => self.access_token )
  end

  def self.embed_html(track_url)
    embed_info = self::APP_CLIENT.get('/oembed', :url => track_url, :maxwidth => "400px", :maxheight => "250px")
    embed_info['html']
  end

  def self.search(params)
    search_terms = compact_search_params(params)
    self::APP_CLIENT.get('/tracks', search_terms, :limit => 5)
  end

  def self.compact_search_params(params)
    params.select {|term, value| value != "" }
  end

  def self.create_sound_profile(code)
    access_token_info = Sound::APP_CLIENT.exchange_token(:code => code)
    access_token = access_token_info.response.parsed_response["access_token"]
    Sound.create(access_token: access_token)
  end

  def self.set_client_by_user(user)
    access_token = Sound.where(user_id: user.id).access_token
    Soundcloud.new(:access_token => self.access_token)
  end
end


text:
'use strict';

import './_navbar.scss';

import React from 'react';

class NavbarContainer extends React.Component{
  render(){
    return(

          {/* NOTE: should maybe consider bringing in link from react router instead of using a tags */}

Home

Repos

Cowsay

Reddit

Settings

    );
  }
}

export default NavbarContainer;

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ServerLogstat',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('server_id', models.IntegerField(unique=True)),
                ('type', models.IntegerField()),
                ('info', models.TextField()),
            ],
        ),
    ]


text:
// external dependencies
const _ = require('lodash');

// internal dependencies
const errors = require('./error-dictionary');

// logic
function PsmImagePicker(imageDictionary) {
  // check the format of the imageDictionary
  this.checkImageDictionaryFormat(imageDictionary);

  // save the image dictionary for usage later
  this.imageDictionary = this.parseImageDictionary(imageDictionary);
}
/**
 * A function that uses the specified search criteria to perform the correct
 * search against the image dictionary.
 *
 * Note: there is a lot of duck punching involved so we can handle more
 * possibilities for how the user might pass data to this function.
 *
 * @return {Object} An object containing the search results.
 */
PsmImagePicker.prototype.search = function(/* keywords, maxResults, size */) {
  var args = Array.prototype.slice.call(arguments);

  if (args.length === 0) {
    throw errors.invalidSearchCriteria;
  } else if (args.length === 1) {
    if (_.isNumber(args[0])) {
      return this.searchByMaxResults.apply(this, args);
    } else if (_.isArray(args[0])) {
      args.push(null);
      return this.searchByKeywordsAndMaxResults.apply(this, args);
    } else if (_.isObject(args[0])) {
      return this.searchByAllCritera([], null, args[0]);
    }

    throw errors.invalidSearchCriteria;
  } else if (args.length === 2) {
    if (_.isArray(args[0])) {
      if (_.isNumber(args[1])) {
        return this.searchByKeywordsAndMaxResults.apply(this, args);
      } else if (_.isObject(args[1])) {
        return this.searchByAllCritera(args[0], null, args[1]);
      }
    } else if (_.isObject(args[0]) && _.isNumber(args[1])) {
      return this.searchByAllCritera([], args[1], args[0]);
    }

    throw errors.invalidSearchCriteria;
  }

  return this.searchByAllCritera.apply(this, args);
};

PsmImagePicker.prototype.searchByMaxResults = function(maxResults) {
  var imageDictionary = _.extend([], this.imageDictionary);

  // ensure maxResults is a valid integer
  if (!_.isNumber(maxResults)) {
    throw errors.invalidSearchCriteria;
  }
  maxResults = parseInt(maxResults, 10);

  // cut the chunk out we need
  imageDictionary = _.take(imageDictionary, maxResults);

  // return a properly formatted object literal
  return {
    totalResults: imageDictionary.length,
    images: _.map(imageDictionary, function(entry) {
      return _.pick(entry, ['url', 'size']);
    })
  };
};

PsmImagePicker.prototype.searchByKeywordsAndMaxResults =
  function(keywords, maxResults) {
    var imageDictionary = _.extend([], this.imageDictionary);
    var keywordsFound;

    // ensure that keywords is a valid array
    if (!_.isArray(keywords)) {
      throw errors.invalidSearchCriteria;
    }

    // make sure all of the specified keywords are lowercase
    keywords = _.map(keywords, function(keyword) {
      return keyword.toLowerCase();
    });

    // iterate through the elements finding images that have one of the
    // specified keywords
    var images = _.filter(imageDictionary, function(entry) {
      keywordsFound = 0;

      if (!keywords.length) {
        entry.keywordsFound = keywordsFound;
        return true;
      }

      _.each(entry.keywords, function(keyword) {
        if (keywords.indexOf(keyword) > -1) {
          keywordsFound++;
        }
      });

      if (!keywordsFound) {
        return false;
      }

      entry.keywordsFound = keywordsFound;
      return true;
    });

    // finally, sort by the number of keywords found
    images = images.sort(function(entryA, entryB) {
      return entryA.keywordsFound < entryB.keywordsFound;
    });

    // check to see if we're returning all results or only the first
    // `maxResults` number of results
    if (_.isNumber(maxResults)) {
      images = _.take(images, maxResults);
    }

    // return a properly formatted object literal
    return {
      totalResults: images.length,
      images: _.map(images, function(entry) {
        return _.pick(entry, ['url', 'size']);
      })
    };
};

PsmImagePicker.prototype.searchByAllCritera =
  function(keywords, maxResults, size) {
    var results = this.searchByKeywordsAndMaxResults(keywords, maxResults);

    // ensure that size is a properly formatted object
    if (!_.isObject(size)) {
      throw errors.invalidSearchCriteria;
    } else if (!_.isNumber(size.height) && !_.isNumber(size.width)) {
      throw errors.invalidSearchCriteria;
    }

    // filter the results based on the specified sizes
    results = _.filter(results.images, function(entry) {
      if (_.isNumber(size.height) && entry.size.height > size.height) {
        return false;
      }

      if (_.isNumber(size.width) && entry.size.width > size.width) {
        return false;
      }

      return true;
    });

    // check to see if we're returning all results or only the first
    // `maxResults` number of results
    if (_.isNumber(maxResults)) {
      results = _.take(results, maxResults);
    }

    // return a properly formatted object literal
    return {
      totalResults: results.length,
      images: results
    };
};

PsmImagePicker.prototype.parseImageDictionary = function(dictionary) {
  _.each(dictionary, function(entry) {
    _.each(entry.keywords, function(keyword, keywordIndex) {
      entry.keywords[keywordIndex] = keyword.toLowerCase();
    });

    entry.size.height = parseInt(entry.size.height, 10);
    entry.size.width = parseInt(entry.size.width, 10);
  });

  return dictionary;
};

PsmImagePicker.prototype.checkImageDictionaryFormat = function(dictionary) {
  if (!_.isArray(dictionary)) {
    throw errors.invalidDictionary;
  }

  if (!dictionary.length) {
    throw errors.invalidDictionary;
  }

  // check every entry in the array
  _.each(dictionary, function(entry) {
    if (!_.isObject(entry)) {
      throw errors.invalidDictionary;
    }

    if (!_.isString(entry.url)) {
      throw errors.invalidDictionary;
    } else if (!_.isObject(entry.size)) {
      throw errors.invalidDictionary;
    } else if (!_.isInteger(entry.size.height)) {
      throw errors.invalidDictionary;
    } else if (!_.isInteger(entry.size.width)) {
      throw errors.invalidDictionary;
    } else if (!_.isArray(entry.keywords)) {
      throw errors.invalidDictionary;
    }
  });
};

exports = module.exports = PsmImagePicker;


text:
package io.algobox.api.module.price.dao.impl;

import com.google.common.collect.Maps;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoClientException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Sorts;
import com.mongodb.util.JSON;
import io.algobox.api.module.price.dao.PriceTickDao;
import io.algobox.api.module.price.domain.mdb.PriceTickMdb;
import io.algobox.price.PriceTick;
import io.algobox.util.JsonUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.jvnet.hk2.annotations.Service;

import javax.inject.Inject;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lte;
import static io.algobox.util.MorePreconditions.checkNotNullOrEmpty;

/**
 * Prices are saved in separated collection by instrument id.
 */
@Service
public final class PriceTickDaoImpl implements PriceTickDao {
  private final Map<String, MongoCollection<Document>> collectionsByInstrumentId =
      Maps.newConcurrentMap();
  private static final Document INDEX = new Document().append(PriceTickMdb.FIELD_TIME, -1);

  private final MongoDatabase mongoDatabase;

  @Inject
  public PriceTickDaoImpl(MongoDatabase database) {
    this.mongoDatabase = database;
  }

  @Override
  public void save(PriceTick priceTick, String source) {
    checkNotNull(priceTick);
    checkNotNullOrEmpty(source);
    checkNotNullOrEmpty(priceTick.getInstrument());
    PriceTickMdb priceTickMdb = new PriceTickMdb(source, priceTick.getInstrument(),
        priceTick.getTime(), priceTick.getAsk(), priceTick.getBid());
    Document document = Document.parse(JsonUtils.toJson(priceTickMdb));
    MongoCollection<Document> collection = getCollection(priceTick.getInstrument());
    try {
      collection.insertOne(document);
    } catch (MongoClientException e) {
      // Handle drivers failures.
      try {
        collection.insertOne(document);
      } catch (DuplicateKeyException ex) {
        // Record already inserted, ignore exception.
      }
    }
  }

  @Override
  public Iterable<PriceTick> find(
      String instrumentId, long fromTimestampUtc, long toTimeStampUtc) {
    return internalFind(instrumentId, fromTimestampUtc, toTimeStampUtc)
        .map(this::createPriceTick);
  }

  private FindIterable<Document> internalFind(
      String instrumentId, long fromTimestampUtc, long toTimeStampUtc) {
    checkNotNullOrEmpty(instrumentId);
    checkArgument(fromTimestampUtc > 0, "From timestamp must be greater than 0.");
    checkArgument(toTimeStampUtc > 0, "To timestamp must be greater than 0.");
    checkArgument(toTimeStampUtc > fromTimestampUtc,
        "To timestamp must be greater than from timestamp.");
    Bson query = and(gte(PriceTickMdb.FIELD_TIME, fromTimestampUtc),
        lte(PriceTickMdb.FIELD_TIME, toTimeStampUtc));
    Bson sort = Sorts.ascending(PriceTickMdb.FIELD_TIME);
    return getCollection(instrumentId).find(query)
        .sort(sort);
  }

  private PriceTick createPriceTick(Document document) {
    return JsonUtils.fromJson(JSON.serialize(document), PriceTick.class);
  }

  private MongoCollection<Document> getCollection(String instrumentId) {
    instrumentId = instrumentId.toUpperCase();
    MongoCollection<Document> collection = collectionsByInstrumentId.get(instrumentId);
    if (collection == null) {
      String collectionName = getCollectionName(
          PriceTickMdb.COLLECTION_PRICE_TICKS_PREFIX, instrumentId);
      collection = mongoDatabase.getCollection(collectionName);
      createIndexIfNotExists(collection);
      collectionsByInstrumentId.put(instrumentId, collection);
    }
    return collection;
  }

  private void createIndexIfNotExists(MongoCollection<Document> collection) {
    Iterable<Document> indexes = collection.listIndexes();
    for (Document index: indexes) {
      if (index.keySet().containsAll(INDEX.keySet()) &&
          INDEX.keySet().containsAll(index.keySet())) {
        return;
      }
    }
    collection.createIndex(INDEX, new IndexOptions().unique(true));
  }

  /**
   * Returns the collection name used by persistence layer or message queues to store and
   * dispatch prices.
   */
  private String getCollectionName(String collectionPrefix, String instrumentId) {
    return checkNotNullOrEmpty(collectionPrefix) +
        checkNotNullOrEmpty(instrumentId).toUpperCase().replaceAll("[^A-Za-z0-9]", "_");
  }
}


text:
//"use strict";

var LibraryOpenAL = {
  $AL__deps: ['$Browser'],
  $AL: {
    contexts: [],
    currentContext: null,

    alcErr: 0,

    stringCache: {},
    alcStringCache: {},

    QUEUE_INTERVAL: 25,
    QUEUE_LOOKAHEAD: 100,

    newSrcId: 1,

#if OPENAL_DEBUG
    //This function is slow and used only for debugging purposes
    srcIdBySrc: function srcIdBySrc(src) {
      var idx = 0;
      for (var srcId in AL.currentContext.src) {
        if (AL.currentContext.src[srcId] == src) {
          idx = srcId;
          break;
        }
      }
      return idx;
    },
#endif

    updateSources: function updateSources(context) {
      // If we are animating using the requestAnimationFrame method, then the main loop does not run when in the background.
      // To give a perfect glitch-free audio stop when switching from foreground to background, we need to avoid updating
      // audio altogether when in the background, so detect that case and kill audio buffer streaming if so.
      if (Browser.mainLoop.timingMode == 1/*EM_TIMING_RAF*/ && document['visibilityState'] != 'visible') return;

      for (var srcId in context.src) {
        AL.updateSource(context.src[srcId]);
      }
    },

    updateSource: function updateSource(src) {
#if OPENAL_DEBUG
      var idx = AL.srcIdBySrc(src);
#endif
      if (src.state !== 0x1012 /* AL_PLAYING */) {
        return;
      }

      var currentTime = AL.currentContext.ctx.currentTime;
      var startTime = src.bufferPosition;

      for (var i = src.buffersPlayed; i < src.queue.length; i++) {
        var entry = src.queue[i];

        var startOffset = startTime - currentTime;
        var endTime = startTime + entry.buffer.duration;

        // Clean up old buffers.
        if (currentTime >= endTime) {
          // Update our location in the queue.
          src.bufferPosition = endTime;
          src.buffersPlayed = i + 1;

          // Stop / restart the source when we hit the end.
          if (src.buffersPlayed >= src.queue.length) {
            if (src.loop) {
              AL.setSourceState(src, 0x1012 /* AL_PLAYING */);
            } else {
              AL.setSourceState(src, 0x1014 /* AL_STOPPED */);
            }
          }
        }
        // Process all buffers that'll be played before the next tick.
        else if (startOffset < (AL.QUEUE_LOOKAHEAD / 1000) && !entry.src) {
          // If the start offset is negative, we need to offset the actual buffer.
          var offset = Math.abs(Math.min(startOffset, 0));

          entry.src = AL.currentContext.ctx.createBufferSource();
          entry.src.buffer = entry.buffer;
          entry.src.connect(src.gain);
          if (typeof(entry.src.start) !== 'undefined') {
            entry.src.start(startTime, offset);
          } else if (typeof(entry.src.noteOn) !== 'undefined') {
            entry.src.noteOn(startTime);
#if OPENAL_DEBUG
            if (offset > 0) {
              Runtime.warnOnce('The current browser does not support AudioBufferSourceNode.start(when, offset); method, so cannot play back audio with an offset '+offset+' secs! Audio glitches will occur!');
            }
#endif
          }
#if OPENAL_DEBUG
          else {
            Runtime.warnOnce('Unable to start AudioBufferSourceNode playback! Not supported by the browser?');
          }

          console.log('updateSource queuing buffer ' + i + ' for source ' + idx + ' at ' + startTime + ' (offset by ' + offset + ')');
#endif
        }

        startTime = endTime;
      }
    },

    setSourceState: function setSourceState(src, state) {
#if OPENAL_DEBUG
      var idx = AL.srcIdBySrc(src);
#endif
      if (state === 0x1012 /* AL_PLAYING */) {
        if (src.state !== 0x1013 /* AL_PAUSED */) {
          src.state = 0x1012 /* AL_PLAYING */;
          // Reset our position.
          src.bufferPosition = AL.currentContext.ctx.currentTime;
          src.buffersPlayed = 0;
#if OPENAL_DEBUG
          console.log('setSourceState resetting and playing source ' + idx);
#endif
        } else {
          src.state = 0x1012 /* AL_PLAYING */;
          // Use the current offset from src.bufferPosition to resume at the correct point.
          src.bufferPosition = AL.currentContext.ctx.currentTime - src.bufferPosition;
#if OPENAL_DEBUG
          console.log('setSourceState resuming source ' + idx + ' at ' + src.bufferPosition.toFixed(4));
#endif
        }
        AL.stopSourceQueue(src);
        AL.updateSource(src);
      } else if (state === 0x1013 /* AL_PAUSED */) {
        if (src.state === 0x1012 /* AL_PLAYING */) {
          src.state = 0x1013 /* AL_PAUSED */;
          // Store off the current offset to restore with on resume.
          src.bufferPosition = AL.currentContext.ctx.currentTime - src.bufferPosition;
          AL.stopSourceQueue(src);
#if OPENAL_DEBUG
          console.log('setSourceState pausing source ' + idx + ' at ' + src.bufferPosition.toFixed(4));
#endif
        }
      } else if (state === 0x1014 /* AL_STOPPED */) {
        if (src.state !== 0x1011 /* AL_INITIAL */) {
          src.state = 0x1014 /* AL_STOPPED */;
          src.buffersPlayed = src.queue.length;
          AL.stopSourceQueue(src);
#if OPENAL_DEBUG
          console.log('setSourceState stopping source ' + idx);
#endif
        }
      } else if (state == 0x1011 /* AL_INITIAL */) {
        if (src.state !== 0x1011 /* AL_INITIAL */) {
          src.state = 0x1011 /* AL_INITIAL */;
          src.bufferPosition = 0;
          src.buffersPlayed = 0;
#if OPENAL_DEBUG
          console.log('setSourceState initializing source ' + idx);
#endif
        }
      }
    },

    stopSourceQueue: function stopSourceQueue(src) {
      for (var i = 0; i < src.queue.length; i++) {
        var entry = src.queue[i];
        if (entry.src) {
          entry.src.stop(0);
          entry.src = null;
        }
      }
    }
  },

  alcProcessContext: function(context) {},
  alcSuspendContext: function(context) {},

  alcMakeContextCurrent: function(context) {
    if (context == 0) {
      AL.currentContext = null;
      return 0;
    } else {
      AL.currentContext = AL.contexts[context - 1];
      return 1;
    }
  },

  alcGetContextsDevice: function(context) {
    if (context <= AL.contexts.length && context > 0) {
      // Returns the only one audio device
      return 1;
    }
    return 0;
  },

  alcGetCurrentContext: function() {
    for (var i = 0; i < AL.contexts.length; ++i) {
      if (AL.contexts[i] == AL.currentContext) {
        return i + 1;
      }
    }
    return 0;
  },

  alcDestroyContext: function(context) {
    // Stop playback, etc
    clearInterval(AL.contexts[context - 1].interval);
  },

  alcCloseDevice: function(device) {
    // Stop playback, etc
  },

  alcOpenDevice: function(deviceName) {
    if (typeof(AudioContext) !== "undefined" ||
        typeof(webkitAudioContext) !== "undefined") {
      return 1; // non-null pointer -- we just simulate one device
    } else {
      return 0;
    }
  },

  alcCreateContext: function(device, attrList) {
    if (device != 1) {
      return 0;
    }

    if (attrList) {
#if OPENAL_DEBUG
      console.log("The attrList argument of alcCreateContext is not supported yet");
#endif
      return 0;
    }

    var ctx;
    try {
      ctx = new AudioContext();
    } catch (e) {
      try {
        ctx = new webkitAudioContext();
      } catch (e) {}
    }

    if (ctx) {
      // Old Web Audio API (e.g. Safari 6.0.5) had an inconsistently named createGainNode function.
      if (typeof(ctx.createGain) === 'undefined') ctx.createGain = ctx.createGainNode;

      var gain = ctx.createGain();
      gain.connect(ctx.destination);
      var context = {
        ctx: ctx,
        err: 0,
        src: {},
        buf: [],
        interval: setInterval(function() { AL.updateSources(context); }, AL.QUEUE_INTERVAL),
        gain: gain
      };
      AL.contexts.push(context);
      return AL.contexts.length;
    } else {
      return 0;
    }
  },

  alGetError: function() {
    if (!AL.currentContext) {
      return 0xA004 /* AL_INVALID_OPERATION */;
    } else {
      // Reset error on get.
      var err = AL.currentContext.err;
      AL.currentContext.err = 0 /* AL_NO_ERROR */;
      return err;
    }
  },

  alcGetError: function(device) {
    var err = AL.alcErr;
    AL.alcErr = 0;
    return err;
  },

  alcGetIntegerv: function(device, param, size, data) {
    if (size == 0 || !data) {
      AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
      return;
    }

    switch(param) {
    case 0x1000 /* ALC_MAJOR_VERSION */:
      {{{ makeSetValue('data', '0', '1', 'i32') }}};
      break;
    case 0x1001 /* ALC_MINOR_VERSION */:
      {{{ makeSetValue('data', '0', '1', 'i32') }}};
      break;
    case 0x1002 /* ALC_ATTRIBUTES_SIZE */:
      if (!device) {
        AL.alcErr = 0xA001 /* ALC_INVALID_DEVICE */;
        return 0;
      }
      {{{ makeSetValue('data', '0', '1', 'i32') }}};
      break;
    case 0x1003 /* ALC_ALL_ATTRIBUTES */:
      if (!device) {
        AL.alcErr = 0xA001 /* ALC_INVALID_DEVICE */;
        return 0;
      }
      {{{ makeSetValue('data', '0', '0', 'i32') }}};
      break;
    case 0x20003 /* ALC_MAX_AUXILIARY_SENDS */:
      if (!device) {
        AL.currentContext.err = 0xA001 /* ALC_INVALID_DEVICE */;
        return 0;
      }
      {{{ makeSetValue('data', '0', '1', 'i32') }}};
    default:
#if OPENAL_DEBUG
      console.log("alcGetIntegerv with param " + param + " not implemented yet");
#endif
      AL.alcErr = 0xA003 /* ALC_INVALID_ENUM */;
      break;
    }
  },

  alDeleteSources: function(count, sources) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alDeleteSources called without a valid context");
#endif
      return;
    }
    for (var i = 0; i < count; ++i) {
      var sourceIdx = {{{ makeGetValue('sources', 'i*4', 'i32') }}};
      delete AL.currentContext.src[sourceIdx];
    }
  },

  alGenSources: function(count, sources) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGenSources called without a valid context");
#endif
      return;
    }
    for (var i = 0; i < count; ++i) {
      var gain = AL.currentContext.ctx.createGain();
      gain.connect(AL.currentContext.gain);
      AL.currentContext.src[AL.newSrcId] = {
        state: 0x1011 /* AL_INITIAL */,
        queue: [],
        loop: false,
        get refDistance() {
          return this._refDistance || 1;
        },
        set refDistance(val) {
          this._refDistance = val;
          if (this.panner) this.panner.refDistance = val;
        },
        get maxDistance() {
          return this._maxDistance || 10000;
        },
        set maxDistance(val) {
          this._maxDistance = val;
          if (this.panner) this.panner.maxDistance = val;
        },
        get rolloffFactor() {
          return this._rolloffFactor || 1;
        },
        set rolloffFactor(val) {
          this._rolloffFactor = val;
          if (this.panner) this.panner.rolloffFactor = val;
        },
        get position() {
          return this._position || [0, 0, 0];
        },
        set position(val) {
          this._position = val;
          if (this.panner) this.panner.setPosition(val[0], val[1], val[2]);
        },
        get velocity() {
          return this._velocity || [0, 0, 0];
        },
        set velocity(val) {
          this._velocity = val;
          if (this.panner) this.panner.setVelocity(val[0], val[1], val[2]);
        },
        get direction() {
          return this._direction || [0, 0, 0];
        },
        set direction(val) {
          this._direction = val;
          if (this.panner) this.panner.setOrientation(val[0], val[1], val[2]);
        },
        get coneOuterGain() {
          return this._coneOuterGain || 0.0;
        },
        set coneOuterGain(val) {
          this._coneOuterGain = val;
          if (this.panner) this.panner.coneOuterGain = val;
        },
        get coneInnerAngle() {
          return this._coneInnerAngle || 360.0;
        },
        set coneInnerAngle(val) {
          this._coneInnerAngle = val;
          if (this.panner) this.panner.coneInnerAngle = val;
        },
        get coneOuterAngle() {
          return this._coneOuterAngle || 360.0;
        },
        set coneOuterAngle(val) {
          this._coneOuterAngle = val;
          if (this.panner) this.panner.coneOuterAngle = val;
        },
        gain: gain,
        panner: null,
        buffersPlayed: 0,
        bufferPosition: 0
      };
      {{{ makeSetValue('sources', 'i*4', 'AL.newSrcId', 'i32') }}};
      AL.newSrcId++;
    }
  },

  alIsSource: function(sourceId) {
    if (!AL.currentContext) {
      return false;
    }

    if (!AL.currentContext.src[sourceId]) {
      return false;
    } else {
      return true;
    }
  },

  alSourcei: function(source, param, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourcei called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourcei called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    case 0x1001 /* AL_CONE_INNER_ANGLE */:
      src.coneInnerAngle = value;
      break;
    case 0x1002 /* AL_CONE_OUTER_ANGLE */:
      src.coneOuterAngle = value;
      break;
    case 0x1007 /* AL_LOOPING */:
      src.loop = (value === 1 /* AL_TRUE */);
      break;
    case 0x1009 /* AL_BUFFER */:
      var buffer = AL.currentContext.buf[value - 1];
      if (value == 0) {
        src.queue = [];
      } else {
        src.queue = [{ buffer: buffer }];
      }
      AL.updateSource(src);
      break;
    case 0x202 /* AL_SOURCE_RELATIVE */:
      if (value === 1 /* AL_TRUE */) {
        if (src.panner) {
          src.panner = null;

          // Disconnect from the panner.
          src.gain.disconnect();

          src.gain.connect(AL.currentContext.ctx.destination);
        }
      } else if (value === 0 /* AL_FALSE */) {
        if (!src.panner) {
          var panner = src.panner = AL.currentContext.ctx.createPanner();
          panner.panningModel = "equalpower";
          panner.distanceModel = "linear";
          panner.refDistance = src.refDistance;
          panner.maxDistance = src.maxDistance;
          panner.rolloffFactor = src.rolloffFactor;
          panner.setPosition(src.position[0], src.position[1], src.position[2]);
          panner.setVelocity(src.velocity[0], src.velocity[1], src.velocity[2]);
          panner.connect(AL.currentContext.ctx.destination);

          // Disconnect from the default source.
          src.gain.disconnect();

          src.gain.connect(panner);
        }
      } else {
        AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
      }
      break;
    default:
#if OPENAL_DEBUG
      console.log("alSourcei with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alSourcef: function(source, param, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourcef called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourcef called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    case 0x1003 /* AL_PITCH */:
#if OPENAL_DEBUG
      console.log("alSourcef was called with 0x1003 /* AL_PITCH */, but Web Audio does not support static pitch changes");
#endif
      break;
    case 0x100A /* AL_GAIN */:
      src.gain.gain.value = value;
      break;
    // case 0x100D /* AL_MIN_GAIN */:
    //   break;
    // case 0x100E /* AL_MAX_GAIN */:
    //   break;
    case 0x1023 /* AL_MAX_DISTANCE */:
      src.maxDistance = value;
      break;
    case 0x1021 /* AL_ROLLOFF_FACTOR */:
      src.rolloffFactor = value;
      break;
    case 0x1022 /* AL_CONE_OUTER_GAIN */:
      src.coneOuterGain = value;
      break;
    case 0x1001 /* AL_CONE_INNER_ANGLE */:
      src.coneInnerAngle = value;
      break;
    case 0x1002 /* AL_CONE_OUTER_ANGLE */:
      src.coneOuterAngle = value;
      break;
    case 0x1020 /* AL_REFERENCE_DISTANCE */:
      src.refDistance = value;
      break;
    default:
#if OPENAL_DEBUG
      console.log("alSourcef with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alSource3i: ['alSource3f'],
  alSource3i: function(source, param, v1, v2, v3) {
    _alSource3f(source, param, v1, v2, v3);
  },

  alSource3f: function(source, param, v1, v2, v3) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSource3f called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSource3f called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    case 0x1004 /* AL_POSITION */:
      src.position = [v1, v2, v3];
      break;
    case 0x1005 /* AL_DIRECTION */:
      src.direction = [v1, v2, v3];
      break;
    case 0x1006 /* AL_VELOCITY */:
      src.velocity = [v1, v2, v3];
      break;
    default:
#if OPENAL_DEBUG
      console.log("alSource3f with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alSourcefv__deps: ['alSource3f'],
  alSourcefv: function(source, param, value) {
    _alSource3f(source, param,
      {{{ makeGetValue('value', '0', 'float') }}},
      {{{ makeGetValue('value', '4', 'float') }}},
      {{{ makeGetValue('value', '8', 'float') }}});
  },

  alSourceQueueBuffers: function(source, count, buffers) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourceQueueBuffers called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourceQueueBuffers called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    for (var i = 0; i < count; ++i) {
      var bufferIdx = {{{ makeGetValue('buffers', 'i*4', 'i32') }}};
      if (bufferIdx > AL.currentContext.buf.length) {
#if OPENAL_DEBUG
        console.error("alSourceQueueBuffers called with an invalid buffer");
#endif
        AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
        return;
      }
    }

    for (var i = 0; i < count; ++i) {
      var bufferIdx = {{{ makeGetValue('buffers', 'i*4', 'i32') }}};
      var buffer = AL.currentContext.buf[bufferIdx - 1];
      src.queue.push({ buffer: buffer, src: null });
    }

    AL.updateSource(src);
  },

  alSourceUnqueueBuffers: function(source, count, buffers) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourceUnqueueBuffers called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourceUnqueueBuffers called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }

    if (count > src.buffersPlayed) {
      AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
      return;
    }

    for (var i = 0; i < count; i++) {
      var entry = src.queue.shift();
      // Write the buffers index out to the return list.
      for (var j = 0; j < AL.currentContext.buf.length; j++) {
        var b = AL.currentContext.buf[j];
        if (b && b == entry.buffer) {
          {{{ makeSetValue('buffers', 'i*4', 'j+1', 'i32') }}};
          break;
        }
      }
      src.buffersPlayed--;
    }

    AL.updateSource(src);
  },

  alDeleteBuffers: function(count, buffers)
  {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alDeleteBuffers called without a valid context");
#endif
      return;
    }
    if (count > AL.currentContext.buf.length) {
      AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
      return;
    }

    for (var i = 0; i < count; ++i) {
      var bufferIdx = {{{ makeGetValue('buffers', 'i*4', 'i32') }}} - 1;

      // Make sure the buffer index is valid.
      if (bufferIdx >= AL.currentContext.buf.length || !AL.currentContext.buf[bufferIdx]) {
        AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
        return;
      }

      // Make sure the buffer is no longer in use.
      var buffer = AL.currentContext.buf[bufferIdx];
      for (var srcId in AL.currentContext.src) {
        var src = AL.currentContext.src[srcId];
        if (!src) {
          continue;
        }
        for (var k = 0; k < src.queue.length; k++) {
          if (buffer === src.queue[k].buffer) {
            AL.currentContext.err = 0xA004 /* AL_INVALID_OPERATION */;
            return;
          }
        }
      }
    }

    for (var i = 0; i < count; ++i) {
      var bufferIdx = {{{ makeGetValue('buffers', 'i*4', 'i32') }}} - 1;
      delete AL.currentContext.buf[bufferIdx];
    }
  },

  alGenBuffers: function(count, buffers) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGenBuffers called without a valid context");
#endif
      return;
    }
    for (var i = 0; i < count; ++i) {
      AL.currentContext.buf.push(null);
      {{{ makeSetValue('buffers', 'i*4', 'AL.currentContext.buf.length', 'i32') }}};
    }
  },

  alIsBuffer: function(bufferId) {
    if (!AL.currentContext) {
      return false;
    }
    if (bufferId > AL.currentContext.buf.length) {
      return false;
    }

    if (!AL.currentContext.buf[bufferId - 1]) {
      return false;
    } else {
      return true;
    }
  },

  alBufferData: function(buffer, format, data, size, freq) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alBufferData called without a valid context");
#endif
      return;
    }
    if (buffer > AL.currentContext.buf.length) {
#if OPENAL_DEBUG
      console.error("alBufferData called with an invalid buffer");
#endif
      return;
    }
    var channels, bytes;
    switch (format) {
    case 0x1100 /* AL_FORMAT_MONO8 */:
      bytes = 1;
      channels = 1;
      break;
    case 0x1101 /* AL_FORMAT_MONO16 */:
      bytes = 2;
      channels = 1;
      break;
    case 0x1102 /* AL_FORMAT_STEREO8 */:
      bytes = 1;
      channels = 2;
      break;
    case 0x1103 /* AL_FORMAT_STEREO16 */:
      bytes = 2;
      channels = 2;
      break;
    case 0x10010 /* AL_FORMAT_MONO_FLOAT32 */:
      bytes = 4;
      channels = 1;
      break;
    case 0x10011 /* AL_FORMAT_STEREO_FLOAT32 */:
      bytes = 4;
      channels = 2;
      break;
    default:
#if OPENAL_DEBUG
      console.error("alBufferData called with invalid format " + format);
#endif
      return;
    }
    try {
      AL.currentContext.buf[buffer - 1] = AL.currentContext.ctx.createBuffer(channels, size / (bytes * channels), freq);
      AL.currentContext.buf[buffer - 1].bytesPerSample =  bytes;
    } catch (e) {
      AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
      return;
    }
    var buf = new Array(channels);
    for (var i = 0; i < channels; ++i) {
      buf[i] = AL.currentContext.buf[buffer - 1].getChannelData(i);
    }
    for (var i = 0; i < size / (bytes * channels); ++i) {
      for (var j = 0; j < channels; ++j) {
        switch (bytes) {
        case 1:
          var val = {{{ makeGetValue('data', 'i*channels+j', 'i8') }}} & 0xff;  // unsigned
          buf[j][i] = -1.0 + val * (2/256);
          break;
        case 2:
          var val = {{{ makeGetValue('data', '2*(i*channels+j)', 'i16') }}};
          buf[j][i] = val/32768;
          break;
        case 4:
          buf[j][i] = {{{ makeGetValue('data', '4*(i*channels+j)', 'float') }}};
          break;
        }
      }
    }
  },

  alGetBufferi: function(buffer, param, value)
  {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetBufferi called without a valid context");
#endif
      return;
    }
    var buf = AL.currentContext.buf[buffer - 1];
    if (!buf) {
#if OPENAL_DEBUG
      console.error("alGetBufferi called with an invalid buffer");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    case 0x2001 /* AL_FREQUENCY */:
      {{{ makeSetValue('value', '0', 'buf.sampleRate', 'i32') }}};
      break;
    case 0x2002 /* AL_BITS */:
      {{{ makeSetValue('value', '0', 'buf.bytesPerSample * 8', 'i32') }}};
      break;
    case 0x2003 /* AL_CHANNELS */:
      {{{ makeSetValue('value', '0', 'buf.numberOfChannels', 'i32') }}};
      break;
    case 0x2004 /* AL_SIZE */:
      {{{ makeSetValue('value', '0', 'buf.length * buf.bytesPerSample * buf.numberOfChannels', 'i32') }}};
      break;
    default:
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alSourcePlay__deps: ['setSourceState'],
  alSourcePlay: function(source) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourcePlay called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourcePlay called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    AL.setSourceState(src, 0x1012 /* AL_PLAYING */);
  },

  alSourceStop__deps: ['setSourceState'],
  alSourceStop: function(source) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourceStop called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourceStop called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    AL.setSourceState(src, 0x1014 /* AL_STOPPED */);
  },

  alSourceRewind__deps: ['setSourceState'],
  alSourceRewind: function(source) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourceRewind called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourceRewind called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    // Stop the source first to clear the source queue
    AL.setSourceState(src, 0x1014 /* AL_STOPPED */);
    // Now set the state of AL_INITIAL according to the specification
    AL.setSourceState(src, 0x1011 /* AL_INITIAL */);
  },

  alSourcePause__deps: ['setSourceState'],
  alSourcePause: function(source) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alSourcePause called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alSourcePause called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    AL.setSourceState(src, 0x1013 /* AL_PAUSED */);
  },

  alGetSourcei: function(source, param, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetSourcei called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alGetSourcei called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }

    // Being that we have no way to receive end events from buffer nodes,
    // we currently proccess and update a source's buffer queue every
    // ~QUEUE_INTERVAL milliseconds. However, this interval is not precise,
    // so we also forcefully update the source when alGetSourcei is queried
    // to aid in the common scenario of application calling alGetSourcei(AL_BUFFERS_PROCESSED)
    // to recycle buffers.
    AL.updateSource(src);

    switch (param) {
    case 0x202 /* AL_SOURCE_RELATIVE */:
      {{{ makeSetValue('value', '0', 'src.panner ? 1 : 0', 'i32') }}};
      break;
    case 0x1001 /* AL_CONE_INNER_ANGLE */:
      {{{ makeSetValue('value', '0', 'src.coneInnerAngle', 'i32') }}};
      break;
    case 0x1002 /* AL_CONE_OUTER_ANGLE */:
      {{{ makeSetValue('value', '0', 'src.coneOuterAngle', 'i32') }}};
      break;
    case 0x1009 /* AL_BUFFER */:
      if (!src.queue.length) {
        {{{ makeSetValue('value', '0', '0', 'i32') }}};
      } else {
        // Find the first unprocessed buffer.
        var buffer = src.queue[src.buffersPlayed].buffer;
        // Return its index.
        for (var i = 0; i < AL.currentContext.buf.length; ++i) {
          if (buffer == AL.currentContext.buf[i]) {
            {{{ makeSetValue('value', '0', 'i+1', 'i32') }}};
            return;
          }
        }
        {{{ makeSetValue('value', '0', '0', 'i32') }}};
      }
      break;
    case 0x1010 /* AL_SOURCE_STATE */:
      {{{ makeSetValue('value', '0', 'src.state', 'i32') }}};
      break;
    case 0x1015 /* AL_BUFFERS_QUEUED */:
      {{{ makeSetValue('value', '0', 'src.queue.length', 'i32') }}}
      break;
    case 0x1016 /* AL_BUFFERS_PROCESSED */:
      if (src.loop) {
        {{{ makeSetValue('value', '0', '0', 'i32') }}}
      } else {
        {{{ makeSetValue('value', '0', 'src.buffersPlayed', 'i32') }}}
      }
      break;
    default:
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alGetSourcef: function(source, param, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetSourcef called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alGetSourcef called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    // case 0x1003 /* AL_PITCH */:
    //   break;
    case 0x100A /* AL_GAIN */:
      {{{ makeSetValue('value', '0', 'src.gain.gain.value', 'float') }}}
      break;
    // case 0x100D /* AL_MIN_GAIN */:
    //   break;
    // case 0x100E /* AL_MAX_GAIN */:
    //   break;
    case 0x1023 /* AL_MAX_DISTANCE */:
      {{{ makeSetValue('value', '0', 'src.maxDistance', 'float') }}}
      break;
    case 0x1021 /* AL_ROLLOFF_FACTOR */:
      {{{ makeSetValue('value', '0', 'src.rolloffFactor', 'float') }}}
      break;
    case 0x1022 /* AL_CONE_OUTER_GAIN */:
      {{{ makeSetValue('value', '0', 'src.coneOuterGain', 'float') }}}
      break;
    case 0x1001 /* AL_CONE_INNER_ANGLE */:
      {{{ makeSetValue('value', '0', 'src.coneInnerAngle', 'float') }}}
      break;
    case 0x1002 /* AL_CONE_OUTER_ANGLE */:
      {{{ makeSetValue('value', '0', 'src.coneOuterAngle', 'float') }}}
      break;
    case 0x1020 /* AL_REFERENCE_DISTANCE */:
      {{{ makeSetValue('value', '0', 'src.refDistance', 'float') }}}
      break;
    // case 0x1024 /* AL_SEC_OFFSET */:
    //   break;
    // case 0x1025 /* AL_SAMPLE_OFFSET */:
    //   break;
    // case 0x1026 /* AL_BYTE_OFFSET */:
    //   break;
    default:
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alGetSourcefv: function(source, param, values) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetSourcefv called without a valid context");
#endif
      return;
    }
    var src = AL.currentContext.src[source];
    if (!src) {
#if OPENAL_DEBUG
      console.error("alGetSourcefv called with an invalid source");
#endif
      AL.currentContext.err = 0xA001 /* AL_INVALID_NAME */;
      return;
    }
    switch (param) {
    case 0x1004 /* AL_POSITION */:
      var position = src.position;
      {{{ makeSetValue('values', '0', 'position[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'position[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'position[2]', 'float') }}}
      break;
    case 0x1005 /* AL_DIRECTION */:
      var direction = src.direction;
      {{{ makeSetValue('values', '0', 'direction[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'direction[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'direction[2]', 'float') }}}
      break;
    case 0x1006 /* AL_VELOCITY */:
      var velocity = src.velocity;
      {{{ makeSetValue('values', '0', 'velocity[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'velocity[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'velocity[2]', 'float') }}}
      break;
    default:
#if OPENAL_DEBUG
      console.error("alGetSourcefv with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alDistanceModel: function(model) {
    if (model !== 0 /* AL_NONE */) {
#if OPENAL_DEBUG
      console.log("Only alDistanceModel(AL_NONE) is currently supported");
#endif
    }
  },

  alGetListenerf: function(pname, values) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetListenerf called without a valid context");
#endif
      return;
    }
    switch (pname) {
    case 0x100A /* AL_GAIN */:
      {{{ makeSetValue('value', '0', 'AL.currentContext.gain.gain', 'float') }}}
      break;
    default:
#if OPENAL_DEBUG
      console.error("alGetListenerf with param " + pname + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }

  },

  alGetListenerfv: function(pname, values) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetListenerfv called without a valid context");
#endif
      return;
    }
    switch (pname) {
    case 0x1004 /* AL_POSITION */:
      var position = AL.currentContext.ctx.listener._position || [0,0,0];
      {{{ makeSetValue('values', '0', 'position[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'position[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'position[2]', 'float') }}}
      break;
    case 0x1006 /* AL_VELOCITY */:
      var velocity = AL.currentContext.ctx.listener._velocity || [0,0,0];
      {{{ makeSetValue('values', '0', 'velocity[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'velocity[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'velocity[2]', 'float') }}}
      break;
    case 0x100F /* AL_ORIENTATION */:
      var orientation = AL.currentContext.ctx.listener._orientation || [0,0,0,0,0,0];
      {{{ makeSetValue('values', '0', 'orientation[0]', 'float') }}}
      {{{ makeSetValue('values', '4', 'orientation[1]', 'float') }}}
      {{{ makeSetValue('values', '8', 'orientation[2]', 'float') }}}
      {{{ makeSetValue('values', '12', 'orientation[3]', 'float') }}}
      {{{ makeSetValue('values', '16', 'orientation[4]', 'float') }}}
      {{{ makeSetValue('values', '20', 'orientation[5]', 'float') }}}
      break;
    default:
#if OPENAL_DEBUG
      console.error("alGetListenerfv with param " + pname + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alGetListeneri: function(pname, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alGetListeneri called without a valid context");
#endif
      return;
    }
    switch (pname) {
    default:
#if OPENAL_DEBUG
      console.error("alGetListeneri with param " + pname + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alListenerf: function(param, value) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alListenerf called without a valid context");
#endif
      return;
    }
    switch (param) {
    case 0x100A /* AL_GAIN */:
      AL.currentContext.gain.value = value;
      break;
    default:
#if OPENAL_DEBUG
      console.error("alListenerf with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alEnable: function(param) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alEnable called without a valid context");
#endif
      return;
    }
    switch (param) {
    default:
#if OPENAL_DEBUG
      console.error("alEnable with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alDisable: function(param) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alDisable called without a valid context");
#endif
      return;
    }
    switch (pname) {
    default:
#if OPENAL_DEBUG
      console.error("alDisable with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alListener3f: function(param, v1, v2, v3) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alListenerfv called without a valid context");
#endif
      return;
    }
    switch (param) {
    case 0x1004 /* AL_POSITION */:
      AL.currentContext.ctx.listener._position = [v1, v2, v3];
      AL.currentContext.ctx.listener.setPosition(v1, v2, v3);
      break;
    case 0x1006 /* AL_VELOCITY */:
      AL.currentContext.ctx.listener._velocity = [v1, v2, v3];
      AL.currentContext.ctx.listener.setVelocity(v1, v2, v3);
      break;
    default:
#if OPENAL_DEBUG
      console.error("alListener3f with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alListenerfv: function(param, values) {
    if (!AL.currentContext) {
#if OPENAL_DEBUG
      console.error("alListenerfv called without a valid context");
#endif
      return;
    }
    switch (param) {
    case 0x1004 /* AL_POSITION */:
      var x = {{{ makeGetValue('values', '0', 'float') }}};
      var y = {{{ makeGetValue('values', '4', 'float') }}};
      var z = {{{ makeGetValue('values', '8', 'float') }}};
      AL.currentContext.ctx.listener._position = [x, y, z];
      AL.currentContext.ctx.listener.setPosition(x, y, z);
      break;
    case 0x1006 /* AL_VELOCITY */:
      var x = {{{ makeGetValue('values', '0', 'float') }}};
      var y = {{{ makeGetValue('values', '4', 'float') }}};
      var z = {{{ makeGetValue('values', '8', 'float') }}};
      AL.currentContext.ctx.listener._velocity = [x, y, z];
      AL.currentContext.ctx.listener.setVelocity(x, y, z);
      break;
    case 0x100F /* AL_ORIENTATION */:
      var x = {{{ makeGetValue('values', '0', 'float') }}};
      var y = {{{ makeGetValue('values', '4', 'float') }}};
      var z = {{{ makeGetValue('values', '8', 'float') }}};
      var x2 = {{{ makeGetValue('values', '12', 'float') }}};
      var y2 = {{{ makeGetValue('values', '16', 'float') }}};
      var z2 = {{{ makeGetValue('values', '20', 'float') }}};
      AL.currentContext.ctx.listener._orientation = [x, y, z, x2, y2, z2];
      AL.currentContext.ctx.listener.setOrientation(x, y, z, x2, y2, z2);
      break;
    default:
#if OPENAL_DEBUG
      console.error("alListenerfv with param " + param + " not implemented yet");
#endif
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      break;
    }
  },

  alIsExtensionPresent: function(extName) {
    extName = Pointer_stringify(extName);

    if (extName == "AL_EXT_float32") return 1;

    return 0;
  },

  alcIsExtensionPresent: function(device, extName) {
    return 0;
  },

  alGetString: function(param) {
    if (AL.stringCache[param]) return AL.stringCache[param];
    var ret;
    switch (param) {
    case 0 /* AL_NO_ERROR */:
      ret = 'No Error';
      break;
    case 0xA001 /* AL_INVALID_NAME */:
      ret = 'Invalid Name';
      break;
    case 0xA002 /* AL_INVALID_ENUM */:
      ret = 'Invalid Enum';
      break;
    case 0xA003 /* AL_INVALID_VALUE */:
      ret = 'Invalid Value';
      break;
    case 0xA004 /* AL_INVALID_OPERATION */:
      ret = 'Invalid Operation';
      break;
    case 0xA005 /* AL_OUT_OF_MEMORY */:
      ret = 'Out of Memory';
      break;
    case 0xB001 /* AL_VENDOR */:
      ret = 'Emscripten';
      break;
    case 0xB002 /* AL_VERSION */:
      ret = '1.1';
      break;
    case 0xB003 /* AL_RENDERER */:
      ret = 'WebAudio';
      break;
    case 0xB004 /* AL_EXTENSIONS */:
      ret = 'AL_EXT_float32';
      break;
    default:
      AL.currentContext.err = 0xA002 /* AL_INVALID_ENUM */;
      return 0;
    }

    ret = allocate(intArrayFromString(ret), 'i8', ALLOC_NORMAL);

    AL.stringCache[param] = ret;

    return ret;
  },

  alGetProcAddress: function(fname) {
    return 0;
  },

  alcGetString: function(device, param) {
    if (AL.alcStringCache[param]) return AL.alcStringCache[param];
    var ret;
    switch (param) {
    case 0 /* ALC_NO_ERROR */:
      ret = 'No Error';
      break;
    case 0xA001 /* ALC_INVALID_DEVICE */:
      ret = 'Invalid Device';
      break;
    case 0xA002 /* ALC_INVALID_CONTEXT */:
      ret = 'Invalid Context';
      break;
    case 0xA003 /* ALC_INVALID_ENUM */:
      ret = 'Invalid Enum';
      break;
    case 0xA004 /* ALC_INVALID_VALUE */:
      ret = 'Invalid Value';
      break;
    case 0xA005 /* ALC_OUT_OF_MEMORY */:
      ret = 'Out of Memory';
      break;
    case 0x1004 /* ALC_DEFAULT_DEVICE_SPECIFIER */:
      if (typeof(AudioContext) !== "undefined" ||
          typeof(webkitAudioContext) !== "undefined") {
        ret = 'Device';
      } else {
        return 0;
      }
      break;
    case 0x1005 /* ALC_DEVICE_SPECIFIER */:
      if (typeof(AudioContext) !== "undefined" ||
          typeof(webkitAudioContext) !== "undefined") {
        ret = 'Device\0';
      } else {
        ret = '\0';
      }
      break;
    case 0x311 /* ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER */:
      return 0;
      break;
    case 0x310 /* ALC_CAPTURE_DEVICE_SPECIFIER */:
      ret = '\0'
      break;
    case 0x1006 /* ALC_EXTENSIONS */:
      if (!device) {
        AL.alcErr = 0xA001 /* ALC_INVALID_DEVICE */;
        return 0;
      }
      ret = '';
      break;
    default:
      AL.alcErr = 0xA003 /* ALC_INVALID_ENUM */;
      return 0;
    }

    ret = allocate(intArrayFromString(ret), 'i8', ALLOC_NORMAL);

    AL.alcStringCache[param] = ret;

    return ret;
  },

  alcGetProcAddress: function(device, fname) {
    return 0;
  },

  alGetEnumValue: function(name) {
    name = Pointer_stringify(name);

    if (name == "AL_FORMAT_MONO_FLOAT32") return 0x10010;
    if (name == "AL_FORMAT_STEREO_FLOAT32") return 0x10011;

    AL.currentContext.err = 0xA003 /* AL_INVALID_VALUE */;
    return 0;
  },

  alSpeedOfSound: function(value) {
    Runtime.warnOnce('alSpeedOfSound() is not yet implemented! Ignoring all calls to it.');
  },

  alDopplerFactor: function(value) {
    Runtime.warnOnce('alDopplerFactor() is not yet implemented! Ignoring all calls to it.');
  },

  alDopplerVelocity: function(value) {
    Runtime.warnOnce('alDopplerVelocity() is not yet implemented! Ignoring all calls to it.');
  }
};

autoAddDeps(LibraryOpenAL, '$AL');
mergeInto(LibraryManager.library, LibraryOpenAL);


text:
Poeng

Byoversikt

Statistikk

Wiki

Chat

Support

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
        Toggle navigation

      </button>
      Mafiasquad

    <?php if($page == "logginn" || $page == "registrer") { ?>

                <form class="form-inline">

                        Email address
                        <input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">

                        Password
                        <input type="password" class="form-control" id="exampleInputPassword3" placeholder="Password">

                            <input type="checkbox"> Remember me

                    <button type="submit" class="btn btn-gradient">Sign in</button>
                </form>

    <?php } else { ?>

          Brukernavn

Min profil

Rediger profil

Logg ut

      <?php } ?>


text:
function d = greatCircleDistance(phi_s, lambda_s, phi_f, lambda_f, r)
% compute the great circle distance given lat and long for two points
% optionally, a fifth parameter (r) can be specified. If this paramter
% isn't specified it's assumed to be the mean radius of the earth. The
% calculation is done using the Vincenty formula.
%
% INPUTS:
% phi_s    = latitude of the standpoint (base) [rad]
% lambda_s = longitude of the standpoint (base) [rad]
% phi_f    = latitude of the forepoint (destination) [rad]
% lambda_f = longitude of the forepoint (destination) [rad]
% r        = radius of the sphere [units determine units of d]
%
% OUTPUT:
% d        = great circle distance from standpoint to forepoint
%
% See http://en.wikipedia.org/wiki/Great-circle_distance

% If no arguments, bail out
if nargin < 4
    fprintf('Usage: greatCircleDistance(phi_s, lambda_s, phi_f, lambda_f, r)\n')
    return
end

% If no radius supplied, assume the mean radius of the earth in km
if nargin < 5
    r = 6371.01; % km
end

% Compute Delta lambda (delta longitude)
Delta_lambda = lambda_f - lambda_s;

% Compute Delta sigma (central angle)
Delta_sigma = atan2(sqrt((cos(phi_f).*sin(Delta_lambda)).^2 + (cos(phi_s).*sin(phi_f) - sin(phi_s).*cos(phi_f).*cos(Delta_lambda)).^2), ...
    sin(phi_s).*sin(phi_f) + cos(phi_s).*cos(phi_f).*cos(Delta_lambda));

d = r*Delta_sigma;

end


text:
package spray.contrib.socketio

import akka.actor.{ Actor, ActorLogging, Props }

object TransientConnectionSession {
  def props(): Props = Props(classOf[TransientConnectionSession])
}

final class TransientConnectionSession() extends ConnectionSession with Actor with ActorLogging {
  def recoveryFinished: Boolean = true
  def recoveryRunning: Boolean = false

  def receive: Receive = working
}


text:
if(VARIABLES.SourceDatabase) {
/*~
USE $VARIABLES.SourceDatabase;
GO
~*/
}


text:
export BOOST_ROOT="${PREFIX}"
export PKG_CONFIG_LIBDIR="${PREFIX}"/lib/pkgconfig

# HDF5 doesn't have pkgconfig files yet
export CPPFLAGS+=" -isystem ${PREFIX}/include"
export LDFLAGS+=" -L${PREFIX}/lib -lhdf5_cpp -lhdf5"

# required for Meson's sanity check
export LD_LIBRARY_PATH="${PREFIX}/lib"
export DYLD_FALLBACK_LIBRARY_PATH="${PREFIX}/lib"

# configure
# '--wrap-mode nofallback' prevents meson from downloading
# stuff from the internet or using subprojects.
meson \
  --default-library static \
  --libdir lib \
  --wrap-mode nofallback \
  --prefix "${PREFIX}" \
  -Dtests=false \
  build .

# build
ninja -C build -v

# install
ninja -C build -v install


text:
package com.etiennelawlor.quickreturn.itemdecorations;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by etiennelawlor on 1/31/15.
 */
public class GridSpacesItemDecoration extends RecyclerView.ItemDecoration {

    // region Member Variables
    private int mSpace;
    // endregion

    // region Constructors
    public GridSpacesItemDecoration(int space) {
        this.mSpace = space;
    }
    // endregion

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int childPosition = parent.getChildAdapterPosition(view);
        if (childPosition == 0 || childPosition == 1) {
            outRect.top = mSpace;
        }

        if (childPosition % 2 == 0) {
            outRect.left = mSpace;
            outRect.right = mSpace / 2;
        } else {
            outRect.left = mSpace / 2;
            outRect.right = mSpace;
        }

        outRect.bottom = mSpace;
    }
}


text:
Painter::Painter() : _window_width(800), _window_height(600)
{
	init_do_SDL_calls();

	glewExperimental = GL_TRUE;
	GLenum glewstatus = glewInit();
	assertf(glewstatus == GLEW_OK, "%s", glewGetErrorString(glewstatus));

	opengl.Construct(_window_width, _window_height);
}

void Painter::Update(unsigned int dt, unsigned int t)
{
	opengl.Update(dt, t);
}

void Painter::Draw()
{
	opengl.Draw();

	SDL_GL_SwapWindow(_window);
}

void Painter::init_do_SDL_calls()
{
	SDL_Init(SDL_INIT_EVERYTHING);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

	_window = SDL_CreateWindow("Spacie",
			SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
			_window_width, _window_height,
			SDL_WINDOW_OPENGL);

	_gl_context = SDL_GL_CreateContext(_window);
}

Painter::~Painter()
{
	SDL_GL_DeleteContext(_gl_context);

	SDL_Quit();
}


text:
<?php
return array (
  'API Connection successful!' => 'Připojení k API bylo úspěšné!',
  'Back to modules' => 'Zpět na přehled modulů',
  'Could not connect to API!' => 'Nebylo možné se připojit k API!',
  'Current Status:' => 'Aktuální stav:',
  'Notes Module Configuration' => 'Nastavení modulu Poznámky',
  'Please read the module documentation under /protected/modules/notes/docs/install.txt for more details!' => 'Pro více informací si prosím přečtěte dokumentaci modulu v /protected/modules/notes/docs/install.txt',
  'Save & Test' => 'Uložit a vyzkoušet',
  'The notes module needs a etherpad server up and running!' => 'Modul Poznámky vyžaduje ke svému provozu běžící etherpad server!',
);


text:
#ifndef MONGOC_CLIENT_POOL_H
#define MONGOC_CLIENT_POOL_H

#if !defined (MONGOC_INSIDE) && !defined (MONGOC_COMPILATION)
# error "Only <mongoc.h> can be included directly."
#endif

#include <bson.h>

#include "mongoc-client.h"
#include "mongoc-config.h"
#ifdef MONGOC_ENABLE_SSL
# include "mongoc-ssl.h"
#endif
#include "mongoc-uri.h"

BSON_BEGIN_DECLS

typedef struct _mongoc_client_pool_t mongoc_client_pool_t;

mongoc_client_pool_t *mongoc_client_pool_new     (const mongoc_uri_t   *uri);
void                  mongoc_client_pool_destroy (mongoc_client_pool_t *pool);
mongoc_client_t      *mongoc_client_pool_pop     (mongoc_client_pool_t *pool);
void                  mongoc_client_pool_push    (mongoc_client_pool_t *pool,
                                                  mongoc_client_t      *client);
mongoc_client_t      *mongoc_client_pool_try_pop (mongoc_client_pool_t *pool);
#ifdef MONGOC_ENABLE_SSL
void                  mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t   *pool,
                                                       const mongoc_ssl_opt_t *opts);
#endif

BSON_END_DECLS

#endif /* MONGOC_CLIENT_POOL_H */


text:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.glamenv-setpzen.demo</groupId>
  <artifactId>java-loggers-samples</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Java Loggers Sample Code</name>
  <url>https://github.com/msakamoto-sf/java-loggers-samples</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>11</java.version>
  </properties>

  <modules>
    <module>jul-default-demo</module>
    <module>jul-globalconf-byfile</module>
    <module>jul-globalconf-byclass</module>
    <module>jul-create-logger</module>
    <module>logback-conf-xml</module>
    <module>logback-conf-groovy</module>
    <module>logback-create-logger</module>
    <module>logback-sift-demo</module>
  </modules>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
      </dependency>
      <!--
      logback-classic の pom を確認すると groovy-all について scope:compile, optional:true で依存している。
      https://search.maven.org/artifact/ch.qos.logback/logback-classic/1.2.3/jar
      → groovyファイルによる設定を使うときは groovy-all を依存関係に明示的に追加する必要がある。

      バージョンについては logback-parent 側のpomで 2.4.0 を利用しているため、2.4系最新を使えば問題無さそう。
      https://search.maven.org/artifact/ch.qos.logback/logback-parent/1.2.3/pom
      -->
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.4.21</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
          <configuration>
            <debug>true</debug>
            <encoding>${project.build.sourceEncoding}</encoding>
            <source>${java.version}</source>
            <target>${java.version}</target>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.4</version>

          <!--
          shade plugin は jar 用のプロジェクトで動作する。
          そのため parent の pom 用プロジェクトで executions の設定をしても、子プロジェクトでは参照されず、shade pluginは動作しない。
          → configuration のみ親で設定し、executions は各子プロジェクトのpom.xmlで設定する。
          ref-1: https://stackoverflow.com/questions/21021485/how-to-configure-maven-shade-plugin-in-a-multi-module-project
          ref-2: http://blog.nithinasokan.com/2014/05/create-shaded-uber-jar-for-maven-multi.html
          ref-3: https://kazuhira-r.hatenablog.com/entry/2020/11/23/001949
          -->

          <configuration>

            <!--
            以下のartifactのjarファイルについて、META-INF/MANIFEST.MFが衝突してしまう。
            ググっても特にこれについてのQAなどが見つからなかった。
            試しに exclude フィルタを使って除外してみたところ、今のところ問題なく動いているのでこれで様子見する。
            see: https://maven.apache.org/plugins/maven-shade-plugin/shade-mojo.html#filters
            -->
            <filters>
              <filter>
                <artifact>ch.qos.logback:*</artifact>
                <excludes>
                  <exclude>META-INF/MANIFEST.MF</exclude>
                </excludes>
              </filter>
              <filter>
                <artifact>org.slf4j:slf4j-api</artifact>
                <excludes>
                  <exclude>META-INF/MANIFEST.MF</exclude>
                </excludes>
              </filter>
              <filter>
                <artifact>org.codehaus.groovy:groovy-all</artifact>
                <excludes>
                  <exclude>META-INF/MANIFEST.MF</exclude>
                </excludes>
              </filter>
            </filters>

            <createDependencyReducedPom>false</createDependencyReducedPom>
            <transformers>
              <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                <!--
                see: https://maven.apache.org/plugins/maven-shade-plugin/examples/executable-jar.html
                -->
                <manifestEntries>
                  <Main-Class>testpkg.Main</Main-Class>
                </manifestEntries>
              </transformer>
            </transformers>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

</project>


text:
package org.apache.cassandra.distributed.test;

import java.io.IOException;
import java.io.Serializable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import org.apache.cassandra.Util;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DataRange;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.PartitionPosition;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.Feature;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.IIsolatedExecutor.SerializableRunnable;
import org.apache.cassandra.distributed.impl.InstanceKiller;
import org.apache.cassandra.io.sstable.CorruptSSTableException;
import org.apache.cassandra.io.sstable.ISSTableScanner;
import org.apache.cassandra.io.sstable.format.ForwardingSSTableReader;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.sstable.format.SSTableReadsListener;
import org.apache.cassandra.io.util.ChannelProxy;
import org.apache.cassandra.net.Verb;
import org.apache.cassandra.repair.RepairParallelism;
import org.apache.cassandra.repair.messages.RepairOption;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.ActiveRepairService.ParentRepairStatus;
import org.apache.cassandra.service.StorageService;
import org.awaitility.Awaitility;

@RunWith(Parameterized.class)
public class FailingRepairTest extends TestBaseImpl implements Serializable
{
    private static ICluster<IInvokableInstance> CLUSTER;

    private final Verb messageType;
    private final RepairParallelism parallelism;
    private final boolean withTracing;
    private final SerializableRunnable setup;

    public FailingRepairTest(Verb messageType, RepairParallelism parallelism, boolean withTracing, SerializableRunnable setup)
    {
        this.messageType = messageType;
        this.parallelism = parallelism;
        this.withTracing = withTracing;
        this.setup = setup;
    }

    @Parameters(name = "{0}/{1}/{2}")
    public static Collection<Object[]> messages()
    {
        List<Object[]> tests = new ArrayList<>();
        for (RepairParallelism parallelism : RepairParallelism.values())
        {
            for (Boolean withTracing : Arrays.asList(Boolean.TRUE, Boolean.FALSE))
            {
                tests.add(new Object[]{ Verb.VALIDATION_REQ, parallelism, withTracing, failingReaders(Verb.VALIDATION_REQ, parallelism, withTracing) });
            }
        }
        return tests;
    }

    private static SerializableRunnable failingReaders(Verb type, RepairParallelism parallelism, boolean withTracing)
    {
        return () -> {
            String cfName = getCfName(type, parallelism, withTracing);
            ColumnFamilyStore cf = Keyspace.open(KEYSPACE).getColumnFamilyStore(cfName);
            Util.flush(cf);
            Set<SSTableReader> remove = cf.getLiveSSTables();
            Set<SSTableReader> replace = new HashSet<>();
            if (type == Verb.VALIDATION_REQ)
            {
                for (SSTableReader r : remove)
                    replace.add(new FailingSSTableReader(r));
            }
            else
            {
                throw new UnsupportedOperationException("verb: " + type);
            }
            cf.getTracker().removeUnsafe(remove);
            cf.addSSTables(replace);
        };
    }

    private static String getCfName(Verb type, RepairParallelism parallelism, boolean withTracing)
    {
        return type.name().toLowerCase() + "_" + parallelism.name().toLowerCase() + "_" + withTracing;
    }

    @BeforeClass
    public static void setupCluster() throws IOException
    {
        // streaming requires networking ATM
        // streaming also requires gossip or isn't setup properly
        CLUSTER = init(Cluster.build()
                              .withNodes(2)
                              .withConfig(c -> c.with(Feature.NETWORK)
                                             .with(Feature.GOSSIP)
                                             .set("disk_failure_policy", "die"))
                              .start());
        CLUSTER.setUncaughtExceptionsFilter((throwable) -> {
            if (throwable.getClass().toString().contains("InstanceShutdown") || // can't check instanceof as it is thrown by a different classloader
                throwable.getMessage() != null && throwable.getMessage().contains("Parent repair session with id"))
                return true;
            return false;
        });
    }

    @AfterClass
    public static void teardownCluster() throws Exception
    {
        if (CLUSTER != null)
            CLUSTER.close();
    }

    @Before
    public void cleanupState()
    {
        for (int i = 1; i <= CLUSTER.size(); i++)
        {
            IInvokableInstance inst = CLUSTER.get(i);
            if (inst.isShutdown())
                inst.startup();
            inst.runOnInstance(InstanceKiller::clear);
        }
    }

    @Test(timeout = 10 * 60 * 1000)
    public void testFailingMessage() throws IOException
    {
        final int replica = 1;
        final int coordinator = 2;
        String tableName = getCfName(messageType, parallelism, withTracing);
        String fqtn = KEYSPACE + "." + tableName;

        CLUSTER.schemaChange("CREATE TABLE " + fqtn + " (k INT, PRIMARY KEY (k))");

        // create data which will NOT conflict
        int lhsOffset = 10;
        int rhsOffset = 20;
        int limit = rhsOffset + (rhsOffset - lhsOffset);

        // setup data which is consistent on both sides
        for (int i = 0; i < lhsOffset; i++)
            CLUSTER.coordinator(replica)
                   .execute("INSERT INTO " + fqtn + " (k) VALUES (?)", ConsistencyLevel.ALL, i);

        // create data on LHS which does NOT exist in RHS
        for (int i = lhsOffset; i < rhsOffset; i++)
            CLUSTER.get(replica).executeInternal("INSERT INTO " + fqtn + " (k) VALUES (?)", i);

        // create data on RHS which does NOT exist in LHS
        for (int i = rhsOffset; i < limit; i++)
            CLUSTER.get(coordinator).executeInternal("INSERT INTO " + fqtn + " (k) VALUES (?)", i);

        // at this point, the two nodes should be out of sync, so confirm missing data
        // node 1
        Object[][] node1Records = toRows(IntStream.range(0, rhsOffset));
        Object[][] node1Actuals = toNaturalOrder(CLUSTER.get(replica).executeInternal("SELECT k FROM " + fqtn));
        Assert.assertArrayEquals(node1Records, node1Actuals);

        // node 2
        Object[][] node2Records = toRows(IntStream.concat(IntStream.range(0, lhsOffset), IntStream.range(rhsOffset, limit)));
        Object[][] node2Actuals = toNaturalOrder(CLUSTER.get(coordinator).executeInternal("SELECT k FROM " + fqtn));
        Assert.assertArrayEquals(node2Records, node2Actuals);

        // Inject the failure
        CLUSTER.get(replica).runOnInstance(() -> setup.run());

        // run a repair which is expected to fail
        List<String> repairStatus = CLUSTER.get(coordinator).callOnInstance(() -> {
            // need all ranges on the host
            String ranges = StorageService.instance.getLocalAndPendingRanges(KEYSPACE).stream()
                                                   .map(r -> r.left + ":" + r.right)
                                                   .collect(Collectors.joining(","));
            Map<String, String> args = new HashMap<String, String>()
            {{
                put(RepairOption.PARALLELISM_KEY, parallelism.getName());
                put(RepairOption.PRIMARY_RANGE_KEY, "false");
                put(RepairOption.INCREMENTAL_KEY, "false");
                put(RepairOption.TRACE_KEY, Boolean.toString(withTracing));
                put(RepairOption.PULL_REPAIR_KEY, "false");
                put(RepairOption.FORCE_REPAIR_KEY, "false");
                put(RepairOption.RANGES_KEY, ranges);
                put(RepairOption.COLUMNFAMILIES_KEY, tableName);
            }};
            int cmd = StorageService.instance.repairAsync(KEYSPACE, args);
            Assert.assertFalse("repair return status was 0, expected non-zero return status, 0 indicates repair not submitted", cmd == 0);
            List<String> status;
            do
            {
                Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
                status = StorageService.instance.getParentRepairStatus(cmd);
            } while (status == null || status.get(0).equals(ParentRepairStatus.IN_PROGRESS.name()));

            return status;
        });
        Assert.assertEquals(repairStatus.toString(), ParentRepairStatus.FAILED, ParentRepairStatus.valueOf(repairStatus.get(0)));

        // its possible that the coordinator gets the message that the replica failed before the replica completes
        // shutting down; this then means that isKilled could be updated after the fact
        IInvokableInstance replicaInstance = CLUSTER.get(replica);
        Awaitility.await().atMost(Duration.ofSeconds(30)).until(replicaInstance::isShutdown);
        Assert.assertEquals("coordinator should not be killed", 0, CLUSTER.get(coordinator).killAttempts());
    }

    private static Object[][] toNaturalOrder(Object[][] actuals)
    {
        // data is returned in token order, so rather than try to be fancy and order expected in token order
        // convert it to natural
        int[] values = new int[actuals.length];
        for (int i = 0; i < values.length; i++)
            values[i] = (Integer) actuals[i][0];
        Arrays.sort(values);
        return toRows(IntStream.of(values));
    }

    private static Object[][] toRows(IntStream values)
    {
        return values
               .mapToObj(v -> new Object[]{ v })
               .toArray(Object[][]::new);
    }

    private static final class FailingSSTableReader extends ForwardingSSTableReader
    {

        private FailingSSTableReader(SSTableReader delegate)
        {
            super(delegate);
        }

        public ISSTableScanner getScanner()
        {
            return new FailingISSTableScanner();
        }

        public ISSTableScanner getScanner(Collection<Range<Token>> ranges)
        {
            return new FailingISSTableScanner();
        }

        public ISSTableScanner getScanner(Iterator<AbstractBounds<PartitionPosition>> rangeIterator)
        {
            return new FailingISSTableScanner();
        }

        public ISSTableScanner getScanner(ColumnFilter columns, DataRange dataRange, SSTableReadsListener listener)
        {
            return new FailingISSTableScanner();
        }

        public ChannelProxy getDataChannel()
        {
            throw new RuntimeException();
        }

        public String toString()
        {
            return "FailingSSTableReader[" + super.toString() + "]";
        }
    }

    private static final class FailingISSTableScanner implements ISSTableScanner
    {
        public long getLengthInBytes()
        {
            return 0;
        }

        public long getCompressedLengthInBytes()
        {
            return 0;
        }

        public long getCurrentPosition()
        {
            return 0;
        }

        public long getBytesScanned()
        {
            return 0;
        }

        public Set<SSTableReader> getBackingSSTables()
        {
            return Collections.emptySet();
        }

        public TableMetadata metadata()
        {
            return null;
        }

        public void close()
        {

        }

        public boolean hasNext()
        {
            throw new CorruptSSTableException(new IOException("Test commands it"), "mahahahaha!");
        }

        public UnfilteredRowIterator next()
        {
            throw new CorruptSSTableException(new IOException("Test commands it"), "mahahahaha!");
        }
    }
}


text:
from pdc_client.test_helpers import CLITestCase
from pdc_client.runner import Runner

class ProductVersionTestCase(CLITestCase):
    def setUp(self):
        self.runner = Runner()
        self.runner.setup()
        self.product_version_detail = {
            'product': 'test-product',
            'product_version_id': 'test-product-version-1',
            'short': 'test-product-version',
            'name': 'Test Product Version',
            'version': "1",
            'active': False,
        }

    def _setup_product_version_detail(self, api):
        api.add_endpoint('product-versions/test-product-version-1', 'GET', self.product_version_detail)

    def test_create(self, api):
        api.add_endpoint('product-versions', 'POST', self.product_version_detail)
        self._setup_product_version_detail(api)

        # compare stdout with data/info.txt
        with self.expect_output('info.txt'):
            # run the command
            self.runner.run([
                'product-version',
                'create',
                '--product', 'test-product',
                '--short', 'test-product-version',
                '--name', 'Test Product Version',
                '--version=1',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions': [
                ('POST', {
                    'product': 'test-product',
                    'short': 'test-product-version',
                    'name': 'Test Product Version',
                    'version': '1',
                }),
            ],
            'product-versions/test-product-version-1': [
                ('GET', {
                }),
            ],
        })

    def test_info(self, api):
        api.add_endpoint('product-versions/test-product-version-1', 'GET', self.product_version_detail)

        # compare stdout with data/info.txt
        with self.expect_output('info.txt'):
            self.runner.run([
                'product-version',
                'info',
                'test-product-version-1',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions/test-product-version-1': [
                ('GET', {
                }),
            ],
        })

    def test_list_all(self, api):
        api.add_endpoint('product-versions', 'GET', [self.product_version_detail])

        # compare stdout with data/list-all.txt
        with self.expect_output('list-all.txt'):
            # run the command
            self.runner.run([
                'product-version',
                'list',
                '--all',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions': [
                ('GET', {
                    'page': 1
                }),
            ],
        })

    def test_list_active(self, api):
        api.add_endpoint('product-versions', 'GET', [])

        # compare stdout with data/list-empty.txt
        with self.expect_output('list-empty.txt'):
            # run the command
            self.runner.run([
                'product-version',
                'list',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions': [
                ('GET', {
                    'active': True,
                    'page': 1
                }),
            ],
        })

    def test_list_inactive(self, api):
        api.add_endpoint('product-versions', 'GET', [self.product_version_detail])

        # compare stdout with data/list-all.txt
        with self.expect_output('list-all.txt'):
            # run the command
            self.runner.run([
                'product-version',
                'list',
                '--inactive',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions': [
                ('GET', {
                    'active': False,
                    'page': 1
                }),
            ],
        })

    def test_update(self, api):
        api.add_endpoint('product-versions/test-product-version-0.9', 'PATCH', self.product_version_detail)
        self._setup_product_version_detail(api)

        with self.expect_output('info.txt'):
            # run the command
            self.runner.run([
                'product-version',
                'update',
                'test-product-version-0.9',
                '--version', '1',
            ])

        # test api calls made by the command
        self.assertEqual(api.calls, {
            'product-versions/test-product-version-0.9': [
                ('PATCH', {
                    'version': '1',
                }),
            ],
            'product-versions/test-product-version-1': [
                ('GET', {
                }),
            ],
        })


text:
namespace autofill_assistant {
// An action to navigate to a given web page.
class NavigateAction : public Action {
 public:
  explicit NavigateAction(ActionDelegate* delegate, const ActionProto& proto);

  NavigateAction(const NavigateAction&) = delete;
  NavigateAction& operator=(const NavigateAction&) = delete;

  ~NavigateAction() override;

 private:
  // Overrides Action:
  void InternalProcessAction(ProcessActionCallback callback) override;
};

}  // namespace autofill_assistant
#endif  // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_ACTIONS_NAVIGATE_ACTION_H_


text:
**redux-form:**
"If your onSubmit function returns a promise, the submitting property will be set to true until the promise has been resolved or rejected. If it is rejected with an object like new SubmissionError({ field1: 'error', field2: 'error' }) then the submission errors will be added to each field (to the error prop) just like async validation errors are."
(From "http://redux-form.com/6.1.1/docs/api/Props.md/")

**redux-saga:**
When working with redux-saga, typically you dispath an unblocked action, then redux-saga catches the event, fork an independent "thread" to handle the action.

**So how do you make your action return a promise?**

#How to use it?

Assume "SAVA_DATA" is the action you want to dispatch when submitting the form.

##1. In your redux-saga:
```javascript
import { submitFormSaga } from "redux-form-submit-with-saga";

export default function* root() {
  yield fork(takeEvery, "SAVE_DATA", saveDataSaga);
  yield fork(submitFormSaga);
}

function* saveDataSaga(form, data) {
  const { response, error } = yield call(fetch...); //Your save data API.
  if (error) {
    yield put({ type: "SAVE_DATA_OK", target: form });
  } else {
    yield put({ type: "SAVE_DATA_FAIL", target: form });
  }
}
```

##2. In your form:
```javascript
import { submitFormSagaPromise } from "redux-form-submit-with-saga";

const FORM_NAME = "YOUR_UNIQUE_FORM_ID";

class SimpleForm extents React.Component {
  const myOnSubmit = (data) => {
    return submitFormSagaPromise(
      dispatch, // This is your store.dispath from redux
      { type: "SAVE_DATA", target: props.form, data: data },
      props.form,
      ["SAVA_DATA_OK", "SAVA_DATA_FAIL"] // The names should match the name in savaDataSaga
    )
  };

  render() {
    return (
      <div>
        <form onSubmit={props.handleSubmit(myOnSubmit)}>
          <div>
            <Field name="firstName" component="input" type="text" placeholder="First Name"/>
          </div>
        </form>
      </div>
    )
  }
}
export default reduxForm({
  form: 'UNIQUE_FORM_ID'  // a unique identifier for this form
})(SimpleForm)
```
#Notes:
1. You can rename "SAVA_DATA", "SAVA_DATA_OK" and "SAVA_DATA_FAIL", as long as they match in your form and saga.
2. Why "target"? => To support submitting multiple different forms simultaneously.


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <comment>ChurchReport messages</comment>
  <entry key="query_sql">Database-Query</entry>
  <entry key="query_id">Query</entry>
  <entry key="rows">Data rows</entry>
  <entry key="cols">Data columns</entry>
  <entry key="aggregatorName">Preselection</entry>
  <entry key="no.report.available">There is not report available in current query</entry>

</properties>