text:
import 'ngDialog'
import '~/authentication'
import '~/filters/moment'
import '~/filters/lodash'
import '~/filters/lstring'
import '~/directives/comments/internal-comments'
import './directives/notification'
import './directives/meeting-document'
import './directives/meeting'
import './directives/decision-reference'
import _       from 'lodash'
import ng      from 'angular'
import rangy   from 'rangy'
import $       from 'jquery'
import roman         from './data/romans'
import sectionList   from './data/sections'
import paragraphList from './data/paragraphes'
import itemList      from './data/items'
import subItemList   from './data/sub-items'
import actorList     from './data/actors'
import statusesList  from './data/statuses'

export { default as template } from './edit.html'

export default ['$scope', '$http', '$route', '$location', '$filter', '$q', '$compile', 'ngDialog', 'user', '$anchorScroll', function($scope, $http, $route, $location, $filter, $q, $compile, ngDialog, user, $anchorScroll) {

        var treaty        = null;
        var body          = $route.current.params.body.toUpperCase();
        var session       = parseInt($route.current.params.session);
        var decision      = parseInt($route.current.params.decision);
        var selectedElement = null;

             if(body=='COP') treaty = { code : "XXVII8" } ;
    //  else if(body=='CP')  treaty = "XXVII8a";
    //  else if(body=='NP')  treaty = "XXVII8b";

        if(!treaty) {
            alert('ONLY "COP" DECISIONS ARE SUPPORTED');
            throw 'ONLY "COP" DECISIONS ARE SUPPORTED';
        }

        if(!_.isFinite(session)  || session <1) { $scope.paramError = "session_invalid";  return this; }
        if(!_.isFinite(decision) || decision<1) { $scope.paramError = "decision_invalid"; return this; }

        var data = { content: 'loading...' };

        $scope.self    = $scope;
        $scope.canEdit = canEdit();
        $scope.canView = canView();
        $scope.canDebug = canDebug();
        $scope.user   = _.pick(user, ['userID', 'name']);
        $scope.close  = close;
        $scope.save   = save;
        $scope.upload = upload;
        $scope.comments    = {};
        $scope.commentResources = [];
        $scope.buildFileUrl = buildFileUrl;
        $scope.selectDecision = selectDecision;
        $scope.selectMeeting  = selectMeeting;
        $scope.selectMeetingDocument = selectMeetingDocument;
        $scope.selectNotification = selectNotification;
        $scope.actionEdit  = edit;
        $scope.isEditable  = isEditable;
        $scope.tag         = tag;
        $scope.actionBox   = surroundSelection;
        $scope.actionUnbox = unsurroundSelection;
        $scope.actionClean = removeSelectionFormatting;
        $scope.jumpTo      = jumpTo;
        $scope.initials=function(t) { return _.startCase(t).replace(/[^A-Z]/g, ''); };
        $scope.addTo       = addTo;
        $scope.removeFrom  = removeFrom;

        $scope.noNarrower = function(t) { return !t.narrowerTerms || !t.narrowerTerms.length; };
        $scope.collections = {
            sections    : sectionList,
            paragraphes : paragraphList,
            items       : itemList,
            subItems    : subItemList,
            actorsMap   : _(actorList   ).reduce(function(r,v){ r[v.code] = v; return r; }, {}),
            statusesMap : _(statusesList).reduce(function(r,v){ r[v.code] = v; return r; }, {})
        };

        $scope.selectedActor = '';
        $scope.selectedStatus = '';

        $scope.$on('comments', loadComments);

        load();

        return this;

        //************************************************************
        //************************************************************
        //************************************************************
        //************************************************************

        //==============================
        //
        //==============================
        function close() {
            $location.url(('/'+body+'/'+session+'/'+decision).toLowerCase());
        }

        //===========================
        //
        //===========================
        function load() {

            var q0 = $http.get('/api/v2013/thesaurus/domains/CBD-SUBJECTS/terms',  { cache: true } );
            var q1 = $http.get('/api/v2013/thesaurus/domains/AICHI-TARGETS/terms', { cache: true } );
            var q2 = $http.get('/api/v2015/treaties/'+ encodeURIComponent(treaty.code), { cache: true } );

            $q.all([q0, q1, q2]).then(function(res) {

                $scope.collections.subjects        =   res[0].data;
                $scope.collections.aichiTargets    =   res[1].data;
                $scope.collections.subjectsMap     = _(res[0].data).reduce(function(r,v){ r[v.identifier] = v; return r; }, {});
                $scope.collections.aichiTargetsMap = _(res[1].data).reduce(function(r,v){ r[v.identifier] = v; return r; }, {});

                treaty   = res[2].data;

                return $http.get('/api/v2016/decision-texts', { params : { q : { $or: [{ decision: roman[session] + '/' + decision}, { treaty:treaty.code,  body: body, session: session, decision: decision }]}, fo: 1 }});

            }).then(function(res){

                data = res.data || {
                    treaty  : treaty.code,
                    body    : body,
                    session : session,
                    decision: decision,
                    meeting : body+'-'+ pad(session),
                    subjects : [],
                    aichiTargets : [],
                    content: 'paste here'
                };

                data = _.defaults(data, {
                    symbol : data.decision,
                    body   : body,
                    treaty : treaty.code,
                    subjects : [],
                    aichiTargets : []
                });

                if(typeof(data.decision)=='string') {
                    data.decision = parseInt(data.symbol.replace(/.*\/(\d+)$/, '$1'));
                }

                $scope.subjects     = data.subjects     = (data.subjects     || []);
                $scope.aichiTargets = data.aichiTargets = (data.aichiTargets || []);

                $('#content').html(data.content);

                clean($('#content')[0]);
                clean($('#content')[0]);
                clean($('#content')[0]);

                $('#content,element').mousedown(mousedown_selectNode);

            }).then(function(){

                lazyRetag();
                loadComments();

            }).catch(function(err){

                err = (err||{}).data || err;

                console.error(err);

                if(err.status==403)
                    $location.url('/403?returnurl='+encodeURIComponent($location.url()));

                alert(err.message||err);
            });
        }

        function lazyRetag(paragraphes) {
            if(paragraphes && paragraphes.length==0) {
                selectNode(null);
                return;
            }

            paragraphes = paragraphes || $('#content element').toArray();

            var el = paragraphes.shift();

            $scope.$applyAsync(function(){ selectNode(el);         });
            $scope.$applyAsync(function(){ tag();                  });
            $scope.$applyAsync(function(){ lazyRetag(paragraphes); });
        }

        //===========================
        //
        //===========================
        function save() {

            if(!canEdit()) {
                alert("Unauthorized to save");
                throw new Error("unauthorized to save");
            }

            var selectedNode = selectedElement;

            selectNode(null);

            //Cleanup data;

            clearCommentButton();

            $('#content element').each(function() {
                var info = $(this).data('info');

                if(info && info.type!='paragraph') {
                    delete info.data;
                    $(this).attr('data-info', ng.toJson(info));
                }
            });

            // Save

            data.content = $('#content').html();

            updateCommentButton();

            var req = {
                method : data._id ? 'PUT' : 'POST',
                url    : '/api/v2016/decision-texts' + (data._id ? '/'+data._id : ''),
                data   : _.pick(data, "_id","treaty","body","session","decision","meeting","content","subjects","aichiTargets")
            };

            $http(req).then(function(res){

                data._id = data._id || res.data._id;

                selectNode(selectedNode);

                alert( "Your document has been successfully saved." );

            }).catch(function(err){

                err = (err||{}).data || err;

                console.error(err);

                alert(err.message||JSON.stringify(err, null, ' '));
            });
        }

        //===========================
        //
        //===========================
        function loadComments() {

            return $http.get('/api/v2017/comments', { params : { q: { type:'decision', resources: data.code } } }).then(function(res){

                var comments = res.data;

                $scope.comments = {};

                comments.forEach(function(comment){
                    comment.resources.forEach(function(key){
                        $scope.comments[key] = $scope.comments[key]||[];
                        $scope.comments[key].push(comment);
                    });
                });

                updateCommentButton();

            }).catch(console.error);
        }

        updateCommentButton();

        //===========================
        //
        //===========================
        function clearCommentButton() {
            ng.element('#content button.comment').remove();
        }

        //===========================
        //
        //===========================
        function updateCommentButton() {

            clearCommentButton();

            $scope.$applyAsync(function(){

                ng.element('#content element[data-type^=paragraph]').each(function(){

                    var $this = ng.element(this);
                    var info =  $this.data('info');
                    var btn   = $compile('<button class="btn btn-link comment" ng-click="jumpTo(\'comment\')"></button>')($scope);

                    if(($scope.comments[info.code]||[]).length)
                        btn.addClass('has-comments');

                    $this.append(btn);
                });

            });

        }

        //===========================
        //
        //===========================
        function edit(editable) {

            var $div = $('#content');

            editable = editable===undefined ? !isEditable() : !!editable;

            $div.prop('contenteditable', editable);

            if(editable)
                $div.focus();
        }

        //===========================
        //
        //===========================
        function isEditable() {
            return $('#content').prop('contenteditable') == 'true';
        }

        //==============================
        //
        //==============================
        function pad(input) {

            var output = (input || '').toString();

            while(output.length<2)
                output = '0' + output;

            return output;
        }

        //===========================
        //
        //===========================
        function tag() {

            if(!selectedElement) return;
            if(!$scope.element)  return;

            var element = $scope.element;

            element.section   = element.type=='paragraph' ? (element.section  || undefined) : undefined;
            element.paragraph = element.type=='paragraph' ? (element.paragraph|| undefined) : undefined;
            element.item      = element.type=='paragraph' ? (element.item     || undefined) : undefined;
            element.subitem   = element.type=='paragraph' ? (element.subitem  || undefined) : undefined;

            var data = element.data = element.data || { };

            data.section   = element.section   && element.section.toUpperCase();
            data.paragraph = element.paragraph && parseInt(element.paragraph);
            data.item      = element.item      && element.item.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
            data.subitem   = element.subitem   && roman.indexOf(element.subitem.toUpperCase());

            // tag
            var tag = element.type || '';

            if(element.section)   tag += ' ' + element.section;
            if(element.paragraph) tag += ' ' + element.paragraph;
            if(element.item)      tag += ''  + element.item;
            if(element.subitem)   tag += ' (' + element.subitem + ')';

            if(tag) $(selectedElement).attr('data-type', tag);
            else    $(selectedElement).removeAttr('data-type');

            updateCommentButton();
        }

        //===========================
        //
        //===========================
        function surroundSelection(tag) {

            var range = window.getSelection().getRangeAt(0);

            var commonAncestor = $(range.commonAncestorContainer);

            if(!commonAncestor.is("#content") && !commonAncestor.parents('#content').length) {
                alert('Please select text from the decision');
                return;
            }

            var span = document.createElement(tag);
            var content = range.extractContents();

            span.appendChild(content);
            range.insertNode(span);

            clean($('#content')[0]);
            clean($('#content')[0]);
            clean($('#content')[0]);

            $(span).mousedown(mousedown_selectNode);

            selectNode(span);
        }

        //===========================
        //
        //===========================
        function unsurroundSelection() {

            if(!selectedElement) return alert('no selectedElement');

            $(selectedElement).contents().unwrap();

            selectedElement = null;
        }

        //===========================
        //
        //===========================
        function selectNode(node) {

            delete $scope.formattingLocked;

            $(selectedElement).attr('data-info', ng.toJson(cleanup($scope.element, true)));

            $(selectedElement).removeClass('selected');

            delete $scope.element;

            selectedElement = node;

            if(!selectedElement) {
                $scope.commentResources = [];
                return;
            }

            $(selectedElement).addClass('selected');

            $scope.element = cleanup($(selectedElement).data('info') || {});

            if(($scope.element.data||{}).type == 'information')
                $scope.element.data.type = 'informational';

            if($scope.element.data) {
                $scope.element.data.statusInfo = $scope.element.data.statusInfo || $scope.element.elementStatusDetails;
                delete $scope.element.elementStatusDetails;
            }

            $scope.formattingLocked = !!$scope.element.type;
            $scope.commentResources = _.compact([data.code, $scope.element.code]);
        }

        //===========================
        //
        //===========================
        function cleanup(element, deleteEmpty) {

            if(element && element.data) {

                element.data.subjects      = _(element.data.subjects     ||[]).uniq().value();
                element.data.aichiTargets  = _(element.data.aichiTargets ||[]).uniq().value();
                element.data.actors        = _(element.data.actors       ||[]).uniq().value();
                element.data.statuses      = _(element.data.statuses     ||[]).uniq().value();
                element.data.decisions     = _(element.data.decisions    ||[]).uniq().value();
                element.data.notifications = _(element.data.notifications||[]).uniq().value();
                element.data.documents     = _(element.data.documents    ||[]).uniq().value();
                element.data.meetings      = _(element.data.meetings     ||[]).uniq().map(mettingUrlToCode).value();

                if(deleteEmpty) { // Remove empty fields/arrays

                    for(var key in element.data) {

                        var val = element.data[key];

                        if(val===undefined) { delete element.data[key]; continue; }
                        if(val===null)      { delete element.data[key]; continue; }
                        if(val==="")        { delete element.data[key]; continue; }

                        if(_.isArray(val) && !val.length) {
                            delete element.data[key]; continue;
                        }
                    }
                }
            }

            return element;
        }

        //===========================
        //
        //===========================
        function mettingUrlToCode(m) {

            var meetingUrlRE = /^https?:\/\/www.cbd.int\/meetings\/([a-zA-Z0-9\-]+)$/;

            if(meetingUrlRE.test(m))
                m = m.replace(meetingUrlRE, '$1');

            return m;
        }

        //===========================
        //
        //===========================
        function mousedown_selectNode(event) {

            var node = this; // jshint ignore: line

            event.stopPropagation();

            jumpTo('top');

            $scope.$applyAsync(function(){
                selectNode(node);
            });
        }

        //===========================
        //
        //===========================
        function clean(node) {

            for(var n = 0; n < node.childNodes.length; n ++) {

                var child = node.childNodes[n];

                if(child.nodeType === 8 || (child.nodeType === 3 && !/\S/.test(child.nodeValue))) {

                    node.removeChild(child);
                    n --;

                } else if(child.nodeType === 1) {

                    clean(child);

                    if(!child.innerHTML)
                        node.removeChild(child);
                }
            }
        }

        //===========================
        //
        //===========================
        function addTo(item, target) {

            if(!_.isArray(target)) throw new Error("target must be an array");

            if(target.indexOf(item) < 0)
                target.push(item);

            return target;
        }

        //===========================
        //
        //===========================
        function removeFrom(item, target) {

            if(!_.isArray(target)) throw new Error("target must be an array");

            var index;

            while((index = target.indexOf(item)) >= 0)
                target.splice(index, 1);

            return target;
        }

        ////////////////////
        // FILES
        ////////////////////

        //===========================
        //
        //===========================
        function upload() {

            var fileUpload = $('<input type="file" accept="application/pdf" multiple="" style="display:none">');

            $("ng-view").append(fileUpload);

            fileUpload.bind("change", function(){
                _.forEach(this.files, uploadFile);
            });

            fileUpload.click();
        }

        //===========================
        //
        //===========================
        function uploadFile(file) {

            if(!file)
                return;

            var fileInfo = {
                filename : file.name.toLowerCase(),
                size : file.size
            };

            $scope.uploads = $scope.uploads || [];
            $scope.uploads.push(fileInfo);

            var postData = {
                filename : file.name,
                metadata : {
                    source  : 'dtt',
                    paragraph : $scope.element.data.code
                }
            };

            return $http.post('/api/v2015/temporary-files', postData).then(resData).then(function(target) {

                return $http.put(target.url, file, { headers : { 'Content-Type' : target.contentType } }).then(function(){
                    return target;
                });

            }).then(function(target) {

                return $http.get('/api/v2015/temporary-files/'+target.uid).then(resData);

            }).then(function(meta) {

                // fileInfo.url         = 'upload://'+meta.uid;  // TODO: Use upload://{uid} instead of hash
                fileInfo.filename    = meta.filename;
                fileInfo.contentType = meta.contentType;
                fileInfo.size        = meta.size;
                fileInfo.hash        = meta.hash;

                var index;

                while(~(index = $scope.uploads.indexOf(fileInfo)))
                    $scope.uploads.splice(index, 1);

                $scope.element.data.files = $scope.element.data.files||[];
                $scope.element.data.files.push(fileInfo);

            }).catch(function(err) {

                console.error((err||{}).message || err);

                fileInfo.error = (err||{}).data || err;

            });
        }

        //===========================
        //
        //===========================
        function buildFileUrl(item) {
            return '/api/v2016/decision-texts/'+data._id+'/attachments/'+item.hash+'/stream';
        }

        ////////////////////
        // DIALOGS
        ////////////////////

        //===========================
        //
        //===========================
        function selectMeetingDocument() {

            openDialog(import('./select-document-dialog'), { showClose: false }).then(function(dialog){

                dialog.closePromise.then(function(res){

                    if(!res.value)
                        return;

                    addTo(res.value, $scope.element.data.documents);
                });
            });
        }

        //===========================
        //
        //===========================
        function selectDecision() {

            openDialog(import('./select-decision-dialog'), { showClose: false }).then(function(dialog){

                dialog.closePromise.then(function(res){

                    if(!res.value)
                        return;

                    addTo(res.value, $scope.element.data.decisions);
                });
            });
        }

        //===========================
        //
        //===========================
        function selectNotification() {

            openDialog(import('./select-notification-dialog'), { showClose: false }).then(function(dialog){

                dialog.closePromise.then(function(res){

                    if(!res.value)
                        return;

                    addTo(res.value.symbol, $scope.element.data.notifications);
                });
            });
        }

        //===========================
        //
        //===========================
        function selectMeeting() {

            openDialog(import('./select-meeting-dialog'), { showClose: false }).then(function(dialog){

                dialog.closePromise.then(function(res){

                    if(!res.value)
                        return;

                    addTo(mettingUrlToCode(res.value.symbol), $scope.element.data.meetings);
                });
            });
        }

        //===========================
        //
        //===========================
        async function openDialog(dialog, options) {

            options = options || {};

            return $q.when(dialog).then(({ template, default: controller })=>{
                options.plain = true;
                options.template = template;
                options.controller = controller;

                var dialog = ngDialog.open(options);

                dialog.closePromise.then(function(res){

                    if(res.value=="$escape")      delete res.value;
                    if(res.value=="$document")    delete res.value;
                    if(res.value=="$closeButton") delete res.value;

                    return res;
                });

                return dialog;
            });
        }

        function canDebug() { return !!_.intersection(user.roles, ["Administrator"]).length; }
        function canEdit()  { return !!_.intersection(user.roles, ["DecisionTrackingTool"]).length; }
        function canView()  { return !!_.intersection(user.roles, ["Administrator","DecisionTrackingTool", "ScbdStaff"]).length; }

        //==============================
        //
        //==============================
        function jumpTo(hash) {

            if(!hash)
                return;

            $scope.$applyAsync(function() {
                $anchorScroll(hash);
            });
        }
    }];

    //===========================
    //
    //===========================
    function replaceWithOwnChildren(el) {
        var parent = el.parentNode;
        while (el.hasChildNodes()) {
            parent.insertBefore(el.firstChild, el);
        }
        parent.removeChild(el);
    }

    //===========================
    //
    //===========================
    function removeSelectionFormatting() {
        var range, sel = rangy.getSelection();

        if(sel.isCollapsed)
            return;

        for (var r = 0; r < sel.rangeCount; ++r) {

            var commonAncestor = $(sel.getRangeAt(r).commonAncestorContainer);

            if(!commonAncestor.is("#content") && !commonAncestor.parents('#content').length) {
                alert('Please select text only from the decision');
                return;
            }
        }

        for (var i = 0; i < sel.rangeCount; ++i) {
            range = sel.getRangeAt(i);

            // Split partially selected nodes
            range.splitBoundaries();

            // Get formatting elements. For this example, we'll count any
            // element with display: inline, except
s.
            var formattingEls = range.getNodes([1], function(el) {
                return el.tagName != "BR";
            });

            // Remove the formatting elements
            for (var j = 0; j<formattingEls.length; j++) {
                replaceWithOwnChildren(formattingEls[j]);
            }
        }
    }

    //===========================
    //
    //===========================
    function resData(res) {
        return res.data;
    }

    //========================================
    //
    //
    //========================================
    function solrEscape(value) {

        if(value===undefined) throw "Value is undefined";
        if(value===null)      throw "Value is null";
        if(value==="")        throw "Value is null";

        if(_.isNumber(value)) value = value.toString();
        if(_.isDate  (value)) value = value.toISOString();

        //TODO add more types

        value = value.toString();

        value = value.replace(/\\/g,   '\\\\');
        value = value.replace(/\+/g,   '\\+');
        value = value.replace(/\-/g,   '\\-');
        value = value.replace(/\&\&/g, '\\&&');
        value = value.replace(/\|\|/g, '\\||');
        value = value.replace(/\!/g,   '\\!');
        value = value.replace(/\(/g,   '\\(');
        value = value.replace(/\)/g,   '\\)');
        value = value.replace(/\{/g,   '\\{');
        value = value.replace(/\}/g,   '\\}');
        value = value.replace(/\[/g,   '\\[');
        value = value.replace(/\]/g,   '\\]');
        value = value.replace(/\^/g,   '\\^');
        value = value.replace(/\"/g,   '\\"');
        value = value.replace(/\~/g,   '\\~');
        value = value.replace(/\*/g,   '\\*');
        value = value.replace(/\?/g,   '\\?');
        value = value.replace(/\:/g,   '\\:');

        return value;
    }


text:
#ifndef DBCOMMON_SRC_DBCOMMON_UTILS_TIMEZONE_UTIL_H_
#define DBCOMMON_SRC_DBCOMMON_UTILS_TIMEZONE_UTIL_H_

// This file is for timezone routines.

#include <stdint.h>

#include <ctime>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace dbcommon {

// default location of the timezone files
const char DEFAULT_TZDIR[] = "/usr/share/zoneinfo";

// location of a symlink to the local timezone
const char LOCAL_TIMEZONE[] = "/etc/localtime";

const int64_t MONTHS_PER_YEAR = 12;

// The number of days in each month in non-leap and leap years.
const int64_t DAYS_PER_MONTH[2][MONTHS_PER_YEAR] = {
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
const int64_t SECONDS_PER_HOUR = 60 * 60;
const int64_t SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
const int64_t DAYS_PER_WEEK = 7;

// Leap years and day of the week repeat every 400 years, which makes it
// a good cycle length.
const int64_t SECONDS_PER_400_YEARS =
    SECONDS_PER_DAY * (365 * (300 + 3) + 366 * (100 - 3));

// Is the given year a leap year?
inline bool isLeap(int64_t year) {
  return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
}

// A variant  (eg. PST or PDT) of a timezone (eg. America/Los_Angeles).
struct TimezoneVariant {
  int64_t gmtOffset;
  bool isDst;
  std::string name;

  std::string toString() const { return "Not-implemented"; }
};

// A region that shares the same legal rules for wall clock time and
// day light savings transitions. They are typically named for the largest
// city in the region (eg. America/Los_Angeles or America/Mexico_City).
class Timezone {
 public:
  virtual ~Timezone();

  // Get the variant for the given time (time_t).
  virtual const TimezoneVariant& getVariant(int64_t clk) const = 0;

  // Get the number of seconds between the ORC epoch in this timezone
  // and Unix epoch.
  // ORC epoch is 1 Jan 2015 00:00:00 local.
  // Unix epoch is 1 Jan 1970 00:00:00 UTC.
  virtual int64_t getEpoch() const = 0;

  // Print the timezone to the stream.
  virtual void print(std::ostream&) const = 0;

  // Get the version of the zone file.
  virtual uint64_t getVersion() const = 0;
};

// Get the local timezone.
// Results are cached.
const Timezone& getLocalTimezone();

// Get a timezone by name (eg. America/Los_Angeles).
// Results are cached.
const Timezone& getTimezoneByName(const std::string& zone);

// Parse a set of bytes as a timezone file as if they came from filename.
std::unique_ptr<Timezone> getTimezone(const std::string& filename,
                                      const std::vector<unsigned char>& b);

class TimezoneError : public std::runtime_error {
 public:
  explicit TimezoneError(const std::string& what);
  explicit TimezoneError(const TimezoneError&);
  virtual ~TimezoneError() noexcept;
};

enum TransitionKind { TRANSITION_JULIAN, TRANSITION_DAY, TRANSITION_MONTH };

struct Transition {
  TransitionKind kind;
  int64_t day;
  int64_t week;
  int64_t month;
  int64_t time;

  std::string toString() const {
    std::stringstream buffer;
    switch (kind) {
      case TRANSITION_JULIAN:
        buffer << "julian " << day;
        break;
      case TRANSITION_DAY:
        buffer << "day " << day;
        break;
      case TRANSITION_MONTH:
        buffer << "month " << month << " week " << week << " day " << day;
        break;
    }
    buffer << " at " << (time / (60 * 60)) << ":" << ((time / 60) % 60) << ":"
           << (time % 60);
    return buffer.str();
  }

  // Get the transition time for the given year.
  // @param year the year
  // @return the number of seconds past local Jan 1 00:00:00 that the
  //    transition happens.
  int64_t getTime(int64_t year) const {
    int64_t result = time;
    switch (kind) {
      case TRANSITION_JULIAN:
        result += SECONDS_PER_DAY * day;
        if (day > 60 && isLeap(year)) {
          result += SECONDS_PER_DAY;
        }
        break;
      case TRANSITION_DAY:
        result += SECONDS_PER_DAY * day;
        break;
      case TRANSITION_MONTH: {
        bool inLeap = isLeap(year);
        int64_t adjustedMonth = (month + 9) % 12 + 1;
        int64_t adjustedYear = (month <= 2) ? (year - 1) : year;
        int64_t adjustedCentury = adjustedYear / 100;
        int64_t adjustedRemainder = adjustedYear % 100;

        // day of the week of the first day of month
        int64_t dayOfWeek = ((26 * adjustedMonth - 2) / 10 + 1 +
                             adjustedRemainder + adjustedRemainder / 4 +
                             adjustedCentury / 4 - 2 * adjustedCentury) %
                            7;
        if (dayOfWeek < 0) {
          dayOfWeek += DAYS_PER_WEEK;
        }

        int64_t d = day - dayOfWeek;
        if (d < 0) {
          d += DAYS_PER_WEEK;
        }
        for (int w = 1; w < week; ++w) {
          if (d + DAYS_PER_WEEK >= DAYS_PER_MONTH[inLeap][month - 1]) {
            break;
          }
          d += DAYS_PER_WEEK;
        }
        result += d * SECONDS_PER_DAY;

        // Add in the time for the month
        for (int m = 0; m < month - 1; ++m) {
          result += DAYS_PER_MONTH[inLeap][m] * SECONDS_PER_DAY;
        }
        break;
      }
    }
    return result;
  }
};

// Represents the parsed POSIX timezone rule strings that are used to
// describe the future transitions, because they can go arbitrarily far into
// the future.
class FutureRule {
 public:
  virtual ~FutureRule();
  virtual bool isDefined() const = 0;
  virtual const TimezoneVariant& getVariant(int64_t clk) const = 0;
  virtual void print(std::ostream* out) const = 0;
};

// Parse the POSIX TZ string.
std::unique_ptr<FutureRule> parseFutureRule(const std::string& ruleString);

// The current rule for finding timezone variants arbitrarily far in
// the future.  They are based on a string representation that
// specifies the standard name and offset. For timezones with
// daylight savings, the string specifies the daylight variant name
// and offset and the rules for switching between them.
//
// rule = <standard name><standard offset><daylight>?
// name = string with no numbers or '+', '-', or ','
// offset = [-+]?hh(:mm(:ss)?)?
// daylight = <name><offset>,<start day>(/<offset>)?,<end day>(/<offset>)?
// day = J<day without 2/29>|<day with 2/29>|M<month>.<week>.<day of week>
class FutureRuleImpl : public FutureRule {
  std::string ruleString;
  TimezoneVariant standard;
  bool hasDst;
  TimezoneVariant dst;
  Transition start;
  Transition end;

  // expanded time_t offsets of transitions
  std::vector<int64_t> offsets;

  // Is the epoch (1 Jan 1970 00:00) in standard time?
  // This code assumes that the transition dates fall in the same order
  // each year. Hopefully no timezone regions decide to move across the
  // equator, which is about what it would take.
  bool startInStd;

  void computeOffsets() {
    if (!hasDst) {
      startInStd = true;
      offsets.resize(1);
    } else {
      // Insert a transition for the epoch and two per a year for the next
      // 400 years. We assume that the all even positions are in standard
      // time if and only if startInStd and the odd ones are the reverse.
      offsets.resize(400 * 2 + 1);
      startInStd = start.getTime(1970) < end.getTime(1970);
      int64_t base = 0;
      for (int64_t year = 1970; year < 1970 + 400; ++year) {
        if (startInStd) {
          offsets[static_cast<uint64_t>(year - 1970) * 2 + 1] =
              base + start.getTime(year) - standard.gmtOffset;
          offsets[static_cast<uint64_t>(year - 1970) * 2 + 2] =
              base + end.getTime(year) - dst.gmtOffset;
        } else {
          offsets[static_cast<uint64_t>(year - 1970) * 2 + 1] =
              base + end.getTime(year) - dst.gmtOffset;
          offsets[static_cast<uint64_t>(year - 1970) * 2 + 2] =
              base + start.getTime(year) - standard.gmtOffset;
        }
        base += (isLeap(year) ? 366 : 365) * SECONDS_PER_DAY;
      }
    }
    offsets[0] = 0;
  }

 public:
  virtual ~FutureRuleImpl();
  bool isDefined() const override;
  const TimezoneVariant& getVariant(int64_t clk) const override;
  void print(std::ostream* out) const override;

  friend class FutureRuleParser;
};

// A parser for the future rule strings.
class FutureRuleParser {
 public:
  FutureRuleParser(const std::string& str, FutureRuleImpl* rule)
      : ruleString(str), length(str.size()), position(0), output(*rule) {
    output.ruleString = str;
    if (position != length) {
      parseName(&(output.standard.name));
      output.standard.gmtOffset = -parseOffset();
      output.standard.isDst = false;
      output.hasDst = position < length;
      if (output.hasDst) {
        parseName(&(output.dst.name));
        output.dst.isDst = true;
        if (ruleString[position] != ',') {
          output.dst.gmtOffset = -parseOffset();
        } else {
          output.dst.gmtOffset = output.standard.gmtOffset + 60 * 60;
        }
        parseTransition(&(output.start));
        parseTransition(&(output.end));
      }
      if (position != length) {
        throwError("Extra text");
      }
      output.computeOffsets();
    }
  }

 private:
  const std::string& ruleString;
  size_t length;
  size_t position;
  FutureRuleImpl& output;

  void throwError(const char* msg) {
    std::stringstream buffer;
    buffer << msg << " at " << position << " in '" << ruleString << "'";
    LOG_ERROR(ERRCODE_INTERNAL_ERROR, "%s", buffer.str().c_str());
  }

  // Parse the names of the form:
  //    ([^-+0-9,]+|<[^>]+>)
  // and set the output string.
  void parseName(std::string* result) {
    if (position == length) {
      throwError("name required");
    }
    size_t start = position;
    if (ruleString[position] == '<') {
      while (position < length && ruleString[position] != '>') {
        position += 1;
      }
      if (position == length) {
        throwError("missing close '>'");
      }
      position += 1;
    } else {
      while (position < length) {
        char ch = ruleString[position];
        if (isdigit(ch) || ch == '-' || ch == '+' || ch == ',') {
          break;
        }
        position += 1;
      }
    }
    if (position == start) {
      throwError("empty string not allowed");
    }
    *result = ruleString.substr(start, position - start);
  }

  // Parse an integer of the form [0-9]+ and return it.
  int64_t parseNumber() {
    if (position >= length) {
      throwError("missing number");
    }
    int64_t result = 0;
    while (position < length) {
      char ch = ruleString[position];
      if (isdigit(ch)) {
        result = result * 10 + (ch - '0');
        position += 1;
      } else {
        break;
      }
    }
    return result;
  }

  // Parse the offsets of the form:
  //    [-+]?[0-9]+(:[0-9]+(:[0-9]+)?)?
  // and convert it into a number of seconds.
  int64_t parseOffset() {
    int64_t scale = 3600;
    bool isNegative = false;
    if (position < length) {
      char ch = ruleString[position];
      isNegative = ch == '-';
      if (ch == '-' || ch == '+') {
        position += 1;
      }
    }
    int64_t result = parseNumber() * scale;
    while (position < length && scale > 1 && ruleString[position] == ':') {
      scale /= 60;
      position += 1;
      result += parseNumber() * scale;
    }
    if (isNegative) {
      result = -result;
    }
    return result;
  }

  // Parse a transition of the following form:
  //   ,(J<number>|<number>|M<number>.<number>.<number>)(/<offset>)?
  void parseTransition(Transition* transition) {
    if (length - position < 2 || ruleString[position] != ',') {
      throwError("missing transition");
    }
    position += 1;
    char ch = ruleString[position];
    if (ch == 'J') {
      transition->kind = TRANSITION_JULIAN;
      position += 1;
      transition->day = parseNumber();
    } else if (ch == 'M') {
      transition->kind = TRANSITION_MONTH;
      position += 1;
      transition->month = parseNumber();
      if (position == length || ruleString[position] != '.') {
        throwError("missing first .");
      }
      position += 1;
      transition->week = parseNumber();
      if (position == length || ruleString[position] != '.') {
        throwError("missing second .");
      }
      position += 1;
      transition->day = parseNumber();
    } else {
      transition->kind = TRANSITION_DAY;
      transition->day = parseNumber();
    }
    if (position < length && ruleString[position] == '/') {
      position += 1;
      transition->time = parseOffset();
    } else {
      transition->time = 2 * 60 * 60;
    }
  }
};

// Parse the POSIX TZ string.
extern std::unique_ptr<FutureRule> parseFutureRule(
    const std::string& ruleString);

// An abstraction of the differences between versions.
class VersionParser {
 public:
  virtual ~VersionParser();

  // Get the version number.
  virtual uint64_t getVersion() const = 0;

  // Get the number of bytes
  virtual uint64_t getTimeSize() const = 0;

  // Parse the time at the given location.
  virtual int64_t parseTime(const unsigned char* ptr) const = 0;

  // Parse the future string
  virtual std::string parseFutureString(const unsigned char* ptr,
                                        uint64_t offset,
                                        uint64_t length) const = 0;
};

class TimezoneImpl : public Timezone {
 public:
  TimezoneImpl(const std::string& name, const std::vector<unsigned char> bytes);
  virtual ~TimezoneImpl();

  // Get the variant for the given time (time_t).
  const TimezoneVariant& getVariant(int64_t clk) const override;

  void print(std::ostream&) const override;

  uint64_t getVersion() const override { return version; }

  int64_t getEpoch() const override { return epoch; }

 private:
  void parseTimeVariants(const unsigned char* ptr, uint64_t variantOffset,
                         uint64_t variantCount, uint64_t nameOffset,
                         uint64_t nameCount);
  void parseZoneFile(const unsigned char* ptr, uint64_t sectionOffset,
                     uint64_t fileLength, const VersionParser& version);
  // filename
  std::string filename;

  // the version of the file
  uint64_t version;

  // the list of variants for this timezone
  std::vector<TimezoneVariant> variants;

  // the list of the times where the local rules change
  std::vector<int64_t> transitions;

  // the variant that starts at this transition.
  std::vector<uint64_t> currentVariant;

  // the variant before the first transition
  uint64_t ancientVariant;

  // the rule for future times
  std::unique_ptr<FutureRule> futureRule;

  // the last explicit transition after which we use the future rule
  int64_t lastTransition;

  // The ORC epoch time in this timezone.
  int64_t epoch;
};

class TimezoneUtil {
 public:
  static TimezoneUtil& instance() {
    static TimezoneUtil s;
    return s;
  }

  static int32_t getGMTOffset(std::time_t time) {
    return static_cast<int32_t>(
        instance().timezone_->getVariant(time).gmtOffset);
  }

  static void setGMTOffset(std::string tzname) {
    instance().timezone_ = &(getTimezoneByName(tzname));
  }

 private:
  TimezoneUtil() { timezone_ = nullptr; }
  ~TimezoneUtil() {}
  TimezoneUtil(const TimezoneUtil&) = delete;
  TimezoneUtil& operator=(const TimezoneUtil&) = delete;
  const Timezone* timezone_;
};

}  // namespace dbcommon

#endif  // DBCOMMON_SRC_DBCOMMON_UTILS_TIMEZONE_UTIL_H_

redpajama_set_name: RedPajamaGithub


text:
// The MIT License (MIT)
// Copyright © 2015 AppsLandia. All rights reserved.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.appslandia.common.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 *
 * @author Loc Ha
 *
 */
public class ReflectionUtils {

	public static final Annotation[] EMPTY_ANNOTATIONS = {};
	public static final Object[] EMPTY_ARGS = {};

	public static interface FieldMatcher {
		boolean match(Field field);
	}

	public static interface FieldTraverser {
		boolean apply(Field field) throws ReflectionException;
	}

	public static interface MethodMatcher {
		boolean match(Method m);
	}

	public static interface MethodTraverser {
		boolean apply(Method m) throws ReflectionException;
	}

	public static final FieldTraverser FIND_FIELD_TRAVERSER = new FieldTraverser() {

		@Override
		public boolean apply(Field field) throws ReflectionException {
			return true;
		}
	};

	public static final MethodTraverser FIND_METHOD_TRAVERSER = new MethodTraverser() {

		@Override
		public boolean apply(Method m) throws ReflectionException {
			return true;
		}
	};

	public static Field findField(Class<?> clazz, final String property) throws ReflectionException {
		return traverse(clazz, new FieldMatcher() {

			@Override
			public boolean match(Field f) {
				if (f.getName().equals(property)) {
					return true;
				}
				if (f.getType() == boolean.class) {
					if (f.getName().equals("is" + StringUtils.firstUpperCase(property))) {
						return true;
					}
				}
				return false;
			}
		}, FIND_FIELD_TRAVERSER);
	}

	public static Method findMethod(Class<?> clazz, final String methodName) throws ReflectionException {
		return traverse(clazz, new MethodMatcher() {

			@Override
			public boolean match(Method m) {
				return m.getName().equals(methodName);
			}
		}, FIND_METHOD_TRAVERSER);
	}

	public static Field traverse(Class<?> clazz, FieldMatcher matcher, FieldTraverser traverser) throws ReflectionException {
		Field last = null;
		while (clazz != null) {
			for (Field field : clazz.getDeclaredFields()) {
				if (matcher.match(field)) {
					last = field;
					if (traverser.apply(field)) {
						return last;
					}
				}
			}
			clazz = clazz.getSuperclass();
		}
		return last;
	}

	public static Method traverse(Class<?> clazz, MethodMatcher matcher, MethodTraverser traverser) throws ReflectionException {
		Method last = null;
		while (clazz != null) {
			for (Method m : clazz.getDeclaredMethods()) {
				if (matcher.match(m)) {
					last = m;
					if (traverser.apply(m)) {
						return last;
					}
				}
			}
			clazz = clazz.getSuperclass();
		}
		return last;
	}

	public static Class<?> getListArgType(ParameterizedType type) {
		Type[] args = type.getActualTypeArguments();
		AssertUtils.assertTrue(args.length == 1);
		return parseArgumentType(args[0]);
	}

	public static Class<?>[] getMapArgTypes(ParameterizedType type) {
		Type[] args = type.getActualTypeArguments();
		AssertUtils.assertTrue(args.length == 2);
		return new Class<?>[] { parseArgumentType(args[0]), parseArgumentType(args[1]) };
	}

	private static Class<?> parseArgumentType(Type type) {
		if (type instanceof Class) {
			return (Class<?>) type;
		}
		if (type instanceof ParameterizedType) {
			Type rawType = ((ParameterizedType) type).getRawType();
			if (rawType instanceof Class) {
				return (Class<?>) rawType;
			}
		}
		throw new IllegalArgumentException("Type is not supported (type=" + type + ")");
	}

	public static void invoke(Method m, Object obj, Object... args) throws ReflectionException {
		try {
			m.invoke(obj, args);
		} catch (ReflectiveOperationException ex) {
			throw new ReflectionException(ex);
		}
	}

	public static void set(Field m, Object obj, Object value) throws ReflectionException {
		try {
			m.set(obj, value);
		} catch (ReflectiveOperationException ex) {
			throw new ReflectionException(ex);
		}
	}

	public static Object get(Field m, Object obj) throws ReflectionException {
		try {
			return m.get(obj);
		} catch (ReflectiveOperationException ex) {
			throw new ReflectionException(ex);
		}
	}

	public static void makeAccessible(Field m) {
		if (((Modifier.isPublic(m.getModifiers()) == false) || (Modifier.isPublic(m.getDeclaringClass().getModifiers()) == false) || Modifier.isFinal(m.getModifiers())) && (m.isAccessible() == false)) {
			m.setAccessible(true);
		}
	}

	public static void makeAccessible(Method m) {
		if (((Modifier.isPublic(m.getModifiers()) == false) || (Modifier.isPublic(m.getDeclaringClass().getModifiers()) == false)) && (m.isAccessible() == false)) {
			m.setAccessible(true);
		}
	}

	public static void makeAccessible(Constructor<?> ctor) {
		if (((Modifier.isPublic(ctor.getModifiers()) == false) || (Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) == false)) && (ctor.isAccessible() == false)) {
			ctor.setAccessible(true);
		}
	}
}


text:
'use strict';

var binsPromise = require('gramene-bins-client').binsPromise;
var treesPromise = require('gramene-trees-client').promise;
var Q = require('q');
var _ = require('lodash');

// given two objects that have the same keys and whose values are all integers
// return a new object that sums them together. If either object is null, return
// the other one.
function addCounts(o1, o2) {
  var result;
  if (o1 && o2) {
    result = _.merge(o1, o2, function (a, b) {
      return a + b;
    });
  }
  else if (o1) {
    result = o1;
  }
  else {
    result = o2;
  }
  return result;
}

function addGenomesToTaxonomy(taxonomy, genomes) {
  var taxonomyPrototype = Object.getPrototypeOf(taxonomy);
  taxonomy.leafNodes().forEach(function (speciesNode) {
    var species = speciesNode.model,
      genome = genomes.get(species.id);

    if (!genome) {
      console.warn('No genome found for', species);
    }

    species.genome = genome;
  });

  function calcStatsForTaxonomyNode(node) {
    var statsFromChildren,
      statsFromGenome;

    if (node.model.genome) {
      statsFromGenome = {
        genomes: 1,
        genes: node.model.geneCount,
        bins: node.model.genome.nbins
      };
    }

    if (node.children && node.children.length) {
      statsFromChildren = _.reduce(node.children, function (total, childNode) {
        return addCounts(total, calcStatsForTaxonomyNode(childNode));
      }, {genomes: 0, genes: 0, bins: 0});
    }

    node.model.stats = addCounts(statsFromGenome, statsFromChildren);

    return node.model.stats;
  }

  calcStatsForTaxonomyNode(taxonomy);

  taxonomyPrototype.genomes = function () {
    return this.leafNodes().map(function (species) {
      return species.model.genome;
    });
  };

  taxonomyPrototype.binCount = genomes.binCount.bind(genomes);

  taxonomyPrototype.getBin = function (idx) {
    return genomes.getBin(idx);
  };

  taxonomyPrototype.getBins = function (start, end) {
    return genomes.getBins(start, end);
  };

  taxonomyPrototype.allBins = function () {
    return genomes.allBins();
  };

  taxonomyPrototype.results = function () { return this.model.results; };
  taxonomyPrototype.stats = function () { return this.model.stats; };
  taxonomyPrototype.globalResultSetStats = function () { return genomes.stats };

  taxonomy.setResults = function () {
    var maxProportion = 0, maxProportionNode;
    genomes.setResults.apply(genomes, arguments);

    function updateCounts(node) {
      var countFromChildren={count: 0, bins: 0},
        countFromGenome={count: 0, bins: 0},
        resultCount, geneCount, proportion;

      if (node.model.genome) {
        countFromGenome = node.model.genome.results;
      }

      if (node.children && node.children.length) {
        countFromChildren = _.reduce(node.children, function (total, childNode) {
          return addCounts(total, updateCounts(childNode));
        }, {count: 0, bins: 0});
      }

      node.model.results = addCounts(countFromGenome, countFromChildren);

      resultCount = node.model.results.count;
      geneCount = node.model.stats.genes;
      proportion = geneCount ? (resultCount / geneCount) : 0;
      node.model.results.proportion = proportion;
      if(proportion > maxProportion) {
        maxProportion = proportion;
        maxProportionNode = node;
      }

      return node.model.results;
    }

    updateCounts(taxonomy);
    genomes.stats.maxProportion = maxProportion;
    genomes.stats.maxProportionNode = maxProportionNode;
  };

  function getNodesAndReturnModel(self, predicate) {
    return function () {
      return this.all(predicate)
        .map(function (node) {
          return node.model;
        });
    }.call(self);
  }

  taxonomyPrototype.species = function () {
    return getNodesAndReturnModel(this, function (node) {
      return node.model.genome;
    });
  };

  taxonomyPrototype.speciesWithResults = function () {
    return getNodesAndReturnModel(this, function (node) {
      return node.model.genome &&
        node.model.genome.results &&
        node.model.genome.results.count;
    });
  }
}

function removeGenomesFromTaxonomy(taxonomy) {
  taxonomy.leafNodes().forEach(function (speciesNode) {
    delete speciesNode.model.genome;
  });

  ['results', 'binCount', 'setResults', 'species'].map(function (fnName) {
    delete taxonomy[fnName];
  })
}

function addGeneratorToTaxonomy(binsGenerator, taxonomy) {
  taxonomy.binParams = {};
  taxonomy.setBinType = function (methodName, param) {

    var newParams = methodName ? {method: methodName, param: param} : {};

    if (_.isEqual(this.binParams, newParams)) {
      return false;
    }

    var binFn = binsGenerator[methodName + 'BinMapper'];

    if (!binFn) {
      removeGenomesFromTaxonomy(taxonomy);
      if (_.isEqual(this.binParams, {})) {
        return false;
      }

      this.binParams = {};
      return true;
    }

    var genomes = binFn(param).binnedGenomes();

    this.binParams = {
      method: methodName,
      param: param
    };

    addGenomesToTaxonomy(taxonomy, genomes);

    return true;
  };
  taxonomy.removeBins = function () { return taxonomy.setBinType() };

  return taxonomy;
}

module.exports = {
  get: function (local) {
    return Q.all([
      binsPromise.get(local),
      treesPromise.get(local)
    ]).spread(addGeneratorToTaxonomy);
  }
};


text:
package ceylon.tool.converter.java2ceylon;

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

import org.antlr.v4.runtime.ParserRuleContext;

import ceylon.tool.converter.java2ceylon.Java8Parser.AssignmentContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.CompilationUnitContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.LocalVariableDeclarationContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.MethodDeclarationContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.NormalClassDeclarationContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.PostDecrementExpressionContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.PostIncrementExpressionContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.PostfixExpressionContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.PreDecrementExpressionContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.PreIncrementExpressionContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.VariableDeclaratorContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.VariableDeclaratorIdContext;
import ceylon.tool.converter.java2ceylon.Java8Parser.VariableInitializerContext;

public class ScopeTree extends Java8BaseVisitor<Void> {
    public Node root, scopeNode;

    public ScopeTree() {
        root = new Node();
    }

    public static class Node {
        ParserRuleContext data;
        Node parent;
        List<Node> children;
        boolean scope, variable, optional;

        Node() {
            data = new ParserRuleContext();
            scope = false;
            variable = false;
            optional = false;
            children = new ArrayList<>();
        }

        void addNode(Node n) {
            children.add(n);
        }
    }

    public Node getNode(ParserRuleContext ctx, Node n) {
        if (ctx == n.data) {
            return n;
        } else {
            for (Node c : n.children) {
                Node found = getNode(ctx, c);
                if (found != null)
                    return found;
            }
        }
        return null;
    }

    @Override
    public Void visitCompilationUnit(CompilationUnitContext ctx) {
        Node n = new Node();
        n.data = ctx;
        n.scope = true;
        root = n;

        scopeNode = n;

        return super.visitCompilationUnit(ctx);
    }

    @Override
    public Void visitNormalClassDeclaration(NormalClassDeclarationContext ctx) {
        Node n = new Node();
        n.data = ctx;
        n.parent = scopeNode;
        n.scope = true;
        scopeNode.addNode(n);

        scopeNode = n;
        visitClassBody(ctx.classBody());
        scopeNode = n.parent;

        return null;
    }

    @Override
    public Void visitVariableDeclaratorId(VariableDeclaratorIdContext ctx) {
        Node n = new Node();
        n.data = ctx;
        n.parent = scopeNode;

        ParserRuleContext parent = ctx.getParent();

        if (parent instanceof VariableDeclaratorContext) {
            VariableInitializerContext initial = ((VariableDeclaratorContext) parent).variableInitializer();

            if (initial != null && initial.getText().equals("null"))
                n.optional = true;
        }

        scopeNode.addNode(n);

        return super.visitVariableDeclaratorId(ctx);
    }

    @Override
    public Void visitMethodDeclaration(MethodDeclarationContext ctx) {
        Node n = new Node();
        n.parent = scopeNode;
        n.data = ctx;
        n.scope = true;
        scopeNode.addNode(n);

        scopeNode = n;

        visitMethodHeader(ctx.methodHeader());
        visitMethodBody(ctx.methodBody());

        scopeNode = n.parent;

        return null;
    }

    @Override
    public Void visitPostIncrementExpression(PostIncrementExpressionContext ctx) {
        String var = ctx.postfixExpression().getText();
        checkVariable(scopeNode, var, false);

        return super.visitPostIncrementExpression(ctx);
    }

    @Override
    public Void visitPostfixExpression(PostfixExpressionContext ctx) {
        if (ctx.postDecrementExpression_lf_postfixExpression(0) != null
                || ctx.postIncrementExpression_lf_postfixExpression(0) != null) {
            String var = ctx.expressionName().getText();
            checkVariable(scopeNode, var, false);
        }

        return super.visitPostfixExpression(ctx);
    }

    @Override
    public Void visitPostDecrementExpression(PostDecrementExpressionContext ctx) {
        String var = ctx.postfixExpression().getText();
        checkVariable(scopeNode, var, false);

        return super.visitPostDecrementExpression(ctx);
    }

    @Override
    public Void visitPreIncrementExpression(PreIncrementExpressionContext ctx) {
        String var = ctx.unaryExpression().getText();
        checkVariable(scopeNode, var, false);

        return super.visitPreIncrementExpression(ctx);
    }

    @Override
    public Void visitPreDecrementExpression(PreDecrementExpressionContext ctx) {
        String var = ctx.unaryExpression().getText();
        checkVariable(scopeNode, var, false);

        return super.visitPreDecrementExpression(ctx);
    }

    @Override
    public Void visitAssignment(AssignmentContext ctx) {
        String leftHandSide = ctx.leftHandSide().getText();

        String expression = ctx.expression().getText();

        checkVariable(scopeNode, leftHandSide, expression.equals("null"));

        return super.visitAssignment(ctx);
    }

    private void checkVariable(Node n, String var, boolean isNull) {
        boolean flag = false;

        for (Node c : n.children) {
            if (c.data instanceof LocalVariableDeclarationContext) {
                LocalVariableDeclarationContext context = (LocalVariableDeclarationContext) c.data;

                for (VariableDeclaratorContext x : context.variableDeclaratorList().variableDeclarator()) {
                    String id = x.variableDeclaratorId().getText();

                    if (var.equals(id)) {
                        c.variable = true;

                        if (isNull)
                            c.optional = true;

                        flag = true;
                        break;
                    }

                }
            }
            if (c.data instanceof VariableDeclaratorIdContext) {
                VariableDeclaratorIdContext context = (VariableDeclaratorIdContext) c.data;

                if (var.equals(context.Identifier().getText())) {
                    c.variable = true;
                    flag = true;

                    if (isNull)
                        c.optional = true;
                }
            }
        }

        if (!flag && n.parent != null)
            checkVariable(n.parent, var, isNull);
    }
}


text:
#include "config.h"

#include "DumpRenderTree.h"
#include "DumpRenderTreeChrome.h"
#include "IntRect.h"
#include "PixelDumpSupportCairo.h"
#include "RefPtrCairo.h"
#include "WebCoreSupport/DumpRenderTreeSupportEfl.h"
#include "ewk_view.h"

PassRefPtr<BitmapContext> createBitmapContextFromWebView(bool, bool, bool, bool drawSelectionRect)
{
    Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(browser->mainView()));
    Ewk_View_Private_Data* privateData = static_cast<Ewk_View_Private_Data*>(smartData->_priv);
    const Evas_Object* mainFrame = browser->mainFrame();

    int x, y, width, height;
    evas_object_geometry_get(browser->mainFrame(), &x, &y, &width, &height);
    const Eina_Rectangle rect = { x, y, width, height };

    RefPtr<cairo_surface_t> surface = adoptRef(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, rect.w, rect.h));
    RefPtr<cairo_t> context = adoptRef(cairo_create(surface.get()));

    if (!ewk_view_paint(privateData, context.get(), &rect))
        return 0;

    if (DumpRenderTreeSupportEfl::isTrackingRepaints(mainFrame)) {
        cairo_push_group(context.get());

        // Paint the gray mask over the original image.
        cairo_set_source_rgba(context.get(), 0, 0, 0, 0.66);
        cairo_paint(context.get());

        // Paint transparent rectangles over the mask to show the repainted regions.
        cairo_set_source_rgba(context.get(), 0, 0, 0, 0);
        cairo_set_operator(context.get(), CAIRO_OPERATOR_SOURCE);

        Eina_List* repaintRects = DumpRenderTreeSupportEfl::trackedRepaintRects(mainFrame);
        void* iter = 0;
        EINA_LIST_FREE(repaintRects, iter) {
            Eina_Rectangle* rect = static_cast<Eina_Rectangle*>(iter);

            cairo_rectangle(context.get(), rect->x, rect->y, rect->w, rect->h);
            cairo_fill(context.get());

            eina_rectangle_free(rect);
        }

        cairo_pop_group_to_source(context.get());
        cairo_paint(context.get());
    }

    if (drawSelectionRect) {
        const WebCore::IntRect selectionRect = DumpRenderTreeSupportEfl::selectionRectangle(mainFrame);

        if (!selectionRect.isEmpty()) {
            cairo_set_line_width(context.get(), 1.0);
            cairo_rectangle(context.get(), selectionRect.x(), selectionRect.y(), selectionRect.width(), selectionRect.height());
            cairo_set_source_rgba(context.get(), 1.0, 0.0, 0.0, 1.0);
            cairo_stroke(context.get());
        }
    }

    return BitmapContext::createByAdoptingBitmapAndContext(0, context.release().leakRef());
}


text:
/*-------------------------------------------------------------------------------------------------*\
 |    I N C L U D E   F I L E S
\*-------------------------------------------------------------------------------------------------*/
#include "acc_common.h"
#include "acc_bmc150_i2c.h"
#include "bma2x2.h"
#include "i2c_driver.h"
#include "bosch_i2c_adapter.h"

#ifndef I2C_DRIVER
# error Needs I2C_DRIVER to be defined. Check Common.h
#endif

//#define _DEBUG_

/*-------------------------------------------------------------------------------------------------*\
 |    E X T E R N A L   V A R I A B L E S   &   F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/
extern uint32_t AccelTimeExtend;

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C   V A R I A B L E S   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E   C O N S T A N T S   &   M A C R O S
\*-------------------------------------------------------------------------------------------------*/
#define delay_ms(msec)      os_dly_wait(MSEC_TO_TICS(msec))
#define PORT_ACCIRQREQ                  4
#define PIN_ACCIRQREQ                   11
#define ACCEL_INT_IRQCh                 PIN_INT0_IRQn
#define ACCEL_INT_PRIO                  2

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E   T Y P E   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    S T A T I C   V A R I A B L E S   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
static bma2x2_t bma2x2;

/*-------------------------------------------------------------------------------------------------*\
 |    F O R W A R D   F U N C T I O N   D E C L A R A T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E     F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/

#if 0
/****************************************************************************************************
 * @fn      WriteAccReg
 *          Sends data to digital Accelerometer's specified register address
 *
 ***************************************************************************************************/
static void WriteAccReg( uint8_t regAddr, uint8_t data )
{
    uint8_t result;

    /* Get the transmit going. Rest is handled in the ISR */
    result = I2C_Start_Transfer( LSM_A_I2C_ADDRESS_7BIT, regAddr, &data, 1, I2C_MASTER_WRITE );
    APP_assert(result == I2C_ERR_OK);

    /* Wait for transfer to finish before returning */
    I2C_Wait_Completion();
}

/****************************************************************************************************
 * @fn      ReadAccReg
 *          Reads data from digital Accelerometer's specified register address
 *
 ***************************************************************************************************/
static uint8_t ReadAccReg( uint8_t regAddr )
{
    uint8_t result;
    uint8_t retVal;

    /* Get the transfer going. Rest is handled in the ISR */
    result = I2C_Start_Transfer( _SENSOR_ADDR_7BIT_, regAddr, &retVal, 1, I2C_MASTER_READ );
    APP_assert(result == I2C_ERR_OK);

    /* Wait for status */
    I2C_Wait_Completion();

    return retVal;
}

/****************************************************************************************************
 * @fn      ReadAccMultiByte
 *          Reads data > 1 byte from digital Accelerometer's specified register start address
 *
 ***************************************************************************************************/
static void ReadAccMultiByte( uint8_t regAddr, uint8_t *pBuffer, uint8_t count )
{
    uint8_t result;
    regAddr = regAddr | 0x80;     /* For multi-byte read MSB of sub-addr field should be 1 */

    /* Get the transfer going. Rest is handled in the ISR */
    result = I2C_Start_Transfer( _SENSOR_ADDR_7BIT_, regAddr, pBuffer, count, I2C_MASTER_READ );
    APP_assert(result == I2C_ERR_OK);

    /* Wait for status */
    I2C_Wait_Completion();
}
#endif

/****************************************************************************************************
 * @fn      Accel_DumpRegisters
 *          Dumps the registers of the chosen Accelerometer device
 *
 ***************************************************************************************************/
static void Accel_DumpRegisters( void )
{
#ifdef _DEBUG_
    D0_printf("\n------- BOSCH BMC150 Accel Register Dump -------\r\n");
    D0_printf("\t CTRL_REG1           (0x20) %02X\r\n", ReadAccReg( REG1          ));
    delay_ms(50);
    D0_printf("\t FIFO_CTRL_REG       (0x2E) %02X\r\n", ReadAccReg( REG2          ));
    D0_printf("------------------------------------------------\r\n");
    delay_ms(50);
#endif
}

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C     F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/

/****************************************************************************************************
 * @fn      Accel_Initialize
 *          Configures the Accelerometer device params & registers for the application.
 *
 * @param   option Normal/Motion sense or Sleep modes for the accels.
 *
 * @return  none
 *
 ***************************************************************************************************/
void Accel_Initialize( AccelInitOption option )
{
    /* Init the Bosch Driver for accel */
    bma2x2.bus_write  = dev_i2c_write;
    bma2x2.bus_read   = dev_i2c_read;
    bma2x2.delay_msec = dev_i2c_delay;
    bma2x2_init(&bma2x2);

    /* Register state before changes */
    Accel_DumpRegisters();

    /* Set key registers to default on startup */
    Accel_ResetDevice();

    /* Clear any existing interrupts */
    Accel_ClearDataInt();

    bma2x2_set_mode(BMA2x2_MODE_NORMAL);        // Normal power
    bma2x2_set_range(BMA2x2_RANGE_4G);          // set range 4g for grange
    //bma2x2_set_bandwidth(BMA2x2_BW_125HZ );     // BW set to 125Hz, ODR = BW*2
    //bma2x2_set_bandwidth(BMA2x2_BW_62_50HZ );     // BW set to 62.5Hz, ODR = BW*2
    bma2x2_set_bandwidth(BMA2x2_BW_31_25HZ );     // BW set to 31.25Hz, ODR = BW*2 (62.5Hz)

    /* Setup interrupt selections */
    bma2x2_set_newdata( BMA2x2_INT1_NDATA, 1 ); //DRDY interrupt on INT1 pad
    /* Latched with 250uS duration */
    bma2x2_set_latch_int(BMA2x2_LATCH_DUR_250US);

    /* Registers after initialization */
    Accel_DumpRegisters();
}

/****************************************************************************************************
 * @fn      Accel_HardwareSetup
 *          Configures the interrupt GPIO and regulators (if any) for the Accelerometer.
 *
 * @param   enable - Enables or disables the GPIOs / Communications interface
 *
 * @return  none
 *
 ***************************************************************************************************/
void Accel_HardwareSetup( osp_bool_t enable )
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    NVIC_InitTypeDef  NVIC_InitStructure;
    EXTI_InitTypeDef  EXTI_InitStructure;

    if (enable == true)
    {
        /* Initialize the I2C Driver interface */
        ASF_assert( true == I2C_HardwareSetup( I2C_SENSOR_BUS ) );

        /* Enable GPIO clocks */
        RCC_APB2PeriphClockCmd( RCC_Periph_ACCEL_INT_GPIO, ENABLE );

        /* Configure INT interrupt Pin */
        GPIO_InitStructure.GPIO_Pin   = ACCEL_INT;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IN;
        GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_400KHz; //Don't care for input mode
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;     //Don't care for input mode
        GPIO_Init (ACCEL_INT_GPIO_GRP, &GPIO_InitStructure);

        /* Enable SYSCFG clock */
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
        /* Connect the EXTI Line to the port pin */
        SYSCFG_EXTILineConfig(EXTI_PORT_SRC_ACCEL_INT, EXTI_PIN_SRC_ACCEL_INT);

        EXTI_ClearFlag(EXTI_LINE_ACCEL_INT);

        EXTI_InitStructure.EXTI_Line = EXTI_LINE_ACCEL_INT;
        EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
        EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
        EXTI_InitStructure.EXTI_LineCmd = ENABLE;
        EXTI_Init(&EXTI_InitStructure);

        /* NVIC config for INT input */
        NVIC_ClearPendingIRQ(ACCEL_INT_IRQChannel);
        NVIC_InitStructure.NVIC_IRQChannel = ACCEL_INT_IRQChannel;
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = ACCEL_INT_PREEMPT_PRIO;
        NVIC_InitStructure.NVIC_IRQChannelSubPriority = ACCEL_INT_SUB_PRIORITY;
        NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
        NVIC_Init(&NVIC_InitStructure);
        /* Int enabled via Accel_ConfigDataInt() */
    }
    else //TODO: disable interrupts and free GPIOs
    {
        //TODO!!
    }

}

/****************************************************************************************************
 * @fn      Accel_ReadData
 *          Reads data from Accelerometer's X, Y, Z data registers
 *
 ***************************************************************************************************/
void Accel_ReadData( AccelData_t *pxyzData )
{
    static uint32_t lastRtc = 0;
    bma2x2acc_t acc;                //create object of type bma250acc_t
    bma2x2_read_accel_xyz(&acc);    //get acceleration data from sensor

    pxyzData->X = acc.x;
    pxyzData->Y = acc.y;
    pxyzData->Z = acc.z;

    //add timestamp here!
    pxyzData->timeStamp = RTC_GetCounter();
    if (pxyzData->timeStamp < lastRtc)
    {
        AccelTimeExtend++; //Rollover counter
    }
    lastRtc = pxyzData->timeStamp;
}

/****************************************************************************************************
 * @fn      Accel_ClearDataInt
 *          Resets the New Data interrupt on the Accelerometer.
 *
 ***************************************************************************************************/
void Accel_ClearDataInt( void )
{
}

/****************************************************************************************************
 * @fn      Accel_ConfigDataInt
 *          Enables/Disables the New Data interrupt on the Accelerometer.
 *
 ***************************************************************************************************/
void Accel_ConfigDataInt( osp_bool_t enInt )
{
    if (enInt)
    {
        bma2x2_set_Int_Enable( BMA2x2_DATA_EN, 1 );
    }
    else
    {
        bma2x2_set_Int_Enable( BMA2x2_DATA_EN, 0 );
    }
}

/****************************************************************************************************
 * @fn      Accel_ResetDevice
 *          Soft resets the Accelerometer.
 *
 ***************************************************************************************************/
void Accel_ResetDevice( void )
{
    /* Soft Reset device */
    bma2x2_soft_reset();  // Problem with I2C at 1.8V OK for YS-SH
    dev_i2c_delay(1);
}

/****************************************************************************************************
 * @fn      Accel_SelfTest
 *          Runs self test on the Accelerometer. Returns true if passed.
 *
 ***************************************************************************************************/
osp_bool_t Accel_SelfTest( void )
{
    return true; //Not supported
}

/*-------------------------------------------------------------------------------------------------*\
 |    E N D   O F   F I L E
\*-------------------------------------------------------------------------------------------------*/


text:
<?php

namespace yii\console;

use yii\base\InvalidRouteException;

/**
 * Application represents a console application.
 *
 * Application extends from [[yii\base\Application]] by providing functionalities that are
 * specific to console requests. In particular, it deals with console requests
 * through a command-based approach:
 *
 * - A console application consists of one or several possible user commands;
 * - Each user command is implemented as a class extending [[\yii\console\Controller]];
 * - User specifies which command to run on the command line;
 * - The command processes the user request with the specified parameters.
 *
 * The command classes reside in the directory specified by [[controllerPath]].
 * Their naming should follow the same naming convention as controllers. For example, the `help` command
 * is implemented using the `HelpController` class.
 *
 * To run the console application, enter the following on the command line:
 *
 * ~~~
 * yii <route> [--param1=value1 --param2 ...]
 * ~~~
 *
 * where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID`
 * (e.g. `sitemap/create`), and `param1`, `param2` refers to a set of named parameters that
 * will be used to initialize the controller action (e.g. `--since=0` specifies a `since` parameter
 * whose value is 0 and a corresponding `$since` parameter is passed to the action method).
 *
 * A `help` command is provided by default, which lists available commands and shows their usage.
 * To use this command, simply type:
 *
 * ~~~
 * yii help
 * ~~~
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Application extends \yii\base\Application
{
	/**
	 * @var string the default route of this application. Defaults to 'help',
	 * meaning the `help` command.
	 */
	public $defaultRoute = 'help';
	/**
	 * @var boolean whether to enable the commands provided by the core framework.
	 * Defaults to true.
	 */
	public $enableCoreCommands = true;
	/**
	 * @var Controller the currently active controller instance
	 */
	public $controller;

	/**
	 * Initialize the application.
	 */
	public function init()
	{
		parent::init();
		if ($this->enableCoreCommands) {
			foreach ($this->coreCommands() as $id => $command) {
				if (!isset($this->controllerMap[$id])) {
					$this->controllerMap[$id] = $command;
				}
			}
		}
		// ensure we have the 'help' command so that we can list the available commands
		if (!isset($this->controllerMap['help'])) {
			$this->controllerMap['help'] = 'yii\console\controllers\HelpController';
		}
	}

	/**
	 * Handles the specified request.
	 * @param Request $request the request to be handled
	 * @return Response the resulting response
	 */
	public function handleRequest($request)
	{
		list ($route, $params) = $request->resolve();
		$this->requestedRoute = $route;
		$result = $this->runAction($route, $params);
		if ($result instanceof Response) {
			return $result;
		} else {
			$response = $this->getResponse();
			$response->exitStatus = (int)$result;
			return $response;
		}
	}

	/**
	 * Returns the response component.
	 * @return Response the response component
	 */
	public function getResponse()
	{
		return $this->getComponent('response');
	}

	/**
	 * Runs a controller action specified by a route.
	 * This method parses the specified route and creates the corresponding child module(s), controller and action
	 * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
	 * If the route is empty, the method will use [[defaultRoute]].
	 * @param string $route the route that specifies the action.
	 * @param array $params the parameters to be passed to the action
	 * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
	 * @throws Exception if the route is invalid
	 */
	public function runAction($route, $params = array())
	{
		try {
			return parent::runAction($route, $params);
		} catch (InvalidRouteException $e) {
			throw new Exception(\Yii::t('yii', 'Unknown command "{command}".', array('{command}' => $route)), 0, $e);
		}
	}

	/**
	 * Returns the configuration of the built-in commands.
	 * @return array the configuration of the built-in commands.
	 */
	public function coreCommands()
	{
		return array(
			'message' => 'yii\console\controllers\MessageController',
			'help' => 'yii\console\controllers\HelpController',
			'migrate' => 'yii\console\controllers\MigrateController',
			'cache' => 'yii\console\controllers\CacheController',
			'asset' => 'yii\console\controllers\AssetController',
		);
	}

	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
	public function registerCoreComponents()
	{
		parent::registerCoreComponents();
		$this->setComponents(array(
			'request' => array(
				'class' => 'yii\console\Request',
			),
			'response' => array(
				'class' => 'yii\console\Response',
			),
		));
	}
}


text:
local MAJOR, MINOR = "AceBucket-3.0", 4
local AceBucket, oldminor = LibStub:NewLibrary(MAJOR, MINOR)

if not AceBucket then return end -- No Upgrade needed

AceBucket.buckets = AceBucket.buckets or {}
AceBucket.embeds = AceBucket.embeds or {}

-- the libraries will be lazyly bound later, to avoid errors due to loading order issues
local AceEvent, AceTimer

-- Lua APIs
local tconcat = table.concat
local type, next, pairs, select = type, next, pairs, select
local tonumber, tostring, rawset = tonumber, tostring, rawset
local assert, loadstring, error = assert, loadstring, error

-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, geterrorhandler

local bucketCache = setmetatable({}, {__mode='k'})

--[[
	 xpcall safecall implementation
]]
local xpcall = xpcall

local function errorhandler(err)
	return geterrorhandler()(err)
end

local function safecall(func, ...)
	if func then
		return xpcall(func, errorhandler, ...)
	end
end

-- FireBucket ( bucket )
--
-- send the bucket to the callback function and schedule the next FireBucket in interval seconds
local function FireBucket(bucket)
	local received = bucket.received

	-- we dont want to fire empty buckets
	if next(received) ~= nil then
		local callback = bucket.callback
		if type(callback) == "string" then
			safecall(bucket.object[callback], bucket.object, received)
		else
			safecall(callback, received)
		end

		for k in pairs(received) do
			received[k] = nil
		end

		-- if the bucket was not empty, schedule another FireBucket in interval seconds
		bucket.timer = AceTimer.ScheduleTimer(bucket, FireBucket, bucket.interval, bucket)
	else -- if it was empty, clear the timer and wait for the next event
		bucket.timer = nil
	end
end

-- BucketHandler ( event, arg1 )
--
-- callback func for AceEvent
-- stores arg1 in the received table, and schedules the bucket if necessary
local function BucketHandler(self, event, arg1)
	if arg1 == nil then
		arg1 = "nil"
	end

	self.received[arg1] = (self.received[arg1] or 0) + 1

	-- if we are not scheduled yet, start a timer on the interval for our bucket to be cleared
	if not self.timer then
		self.timer = AceTimer.ScheduleTimer(self, FireBucket, self.interval, self)
	end
end

-- RegisterBucket( event, interval, callback, isMessage )
--
-- event(string or table) - the event, or a table with the events, that this bucket listens to
-- interval(int) - time between bucket fireings
-- callback(func or string) - function pointer, or method name of the object, that gets called when the bucket is cleared
-- isMessage(boolean) - register AceEvent Messages instead of game events
local function RegisterBucket(self, event, interval, callback, isMessage)
	-- try to fetch the librarys
	if not AceEvent or not AceTimer then
		AceEvent = LibStub:GetLibrary("AceEvent-3.0", true)
		AceTimer = LibStub:GetLibrary("AceTimer-3.0", true)
		if not AceEvent or not AceTimer then
			error(MAJOR .. " requires AceEvent-3.0 and AceTimer-3.0", 3)
		end
	end

	if type(event) ~= "string" and type(event) ~= "table" then error("Usage: RegisterBucket(event, interval, callback): 'event' - string or table expected.", 3) end
	if not callback then
		if type(event) == "string" then
			callback = event
		else
			error("Usage: RegisterBucket(event, interval, callback): cannot omit callback when event is not a string.", 3)
		end
	end
	if not tonumber(interval) then error("Usage: RegisterBucket(event, interval, callback): 'interval' - number expected.", 3) end
	if type(callback) ~= "string" and type(callback) ~= "function" then error("Usage: RegisterBucket(event, interval, callback): 'callback' - string or function or nil expected.", 3) end
	if type(callback) == "string" and type(self[callback]) ~= "function" then error("Usage: RegisterBucket(event, interval, callback): 'callback' - method not found on target object.", 3) end

	local bucket = next(bucketCache)
	if bucket then
		bucketCache[bucket] = nil
	else
		bucket = { handler = BucketHandler, received = {} }
	end
	bucket.object, bucket.callback, bucket.interval = self, callback, tonumber(interval)

	local regFunc = isMessage and AceEvent.RegisterMessage or AceEvent.RegisterEvent

	if type(event) == "table" then
		for _,e in pairs(event) do
			regFunc(bucket, e, "handler")
		end
	else
		regFunc(bucket, event, "handler")
	end

	local handle = tostring(bucket)
	AceBucket.buckets[handle] = bucket

	return handle
end

--- Register a Bucket for an event (or a set of events)
-- @param event The event to listen for, or a table of events.
-- @param interval The Bucket interval (burst interval)
-- @param callback The callback function, either as a function reference, or a string pointing to a method of the addon object.
-- @return The handle of the bucket (for unregistering)
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceBucket-3.0")
-- MyAddon:RegisterBucketEvent("BAG_UPDATE", 0.2, "UpdateBags")
--
-- function MyAddon:UpdateBags()
--   -- do stuff
-- end
function AceBucket:RegisterBucketEvent(event, interval, callback)
	return RegisterBucket(self, event, interval, callback, false)
end

--- Register a Bucket for an AceEvent-3.0 addon message (or a set of messages)
-- @param message The message to listen for, or a table of messages.
-- @param interval The Bucket interval (burst interval)
-- @param callback The callback function, either as a function reference, or a string pointing to a method of the addon object.
-- @return The handle of the bucket (for unregistering)
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceBucket-3.0")
-- MyAddon:RegisterBucketEvent("SomeAddon_InformationMessage", 0.2, "ProcessData")
--
-- function MyAddon:ProcessData()
--   -- do stuff
-- end
function AceBucket:RegisterBucketMessage(message, interval, callback)
	return RegisterBucket(self, message, interval, callback, true)
end

--- Unregister any events and messages from the bucket and clear any remaining data.
-- @param handle The handle of the bucket as returned by RegisterBucket*
function AceBucket:UnregisterBucket(handle)
	local bucket = AceBucket.buckets[handle]
	if bucket then
		AceEvent.UnregisterAllEvents(bucket)
		AceEvent.UnregisterAllMessages(bucket)

		-- clear any remaining data in the bucket
		for k in pairs(bucket.received) do
			bucket.received[k] = nil
		end

		if bucket.timer then
			AceTimer.CancelTimer(bucket, bucket.timer)
			bucket.timer = nil
		end

		AceBucket.buckets[handle] = nil
		-- store our bucket in the cache
		bucketCache[bucket] = true
	end
end

--- Unregister all buckets of the current addon object (or custom "self").
function AceBucket:UnregisterAllBuckets()
	-- hmm can we do this more efficient? (it is not done often so shouldn't matter much)
	for handle, bucket in pairs(AceBucket.buckets) do
		if bucket.object == self then
			AceBucket.UnregisterBucket(self, handle)
		end
	end
end

-- embedding and embed handling
local mixins = {
	"RegisterBucketEvent",
	"RegisterBucketMessage",
	"UnregisterBucket",
	"UnregisterAllBuckets",
}

-- Embeds AceBucket into the target object making the functions from the mixins list available on target:..
-- @param target target object to embed AceBucket in
function AceBucket:Embed( target )
	for _, v in pairs( mixins ) do
		target[v] = self[v]
	end
	self.embeds[target] = true
	return target
end

function AceBucket:OnEmbedDisable( target )
	target:UnregisterAllBuckets()
end

for addon in pairs(AceBucket.embeds) do
	AceBucket:Embed(addon)
end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84.h
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-84.tmpl.h
*/
/*
 * @description
 * CWE: 195 Signed to Unsigned Conversion Error
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Positive integer
 * Sinks: malloc
 *    BadSink : Allocate memory using malloc() with the size of data
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"

namespace CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84
{

#ifndef OMITBAD

class CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_bad
{
public:
    CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_bad(int dataCopy);
    ~CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_bad();

private:
    int data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_goodG2B
{
public:
    CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_goodG2B(int dataCopy);
    ~CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_84_goodG2B();

private:
    int data;
};

#endif /* OMITGOOD */

}


text:
// +build !linux

package lldp

import (
	"github.com/skydive-project/skydive/probe"
	tp "github.com/skydive-project/skydive/topology/probes"
)

// NewProbe returns a new LLDP probe
func NewProbe(ctx tp.Context, bundle *probe.Bundle) (probe.Handler, error) {
	return nil, probe.ErrNotImplemented
}

// Register registers graph metadata decoders
func Register() {
}


text:
package org.apache.nifi.controller;

import org.apache.nifi.annotation.configuration.DefaultSchedule;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.scheduling.SchedulingStrategy;

/**
 * Dummy processor to test @DefaultSchedule annotation
 */
@DefaultSchedule(concurrentTasks = 5, strategy = SchedulingStrategy.CRON_DRIVEN, period = "0 0 0 1/1 * ?")
public class DummyScheduledProcessor extends AbstractProcessor {
    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {

    }
}


text:
package pl.touk.sputnik.review;

import lombok.Getter;
import org.jetbrains.annotations.NotNull;

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

public class ReviewResult {
    @Getter
    private final List<Violation> violations = new ArrayList<Violation>();

    public void add(@NotNull Violation violation) {
        violations.add(violation);
    }
}


text:
package com.intellij.ide.plugins;

import com.intellij.ide.plugins.auth.PluginRepositoryAuthListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public final class CustomPluginRepositoryService implements PluginRepositoryAuthListener {
  public static CustomPluginRepositoryService getInstance() {
    return ApplicationManager.getApplication().getService(CustomPluginRepositoryService.class);
  }

  public CustomPluginRepositoryService() {
    ApplicationManager
      .getApplication()
      .getMessageBus()
      .connect()
      .subscribe(PLUGIN_REPO_AUTH_CHANGED_TOPIC, this);
  }

  private Collection<PluginNode> myCustomRepositoryPluginsList;
  private Map<String, List<PluginNode>> myCustomRepositoryPluginsMap;
  private final Object myRepositoriesLock = new Object();

  private static final Logger LOG = Logger.getInstance(CustomPluginRepositoryService.class);

  public @NotNull Map<String, List<PluginNode>> getCustomRepositoryPluginMap() {
    synchronized (myRepositoriesLock) {
      if (myCustomRepositoryPluginsMap != null) {
        return myCustomRepositoryPluginsMap;
      }
    }

    Map<PluginId, PluginNode> latestCustomPluginsAsMap = new HashMap<>();
    Map<String, List<PluginNode>> customRepositoryPluginsMap = new HashMap<>();
    for (String host : RepositoryHelper.getPluginHosts()) {
      if (host != null) {
        try {
          List<PluginNode> descriptors = RepositoryHelper.loadPlugins(host, null, null);
          for (PluginNode descriptor : descriptors) {
            PluginId pluginId = descriptor.getPluginId();
            IdeaPluginDescriptor savedDescriptor = latestCustomPluginsAsMap.get(pluginId);
            if (savedDescriptor == null ||
                StringUtil.compareVersionNumbers(descriptor.getVersion(), savedDescriptor.getVersion()) > 0) {
              latestCustomPluginsAsMap.put(pluginId, descriptor);
            }
          }
          customRepositoryPluginsMap.put(host, descriptors);
        }
        catch (IOException e) {
          LOG.info(host, e);
        }
      }
    }

    synchronized (myRepositoriesLock) {
      if (myCustomRepositoryPluginsMap == null) {
        myCustomRepositoryPluginsMap = customRepositoryPluginsMap;
        myCustomRepositoryPluginsList = latestCustomPluginsAsMap.values();
      }
      return myCustomRepositoryPluginsMap;
    }
  }

  @Override
  public void authenticationChanged() {
    clearCache();
  }

  public @NotNull Collection<PluginNode> getCustomRepositoryPlugins() {
    synchronized (myRepositoriesLock) {
      if (myCustomRepositoryPluginsList != null) {
        return myCustomRepositoryPluginsList;
      }
    }
    getCustomRepositoryPluginMap();
    return myCustomRepositoryPluginsList;
  }

  public void clearCache() {
    synchronized (myRepositoriesLock) {
      myCustomRepositoryPluginsList = null;
      myCustomRepositoryPluginsMap = null;
    }
  }
}


text:
@interface MTHomeDropdownSubCell : UITableViewCell
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end


text:
[![Dependency Status](https://www.versioneye.com/user/projects/57fcb9c89907da004067f78c/badge.svg?style=flat-square)](https://www.versioneye.com/user/projects/57fcb9c89907da004067f78c)

# Lucee 5 Application Template for Heroku

Blank application template to deploy [Lucee 5](http://lucee.org) apps on Heroku

---

Find this project useful? [Show some love :revolving_hearts:](https://www.creatorlove.com/mikesprague/lucee-5-heroku-buildpack) and buy me a cup of cofee! :coffee:

---

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

Demo: [https://lucee5.herokuapp.com](https://lucee5.herokuapp.com) | [https://lucee5.herokuapp.com/test.cfm](https://lucee5.herokuapp.com/test.cfm)

## Credits/Notes:

- This project is based off of the offical Lucee Heroku Buildpack

## Requirements

- [Maven](http://maven.apache.org/) to build the project
- [Foreman](https://github.com/ddollar/foreman) to run locally

## Instructions

To get started, run the following commands in GitBash (or your terminal of preference):

```bash
$ git clone https://github.com/mikesprague/lucee5-heroku.git
$ cd lucee5-heroku
$ mvn package
$ foreman start
```

NOTE: On Windows, start foreman with the following command:

```bash
$ foreman start -f Procfile.dev
```

You should now have Lucee up and running at <http://localhost:5000>. Start adding your code.

To deploy your site to Heroku you need to setup a free Heroku account, install the Heroku toolbelt (Suggested reading: [Getting Started with Java on Heroku](https://devcenter.heroku.com/articles/getting-started-with-java)). Then...

```bash
$ heroku apps:create [NAME]
$ git push heroku master
$ heroku open
```

You should now be looking at your app running on Heroku.

NOTES:

* If you need access to the admin, disable the first rule in urlrewrite.xml.
* Default password for web admins is `password`. This should be changed to something secure before deploying your app.
* Make any settings (datasources, mail settings, etc.) changes you want locally via the web context, commit your changes and then deploy your app and they will also exist on Heroku.
  * Better practice to add any settings changes, datasources, etc. via Application.cfc; use web context for changes if you must set them via Lucee Admin
  * Server context will be overwritten on deploy, very important desired changes are made to web context if you wish to keep them
* If you get a Heroku application error try reloading the page. This is a known issue. I think the Lucee dependencies aren't quite ready when this happens, I need to look into it further.

Enjoy!

## Known Projects Using the Lucee 5 Application Template for Heroku

Have a project making use of this application template? Lem me know and I'll be happy to list it below!

* [Wheelie CMS](https://github.com/timsayshey/wheelie/) developed by [Tim Badolato (@timsayshey)](https://github.com/timsayshey)
  * CFWheels and Lucee powered CMS with one-click Heroku deploy powered by this project
  * Check out the project repo for full details: [https://github.com/timsayshey/wheelie/](https://github.com/timsayshey/wheelie/)