text:
class Packet(object):
    @classmethod
    def _deserialize(cls, fd):
        raise NotImplementedError

    @classmethod
    def _deserialize_from(cls, buf, offset, **kw):
        raise NotImplementedError

    @classmethod
    def deserialize(cls, fd, **kw):
        return cls._deserialize(fd, **kw)

    @classmethod
    def deserialize_from(cls, buf, offset, **kw):
        return cls._deserialize_from(buf, offset, **kw)

    def _serialize(self):
        raise NotImplementedError

    def _serialize_into(self, buf, offset):
        raise NotImplementedError

    def serialize(self, packet=None, **kw):
        if packet is None:
            packet = bytearray()

        self._serialize(packet, **kw)

        return packet

    def serialize2(self):
        buf = bytearray(self.size)
        self.serialize_into(buf, 0)
        return buf

    def serialize_into(self, buf, offset):
        return self._serialize_into(buf, offset)

    def __bytes__(self):
        return self.serialize()

class TagData(Packet):
    @property
    def size(self):
        if isinstance(self.data, Packet):
            return self.data.size
        else:
            return len(self.data)

__all__ = ["Packet", "TagData"]


text:
<?php

class WPMDBPro_Media_Files_CLI_Bar extends \cli\progress\Bar {

    public function setMessage( $message ) {
        $this->_message = $message;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "amqp_private.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

char const *amqp_version(void) {
  return VERSION; /* defined in config.h */
}

void init_amqp_pool(amqp_pool_t *pool, size_t pagesize) {
  pool->pagesize = pagesize ? pagesize : 4096;

  pool->pages.num_blocks = 0;
  pool->pages.blocklist = NULL;

  pool->large_blocks.num_blocks = 0;
  pool->large_blocks.blocklist = NULL;

  pool->next_page = 0;
  pool->alloc_block = NULL;
  pool->alloc_used = 0;
}

static void empty_blocklist(amqp_pool_blocklist_t *x) {
  int i;

  for (i = 0; i < x->num_blocks; i++) {
    free(x->blocklist[i]);
  }
  if (x->blocklist != NULL) {
    free(x->blocklist);
  }
  x->num_blocks = 0;
  x->blocklist = NULL;
}

void recycle_amqp_pool(amqp_pool_t *pool) {
  empty_blocklist(&pool->large_blocks);
  pool->next_page = 0;
  pool->alloc_block = NULL;
  pool->alloc_used = 0;
}

void empty_amqp_pool(amqp_pool_t *pool) {
  recycle_amqp_pool(pool);
  empty_blocklist(&pool->pages);
}

/* Returns 1 on success, 0 on failure */
static int record_pool_block(amqp_pool_blocklist_t *x, void *block) {
  size_t blocklistlength = sizeof(void *) * (x->num_blocks + 1);

  if (x->blocklist == NULL) {
    x->blocklist = malloc(blocklistlength);
    if (x->blocklist == NULL)
      return 0;
  } else {
    void *newbl = realloc(x->blocklist, blocklistlength);
    if (newbl == NULL)
      return 0;
    x->blocklist = newbl;
  }

  x->blocklist[x->num_blocks] = block;
  x->num_blocks++;
  return 1;
}

void *amqp_pool_alloc(amqp_pool_t *pool, size_t amount) {
  if (amount == 0) {
    return NULL;
  }

  amount = (amount + 7) & (~7); /* round up to nearest 8-byte boundary */

  if (amount > pool->pagesize) {
    void *result = calloc(1, amount);
    if (result == NULL) {
      return NULL;
    }
    if (!record_pool_block(&pool->large_blocks, result))
      return NULL;
    return result;
  }

  if (pool->alloc_block != NULL) {
    assert(pool->alloc_used <= pool->pagesize);

    if (pool->alloc_used + amount <= pool->pagesize) {
      void *result = pool->alloc_block + pool->alloc_used;
      pool->alloc_used += amount;
      return result;
    }
  }

  if (pool->next_page >= pool->pages.num_blocks) {
    pool->alloc_block = calloc(1, pool->pagesize);
    if (pool->alloc_block == NULL) {
      return NULL;
    }
    if (!record_pool_block(&pool->pages, pool->alloc_block))
      return NULL;
    pool->next_page = pool->pages.num_blocks;
  } else {
    pool->alloc_block = pool->pages.blocklist[pool->next_page];
    pool->next_page++;
  }

  pool->alloc_used = amount;

  return pool->alloc_block;
}

void amqp_pool_alloc_bytes(amqp_pool_t *pool, size_t amount, amqp_bytes_t *output) {
  output->len = amount;
  output->bytes = amqp_pool_alloc(pool, amount);
}

amqp_bytes_t amqp_cstring_bytes(char const *cstr) {
  amqp_bytes_t result;
  result.len = strlen(cstr);
  result.bytes = (void *) cstr;
  return result;
}

amqp_bytes_t amqp_bytes_malloc_dup(amqp_bytes_t src) {
  amqp_bytes_t result;
  result.len = src.len;
  result.bytes = malloc(src.len);
  if (result.bytes != NULL) {
    memcpy(result.bytes, src.bytes, src.len);
  }
  return result;
}

amqp_bytes_t amqp_bytes_malloc(size_t amount) {
  amqp_bytes_t result;
  result.len = amount;
  result.bytes = malloc(amount); /* will return NULL if it fails */
  return result;
}

void amqp_bytes_free(amqp_bytes_t bytes) {
  free(bytes.bytes);
}


text:
package com.carrotgarden.nexus.aws.s3.publish.config;

import java.util.concurrent.ConcurrentHashMap;

/**
 * [ repo-id : config-entry-map ]
 */
@SuppressWarnings("serial")
public class ConfigEntryStore extends ConcurrentHashMap<String, ConfigEntryMap> {

}


text:
$(document).on('ready page:load', function(){
  // Prevents duplicate event bindings
  $(document).off("click");
  $(document).foundation();
  selectable();

  // Section creation and deletion
  createSection();
  deleteSection();
  renderNewSectionForm();
  cancelSectionCreation();
  addArtist();

  // Remove and Render Warnings
  renderDeleteSectionWarning();
  removeDeleteSectionWarning();
  renderDeleteSongWarning();
  removeDeleteSongWarning();

  // Add and Remove Measures
  addMeasureAfter();
  addMeasureBefore();
  deleteMeasure();

  // Add and Remove Cells
  addCell();
  removeCell();

  // Edit Cell Attributes
  changeRhyme();
  changeStress();
  changeEndRhyme();
  changeLyric();
  changeRhythm();

  // Open and Close Edit Menu
  openEditMenu();
  closeEditMenu();

  // Publication
  tagForPublication();
  publish();

  // Tabbing and Adding Lyrics
  tabToCell();
  focusLyrics();
  submitLyrics();
});

var selectable = function(){
  $('.selectable').selectable({
    filter: ".select",
  });
}

// --------- Section Creation and Deletion ---------
var createSection = function(){
  $(document).on("submit", ".new-section-form", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var sectionData = $(".new-section-form").serializeArray();
    var thisFormAndContainers = $(this).parent().parent().parent();
    var request = $.ajax({
      url: "/songs/" + songID + "/create_section",
      type: "PUT",
      data: sectionData
    });
    request.done(function(response){
      $(".song-edit").html(response);
      selectable();
    })
  })
}

var deleteSection = function(){
  $(document).on("click", ".delete-section", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var section = $(this).parents(".edit-section");
    var sectionID = section.children("input[name='section-id']").val();
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/delete_section"),
      data: {
        sectionID: sectionID,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      section.remove();
    })
  })
}

var renderNewSectionForm = function(){
  $(document).on("click", ".add-section-button", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisButton = $(this);
    var sectionNumber = $(this).attr("data-value");
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/render_section_form",
      data: {
        sectionNumber: sectionNumber,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      $(thisButton).replaceWith(response)
    })
  })
}

var cancelSectionCreation = function(){
  $(document).on("click", ".cancel-section-creation", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisForm = $(this).parent().parent();
    var thisFormsWrapper = thisForm.parent().parent();
    var sectionNumber = $(this).siblings("input[name='section-number']").val();
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/cancel_section_form",
      data: {
        sectionNumber: sectionNumber,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      $(thisFormsWrapper).replaceWith(response);
    })
  })
}

var addArtist = function(){
  $(document).on("click", ".add-artist", function(event){
    event.preventDefault();
    console.log("Ran once")
    var prevArtistNum = $(this).prev().attr("data-value");
    var artistNum = (parseInt(prevArtistNum) + 1).toString();
    $(this).before('<input type="text" name="artist-' + artistNum + '" data-value="' + artistNum + '" placeholder="Artist">');
  });
}

// --------- Remove and Render Warnings ---------
var renderDeleteSectionWarning = function(){
  $(document).on("click", ".render-delete-section-warning", function(event){
    event.preventDefault();
    var thisButton = $(this);
    var songID = $("input[name='song-id']").attr("value");
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/render_delete_section_warning",
      data: {
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisButton.replaceWith(response);
    })
  })
}

var removeDeleteSectionWarning = function(){
  $(document).on("click", ".cancel-section-deletion", function(event){
    event.preventDefault();
    var thisForm = $(this).parent().parent().parent();
    thisForm.replaceWith('<button class="alert button float-right render-delete-section-warning">Delete Section</button>');
  })
}

var renderDeleteSongWarning = function(){
  $(document).on("click", ".render-delete-song-warning", function(event){
    event.preventDefault();
    var thisButton = $(this);
    var songID = $("input[name='song-id']").attr("value");
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/render_delete_song_warning",
      data: {
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisButton.replaceWith(response);
    })
  })
}

var removeDeleteSongWarning = function(){
  $(document).on("click", ".cancel-song-deletion", function(event){
    event.preventDefault();
    var thisForm = $(this).parent().parent().parent();
    thisForm.replaceWith('<button class="alert button float-right render-delete-song-warning">Delete Song</button>');
  })
}

// --------- Add and Remove Measures ---------
var addMeasureAfter = function(){
  $(document).on("click", ".add-measure-after", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisSection = $(this).parents(".edit-section");
    var cellID = $(".ui-selected").first().attr("name");
    // refactor use this when combining before and after
    var beforeOrAfter = $(this).val();
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/add_measure_after"),
      data: {
        cellID: cellID,
        before_or_after: beforeOrAfter,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisSection.replaceWith(response);
      selectable();
    });
  });
}

var addMeasureBefore = function(){
  $(document).on("click", ".add-measure-before", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisSection = $(this).parents(".edit-section");
    var cellID = $(".ui-selected").first().attr("name");
    var beforeOrAfter = $(this).val();
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/add_measure_before"),
      data: {
        cellID: cellID,
        before_or_after: beforeOrAfter,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisSection.replaceWith(response);
      selectable();
    });
  });
}

var deleteMeasure = function(){
  $(document).on("click", ".delete-measure", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisSection = $(this).parents(".edit-section");
    var measure = $(".ui-selected").first().parent().parent()
    var measureID = measure.children("input").val();
    console.log("this is measureID" + measureID)
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/delete_measure"),
      data: {
        measureID: measureID,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisSection.replaceWith(response);
      selectable();
    });
  });
}

// --------- Add and Remove Cells ---------
var addCell = function(){
  $(document).on("click", ".add-cell", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var allCells = $(".ui-selected")
    var cellIDs = getCellIDs(allCells);
    var beforeOrAfter = $(this).val();
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/add_cell"),
      data: {
        cellIDs: cellIDs,
        before_or_after: beforeOrAfter,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      for (var key in response){
        $("input[value='" + key + "'][name='measure_id']").parent().replaceWith(response[key])
      }
      selectCellsByID(cellIDs);
    })
  })
}

var removeCell = function(){
  $(document).on("click", ".remove-cell", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisSection = $(this).parents(".edit-section");
    var allCells = $(".ui-selected")
    var previousCells = getPreviousCells(allCells);
    var previousCellIDs = getCellIDs(previousCells);
    var cellIDs = getCellIDs(allCells);
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/delete_cell"),
      data: {
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      // for (var key in response){
      //   $("input[value='" + key + "'][name='measure_id']").parent().replaceWith(response[key])
      // }
      thisSection.replaceWith(response);
      selectable();
      selectCellsByID(previousCellIDs);
    })
  })
}

// --------- Edit Cell Attributes ---------
var changeRhyme = function(){
  $(document).on("click", ".change-rhyme", function(event){
    event.preventDefault();
    var allCells = $(".ui-selected");
    var cellIDs = getCellIDs(allCells);
    var quality = $(this).val();
    // refactor This is to get song id
    var songID = $("input[name='song-id']").attr("value");
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/change_rhyme"),
      data: {
        quality: quality,
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      $.each(allCells, function(){
        $(this).attr("data-rhyme", response['quality'])
      })
    })
  })
}

var changeStress = function(){
  $(document).on("click", ".change-stress", function(event){
    event.preventDefault();
    var allCells = $(".ui-selected");
    var cellIDs = getCellIDs(allCells);
    // refactor Don't think I need following line
    // var quality = $(this).attr("value");
    // refactor This is to get song id
    var songID = $("input[name='song-id']").attr("value");
    // refactor to not include authenticity_token in params if possible
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/change_stress"),
      data: {
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      if (response['quality']){
        $.each(allCells, function(){
          $(this).addClass("stressed");
        })
      } else {
        $.each(allCells, function(){
          $(this).removeClass("stressed");
        })
      }
    })
  })
}

var changeEndRhyme = function(){
  $(document).on("click", ".change-end-rhyme", function(event){
    event.preventDefault();
    var allCells = $(".ui-selected");
    var cellIDs = getCellIDs(allCells);
    // refactor This is to get song id
    var songID = $("input[name='song-id']").attr("value");
    // refactor to not include authenticity_token in params if possible
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/change_end_rhyme"),
      data: {
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      if (response['quality']){
        $.each(allCells, function(){
          $(this).addClass("end-rhyme");
        })
      } else {
        $.each(allCells, function(){
          $(this).removeClass("end-rhyme");
        })
      }
    })
  })
}

var changeLyric = function(){
  $(document).on("click", ".change-lyrics", function(event){
    event.preventDefault();
    // refactor I use next two lines repeatedly
    var songID = $("input[name='song-id']").attr("value");
    var allCells = $(".ui-selected")
    var cellIDs = getCellIDs(allCells);
    var replacementLyrics = $(".replacement-lyrics").val();
    $(".replacement-lyrics").val('');
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/change_lyrics"),
      data: {
        lyrics: replacementLyrics,
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      $.each(allCells, function(){
        $(this).html(replacementLyrics);
      });
      selectNextCells();
    })
  })
}

var changeRhythm = function(){
  $(document).on("click", ".change-rhythm", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var allCells = $(".ui-selected")
    var cellIDs = getCellIDs(allCells);
    var replacementDuration = $(this).val();
    $.ajax({
      method: "PUT",
      url: ("/songs/" + songID + "/change_rhythm"),
      data: {
        duration: replacementDuration,
        cellIDs: cellIDs,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      for (var key in response){
        $("input[value='" + key + "'][name='measure_id']").parent().replaceWith(response[key])
      }
      selectCellsByID(cellIDs);
    })
  })
}

// --------- Open and Close Edit Menu ---------
var openEditMenu = function(){
  $(document).on("click", ".open-edit-menu", function(event){
    event.preventDefault();
    var thisButton = $(this);
    var songID = $("input[name='song-id']").attr("value");
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/open_edit_menu",
      data: {
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisButton.replaceWith(response);
    })
  })
}

var closeEditMenu = function(){
  $(document).on("click", ".close-edit-menu", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisForm = $(this).parent().parent().parent();
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/close_edit_menu",
      data: {
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisForm.replaceWith(response);
    })
  })
}

// --------- Publication ---------
// Allows super users to publish a song
var publish = function(){
  $(document).on("click", ".publish", function(event){
    event.preventDefault();
    var thisButton = $(this);
    var value = $(this).val();
    var songID = $("input[name='song-id']").attr("value");
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/publish",
      data: {
        value: value,
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisButton.replaceWith(response);
    })
  })
}

// Allows users to tag their song for publication
var tagForPublication = function(){
  $(document).on("click", ".tag-for-publication", function(event){
    event.preventDefault();
    var songID = $("input[name='song-id']").attr("value");
    var thisButton = $(this);
    $.ajax({
      method: "PUT",
      url: "/songs/" + songID + "/tag_for_publication",
      data: {
        authenticity_token: getCSRFTokenValue()
      }
    }).done(function(response){
      thisButton.replaceWith(response);
    })
  })
}

// --------- Tabbing and Adding Lyrics ---------
var tabToCell = function(){
  $(document).off("keydown", "body").on("keydown", "body", function(event){
    if (event.keyCode === 9){
      var selectedCell = $(".ui-selected");
      if (selectedCell.length){
        event.preventDefault();
        if (event.shiftKey){
          selectPreviousCells();
        } else {
          selectNextCells();
        }
      }
    }
  });
}

var submitLyrics = function(){
  $(document).off("keypress", ".replacement-lyrics").on("keypress", ".replacement-lyrics", function(event){
    if (event.keyCode === 13){
      $(".change-lyrics").click();
    }
  })
}

var focusLyrics = function(){
  $(document).off("keypress", "body").on("keypress", "body", function(event){
    $(".replacement-lyrics").focus();
  })
}

//--------------- HELPER METHODS -------------------
var getCSRFTokenValue = function(){
  return $('meta[name="csrf-token"]').attr('content');
}

var selectNextCells = function(){
  var selectedCells = $(".ui-selected");
  var nextCells = getNextCells(selectedCells);
  unselectCells(selectedCells);
  selectCells(nextCells);
}

var selectPreviousCells = function(){
  var selectedCells = $(".ui-selected");
  var previousCells = getPreviousCells(selectedCells);
  unselectCells(selectedCells);
  selectCells(previousCells);
}

// returns the next cell in the measure, or the first cell in the next measure, or the firt cell in the next section, or undefined if none of the above.
var getNextCells = function(currentCells){
  var nextCells = currentCells.map(function(){
    var cell = $(this);
    var nextCell;
    if (cell.next().length){
      nextCell = cell.next();
    } else if (cell.parents(".edit-measure").next().find(".col.select").first().length) {
      nextCell = cell.parents(".edit-measure").next().find(".col.select").first();
    } else {
      nextCell = cell.parents(".phrase-div").next().find(".col.select").first();
    }
    return nextCell;
  });
  return nextCells;
}

// returns previous cell in measure, or the last cell in previous measure, or the last cell in previous section, or undefined if none of the above.
var getPreviousCells = function(currentCells){
  var previousCells = currentCells.map(function(){
    var cell = $(this);
    var prevCell;
    if (cell.prev().length){
      prevCell = cell.prev();
    } else if (cell.parents(".edit-measure").prev().find(".col.select").last().length) {
      prevCell = cell.parents(".edit-measure").prev().find(".col.select").last();
    } else {
      prevCell = cell.parents(".phrase-div").prev().find(".col.select").last();
    }
    return prevCell;
  });
  return previousCells;
}

var selectCells = function(cells){
  // iterate through array of jQuery cells
  cells.each(function(){
    // if not undefined, select the cell
    if ($(this)){
      $(this).addClass("ui-selected");
    }
  });
}

var unselectCells = function(cells){
  // iterate through array of jQuery cells
  cells.each(function(){
    // if not undefined, unselect the cell
    if ($(this)){
      $(this).removeClass("ui-selected");
    }
  });
}

var getCellIDs = function(cells){
  var cellIDs = $.map(cells, function(cell){
      return $(cell).attr("name");
  });
  return cellIDs;
}

// I need this for cells in measures that are rendered with errors because the cells cannot be saved as jQuery objects (because they are replaced)
var selectCellsByID = function(cellIDs){
  // if cell with cellID exists, add stress
  for (var i = 0; i < cellIDs.length; i++){
    if ($('div.col[name="' + cellIDs[i] + '"]')){
      $('div.col[name="' + cellIDs[i] + '"]').addClass("ui-selected");
    }
  }
}


text:
package tsdb

import (
	"context"
	"io/ioutil"
	"os"
	"testing"
	"time"

	"github.com/influxdata/influxdb/kit/prom/promtest"
	"github.com/influxdata/influxdb/models"
	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
)

func TestMetrics_SeriesPartition(t *testing.T) {
	// metrics to be shared by multiple file stores.
	metrics := newSeriesFileMetrics(prometheus.Labels{"engine_id": "", "node_id": ""})

	t1 := newSeriesPartitionTracker(metrics, prometheus.Labels{"series_file_partition": "0", "engine_id": "0", "node_id": "0"})
	t2 := newSeriesPartitionTracker(metrics, prometheus.Labels{"series_file_partition": "0", "engine_id": "1", "node_id": "0"})

	reg := prometheus.NewRegistry()
	reg.MustRegister(metrics.PrometheusCollectors()...)

	base := namespace + "_" + seriesFileSubsystem + "_"

	// All the metric names
	gauges := []string{
		base + "series_total",
		base + "disk_bytes",
		base + "segments_total",
		base + "index_compactions_active",
	}

	counters := []string{
		base + "series_created",
		base + "compactions_total",
	}

	histograms := []string{
		base + "index_compactions_duration_seconds",
	}

	// Generate some measurements.
	for i, tracker := range []*seriesPartitionTracker{t1, t2} {
		tracker.SetSeries(uint64(i + len(gauges[0])))
		tracker.SetDiskSize(uint64(i + len(gauges[1])))
		tracker.SetSegments(uint64(i + len(gauges[2])))

		labels := tracker.Labels()
		labels["component"] = "index"
		tracker.metrics.CompactionsActive.With(labels).Add(float64(i + len(gauges[3])))

		tracker.AddSeriesCreated(uint64(i + len(counters[0])))
		labels = tracker.Labels()
		labels["status"] = "ok"
		tracker.metrics.Compactions.With(labels).Add(float64(i + len(counters[1])))

		labels = tracker.Labels()
		labels["component"] = "index"
		tracker.metrics.CompactionDuration.With(labels).Observe(float64(i + len(histograms[0])))
	}

	// Test that all the correct metrics are present.
	mfs, err := reg.Gather()
	if err != nil {
		t.Fatal(err)
	}

	// The label variants for the two caches.
	labelVariants := []prometheus.Labels{
		prometheus.Labels{"engine_id": "0", "node_id": "0"},
		prometheus.Labels{"engine_id": "1", "node_id": "0"},
	}

	for i, labels := range labelVariants {
		labels["series_file_partition"] = "0"
		var metric *dto.Metric

		for _, name := range gauges {
			exp := float64(i + len(name))

			if name == base+"index_compactions_active" {
				// Make a copy since we need to add a label
				l := make(prometheus.Labels, len(labels))
				for k, v := range labels {
					l[k] = v
				}
				l["component"] = "index"
				metric = promtest.MustFindMetric(t, mfs, name, l)
			} else {
				metric = promtest.MustFindMetric(t, mfs, name, labels)
			}

			if got := metric.GetGauge().GetValue(); got != exp {
				t.Errorf("[%s %d] got %v, expected %v", name, i, got, exp)
			}
		}

		for _, name := range counters {
			exp := float64(i + len(name))

			if name == base+"compactions_total" {
				// Make a copy since we need to add a label
				l := make(prometheus.Labels, len(labels))
				for k, v := range labels {
					l[k] = v
				}
				l["status"] = "ok"

				metric = promtest.MustFindMetric(t, mfs, name, l)
			} else {
				metric = promtest.MustFindMetric(t, mfs, name, labels)
			}

			if got := metric.GetCounter().GetValue(); got != exp {
				t.Errorf("[%s %d] got %v, expected %v", name, i, got, exp)
			}
		}

		for _, name := range histograms {
			// Make a copy since we need to add a label
			l := make(prometheus.Labels, len(labels))
			for k, v := range labels {
				l[k] = v
			}
			l["component"] = "index"

			exp := float64(i + len(name))
			metric := promtest.MustFindMetric(t, mfs, name, l)
			if got := metric.GetHistogram().GetSampleSum(); got != exp {
				t.Errorf("[%s %d] got %v, expected %v", name, i, got, exp)
			}
		}
	}
}

// This test ensures that disabling metrics works even if a series file has been created before.
func TestMetrics_Disabled(t *testing.T) {
	// This test messes with global state. Gotta fix it up otherwise other tests panic. I really
	// am beginning to wonder about our metrics.
	defer func() {
		mmu.Lock()
		sms = nil
		ims = nil
		mmu.Unlock()
	}()

	path, err := ioutil.TempDir("", "sfile-metrics-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(path)

	// Step 1. make a series file with metrics and some labels
	sfile := NewSeriesFile(path)
	sfile.SetDefaultMetricLabels(prometheus.Labels{"foo": "bar"})
	if err := sfile.Open(context.Background()); err != nil {
		t.Fatal(err)
	}
	if err := sfile.Close(); err != nil {
		t.Fatal(err)
	}

	// Step 2. open the series file again, but disable metrics
	sfile = NewSeriesFile(path)
	sfile.DisableMetrics()
	if err := sfile.Open(context.Background()); err != nil {
		t.Fatal(err)
	}
	defer sfile.Close()

	// Step 3. add a series
	points := []models.Point{models.MustNewPoint("a", models.Tags{}, models.Fields{"f": 1.0}, time.Now())}
	if err := sfile.CreateSeriesListIfNotExists(NewSeriesCollection(points)); err != nil {
		t.Fatal(err)
	}
}


text:
#import "UIConstants.h"

@implementation UIConstants

+ (instancetype)shared
{
    static UIConstants *sharedInstance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        if (sharedInstance == nil){
            sharedInstance = [[UIConstants alloc] init];
        }
    });
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // initialization
        _deepBlueColor  = [UIColor colorWithRed:0.0 green:(121.0/255) blue:1.0 alpha:1.0];
        _middleBlueColor = [UIColor colorWithRed:(177.0/255) green:(210.0/255) blue:1.0 alpha:1.0];
        _lightBlueColor = [UIColor colorWithRed:(191.0/255) green:(221.0/255) blue:1.0 alpha:1.0];
    }
    return self;
}

@end


text:
class AddVirtualIdToCommunes < ActiveRecord::Migration
  def change
    add_column :communes, :virtual_id, :string
  end
end


text:
Steam Redirector
=========

A quick tool I wrote using Python and Flask that allows you to create a quick landing page that will point users toward the Steam webpage or directly launch the Steam Application.

This allows you to send potential users to their actual Steam application, where they're logged in.  This is advantageous, as many users aren't logged into Steam on the webpage, but they are in the application.  This will reduce the friction, and hopefully increase overall conversion.

You can check out a live demo [here](http://steamapps.herokuapp.com/SongBringer/367080/tGWGLL0).

Using this tool
------------
This tool uses URLs as input parameters.  There are three possible input parameters that you can input into the URL.

* The name of your game. For example, Songbringer.
* The unique Steam key ID identifier.  For example, the unique steam key ID for the game located at "http://store.steampowered.com/app/367080" is 367080.
* An optional key ID for a background image that is hosted on imgur.  For example, for the image URL "http://imgur.com/tGWGLL0", the unique id would be tGWGLL0

The finished built URL will look like: [http://steamapps.herokuapp.com/SongBringer/367080/tGWGLL0](http://steamapps.herokuapp.com/SongBringer/367080/tGWGLL0)

![alt text](readme_picture.PNG "readme")

Installation
------------
Clone the repository and push to Heroku.  I've included the Procfiles and requirements.txt.  It should be pretty painless.

How did this project come about?
------------

This project was created at Tool Jam 2016, a hackathon for creating game development tools.

Tool Jam was presented by [Playcrafting](https://www.playcrafting.com/) and [Microsoft](https://developer.microsoft.com/) and took place in San Francisco on May 13th through 15th.

[Click here](https://github.com/TobiahZ/ToolJam2016) to see other Tool Jam 2016 projects.

Video Pitch
------------

[![Final Presnetation: Steam-Redirector](http://video.ch9.ms/ch9/62cd/1806924e-3242-4ef0-b2f8-91fcd92a62cd/tj16steam_Custom.jpg)](https://channel9.msdn.com/Events/ToolJam/2016/Steam-Redirector "Final Presnetation: Steam-Redirector")

Todo
------------
* Code cleanup
* Better error handling
* Fix mobile rendering


text:
StatsD reporter backend for exometer_core Edit

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `exometer_statix` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [{:exometer_statix, "~> 0.1.0"}]
end
```

## How to use

```elixir
prefix           = :myapp
polling_interval = 1_000
memory_stats     = ~w(atom binary ets processes total)a
reporter         = Elixir.ExometerStatix
reporter_opts    = [port: 9125, prefix: prefix]

config :exometer_core,
  predefined: [
    {~w(erlang memory)a, {:function, :erlang, :memory, [], :proplist, memory_stats}, []},
    {~w(erlang statistics)a, {:function, :erlang, :statistics, [:'$dp'], :value, [:run_queue]}, []},
  ],
  report: [
    reporters: [{reporter, reporter_opts}],
    subscribers: [
      {reporter, [:erlang, :memory], memory_stats, polling_interval, true},
      {reporter, [:erlang, :statistics], :run_queue, polling_interval, true},
    ]
  ]

config :elixometer,
  reporter: reporter,
  update_frequency: polling_interval,
  env: Mix.env,
  metric_prefix: prefix
````

### Logger setting

Exometer depends on lager. To unify logging in a elixir project, you can use [lagger_logger](https://github.com/PSPDFKit-labs/lager_logger) or [logger_lager_backend](https://github.com/jonathanperret/logger_lager_backend)

```elixir
config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id, :application, :module, :function, :file, :line]

config :lager, :error_logger_redirect, false
config :lager, :error_logger_whitelist, [Logger.ErrorHandler]
config :lager, :crash_log, false
config :lager, :handlers, [{LagerLogger, [level: :info]}]
```

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/exometer_statix](https://hexdocs.pm/exometer_statix).


text:
import OHIF from '@ohif/core';
import cornerstone from 'cornerstone-core';
import csTools from 'cornerstone-tools';
import throttle from 'lodash.throttle';

import LabellingFlow from '../../components/Labelling/LabellingFlow';
import ToolContextMenu from '../../connectedComponents/ToolContextMenu';

const {
  onAdded,
  onRemoved,
  onModified,
} = OHIF.measurements.MeasurementHandlers;

const MEASUREMENT_ACTION_MAP = {
  added: onAdded,
  removed: onRemoved,
  modified: throttle(event => {
    return onModified(event);
  }, 300),
};

/**
 *
 *
 * @export
 * @param {Object} servicesManager
 * @param {Object} configuration
 */
export default function init({
  servicesManager,
  commandsManager,
  configuration,
}) {
  const { UIDialogService } = servicesManager.services;

  // TODO: MEASUREMENT_COMPLETED (not present in initial implementation)
  const onMeasurementsChanged = (action, event) => {
    return MEASUREMENT_ACTION_MAP[action](event);
  };
  const onMeasurementAdded = onMeasurementsChanged.bind(this, 'added');
  const onMeasurementRemoved = onMeasurementsChanged.bind(this, 'removed');
  const onMeasurementModified = onMeasurementsChanged.bind(this, 'modified');
  const onLabelmapModified = onMeasurementsChanged.bind(
    this,
    'labelmapModified'
  );

  const _getDefaultPosition = event => ({
    x: (event && event.currentPoints.client.x) || 0,
    y: (event && event.currentPoints.client.y) || 0,
  });

  const _updateLabellingHandler = (labellingData, measurementData) => {
    const { location, description, response } = labellingData;

    if (location) {
      measurementData.location = location;
    }

    measurementData.description = description || '';

    if (response) {
      measurementData.response = response;
    }

    commandsManager.runCommand(
      'updateTableWithNewMeasurementData',
      measurementData
    );
  };

  const showLabellingDialog = (props, contentProps, measurementData) => {
    if (!UIDialogService) {
      console.warn('Unable to show dialog; no UI Dialog Service available.');
      return;
    }

    UIDialogService.create({
      id: 'labelling',
      isDraggable: false,
      showOverlay: true,
      centralize: true,
      content: LabellingFlow,
      contentProps: {
        measurementData,
        labellingDoneCallback: () =>
          UIDialogService.dismiss({ id: 'labelling' }),
        updateLabelling: labellingData =>
          _updateLabellingHandler(labellingData, measurementData),
        ...contentProps,
      },
      ...props,
    });
  };

  const onRightClick = event => {
    if (!UIDialogService) {
      console.warn('Unable to show dialog; no UI Dialog Service available.');
      return;
    }

    UIDialogService.dismiss({ id: 'context-menu' });
    UIDialogService.create({
      id: 'context-menu',
      isDraggable: false,
      preservePosition: false,
      defaultPosition: _getDefaultPosition(event.detail),
      content: ToolContextMenu,
      contentProps: {
        eventData: event.detail,
        onDelete: (nearbyToolData, eventData) => {
          const element = eventData.element;
          commandsManager.runCommand('removeToolState', {
            element,
            toolType: nearbyToolData.toolType,
            tool: nearbyToolData.tool,
          });
        },
        onClose: () => UIDialogService.dismiss({ id: 'context-menu' }),
        onSetLabel: (eventData, measurementData) => {
          showLabellingDialog(
            { centralize: true, isDraggable: false },
            { skipAddLabelButton: true, editLocation: true },
            measurementData
          );
        },
        onSetDescription: (eventData, measurementData) => {
          showLabellingDialog(
            { defaultPosition: _getDefaultPosition(eventData) },
            { editDescriptionOnDialog: true },
            measurementData
          );
        },
      },
    });
  };

  const onTouchPress = event => {
    if (!UIDialogService) {
      console.warn('Unable to show dialog; no UI Dialog Service available.');
      return;
    }

    UIDialogService.create({
      eventData: event.detail,
      content: ToolContextMenu,
      contentProps: {
        isTouchEvent: true,
      },
    });
  };

  const onTouchStart = () => resetLabelligAndContextMenu();

  const onMouseClick = () => resetLabelligAndContextMenu();

  const resetLabelligAndContextMenu = () => {
    if (!UIDialogService) {
      console.warn('Unable to show dialog; no UI Dialog Service available.');
      return;
    }

    UIDialogService.dismiss({ id: 'context-menu' });
    UIDialogService.dismiss({ id: 'labelling' });
  };

  // TODO: This makes scrolling painfully slow
  // const onNewImage = ...

  /*
   * Because click gives us the native "mouse up", buttons will always be `0`
   * Need to fallback to event.which;
   *
   */
  const handleClick = cornerstoneMouseClickEvent => {
    const mouseUpEvent = cornerstoneMouseClickEvent.detail.event;
    const isRightClick = mouseUpEvent.which === 3;

    if (isRightClick) {
      onRightClick(cornerstoneMouseClickEvent);
    } else {
      onMouseClick(cornerstoneMouseClickEvent);
    }
  };

  function elementEnabledHandler(evt) {
    const element = evt.detail.element;

    element.addEventListener(
      csTools.EVENTS.MEASUREMENT_ADDED,
      onMeasurementAdded
    );
    element.addEventListener(
      csTools.EVENTS.MEASUREMENT_REMOVED,
      onMeasurementRemoved
    );
    element.addEventListener(
      csTools.EVENTS.MEASUREMENT_MODIFIED,
      onMeasurementModified
    );
    element.addEventListener(
      csTools.EVENTS.LABELMAP_MODIFIED,
      onLabelmapModified
    );

    element.addEventListener(csTools.EVENTS.TOUCH_PRESS, onTouchPress);
    element.addEventListener(csTools.EVENTS.MOUSE_CLICK, handleClick);
    element.addEventListener(csTools.EVENTS.TOUCH_START, onTouchStart);

    // TODO: This makes scrolling painfully slow
    // element.addEventListener(cornerstone.EVENTS.NEW_IMAGE, onNewImage);
  }

  function elementDisabledHandler(evt) {
    const element = evt.detail.element;

    element.removeEventListener(
      csTools.EVENTS.MEASUREMENT_ADDED,
      onMeasurementAdded
    );
    element.removeEventListener(
      csTools.EVENTS.MEASUREMENT_REMOVED,
      onMeasurementRemoved
    );
    element.removeEventListener(
      csTools.EVENTS.MEASUREMENT_MODIFIED,
      onMeasurementModified
    );
    element.removeEventListener(
      csTools.EVENTS.LABELMAP_MODIFIED,
      onLabelmapModified
    );

    element.removeEventListener(csTools.EVENTS.TOUCH_PRESS, onTouchPress);
    element.removeEventListener(csTools.EVENTS.MOUSE_CLICK, handleClick);
    element.removeEventListener(csTools.EVENTS.TOUCH_START, onTouchStart);

    // TODO: This makes scrolling painfully slow
    // element.removeEventListener(cornerstone.EVENTS.NEW_IMAGE, onNewImage);
  }

  cornerstone.events.addEventListener(
    cornerstone.EVENTS.ELEMENT_ENABLED,
    elementEnabledHandler
  );
  cornerstone.events.addEventListener(
    cornerstone.EVENTS.ELEMENT_DISABLED,
    elementDisabledHandler
  );
}


text:
package org.sana.android.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import org.sana.android.db.SanaDB.SoundSQLFormat;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.util.Log;

/**
 * Content provider for audio content.
 *
 * @author Sana Development Team
 *
 */
public class SoundProvider extends ContentProvider {

    private static final String TAG = "SoundProvider";

    private static final String SOUND_TABLE_NAME = "sounds";
    public static final String SOUND_BUCKET_NAME = "/sdcard/dcim/sana/";

    private static final int SOUNDS = 1;
    private static final int SOUND_ID = 2;

    private DatabaseHelper mOpenHelper;
    private static final UriMatcher sUriMatcher;
    private static HashMap<String,String> sSoundProjectionMap;

    /** {@inheritDoc} */
    @Override
    public boolean onCreate() {
        Log.i(TAG, "onCreate()");
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    private String buildFilenameFromId(String soundId) {
    	return "/data/data/org.sana/files/sound_" + soundId;
    }

    private String buildFilenameFromUri(Uri uri) {
    	return buildFilenameFromId(uri.getPathSegments().get(1));
    }

    private boolean deleteFile(String soundId) {
    	String filename = buildFilenameFromId(soundId);

    	File f = new File(filename);
    	boolean result = f.delete();
    	Log.i(TAG, "Deleting file for id " + soundId + " : " + filename + " "
    			+ (result ? "succeeded" : "failed"));
    	return result;
    }

    private boolean deleteFile(Uri uri) {
    	String filename = buildFilenameFromUri(uri);

    	File f = new File(filename);
    	boolean result = f.delete();
    	Log.i(TAG, "Deleting file for " + uri + " : " + filename + " "
    			+ (result ? "succeeded" : "failed"));
    	return result;
    }

    /** {@inheritDoc} */
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws
    	FileNotFoundException
    {
        //String filename = SOUND_BUCKET_NAME + uri.getFragment();
        String filename = buildFilenameFromUri(uri);
        //String filename = "/data/data/org.sana/files/" + uri.getPathSegments().get(1);
        Log.i(TAG, "openFile() for filename: " + filename);
        File f = new File(filename);

        int m = ParcelFileDescriptor.MODE_READ_ONLY;
        if ("w".equals(mode)) {
            m = ParcelFileDescriptor.MODE_WRITE_ONLY
            		| ParcelFileDescriptor.MODE_CREATE;
        } else if("rw".equals(mode) || "rwt".equals(mode)) {
            m = ParcelFileDescriptor.MODE_READ_WRITE;
        }
        return ParcelFileDescriptor.open(f,m);
    }

    /** {@inheritDoc} */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder)
    {
        Log.i(TAG, "query() uri="+uri.toString() + " projection="
        		+ TextUtils.join(",",projection));

        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(SOUND_TABLE_NAME);

        switch(sUriMatcher.match(uri)) {
        case SOUNDS:
            break;
        case SOUND_ID:
            qb.appendWhere(SoundSQLFormat._ID + "="
            		+ uri.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        String orderBy;
        if(TextUtils.isEmpty(sortOrder)) {
            orderBy = SoundSQLFormat.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
        		null, orderBy);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    /** {@inheritDoc} */
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count = 0;

        switch(sUriMatcher.match(uri)) {
        case SOUNDS:
            count = db.update(SOUND_TABLE_NAME, values,selection,selectionArgs);
            break;

        case SOUND_ID:
            String procedureId = uri.getPathSegments().get(1);
            count = db.update(SOUND_TABLE_NAME, values, SoundSQLFormat._ID + "="
            		+ procedureId + (!TextUtils.isEmpty(selection)
            				? " AND (" + selection + ")" : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /** {@inheritDoc} */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case SOUNDS:
            //count = db.delete(SOUND_TABLE_NAME, selection, selectionArgs);
            LinkedList<String> idList = new LinkedList<String>();
        	Cursor c = query(SoundSQLFormat.CONTENT_URI, new String[] {
        			SoundSQLFormat._ID }, selection, selectionArgs, null);
        	if(c.moveToFirst()) {
        		while(!c.isAfterLast()) {
        			String id = c.getString(c.getColumnIndex(SoundSQLFormat._ID));
        			idList.add(id);
        			c.moveToNext();
        		}
        	}
        	c.deactivate();

            count = db.delete(SOUND_TABLE_NAME, selection, selectionArgs);

            for(String id : idList) {
            	deleteFile(id);
            }
            break;
        case SOUND_ID:
            String soundId = uri.getPathSegments().get(1);
            count = db.delete(SOUND_TABLE_NAME, SoundSQLFormat._ID + "="
            		+ soundId + (!TextUtils.isEmpty(selection) ? " AND ("
            				+ selection + ")" : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /** {@inheritDoc} */
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (sUriMatcher.match(uri) != SOUNDS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if(initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        Long now = Long.valueOf(System.currentTimeMillis());

        if(values.containsKey(SoundSQLFormat.CREATED_DATE) == false) {
            values.put(SoundSQLFormat.CREATED_DATE, now);
        }

        if(values.containsKey(SoundSQLFormat.MODIFIED_DATE) == false) {
            values.put(SoundSQLFormat.MODIFIED_DATE, now);
        }

        if(values.containsKey(SoundSQLFormat.ENCOUNTER_ID) == false) {
            values.put(SoundSQLFormat.ENCOUNTER_ID, "");
        }

        if(values.containsKey(SoundSQLFormat.FILE_URI) == false) {
            values.put(SoundSQLFormat.FILE_URI, "");
        }

//        if(values.containsKey(SoundSQLFormat.FILE_VALID) == false) {
//            values.put(SoundSQLFormat.FILE_VALID, false);
//        }
//
//        if(values.containsKey(SoundSQLFormat.FILE_SIZE) == false) {
//            values.put(SoundSQLFormat.FILE_SIZE, 0);
//        }

        if(values.containsKey(SoundSQLFormat.UPLOAD_PROGRESS) == false) {
            values.put(SoundSQLFormat.UPLOAD_PROGRESS, 0);
        }

        if(values.containsKey(SoundSQLFormat.UPLOADED) == false) {
            values.put(SoundSQLFormat.UPLOADED, false);
        }

        if(values.containsKey(SoundSQLFormat.ELEMENT_ID) == false) {
            values.put(SoundSQLFormat.ELEMENT_ID, "");
        }

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(SOUND_TABLE_NAME,
        		SoundSQLFormat.ENCOUNTER_ID, values);
        if(rowId > 0) {

            String filename = rowId + "";
            try {
                getContext().openFileOutput(filename,
                		Context.MODE_PRIVATE).close();
            } catch (FileNotFoundException e) {
                Log.e(TAG, "Couldn't make the file: " + e);
            } catch (IOException e) {
                Log.e(TAG, "Couldn't make the file: " + e);
            }
            String path =
            	getContext().getFileStreamPath(filename).getAbsolutePath();
            Log.i(TAG, "File path is : " + path);
            Uri noteUri = ContentUris.withAppendedId(SoundSQLFormat.CONTENT_URI,
            		rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    /** {@inheritDoc} */
    @Override
    public String getType(Uri uri) {
        Log.i(TAG, "getType(uri="+uri.toString()+")");
        switch(sUriMatcher.match(uri)) {
        case SOUNDS:
            return SoundSQLFormat.CONTENT_TYPE;
        case SOUND_ID:
            return SoundSQLFormat.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    /**
     * Creates the table.
     * @param db the database to create the table in.
     */
    public static void onCreateDatabase(SQLiteDatabase db) {
        Log.i(TAG, "Creating Sound Table");
        db.execSQL("CREATE TABLE " + SOUND_TABLE_NAME + " ("
                + SoundSQLFormat._ID + " INTEGER PRIMARY KEY,"
                + SoundSQLFormat.ENCOUNTER_ID + " TEXT,"
                + SoundSQLFormat.ELEMENT_ID + " TEXT,"
                + SoundSQLFormat.FILE_URI + " TEXT,"
//                + SoundSQLFormat.FILE_VALID + " INTEGER,"
//                + SoundSQLFormat.FILE_SIZE + " INTEGER,"
                + SoundSQLFormat.UPLOAD_PROGRESS + " INTEGER,"
                + SoundSQLFormat.UPLOADED + " INTEGER,"
                + SoundSQLFormat.CREATED_DATE + " INTEGER,"
                + SoundSQLFormat.MODIFIED_DATE + " INTEGER"
                + ");");
    }

    /**
     * Updates this providers table
     * @param db the db to update in
     * @param oldVersion the current db version
     * @param newVersion the new db version
     */
    public static void onUpgradeDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion);
        if (oldVersion == 1 && newVersion == 2) {
        	// Do nothing
        }
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(SanaDB.SOUND_AUTHORITY, "sounds", SOUNDS);
        sUriMatcher.addURI(SanaDB.SOUND_AUTHORITY, "sounds/#", SOUND_ID);

        sSoundProjectionMap = new HashMap<String, String>();
        sSoundProjectionMap.put(SoundSQLFormat._ID, SoundSQLFormat._ID);
        sSoundProjectionMap.put(SoundSQLFormat.ELEMENT_ID, SoundSQLFormat.ELEMENT_ID);
        sSoundProjectionMap.put(SoundSQLFormat.ENCOUNTER_ID, SoundSQLFormat.ENCOUNTER_ID);
        sSoundProjectionMap.put(SoundSQLFormat.FILE_URI, SoundSQLFormat.FILE_URI);
//        sSoundProjectionMap.put(SoundSQLFormat.FILE_VALID, SoundSQLFormat.FILE_VALID);
//        sSoundProjectionMap.put(SoundSQLFormat.FILE_SIZE, SoundSQLFormat.FILE_SIZE);
        sSoundProjectionMap.put(SoundSQLFormat.UPLOADED, SoundSQLFormat.UPLOADED);
        sSoundProjectionMap.put(SoundSQLFormat.UPLOAD_PROGRESS, SoundSQLFormat.UPLOAD_PROGRESS);
        sSoundProjectionMap.put(SoundSQLFormat.CREATED_DATE, SoundSQLFormat.CREATED_DATE);
        sSoundProjectionMap.put(SoundSQLFormat.MODIFIED_DATE, SoundSQLFormat.MODIFIED_DATE);
    }

}


text:
package org.hillview.sketches;

import org.hillview.dataset.api.ISketch;
import org.hillview.table.api.ContentsKind;
import org.hillview.table.api.IColumn;
import org.hillview.table.api.IRowIterator;
import org.hillview.table.api.ITable;
import org.hillview.utils.Converters;
import org.hillview.utils.Randomness;

import javax.annotation.Nullable;
import java.security.InvalidParameterException;
import java.util.List;

/**
 * Implements the Johnson-Lindenstrauss (JL) sketch. It projects a column of doubles down to low
 * dimensional vectors, where the projection matrix consists of random +1,-1 entries. Currently,
 * this sketch can be used to compute approximate inner products. However, it is much slower than
 * sampling based methods (SampleCorrelationSketch). A potential advantage over that method is that
 * the JL sketch gives a guarantee even if the entries are not bounded, whereas the sampling based
 * methods assume boundedness for provable guarantees.
 */
public class JLSketch implements ISketch<ITable, JLProjection>{
    /**
     * The list of columns that we wish to sketch. Currently, every column is assumed to be of type
     * int or double.
     */
    private final List<String> colNames;
    /**
     * The dimension that we wish to project down to.
     */
    private final int lowDim;

    public JLSketch(List<String> colNames, int lowDim) {
        this.colNames= colNames;
        this.lowDim = lowDim;
    }

    @Nullable
    @Override
    public JLProjection zero() {
        return new JLProjection(this.colNames, this.lowDim);
    }

    @Nullable
    @Override
    public JLProjection add(@Nullable JLProjection left, @Nullable JLProjection right) {
        left = Converters.checkNull(left);
        right = Converters.checkNull(right);
        for (String s: left.colNames) {
            double a[] = left.hMap.get(s);
            double b[] = right.hMap.get(s);
            double val[] = new double[this.lowDim];
            for (int i = 0; i < this.lowDim; i++)
                val[i] = a[i] + b[i];
            left.hMap.put(s, val);
        }
        left.highDim += right.highDim;
        return left;
    }

    /**
     * The sketch of a column is the product with a random matrix of {-1,+1} entries. The same
     * matrix is applied to every column. Currently, we discard the random bits after processing the
     * relevant row of the Table.
     * @param data  Data to sketch.
     * @return A JL projection.
     */
    @Override
    public JLProjection create(ITable data) {
        for (String col : this.colNames) {
            if ((data.getSchema().getKind(col) != ContentsKind.Double) &&
                    (data.getSchema().getKind(col) != ContentsKind.Integer))
                throw new InvalidParameterException("Projection Sketch requires column to be " +
                        "integer or double: " + col);
        }
        JLProjection jlProj = new JLProjection(this.colNames, this.lowDim);
        long seed = System.nanoTime();
        Randomness rn = new Randomness(seed);
        int i, bit;
        double val;
        String name;
        IColumn iCol;
        IRowIterator rowIt = data.getRowIterator();
        i = rowIt.getNextRow();
        while (i != -1) {
            for (int j = 0; j < this.lowDim; j++) {
                bit = ((rn.nextInt(2) == 0) ? 1 : -1);
                for (String colName: this.colNames) {
                    iCol= data.getColumn(colName);
                    val = (iCol.isMissing(i) ? 0 : (iCol.asDouble(i, null) * bit));
                    jlProj.update(colName, j, val);
                }
            }
            i = rowIt.getNextRow();
        }
        jlProj.highDim = data.getNumOfRows();
        return jlProj;
    }
}