text:
/*---------------------------------------------------------
 * OpenERP web_calendar
 *---------------------------------------------------------*/

(function() {
    // Monkey patch dhtml scheduler in order to fix a bug.
    if (this.scheduler) {
        // It manually implements some kind of dbl click event
        // bubbling but fails to do it properly.
        var old_scheduler_dblclick = scheduler._on_dbl_click;
        scheduler._on_dbl_click = function(e, src) {
            if (src && !src.className) {
                return;
            } else {
                old_scheduler_dblclick.apply(this, arguments);
            }
        };

        // It uses the date+time format, leading to month range being between
        // 1/5 08:53 - 1/6 08:52 instead of 1/5 00:00 - 31/5 23:59
        scheduler._click.dhx_cal_today_button = function() {
            if (scheduler.callEvent("onBeforeTodayDisplayed", [])) {
                scheduler.setCurrentView( scheduler.date.date_part(new Date()) );
            }
        };
    }
}());

openerp.web_calendar = function(instance) {
var _t = instance.web._t,
   _lt = instance.web._lt;
var QWeb = instance.web.qweb;
instance.web.views.add('calendar', 'instance.web_calendar.CalendarView');
instance.web_calendar.CalendarView = instance.web.View.extend({
    template: "CalendarView",
    display_name: _lt('Calendar'),
// Dhtmlx scheduler ?
    init: function(parent, dataset, view_id, options) {
        var self = this;
        this._super(parent);
        this.ready = $.Deferred();
        this.set_default_options(options);
        this.dataset = dataset;
        this.model = dataset.model;
        this.fields_view = {};
        this.view_id = view_id;
        this.view_type = 'calendar';
        this.has_been_loaded = $.Deferred();
        this.dataset_events = [];
        this.COLOR_PALETTE = ['#f57900', '#cc0000', '#d400a8', '#75507b', '#3465a4', '#73d216', '#c17d11', '#edd400',
             '#fcaf3e', '#ef2929', '#ff00c9', '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f',
             '#ff8e00', '#ff0000', '#b0008c', '#9000ff', '#0078ff', '#00ff00', '#e6ff00', '#ffff00',
             '#905000', '#9b0000', '#840067', '#510090', '#0000c9', '#009b00', '#9abe00', '#ffc900' ];
        this.color_map = {};
        this.last_search = [];
        this.range_start = null;
        this.range_stop = null;
        this.update_range_dates(Date.today());
        this.selected_filters = [];
    },
    view_loading: function(r) {
        return this.load_calendar(r);
    },
    destroy: function() {
        scheduler.clearAll();
        this._super();
    },
    load_calendar: function(data) {
        this.fields_view = data;
        this.$el.addClass(this.fields_view.arch.attrs['class']);
        this.calendar_fields = {};
        this.ids = this.dataset.ids;
        this.color_values = [];
        this.info_fields = [];

        this.name = this.fields_view.name || this.fields_view.arch.attrs.string;
        this.view_id = this.fields_view.view_id;

        // mode, one of month, week or day
        this.mode = this.fields_view.arch.attrs.mode;

        // date_start is mandatory, date_delay and date_stop are optional
        this.date_start = this.fields_view.arch.attrs.date_start;
        this.date_delay = this.fields_view.arch.attrs.date_delay;
        this.date_stop = this.fields_view.arch.attrs.date_stop;

        this.day_length = this.fields_view.arch.attrs.day_length || 8;
        this.color_field = this.fields_view.arch.attrs.color;
        this.color_string = this.fields_view.fields[this.color_field] ?
            this.fields_view.fields[this.color_field].string : _t("Filter");

        if (this.color_field && this.selected_filters.length === 0) {
            var default_filter;
            if ((default_filter = this.dataset.context['calendar_default_' + this.color_field])) {
                this.selected_filters.push(default_filter + '');
            }
        }
        this.fields =  this.fields_view.fields;

        if (!this.date_start) {
            throw new Error(_t("Calendar view has not defined 'date_start' attribute."));
        }

        //* Calendar Fields *
        this.calendar_fields.date_start = {'name': this.date_start, 'kind': this.fields[this.date_start].type};

        if (this.date_delay) {
            if (this.fields[this.date_delay].type != 'float') {
                throw new Error(_t("Calendar view has a 'date_delay' type != float"));
            }
            this.calendar_fields.date_delay = {'name': this.date_delay, 'kind': this.fields[this.date_delay].type};
        }
        if (this.date_stop) {
            this.calendar_fields.date_stop = {'name': this.date_stop, 'kind': this.fields[this.date_stop].type};
        }

        for (var fld = 0; fld < this.fields_view.arch.children.length; fld++) {
            this.info_fields.push(this.fields_view.arch.children[fld].attrs.name);
        }

        this.init_scheduler();

        if (!this.sidebar && this.options.$sidebar) {
            this.sidebar = new instance.web_calendar.Sidebar(this);
            this.has_been_loaded.then(this.sidebar.appendTo(this.$el.find('.oe_calendar_sidebar_container')));
        }
        this.trigger('calendar_view_loaded', data);
        return this.has_been_loaded.resolve();
    },
    init_scheduler: function() {
        var self = this;
        scheduler.clearAll();
        if (this.fields[this.date_start]['type'] == 'time') {
            scheduler.config.xml_date = "%H:%M:%S";
        } else {
            scheduler.config.xml_date = "%Y-%m-%d %H:%i";
        }
        scheduler.config.api_date = "%Y-%m-%d %H:%i";
        scheduler.config.multi_day = true; //Multi day events are not rendered in daily and weekly views
        scheduler.config.start_on_monday = Date.CultureInfo.firstDayOfWeek !== 0; //Sunday = Sunday, Others = Monday
        scheduler.config.time_step = 30;
        scheduler.config.scroll_hour = 8;
        scheduler.config.drag_resize = true;
        scheduler.config.drag_create = true;
        scheduler.config.mark_now = true;
        scheduler.config.day_date = '%l %j';
        scheduler.config.details_on_create = false;

        scheduler.locale = {
            date:{
                month_full: Date.CultureInfo.monthNames,
                month_short: Date.CultureInfo.abbreviatedMonthNames,
                day_full: Date.CultureInfo.dayNames,
                day_short: Date.CultureInfo.abbreviatedDayNames
            },
            labels:{
                dhx_cal_today_button: _t("Today"),
                day_tab: _t("Day"),
                week_tab: _t("Week"),
                month_tab: _t("Month"),
                new_event: _t("New event"),
                icon_save: _t("Save"),
                icon_cancel: _t("Cancel"),
                icon_details: _t("Details"),
                icon_edit: _t("Edit"),
                icon_delete: _t("Delete"),
                confirm_closing: "",//Your changes will be lost, are your sure ?
                confirm_deleting: _t("Event will be deleted permanently, are you sure?"),
                section_description: _t("Description"),
                section_time: _t("Time period"),
                full_day: _t("Full day"),

                /*recurring events*/
                confirm_recurring: _t("Do you want to edit the whole set of repeated events?"),
                section_recurring: _t("Repeat event"),
                button_recurring: _t("Disabled"),
                button_recurring_open: _t("Enabled"),

                /*agenda view extension*/
                agenda_tab: _t("Agenda"),
                date: _t("Date"),
                description: _t("Description"),

                /*year view extension*/
                year_tab: _t("Year"),

                /* week agenda extension */
                week_agenda_tab: _t("Agenda")
            }
        };

        scheduler.init(this.$el.find('.oe_calendar')[0], null, this.mode || 'month');
        scheduler.detachAllEvents();
        scheduler.attachEvent('onViewChange', this.proxy('view_changed'));
        scheduler.attachEvent('onEventChanged', this.proxy('quick_save'));
        scheduler.attachEvent('onEventDeleted', this.proxy('delete_event'));
        scheduler.attachEvent('onEventAdded', function(event_id, event_obj) {
            var fn = event_obj._force_slow_create ? 'slow_create' : 'quick_create';
            self[fn].apply(self, arguments);
        });
        scheduler.attachEvent('onClick', function(event_id, mouse_event) {
            if (!self.$el.find('.dhx_cal_editor').length && self.current_mode() === 'month') {
                self.open_event(event_id);
            } else {
                return true;
            }
        });
        scheduler.attachEvent('onDblClick', function(event_id, mouse_event) {
            if (!self.$el.find('.dhx_cal_editor').length) {
                self.open_event(event_id);
            }
        });
        scheduler.attachEvent('onEmptyClick', function(start_date, mouse_event) {
            scheduler._loading = false; // Dirty workaround for a dhtmleditor bug I couln't track
            if (!self.$el.find('.dhx_cal_editor').length) {
                var end_date = new Date(start_date);
                end_date.addHours(1);
                scheduler.addEvent({
                    start_date: start_date,
                    end_date: end_date,
                    _force_slow_create: true,
                });
            }
        });
        scheduler.attachEvent("onBeforeLightbox", function (event_id) {
            var index = self.dataset.get_id_index(event_id);
            if (index !== null) {
                self.open_event(self.dataset.ids[index]);
            } else {
                self.slow_create(event_id, scheduler.getEvent(event_id));
            }
           return false;
        });

        this.refresh_scheduler();

        // Remove hard coded style attributes from dhtmlx scheduler
        this.$el.find(".dhx_cal_navline").removeAttr('style');
        instance.web.bus.on('resize',this,function(){
            self.$el.find(".dhx_cal_navline").removeAttr('style');
        });
    },
    view_changed: function(mode, date) {
        this.$el.find('.oe_calendar').removeClass('oe_cal_day oe_cal_week oe_cal_month').addClass('oe_cal_' + mode);
        if (!date.between(this.range_start, this.range_stop)) {
            this.update_range_dates(date);
            this.ranged_search();
        }
        this.ready.resolve();
    },
    update_range_dates: function(date) {
        this.range_start = date.clone().moveToFirstDayOfMonth();
        this.range_stop = this.range_start.clone().addMonths(1).addSeconds(-1);
    },
    refresh_scheduler: function() {
        scheduler.setCurrentView(scheduler._date);
    },
    reload_event: function(id) {
        this.dataset.read_ids([id], _.keys(this.fields)).done(this.proxy('events_loaded'));
    },
    get_color: function(key) {
        if (this.color_map[key]) {
            return this.color_map[key];
        }
        var index = _.keys(this.color_map).length % this.COLOR_PALETTE.length;
        var color = this.COLOR_PALETTE[index];
        this.color_map[key] = color;
        return color;
    },
    events_loaded: function(events, fn_filter, no_filter_reload) {
        var self = this;

        //To parse Events we have to convert date Format
        var res_events = [],
            sidebar_items = {};
        var selection_label;
        if(this.fields[this.color_field].selection) {
            selection_label = {};
            _(this.fields[this.color_field].selection).each(function(value){
                selection_label[value[0]] = value[1];
            });
        }
        for (var e = 0; e < events.length; e++) {
            var evt = events[e];
            if (!evt[this.date_start]) {
                break;
            }

            if (this.color_field) {
                var filter = evt[this.color_field];
                if (filter) {
                    if (typeof filter !== 'object') {
                        filter = [filter, filter];
                    }
                    if (selection_label) {
                        filter[1] = selection_label[filter[0]];
                    }
                    var filter_value = filter[0];
                    if (typeof(fn_filter) === 'function' && !fn_filter(filter_value)) {
                        continue;
                    }
                    var filter_item = {
                        value: filter_value,
                        label: filter[1],
                        color: this.get_color(filter_value)
                    };
                    if (!sidebar_items[filter_value]) {
                        sidebar_items[filter_value] = filter_item;
                    }
                    evt.color = filter_item.color;
                    evt.textColor = '#ffffff';
                } else {
                    evt.textColor = '#000000';
                }
            }

            if (this.fields[this.date_start]['type'] == 'date') {
                evt[this.date_start] = instance.web.auto_str_to_date(evt[this.date_start]).set({hour: 9}).toString('yyyy-MM-dd HH:mm:ss');
            }
            if (this.date_stop && evt[this.date_stop] && this.fields[this.date_stop]['type'] == 'date') {
                evt[this.date_stop] = instance.web.auto_str_to_date(evt[this.date_stop]).set({hour: 17}).toString('yyyy-MM-dd HH:mm:ss');
            }
            res_events.push(this.convert_event(evt));
        }
        scheduler.parse(res_events, 'json');
        this.refresh_scheduler();
        if (!no_filter_reload && this.sidebar) {
            this.sidebar.filter.events_loaded(sidebar_items);
        }
    },
    convert_event: function(evt) {
        var date_start = instance.web.str_to_datetime(evt[this.date_start]),
            date_stop = this.date_stop ? instance.web.str_to_datetime(evt[this.date_stop]) : null,
            date_delay = evt[this.date_delay] || 1.0,
            res_text = '';

        if (this.info_fields) {
            res_text = _.map(this.info_fields, function(fld) {
                if(evt[fld] instanceof Array)
                    return evt[fld][1];
                return evt[fld];
            });
        }
        if (!date_stop && date_delay) {
            date_stop = date_start.clone().addHours(date_delay);
        }
        var r = {
            'start_date': date_start.toString('yyyy-MM-dd HH:mm:ss'),
            'end_date': date_stop.toString('yyyy-MM-dd HH:mm:ss'),
            'text': res_text.join(', '),
            'id': evt.id
        };
        if (evt.color) {
            r.color = evt.color;
        }
        if (evt.textColor) {
            r.textColor = evt.textColor;
        }
        return r;
    },
    get_event_data: function(event_obj) {
        var data = {
            name: event_obj.text || scheduler.locale.labels.new_event
        };
        if (this.fields[this.date_start].type == 'date') {
            data[this.date_start] = instance.web.date_to_str(event_obj.start_date)
        }else {
            data[this.date_start] = instance.web.datetime_to_str(event_obj.start_date)
        }
        if (this.date_stop) {
            data[this.date_stop] = instance.web.datetime_to_str(event_obj.end_date);
        }
        if (this.date_delay) {
            var diff_seconds = Math.round((event_obj.end_date.getTime() - event_obj.start_date.getTime()) / 1000);
            data[this.date_delay] = diff_seconds / 3600;
        }
        return data;
    },
    do_search: function(domain, context, group_by) {
        this.last_search = arguments;
        this.ranged_search();
    },
    ranged_search: function() {
        var self = this;
        scheduler.clearAll();
        $.when(this.has_been_loaded, this.ready).done(function() {
            self.dataset.read_slice(_.keys(self.fields), {
                offset: 0,
                domain: self.get_range_domain(),
                context: self.last_search[1]
            }).done(function(events) {
                self.dataset_events = events;
                self.events_loaded(events);
            });
        });
    },
    get_range_domain: function() {
        var format = instance.web.date_to_str;
        var A = format(this.range_start.clone().addDays(-6));
        var B = format(this.range_stop.clone().addDays(6));
        var domain = [
            '&', [this.date_start, '>=', A], [this.date_start, '<=', B]
        ];
        if (this.date_stop) {
            domain.push(
            '&', [this.date_stop, '>=', A], [this.date_stop, '<=', B],
            '&', [this.date_start, '<', A], [this.date_stop, '>', B]);
            domain.unshift("|", "|");
        }
        domain.concat(this.last_search[0].slice(0))
        return domain;
    },
    do_show: function () {
        var self = this;
        $.when(this.has_been_loaded).done(function() {
            self.$el.show();
            self.do_push_state({});
        });
    },
    get_selected_ids: function() {
        // no way to select a record anyway
        return [];
    },
    current_mode: function() {
        return scheduler.getState().mode;
    },

    quick_save: function(event_id, event_obj) {
        var self = this;
        var data = this.get_event_data(event_obj);
        delete(data.name);
        var index = this.dataset.get_id_index(event_id);
        if (index !== null) {
            event_id = this.dataset.ids[index];
            this.dataset.write(event_id, data, {});
        }
    },
    quick_create: function(event_id, event_obj) {
        var self = this;
        var data = this.get_event_data(event_obj);
        this.dataset.create(data).done(function(r) {
            var id = r;
            self.dataset.ids.push(id);
            scheduler.changeEventId(event_id, id);
            self.reload_event(id);
        }).fail(function(r, event) {
            event.preventDefault();
            self.slow_create(event_id, event_obj);
        });
    },
    get_form_popup_infos: function() {
        var parent = this.getParent();
        var infos = {
            view_id: false,
            title: this.name,
        };
        if (parent instanceof instance.web.ViewManager) {
            infos.view_id = parent.get_view_id('form');
            if (parent instanceof instance.web.ViewManagerAction && parent.action && parent.action.name) {
                infos.title = parent.action.name;
            }
        }
        return infos;
    },
    slow_create: function(event_id, event_obj) {
        var self = this;
        if (this.current_mode() === 'month') {
            event_obj['start_date'].addHours(8);
            if (event_obj._length === 1) {
                event_obj['end_date'] = new Date(event_obj['start_date']);
                event_obj['end_date'].addHours(1);
            } else {
                event_obj['end_date'].addHours(-4);
            }
        }
        var defaults = {};
        _.each(this.get_event_data(event_obj), function(val, field_name) {
            defaults['default_' + field_name] = val;
        });
        var something_saved = false;
        var pop = new instance.web.form.FormOpenPopup(this);
        var pop_infos = this.get_form_popup_infos();
        pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
            title: _.str.sprintf(_t("Create: %s"), pop_infos.title),
            disable_multiple_selection: true,
            view_id: pop_infos.view_id,
        });
        pop.on('closed', self, function() {
            if (!something_saved) {
                scheduler.deleteEvent(event_id);
            }
        });
        pop.on('create_completed', self, function(id) {
            something_saved = true;
            self.dataset.ids.push(id);
            scheduler.changeEventId(event_id, id);
            self.reload_event(id);
        });
    },
    open_event: function(event_id) {
        var self = this;
        var index = this.dataset.get_id_index(event_id);
        if (index === null) {
            // Some weird behaviour in dhtmlx scheduler could lead to this case
            // eg: making multiple days event in week view, dhtmlx doesn't trigger eventAdded !!??
            // so the user clicks back on the orphan event and we land here. We have to duplicate
            // the dhtmlx internal event because it will delete it on next sheduler refresh.
            var event_obj = scheduler.getEvent(event_id);
            scheduler.deleteEvent(event_id);
            scheduler.addEvent({
                start_date: event_obj.start_date,
                end_date: event_obj.end_date,
                text: event_obj.text,
                _force_slow_create: true,
            });
        } else {
            var pop = new instance.web.form.FormOpenPopup(this);
            var pop_infos = this.get_form_popup_infos();
            var id_from_dataset = this.dataset.ids[index]; // dhtmlx scheduler loses id's type
            pop.show_element(this.dataset.model, id_from_dataset, this.dataset.get_context(), {
                title: _.str.sprintf(_t("Edit: %s"), pop_infos.title),
                view_id: pop_infos.view_id,
            });
            pop.on('write_completed', self, function(){
                self.reload_event(id_from_dataset);
            });
        }
    },
    delete_event: function(event_id, event_obj) {
        // dhtmlx sends this event even when it does not exist in openerp.
        // Eg: use cancel in dhtmlx new event dialog
        var self = this;
        var index = this.dataset.get_id_index(event_id);
        if (index !== null) {
            this.dataset.unlink(this.dataset.ids[index]);
        }
    },
});

instance.web_calendar.Sidebar = instance.web.Widget.extend({
    template: 'CalendarView.sidebar',
    start: function() {
        this._super();
        this.mini_calendar = scheduler.renderCalendar({
            container: this.$el.find('.oe_calendar_mini')[0],
            navigation: true,
            date: scheduler._date,
            handler: function(date, calendar) {
                scheduler.setCurrentView(date, 'day');
            }
        });
        scheduler.linkCalendar(this.mini_calendar);
        this.filter = new instance.web_calendar.SidebarFilter(this, this.getParent());
        this.filter.appendTo(this.$el.find('.oe_calendar_filter'));
    }
});
instance.web_calendar.SidebarFilter = instance.web.Widget.extend({
    events: {
        'change input:checkbox': 'filter_click'
    },
    init: function(parent, view) {
        this._super(parent);
        this.view = view;
    },
    events_loaded: function(filters) {
        var selected_filters = this.view.selected_filters.slice(0);
        this.$el.html(QWeb.render('CalendarView.sidebar.responsible', { filters: filters }));
        this.$('div.oe_calendar_responsible input').each(function() {
            if (_.indexOf(selected_filters, $(this).val()) > -1) {
                $(this).click();
            }
        });
    },
    filter_click: function(e) {
        var self = this,
            responsibles = [],
            $e = $(e.target);
        this.view.selected_filters = [];
        this.$('div.oe_calendar_responsible input:checked').each(function() {
            responsibles.push($(this).val());
            self.view.selected_filters.push($(this).val());
        });
        scheduler.clearAll();
        if (responsibles.length) {
            this.view.events_loaded(this.view.dataset_events, function(filter_value) {
                return _.indexOf(responsibles, filter_value.toString()) > -1;
            }, true);
        } else {
            this.view.events_loaded(this.view.dataset_events, false, true);
        }
    }
});

};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:


text:
package org.artifactory.ui.rest.model.artifacts.browse.treebrowser.tabs.builds;

import org.artifactory.api.context.ContextHelper;
import org.artifactory.build.BuildRun;

/**
 * @author Chen Keinan
 */
public class ProduceBy {

    private String name;
    private String number;
    private long started;
    private String startedString;
    private String ciUrl;
    private String releaseStatus;
    private String moduleID;

    public ProduceBy(BuildRun artifactBuild, String module) {
        if (artifactBuild != null) {
            this.name = artifactBuild.getName();
            this.number = artifactBuild.getNumber();
            this.started = artifactBuild.getStartedDate().getTime();
            this.startedString = ContextHelper.get().getCentralConfig().format(this.started);
            this.ciUrl = artifactBuild.getCiUrl();
            this.releaseStatus = artifactBuild.getReleaseStatus();
            this.moduleID = module;
        }
    }

    public ProduceBy() {
    }

    public String getModuleID() {
        return moduleID;
    }

    public void setModuleID(String module) {
        this.moduleID = module;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public long getStarted() {
        return started;
    }

    public void setStarted(long started) {
        this.started = started;
    }

    public String getStartedString() {
        return startedString;
    }

    public void setStartedString(String startedString) {
        this.startedString = startedString;
    }

    public String getCiUrl() {
        return ciUrl;
    }

    public void setCiUrl(String ciUrl) {
        this.ciUrl = ciUrl;
    }

    public String getReleaseStatus() {
        return releaseStatus;
    }

    public void setReleaseStatus(String releaseStatus) {
        this.releaseStatus = releaseStatus;
    }
}

redpajama_set_name: RedPajamaGithub


text:
In this document I write everything I encountered by using Couchbase Lite and that we have to take care when developing an app with that.

## Mature project with some moving parts

With the 1.0 and 1.1 releases, the project is mature and ready for production. However, it also has some moving parts, like with the new ForestDB storage. Take care when making decisions about which parts of the technology to use.

## Replication works well

The library handles the synchronization and does it well. We don't have to worry about being disconnected. We work on the local database and the rest is handled transparently.

## Core Data wrapper

The distribution provides in its "Extras" folder, an implementation of `NSIncrementalStore` which allows to use Core Data to manipulate the documents instead of the regular CBL API: `CBLIncrementalStore`.

### All must be declared in Core Data for it to work

If you plan to use the Core Data wrapper for only a sub-part of the application, you still need to declare the whole data model (*.xcdatamodel*) for the wrapper to work.

In my tests, I wanted to use a NSFetchedResultsController to show items in a UITableView. I wanted to continue to use the regular CBL API for the other screens in the app. I still had to define every entity in the data model otherwise the wrapper would crash.

It also means we cannot have documents that do not have a specific "type" otherwise the store would not understand.

### Data must keep the "old" way of modeling data

Since Core Data is used like a regular ORM with SQL-like stores in mind, we lose the power of using denormalized documents. Each document must comply with the defined model.

A document can have more properties than those defined in the model, however it cannot have "child" documents.

### Can be used together with the regular CBL API

The regular CBL API is still available. This means we can use the wrapper for certain things, but keep CBL for others.

## The Sync Gateway configuration file

**Everything** related to the sync gateway is handled by one only file: server configuration, users, roles, authorization, channels. This way of doing is not really ideal since it might result in a huge bulky JSON file. Hopefully, it can be very easy to create one file per configuration type and merge them together to feed the `sync_gateway` command.

## The sync function

The sync function is also included in the configuration file. Having Javascript code inside a JSON document makes it very hard to read and text editors do not understand the syntax. Creating the function on a JS file and pasting it into the configuration file is easier.

The four main parts are users, roles, channels and of course documents.

* Users and roles are created in the configuration file or by the admin using the Admin REST API
* Users can have zero or multiple roles
* Roles are added to users by the admin or by the sync function
* Channels are created on the fly by the sync function
* There can be any number of channels
* Documents are assigned to channels by the sync function
* User and roles are given access to channels by the sync function
  * Once *one* document gives access to a channel, the user/role has access to every document in the channel
* The sync function is executed for each new revision of a document. The channels can therefore change for every new revision
* When the sync function validates a newly deleted document, it has to take care that all the properties have been removed. The function should treat deletions specially.

### Be extra careful when deleting a document that gives access to channels

Once a document is deleted, the access rights it has given to users/roles are revoked. If multiple documents give access to a channel, the rights are not revoked.

This means that when a document giving accesses is deleted, **no** document in the related channels will not be replicated to the users. This also means that the users will not be able to see that this particular document has been deleted (since they are not in the channel anymore).

There are multiple solutions to this:

* Put documents that give accesses and can be deleted in at least two channels. When the document is deleted it will stay in another channel which the users still have access and will see the deletion
* Create a "hardcoded" channel and give access to it to users using the sync gateway config file or the REST API. Doing this will prevent having channels that "disappear" when a document is deleted

See [this thread](https://groups.google.com/d/msg/mobile-couchbase/scBfRI7eeIA/JWd_K4QLyDUJ) and [this pull request](https://github.com/jschmid/couchbase-chat/pull/11) talking about a specific problem I had when developing the chat application.

### Validate everything on the client side

The sync function allows to put documents into channels, but it also acts as a security mechanism. Calls to `requireUser()`/`requireRole()`/`requireAccess()` are the only way to prevent users to do bad things on the server side.

However, this is only meant to prevent bad behavior from bad guys.
The client side must check everything on its side. In a perfect world, the sync function should never ever reject a document (apart from hacking attempts of course).

[This thread](https://groups.google.com/d/msg/mobile-couchbase/ijaSWNKWdww/hHIGLY1JKKMJ) shows a design decision made by the Couchbase folks. The client is not notified by the Couchbase Lite SDK when the sync gateway rejects a document. The client is therefore in a weird state where is has the document locally, already tried to sync it to the backend, but does not know that is has been rejected. The client will present the document to the user without knowing it is not and will never be synchronized.

When you put a document on your local database, it might be replicated hours after the user did the action. We cannot prompt the user to update he's document because he might not remember what he had done.

The client apps must be 100% sure that everything it creates will be validated by the sync gateway.

### The sync function must re-run entirely if it has changed

It seems normal that if it changes, the sync function will have to re-run on every document to find the newly added channels or roles.

[This thread](
https://forums.couchbase.com/t/sync-gateway-initial-shadow-scalability-concerns/3776) shows that this can cause problems with a production setup that already has thousands of documents. Currently, if the function changes, all Sync gateway instances must be brought down. Only one gateway can re-run on all documents. Only then the other instances can be brought up.

## Couchbase Lite does not have a "real" authentication mechanism

The documentation states that a user can authenticate using HTTP, Facebook, Persona, or a custom authentication.

The library code does not provide a way to check the credentials before going further in the app workflow.

For example, if you use the HTTP authentication:

* Configure the CBL replication object with the HTTP credentials
* Register to get notified when replication changes its status
* Start the replication
* Get notified that there is an error
  * Check the error and notice that this is an authentication error

The best way for me is the have the user authenticate to our own backend. Once the authentication succeeded, the backend sends a somewhat random username/password pair to the application which can use it to replicate with the Sync Gateway.

## Do not access Couchbase directly

Do every CRUD operation using the Sync Gateway API, never directly the Couchbase API. If you need special access to a bucket, check [bucket shadowing](https://github.com/couchbase/sync_gateway/wiki/Bucket-Shadowing), although it seems to have been [deprecated](https://gitter.im/couchbase/mobile?at=55a8d8c6ad99869443daa873).

## Website using Couchbase

The Sync Gateway is compatible with PouchDB, a Javascript database used on websites. Check [this article](http://blog.couchbase.com/first-steps-with-pouchdb--sync-gateway-todomvc-todolite) to learn about it.

## General thoughts

### NoSQL paradigm

Sometimes writing the sync function seems a bit cumbersome because we miss parameters, we cannot query the DB while in the sync function to get other info. We have to understand that sometimes data can and must be duplicated between multiple documents. Once this is understood, writing the sync function gets easier.


text:
package org.optaplanner.core.impl.heuristic.selector.entity.decorator;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.optaplanner.core.impl.domain.entity.PlanningEntityDescriptor;
import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import org.optaplanner.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import org.optaplanner.core.impl.heuristic.selector.entity.AbstractEntitySelector;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.phase.AbstractSolverPhaseScope;
import org.optaplanner.core.impl.score.director.ScoreDirector;

public class FilteringEntitySelector extends AbstractEntitySelector {

    protected final EntitySelector childEntitySelector;
    protected final List<SelectionFilter> filterList;
    protected final boolean bailOutEnabled;

    protected ScoreDirector scoreDirector = null;

    public FilteringEntitySelector(EntitySelector childEntitySelector, List<SelectionFilter> filterList) {
        this.childEntitySelector = childEntitySelector;
        this.filterList = filterList;
        bailOutEnabled = childEntitySelector.isNeverEnding();
        solverPhaseLifecycleSupport.addEventListener(childEntitySelector);
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    @Override
    public void phaseStarted(AbstractSolverPhaseScope phaseScope) {
        super.phaseStarted(phaseScope);
        scoreDirector = phaseScope.getScoreDirector();
    }

    @Override
    public void phaseEnded(AbstractSolverPhaseScope phaseScope) {
        super.phaseEnded(phaseScope);
        scoreDirector = null;
    }

    public PlanningEntityDescriptor getEntityDescriptor() {
        return childEntitySelector.getEntityDescriptor();
    }

    public boolean isContinuous() {
        return childEntitySelector.isContinuous();
    }

    public boolean isNeverEnding() {
        return childEntitySelector.isNeverEnding();
    }

    public long getSize() {
        return childEntitySelector.getSize();
    }

    public Iterator<Object> iterator() {
        return new JustInTimeFilteringEntityIterator(childEntitySelector.iterator());
    }

    private class JustInTimeFilteringEntityIterator extends UpcomingSelectionIterator<Object> {

        private final Iterator<Object> childEntityIterator;

        public JustInTimeFilteringEntityIterator(Iterator<Object> childEntityIterator) {
            this.childEntityIterator = childEntityIterator;
        }

        @Override
        protected Object createUpcomingSelection() {
            Object next;
            long attemptsBeforeBailOut = bailOutEnabled ? determineBailOutSize() : 0L;
            do {
                if (!childEntityIterator.hasNext()) {
                    return noUpcomingSelection();
                }
                if (bailOutEnabled) {
                    // if childEntityIterator is neverEnding and nothing is accepted, bail out of the infinite loop
                    if (attemptsBeforeBailOut <= 0L) {
                        logger.warn("Bailing out of neverEnding selector ({}) to avoid infinite loop.",
                                FilteringEntitySelector.this);
                        return noUpcomingSelection();
                    }
                    attemptsBeforeBailOut--;
                }
                next = childEntityIterator.next();
            } while (!accept(scoreDirector, next));
            return next;
        }

    }

    protected long determineBailOutSize() {
        return childEntitySelector.getSize() * 10L;
    }

    public ListIterator<Object> listIterator() {
        // TODO Not yet implemented
        throw new UnsupportedOperationException();
    }

    public ListIterator<Object> listIterator(int index) {
        // TODO Not yet implemented
        throw new UnsupportedOperationException();
    }

    public Iterator<Object> endingIterator() {
        return new JustInTimeFilteringEntityIterator(childEntitySelector.endingIterator());
    }

    private boolean accept(ScoreDirector scoreDirector, Object entity) {
        for (SelectionFilter filter : filterList) {
            if (!filter.accept(scoreDirector, entity)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        return "Filtering(" + childEntitySelector + ")";
    }

}


text:
package org.kuali.coeus.common.budget.framework.core;

import org.kuali.coeus.common.budget.framework.copy.DeepCopyIgnore;
import org.kuali.coeus.common.budget.framework.rate.RateClass;
import org.kuali.coeus.sys.api.model.ScaleTwoDecimal;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.coeus.sys.framework.persistence.ScaleTwoDecimalConverter;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter;

import javax.persistence.*;
import java.sql.Date;

@MappedSuperclass
public abstract class AbstractBudget extends KcPersistableBusinessObjectBase implements Comparable<AbstractBudget> {
    private static final long serialVersionUID = -4997453399414404715L;

    @Column(name = "VERSION_NUMBER")
    private Integer budgetVersionNumber;

    @DeepCopyIgnore
    @PortableSequenceGenerator(name = "SEQ_BUDGET_ID")
    @GeneratedValue(generator = "SEQ_BUDGET_ID")
    @Id
    @Column(name = "BUDGET_ID")
    private Long budgetId;

    @Column(name = "DOCUMENT_NUMBER")
    private String documentNumber;

    @Column(name = "COST_SHARING_AMOUNT")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal costSharingAmount;

    @Column(name = "END_DATE")
    private Date endDate;

    @Column(name = "START_DATE")
    private Date startDate;

    @Column(name = "FINAL_VERSION_FLAG")
    @Convert(converter = BooleanYNConverter.class)
    private Boolean finalVersionFlag = Boolean.FALSE;

    @Column(name = "OH_RATE_TYPE_CODE")
    private String ohRateTypeCode;

    @Column(name = "OH_RATE_CLASS_CODE")
    private String ohRateClassCode;

    @Column(name = "RESIDUAL_FUNDS")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal residualFunds;

    @Column(name = "TOTAL_COST")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal totalCost;

    @Column(name = "TOTAL_DIRECT_COST")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal totalDirectCost;

    @Column(name = "TOTAL_INDIRECT_COST")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal totalIndirectCost;

    @Column(name = "TOTAL_COST_LIMIT")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal totalCostLimit;

    @Column(name = "TOTAL_DIRECT_COST_LIMIT")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal totalDirectCostLimit;

    @Column(name = "UNDERRECOVERY_AMOUNT")
    @Convert(converter = ScaleTwoDecimalConverter.class)
    private ScaleTwoDecimal underrecoveryAmount;

    @Column(name = "COMMENTS")
    @Lob
    private String comments;

    @Column(name = "MODULAR_BUDGET_FLAG")
    @Convert(converter = BooleanYNConverter.class)
    private Boolean modularBudgetFlag;

    @Column(name = "UR_RATE_CLASS_CODE")
    private String urRateClassCode;

    @Column(name = "ON_OFF_CAMPUS_FLAG")
    private String onOffCampusFlag;

    @Column(name = "SUBMIT_COST_SHARING")
    @Convert(converter = BooleanYNConverter.class)
    private Boolean submitCostSharingFlag = Boolean.TRUE;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "UR_RATE_CLASS_CODE", referencedColumnName = "RATE_CLASS_CODE", insertable = false, updatable = false)
    private RateClass urRateClass;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "OH_RATE_CLASS_CODE", referencedColumnName = "RATE_CLASS_CODE", insertable = false, updatable = false)
    private RateClass rateClass;

    @Transient
    private boolean descriptionUpdatable;

    @Column(name="BUDGET_NAME")
    private String name;

    @Transient
    private String budgetStatus;

    @Transient
    private String printBudgetCommentFlag;

    @Transient
    private String documentDescription;

    public Integer getBudgetVersionNumber() {
        return budgetVersionNumber;
    }

    public void setBudgetVersionNumber(Integer budgetVersionNumber) {
        this.budgetVersionNumber = budgetVersionNumber;
    }

    public ScaleTwoDecimal getCostSharingAmount() {
        return costSharingAmount == null ? ScaleTwoDecimal.ZERO : costSharingAmount;
    }

    public void setCostSharingAmount(ScaleTwoDecimal costSharingAmount) {
        this.costSharingAmount = costSharingAmount;
    }

    public Boolean getFinalVersionFlag() {
        return isFinalVersionFlag();
    }

    public Boolean isFinalVersionFlag() {
        return finalVersionFlag;
    }

    public void setFinalVersionFlag(Boolean finalVersionFlag) {
        this.finalVersionFlag = finalVersionFlag;
    }

    public String getOhRateTypeCode() {
        return ohRateTypeCode;
    }

    public void setOhRateTypeCode(String ohRateTypeCode) {
        this.ohRateTypeCode = ohRateTypeCode;
    }

    public String getOhRateClassCode() {
        return ohRateClassCode;
    }

    public void setOhRateClassCode(String ohRateClassCode) {
        this.ohRateClassCode = ohRateClassCode;
    }

    public RateClass getRateClass() {
        return this.rateClass;
    }

    public void setRateClass(RateClass rateClass) {
        this.rateClass = rateClass;
    }

    public String getDocumentNumber() {
        return documentNumber;
    }

    public void setDocumentNumber(String documentNumber) {
        this.documentNumber = documentNumber;
    }

    public ScaleTwoDecimal getResidualFunds() {
        return residualFunds;
    }

    public void setResidualFunds(ScaleTwoDecimal residualFunds) {
        this.residualFunds = residualFunds;
    }

    public ScaleTwoDecimal getTotalCost() {
        return totalCost == null ? ScaleTwoDecimal.ZERO : totalCost;
    }

    public void setTotalCost(ScaleTwoDecimal totalCost) {
        this.totalCost = totalCost;
    }

    public void setTotalDirectCost(ScaleTwoDecimal totalDirectCost) {
        this.totalDirectCost = totalDirectCost;
    }

    public void setTotalIndirectCost(ScaleTwoDecimal totalIndirectCost) {
        this.totalIndirectCost = totalIndirectCost;
    }

    public void setUnderrecoveryAmount(ScaleTwoDecimal underrecoveryAmount) {
        this.underrecoveryAmount = underrecoveryAmount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBudgetStatus() {
        return budgetStatus;
    }

    public void setBudgetStatus(String budgetStatus) {
        this.budgetStatus = budgetStatus;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public ScaleTwoDecimal getTotalCostLimit() {
        return totalCostLimit == null ? ScaleTwoDecimal.ZERO : totalCostLimit;
    }

    public void setTotalCostLimit(ScaleTwoDecimal totalCostLimit) {
        this.totalCostLimit = totalCostLimit;
    }

    public ScaleTwoDecimal getTotalDirectCost() {
        return totalDirectCost == null ? new ScaleTwoDecimal(0) : totalDirectCost;
    }

    public ScaleTwoDecimal getTotalIndirectCost() {
        return totalIndirectCost == null ? new ScaleTwoDecimal(0) : totalIndirectCost;
    }

    public ScaleTwoDecimal getUnderrecoveryAmount() {
        return underrecoveryAmount == null ? new ScaleTwoDecimal(0) : underrecoveryAmount;
    }

    public String getDocumentDescription() {
        return documentDescription;
    }

    public void setDocumentDescription(String documentDescription) {
        this.documentDescription = documentDescription;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public boolean isDescriptionUpdatable() {
        return descriptionUpdatable;
    }

    public String getDescriptionUpdatable() {
        return descriptionUpdatable ? "Yes" : "No";
    }

    public void setDescriptionUpdatable(boolean descriptionUpdatable) {
        this.descriptionUpdatable = descriptionUpdatable;
    }

    public int compareTo(AbstractBudget otherVersion) {
        return this.budgetVersionNumber.compareTo(otherVersion.getBudgetVersionNumber());
    }

    public Long getBudgetId() {
        return budgetId;
    }

    public void setBudgetId(Long budgetId) {
        this.budgetId = budgetId;
    }

    public Boolean getModularBudgetFlag() {
        return modularBudgetFlag;
    }

    public void setModularBudgetFlag(Boolean modularBudgetFlag) {
        this.modularBudgetFlag = modularBudgetFlag;
    }

    public String getUrRateClassCode() {
        return urRateClassCode;
    }

    public void setUrRateClassCode(String urRateClassCode) {
        this.urRateClassCode = urRateClassCode;
    }

    public String getOnOffCampusFlag() {
        return onOffCampusFlag;
    }

    public void setOnOffCampusFlag(String onOffCampusFlag) {
        this.onOffCampusFlag = onOffCampusFlag;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((budgetId == null) ? 0 : budgetId.hashCode());
        result = prime * result + ((budgetStatus == null) ? 0 : budgetStatus.hashCode());
        result = prime * result + ((budgetVersionNumber == null) ? 0 : budgetVersionNumber.hashCode());
        result = prime * result + ((comments == null) ? 0 : comments.hashCode());
        result = prime * result + ((costSharingAmount == null) ? 0 : costSharingAmount.hashCode());
        result = prime * result + (descriptionUpdatable ? 1231 : 1237);
        result = prime * result + ((documentDescription == null) ? 0 : documentDescription.hashCode());
        result = prime * result + ((documentNumber == null) ? 0 : documentNumber.hashCode());
        result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
        result = prime * result + (finalVersionFlag ? 1231 : 1237);
        result = prime * result + ((modularBudgetFlag == null) ? 0 : modularBudgetFlag.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((ohRateClassCode == null) ? 0 : ohRateClassCode.hashCode());
        result = prime * result + ((ohRateTypeCode == null) ? 0 : ohRateTypeCode.hashCode());
        result = prime * result + ((onOffCampusFlag == null) ? 0 : onOffCampusFlag.hashCode());
        result = prime * result + ((rateClass == null) ? 0 : rateClass.hashCode());
        result = prime * result + ((residualFunds == null) ? 0 : residualFunds.hashCode());
        result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
        result = prime * result + ((totalCost == null) ? 0 : totalCost.hashCode());
        result = prime * result + ((totalCostLimit == null) ? 0 : totalCostLimit.hashCode());
        result = prime * result + ((totalDirectCost == null) ? 0 : totalDirectCost.hashCode());
        result = prime * result + ((totalIndirectCost == null) ? 0 : totalIndirectCost.hashCode());
        result = prime * result + ((underrecoveryAmount == null) ? 0 : underrecoveryAmount.hashCode());
        result = prime * result + ((urRateClassCode == null) ? 0 : urRateClassCode.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        AbstractBudget other = (AbstractBudget) obj;
        if (budgetId == null) {
            if (other.budgetId != null)
                return false;
        } else if (!budgetId.equals(other.budgetId))
            return false;
        if (budgetStatus == null) {
            if (other.budgetStatus != null)
                return false;
        } else if (!budgetStatus.equals(other.budgetStatus))
            return false;
        if (budgetVersionNumber == null) {
            if (other.budgetVersionNumber != null)
                return false;
        } else if (!budgetVersionNumber.equals(other.budgetVersionNumber))
            return false;
        if (comments == null) {
            if (other.comments != null)
                return false;
        } else if (!comments.equals(other.comments))
            return false;
        if (costSharingAmount == null) {
            if (other.costSharingAmount != null)
                return false;
        } else if (!costSharingAmount.equals(other.costSharingAmount))
            return false;
        if (descriptionUpdatable != other.descriptionUpdatable)
            return false;
        if (documentDescription == null) {
            if (other.documentDescription != null)
                return false;
        } else if (!documentDescription.equals(other.documentDescription))
            return false;
        if (documentNumber == null) {
            if (other.documentNumber != null)
                return false;
        } else if (!documentNumber.equals(other.documentNumber))
            return false;
        if (endDate == null) {
            if (other.endDate != null)
                return false;
        } else if (!endDate.equals(other.endDate))
            return false;
        if (finalVersionFlag != other.finalVersionFlag)
            return false;
        if (modularBudgetFlag == null) {
            if (other.modularBudgetFlag != null)
                return false;
        } else if (!modularBudgetFlag.equals(other.modularBudgetFlag))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (ohRateClassCode == null) {
            if (other.ohRateClassCode != null)
                return false;
        } else if (!ohRateClassCode.equals(other.ohRateClassCode))
            return false;
        if (ohRateTypeCode == null) {
            if (other.ohRateTypeCode != null)
                return false;
        } else if (!ohRateTypeCode.equals(other.ohRateTypeCode))
            return false;
        if (onOffCampusFlag == null) {
            if (other.onOffCampusFlag != null)
                return false;
        } else if (!onOffCampusFlag.equals(other.onOffCampusFlag))
            return false;
        if (rateClass == null) {
            if (other.rateClass != null)
                return false;
        } else if (!rateClass.equals(other.rateClass))
            return false;
        if (residualFunds == null) {
            if (other.residualFunds != null)
                return false;
        } else if (!residualFunds.equals(other.residualFunds))
            return false;
        if (startDate == null) {
            if (other.startDate != null)
                return false;
        } else if (!startDate.equals(other.startDate))
            return false;
        if (totalCost == null) {
            if (other.totalCost != null)
                return false;
        } else if (!totalCost.equals(other.totalCost))
            return false;
        if (totalCostLimit == null) {
            if (other.totalCostLimit != null)
                return false;
        } else if (!totalCostLimit.equals(other.totalCostLimit))
            return false;
        if (totalDirectCost == null) {
            if (other.totalDirectCost != null)
                return false;
        } else if (!totalDirectCost.equals(other.totalDirectCost))
            return false;
        if (totalIndirectCost == null) {
            if (other.totalIndirectCost != null)
                return false;
        } else if (!totalIndirectCost.equals(other.totalIndirectCost))
            return false;
        if (underrecoveryAmount == null) {
            if (other.underrecoveryAmount != null)
                return false;
        } else if (!underrecoveryAmount.equals(other.underrecoveryAmount))
            return false;
        if (urRateClassCode == null) {
            if (other.urRateClassCode != null)
                return false;
        } else if (!urRateClassCode.equals(other.urRateClassCode))
            return false;
        return true;
    }

    public ScaleTwoDecimal getTotalDirectCostLimit() {
        return totalDirectCostLimit == null ? ScaleTwoDecimal.ZERO : totalDirectCostLimit;
    }

    public void setTotalDirectCostLimit(ScaleTwoDecimal totalDirectCostLimit) {
        this.totalDirectCostLimit = totalDirectCostLimit;
    }

    public void setPrintBudgetCommentFlag(String printBudgetCommentFlag) {
        this.printBudgetCommentFlag = printBudgetCommentFlag;
    }

    public String getPrintBudgetCommentFlag() {
        return printBudgetCommentFlag;
    }

    public Boolean getSubmitCostSharingFlag() {
        return submitCostSharingFlag;
    }

    public void setSubmitCostSharingFlag(Boolean submitCostSharingFlag) {
        this.submitCostSharingFlag = submitCostSharingFlag;
    }

    public RateClass getUrRateClass() {
        return urRateClass;
    }

    public void setUrRateClass(RateClass urRateClass) {
        this.urRateClass = urRateClass;
    }
}


text:
package com.rm.app.r.component.explanation;

import com.rm.app.log.RMLogger;
import com.rm.app.r.RMEngine;
import com.rm.app.r.component.RComponent;
import com.rm.app.r.component.equation.REQComponent;
import com.rm.app.r.component.explanation.statement.RExStatement;
import com.rm.app.r.flow.RFlowProperties;
import com.rm.app.r.flow.output.TextWindow;

public class RComExComponent extends RDefaultEXComponent {

	private String key;

	protected static int[] cmds4mr = { RExStatement.RCMD_SUM_SETTER,
			RExStatement.RCMD_SIG_STATE, RExStatement.RCMD_POWER_STATE,
			RExStatement.RCMD_COEF_TABLE, RExStatement.RCMD_COEF_STATE,
			RExStatement.RCMD_FULL_PLOT };

	protected static int[] cmds4sem = { RExStatement.RCMD_SUM_SETTER,
			RExStatement.RCMD_SEM_FIT_EQN, RExStatement.RCMD_SEM_FIT_NFI,
			RExStatement.RCMD_SEM_FIT_RMSEA, RExStatement.RCMD_SEM_DIAGRAM,
			RExStatement.RCMD_SEM_FULL_SUM, };

	public RComExComponent(String key) {
		super(key);
		this.key = key;
	}

	public String getKey() {
		return key;
	}

	public String getRCommand(RFlowProperties properties) {
		return super.getRCommand(properties);
	}

	public long holdedMS() {
		return 1000;
	}

	public static int[] getCmds(String eqType) {
		int[] rcmds = null;
		RMLogger.debug("Eq Type:" + eqType);
		if (REQComponent.TYPE_EQUATION_MR.equals(eqType)
				|| REQComponent.TYPE_EQUATION_SR.equals(eqType)) {
			rcmds = cmds4mr;
		} else if (REQComponent.TYPE_EQUATION_SEM.equals(eqType)) {
			rcmds = cmds4sem;
		}
		return rcmds;
	}

	public int handleCallBack(StringBuffer sb, RFlowProperties properties) {
		int[] cmds = this.getCmds(properties.getEqType());
		StringBuffer output = new StringBuffer();
		for (int rcmd : cmds) {
			RExStatement statement = getRExStatement(rcmd);
			String strCmd = statement.getRCommand(properties);
			String str = "";
			if (strCmd != null) {
				str = RMEngine.executeAndWaitReturn(strCmd, 200, false);
			}
			System.out.println(str);
			str = statement.formatDisplay(str, properties);
			output.append(str);
			output.append("\n");
			output.append("\n");
		}
		TextWindow.info.add(output.toString());
		return RComponent.SUCEESS;
	}

	public boolean validation() throws Exception {
		return true;
	}

}


text:
from setuptools import setup, Command

from distutils.command.build_py import build_py

with open('README.rst') as infile:
    long_description = infile.read()

from psrecord import __version__

setup(name='psrecord',
      version=__version__,
      description='Python package to record activity from processes',
      long_description=long_description,
      url='https://github.com/astrofrog/psrecord',
      license='Simplified BSD License',
      author='Thomas Robitaille',
      author_email='thomas.robitaille@gmail.com',
      packages=['psrecord', 'psrecord.tests'],
      provides=['psrecord'],
      scripts=['scripts/psrecord'],
      install_requires=['psutil'],
      cmdclass={'build_py': build_py},
      classifiers=[
                   "Development Status :: 3 - Alpha",
                   "Programming Language :: Python",
                   "License :: OSI Approved :: BSD License",
                  ],
     )


text:
.. _sub_phys_pkg_bulk_force:

BULK_FORCE: Bulk Formula Package
---------------------------------

author: Stephanie Dutkiewicz

Instead of forcing the model with heat and fresh water flux data, this
package calculates these fluxes using the changing sea surface
temperature. We need to read in some atmospheric data: **air
temperature, air humidity, down shortwave radiation, down longwave
radiation, precipitation, wind speed**. The current setup also reads in
**wind stress**, but this can be changed so that the stresses are
calculated from the wind speed.

The current setup requires that there is the thermodynamic-seaice
package (*pkg/thsice*, also refered below as seaice) is also used. It
would be useful though to have it also setup to run with some very
simple parametrization of the sea ice.

The heat and fresh water fluxes are calculated in *bulkf\_forcing.F*
called from *forward\_step.F*. These fluxes are used over open water,
fluxes over seaice are recalculated in the sea-ice package. Before the
call to *bulkf\_forcing.F* we call *bulkf\_fields\_load.F* to find the
current atmospheric conditions. The only other changes to the model code
come from the initializing and writing diagnostics of these fluxes.

subroutine BULKF_FIELDS_LOAD
++++++++++++++++++++++++++++

Here we find the atmospheric data needed for the bulk formula
calculations. These are read in at periodic intervals and values are
interpolated to the current time. The data file names come from
**data.blk**. The values that can be read in are: air temperature, air
humidity, precipitation, down solar radiation, down long wave radiation,
zonal and meridional wind speeds, total wind speed, net heat flux, net
freshwater forcing, cloud cover, snow fall, zonal and meridional wind
stresses, and SST and SSS used for relaxation terms. Not all these files
are necessary or used. For instance cloud cover and snow fall are not
used in the current bulk formula calculation. If total wind speed is not
supplied, wind speed is calculate from the zonal and meridional
components. If wind stresses are not read in, then the stresses are
calculated from the wind speed. Net heat flux and net freshwater can be
read in and used over open ocean instead of the bulk formula
calculations (but over seaice the bulkf formula is always used). This is
"hardwired" into *bulkf\_forcing* and the "ch" in the variable names
suggests that this is "cheating". SST and SSS need to be read in if
there is any relaxation used.

subroutine BULKF_FORCING
++++++++++++++++++++++++

In *bulkf\_forcing.F*, we calculate heat and fresh water fluxes (and
wind stress, if necessary) for each grid cell. First we determine if the
grid cell is open water or seaice and this information is carried by
**iceornot**. There is a provision here for a different designation if
there is snow cover (but currently this does not make any difference).
We then call *bulkf\_formula\_lanl.F* which provides values for: up long
wave radiation, latent and sensible heat fluxes, the derivative of these
three with respect to surface temperature, wind stress, evaporation. Net
long wave radiation is calculated from the combination of the down long
wave read in and the up long wave calculated.

We then find the albedo of the surface - with a call to *sfc\_albedo* if
there is sea-ice (see the seaice package for information on the
subroutine). If the grid cell is open ocean the albedo is set as 0.1.
Note that this is a parameter that can be used to tune the results. The
net short wave radiation is then the down shortwave radiation minus the
amount reflected.

If the wind stress needed to be calculated in *bulkf\_formula\_lanl.F*,
it was calculated to grid cell center points, so in *bulkf\_forcing.F*
we regrid to **u** and **v** points. We let the model know if it has
read in stresses or calculated stresses by the switch **readwindstress**
which is can be set in data.blk, and defaults to **.TRUE.**.

We then calculate **Qnet** and **EmPmR** that will be used as the fluxes
over the open ocean. There is a provision for using runoff. If we are
"cheating" and using observed fluxes over the open ocean, then there is
a provision here to use read in **Qnet** and **EmPmR**.

The final call is to calculate averages of the terms found in this
subroutine.

subroutine BULKF_FORMULA_LANL
+++++++++++++++++++++++++++++

This is the main program of the package where the heat fluxes and
freshwater fluxes over ice and open water are calculated. Note that this
subroutine is also called from the seaice package during the iterations
to find the ice surface temperature.

Latent heat (:math:`L`) used in this subroutine depends on the state of
the surface: vaporization for open water, fusion and vaporization for
ice surfaces. Air temperature is converted from Celsius to Kelvin. If
there is no wind speed (:math:`u_s`) given, then the wind speed is
calculated from the zonal and meridional components.

We calculate the virtual temperature:

.. math:: T_o = T_{air} (1+\gamma q_{air})

where :math:`T_{air}` is the air temperature at :math:`h_T`,
:math:`q_{air}` is humidity at :math:`h_q` and :math:`\gamma` is a
constant.

The saturated vapor pressure is calculate (QQ ref):

.. math:: q_{sat} = \frac{a}{p_o} e^{L (b-\frac{c}{T_{srf}})}

where :math:`a,b,c` are constants, :math:`T_{srf}` is surface
temperature and :math:`p_o` is the surface pressure.

The two values crucial for the bulk formula calculations are the
difference between air at sea surface and sea surface temperature:

.. math:: \Delta T = T_{air} - T_{srf} +\alpha h_T

where :math:`\alpha` is adiabatic lapse rate and :math:`h_T` is the
height where the air temperature was taken; and the difference between
the air humidity and the saturated humidity

.. math:: \Delta q = q_{air} - q_{sat}.

We then calculate the turbulent exchange coefficients following Bryan et
al (1996) and the numerical scheme of Hunke and Lipscombe (1998). We
estimate initial values for the exchange coefficients, :math:`c_u`,
:math:`c_T` and :math:`c_q` as

.. math:: \frac{\kappa}{ln(z_{ref}/z_{rou})}

where :math:`\kappa` is the Von Karman constant, :math:`z_{ref}` is a
reference height and :math:`z_{rou}` is a roughness length scale which
could be a function of type of surface, but is here set as a constant.
Turbulent scales are:

.. math::

   \begin{aligned}
   u^* & = & c_u u_s \nonumber\\
   T^* & = & c_T \Delta T \nonumber\\
   q^* & = & c_q \Delta q \nonumber\end{aligned}

We find the "integrated flux profile" for momentum and stability if
there are stable QQ conditions (:math:`\Upsilon>0`) :

.. math:: \psi_m = \psi_s = -5 \Upsilon

and for unstable QQ conditions (:math:`\Upsilon<0`):

.. math::

   \begin{aligned}
   \psi_m & = & 2 ln(0.5(1+\chi)) + ln(0.5(1+\chi^2)) - 2 \tan^{-1} \chi + \pi/2
   \nonumber \\
   \psi_s & = & 2 ln(0.5(1+\chi^2)) \nonumber\end{aligned}

where

.. math::

   \Upsilon = \frac{\kappa g z_{ref}}{u^{*2}} (\frac{T^*}{T_o} +
   \frac{q^*}{1/\gamma + q_a})

and :math:`\chi=(1-16\Upsilon)^{1/2}`.

The coefficients are updated through 5 iterations as:

.. math::

   \begin{aligned}
   c_u & = & \frac {\hat{c_u}}{1+\hat{c_u}(\lambda - \psi_m)/\kappa} \nonumber \\
   c_T & = & \frac {\hat{c_T}}{1+\hat{c_T}(\lambda - \psi_s)/\kappa} \nonumber \\
   c_q & = & c'_T\end{aligned}

where :math:`\lambda =ln(h_T/z_{ref})`.

We can then find the bulk formula heat fluxes:

Sensible heat flux:

.. math:: Q_s=\rho_{air} c_{p_{air}} u_s c_u c_T \Delta T

Latent heat flux:

.. math:: Q_l=\rho_{air} L u_s c_u c_q \Delta q

Up long wave radiation

.. math:: Q_{lw}^{up}=\epsilon \sigma T_{srf}^4

where :math:`\epsilon` is emissivity (which can be different for open
ocean, ice and snow), :math:`\sigma` is Stefan-Boltzman constant.

We calculate the derivatives of the three above functions with respect
to surface temperature

.. math::

   \begin{aligned}
   \frac{dQ_s}{d_T} & = & \rho_{air} c_{p_{air}} u_s c_u c_T \nonumber \\
   \frac{dQ_l}{d_T} & = & \frac{\rho_{air} L^2 u_s c_u c_q c}{T_{srf}^2} \nonumber \\
   \frac{dQ_{]lw}^{up}}{d_T} & = &  4 \epsilon \sigma t_{srf}^3 \nonumber\end{aligned}

And total derivative :math:`\frac{dQ_o}{dT}= \frac{dQ_s}{dT} +
\frac{dQ_l}{dT} + \frac{dQ_{lw}^{up}}{dT}`.

If we do not read in the wind stress, it is calculated here.

Initializing subroutines
++++++++++++++++++++++++

:code:`bulkf_init.F`: Set bulkf variables to zero.

:code:`bulkf_readparms.F`: Reads **data.blk**

Diagnostic subroutines
++++++++++++++++++++++

:code:`bulkf_ave.F`: Keeps track of means of the bulkf variables

:code:`bulkf_diags.F`: Finds averages and writes out diagnostics

Common Blocks
+++++++++++++

:code:`BULKF.h`: BULKF Variables, data file names, and logicals **readwindstress** and
**readsurface**

:code:`BULKF_DIAGS.h`: matrices for diagnostics: averages of fields from *bulkf_diags.F*

:code:`BULKF_ICE_CONSTANTS.h`: all the parameters needed by the ice model and in the bulkf formula
calculations.

Input file DATA.ICE
+++++++++++++++++++

We read in the file names of atmospheric data used in the bulk formula
calculations. Here we can also set the logicals: **readwindstress** if
we read in the wind stress rather than calculate it from the wind speed;
and **readsurface** to read in the surface temperature and salinity if
these will be used as part of a relaxing term.

Important Notes
+++++++++++++++

#. heat fluxes have different signs in the ocean and ice models.

#. **StartIceModel** must be changed in **data.ice**: 1 (if starting from no ice), 0 (if using pickup.ic file).

References
++++++++++

Bryan F.O., B.G Kauffman, W.G. Large, P.R. Gent, 1996: The NCAR CSM flux
coupler. Technical note TN-425+STR, NCAR.

Hunke, E.C and W.H. Lipscomb, circa 2001: CICE: the Los Alamos Sea Ice
Model Documentation and Software User's Manual. LACC-98-16v.2.
(note: this documentation is no longer available as CICE has
progressed to a very different version 3)

Experiments and tutorials that use bulk\_force
++++++++++++++++++++++++++++++++++++++++++++++

-  Global ocean experiment in global\_ocean.cs32x15 verification
   directory, input from input.thsice directory.


text:
export default function tryResult(expressionFn, catchExpression) {
  try {
    return expressionFn();
  } catch (e) {
    return catchExpression(e);
  }
}


text:
<?php

/**
 * URL utility class
 *
 * This class provides methods to deal with encoding and decoding url (percent encoded) strings.
 *
 * It was not possible to use PHP's built-in methods for this, because some clients don't like
 * encoding of certain characters.
 *
 * Specifically, it was found that GVFS (gnome's webdav client) does not like encoding of ( and
 * ). Since these are reserved, but don't have a reserved meaning in url, these characters are
 * kept as-is.
 */
class Sabre_DAV_URLUtil {

    /**
     * Encodes the path of a url.
     *
     * slashes (/) are treated as path-separators.
     *
     * @param string $path
     * @return string
     */
    static function encodePath($path) {

        $path = explode('/',$path);
        return implode('/',array_map(array('Sabre_DAV_URLUtil','encodePathSegment'), $path));

    }

    /**
     * Encodes a 1 segment of a path
     *
     * Slashes are considered part of the name, and are encoded as %2f
     *
     * @param string $pathSegment
     * @return string
     */
    static function encodePathSegment($pathSegment) {

        $newStr = '';
        for($i=0;$i<strlen($pathSegment);$i++) {
            $c = ord($pathSegment[$i]);

            if(

                /* Unreserved chacaters */

                ($c>=0x41 /* A */ && $c<=0x5a /* Z */) ||
                ($c>=0x61 /* a */ && $c<=0x7a /* z */) ||
                ($c>=0x30 /* 0 */ && $c<=0x39 /* 9 */) ||
                $c===0x5f /* _ */ ||
                $c===0x2d /* - */ ||
                $c===0x2e /* . */ ||
                $c===0x7E /* ~ */ ||

                /* Reserved, but no reserved purpose */
                $c===0x28 /* ( */ ||
                $c===0x29 /* ) */

            ) {
                $newStr.=$pathSegment[$i];
            } else {
                $newStr.='%' . str_pad(dechex($c), 2, '0', STR_PAD_LEFT);
            }

        }
        return $newStr;

    }

    /**
     * Decodes a url-encoded path
     *
     * @param string $path
     * @return string
     */
    static function decodePath($path) {

        return self::decodePathSegment($path);

    }

    /**
     * Decodes a url-encoded path segment
     *
     * @param string $path
     * @return string
     */
    static function decodePathSegment($path) {

        $path = urldecode($path);
        $encoding = mb_detect_encoding($path, array('UTF-8','ISO-8859-1'));

        switch($encoding) {

            case 'ISO-8859-1' :
                $path = utf8_encode($path);
        }

        return $path;

    }

    /**
     * Returns the 'dirname' and 'basename' for a path.
     *
     * The reason there is a custom function for this purpose, is because
     * basename() is locale aware (behaviour changes if C locale or a UTF-8 locale is used)
     * and we need a method that just operates on UTF-8 characters.
     *
     * In addition basename and dirname are platform aware, and will treat backslash (\) as a
     * directory separator on windows.
     *
     * This method returns the 2 components as an array.
     *
     * If there is no dirname, it will return an empty string. Any / appearing at the end of the
     * string is stripped off.
     *
     * @param string $path
     * @return array
     */
    static function splitPath($path) {

        $matches = array();
        if(preg_match('/^(?:(?:(.*)(?:\/+))?([^\/]+))(?:\/?)$/u',$path,$matches)) {
            return array($matches[1],$matches[2]);
        } else {
            return array(null,null);
        }

    }

}


text:
import account_invoice
import paypal
import res_company


text:
/*
 * Base structure
 */

html,
body {
  height: 100%;
  background-color: #fff;
}

/* Extra markup and styles for table-esque vertical and horizontal centering */
.site-wrapper {
  display: table;
  width: 100%;
  height: 100%; /* For at least Firefox */
  min-height: 100%;
}
.site-wrapper-inner {
  width: 1024px;
  margin: 10px auto 0 auto;
}

.customLoginForm{
  width: 400px;
  margin: 50px auto;
}


text:
require "umlaut_journal_tocs/engine"

module UmlautJournalTocs

  # Custom visibility logic for our resolve section,
  # we don't want to show at all if it's not a suitable citation,
  # otherwise :in_progress logic.
  SectionVisibilityLogic = lambda do |section_renderer|
    return false unless JournalTocsAdapter.suitable_citation?(section_renderer.request)

    # :in_progress logic
    return (! section_renderer.responses_empty?) || section_renderer.services_in_progress?
  end

  def self.resolve_section_definition
    {
      :div_id     => "journal_tocs_bento",
      :html_area  => :main,
      :partial    => "umlaut_journal_tocs/resolve_section",
      :service_type_values => [:journal_tocs_bento],
      :visibility => SectionVisibilityLogic
    }
  end

end


text:
exports.yargs = {
  command: 'clear',
  describe: 'Clear options',
  aliases: ['c'],

  builder: (yargs) => {
    yargs.option('category', {
      alias: ['c'],
      describe: 'Select category',
      default: 'global',
    })
  },

  handler: (argv) => {
    const { options } = require('../../../lib/globals/options')

    const { category } = argv

    options.clearOptions(category)
  },
}


text:
import { push } from 'react-router-redux';

/**
 * Attempts to login the user with the given credentials.
 *
 * @param  {String} email
 * @param  {String} password
 * @return {Function}
 */
export function attemptLogin (email, password) {
  return function (dispatch) {
    dispatch({ type: 'ATTEMPTING_AUTH' });
    // after a "successful" login attempt...
    setTimeout(() => dispatch(loginSuccess('exampletoken', email)), 500);
  };
}

/**
 * Creates an action for a successful login using the given token
 * and then routes the user to the dashboard.
 *
 * @param  {String} token
 * @return {Function}
 */
export function loginSuccess (token, email) {
  return function (dispatch) {
    dispatch({ type: 'AUTH_SUCCESS', token, email });
    dispatch(push('/'));
  };
}

/**
 * Creates an action for when a login fails.
 *
 * @param  {Error} err
 * @return {Object}
 */
export function loginFailed (err) {
  return {
    type: 'AUTH_FAILED',
    message: err.message
  };
}

/**
 * Logs the user out.
 *
 * @return {Function}
 */
export function logout () {
  return function (dispatch) {
    dispatch({ type: 'AUTH_LOGOUT' });
    dispatch(push('/login'));
  };
}


text:
package start;
import java.util.ArrayList;
import java.util.HashMap;
public class detourDistance {

	static class point{
		private double longitude, latitude;

		public point(double latitude, double longitude){
			this.longitude = longitude;
			this.latitude = latitude;
		}

		void setLongitude(double longitude){
			this.longitude = longitude;
		}

		void setLatitude(double latitude){
			this.latitude = latitude;
		}

		double getLongitude(){
			return this.longitude;
		}

		double getLatitude(){
			return this.latitude;
		}
	}

	static ArrayList<String> possibleDetours = new ArrayList<String>();
	static HashMap<String, point> points = new HashMap<String, point>();
	static point A = new point(25, 75) , B = new point(35, 60), C = new point(25, 100), D = new point(35, 100);

	static double calcDistance(point source, point destination){
		final double radiusOfEarth = 3960; // miles
		double diffLat = Math.toRadians(destination.latitude - source.latitude);
		double diffLong = Math.toRadians(destination.longitude - source.longitude);
		double lat1 = Math.toRadians(source.latitude);
		double lat2 = Math.toRadians(destination.latitude);
		double a = Math.pow(Math.sin(diffLat/2) , 2) + Math.pow(Math.sin(diffLong/2), 2)* Math.cos(lat1)* Math.cos(lat2);
		double c  = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double distance = radiusOfEarth * c;

		return distance;
	}
	static int shorterDetour(){
		ArrayList<Double> dDistances = new ArrayList<Double>();
		double currentDistance = 0;

		for(String eachDetour : possibleDetours){
			char[] vertices = eachDetour.toCharArray();
			for(int index = 0; index < vertices.length-1; index ++){
				String source = ""+vertices[index];
				String destination = ""+vertices[index+1];
				currentDistance += calcDistance(points.get(source), points.get(destination));
			}
			dDistances.add(currentDistance);
		}

		double minDD = dDistances.get(0);
		int index = 0;

		for(double current : dDistances)
			if(minDD > current){
				minDD = current;
				index = dDistances.indexOf(current);
			}
		System.out.println("Shorter detour distance is: "+ Math.round(minDD)+" miles");
		return index;
	}

	public static void main(String[] args){
		points.put("A", A);
		points.put("B", B);
		points.put("C", C);
		points.put("D", D);
		System.out.println("Shorter detour path is: "+possibleDetours.get(shorterDetour()));

	}
}


text:
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 100;
    src: local('Roboto Thin'), local('Roboto-Thin'), url(/font/Roboto-Thin.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 300;
    src: local('Roboto Light'), local('Roboto-Light'), url(/font/Roboto-Light.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 400;
    src: local('Roboto Regular'), local('Roboto-Regular'), url(/font/Roboto-Regular.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 500;
    src: local('Roboto Medium'), local('Roboto-Medium'), url(/font/Roboto-Medium.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 700;
    src: local('Roboto Bold'), local('Roboto-Bold'), url(/font/Roboto-Bold.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 900;
    src: local('Roboto Black'), local('Roboto-Black'), url(/font/Roboto-Black.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 100;
    src: local('Roboto Thin Italic'), local('Roboto-ThinItalic'), url(/font/Roboto-ThinItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 300;
    src: local('Roboto Light Italic'), local('Roboto-LightItalic'), url(/font/Roboto-LightItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 400;
    src: local('Roboto Italic'), local('Roboto-Italic'), url(/font/Roboto-Italic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 500;
    src: local('Roboto Medium Italic'), local('Roboto-MediumItalic'), url(/font/Roboto-MediumItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 700;
    src: local('Roboto Bold Italic'), local('Roboto-BoldItalic'), url(/font/Roboto-BoldItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto';
    font-style: italic;
    font-weight: 900;
    src: local('Roboto Black Italic'), local('Roboto-BlackItalic'), url(/font/Roboto-BlackItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: normal;
    font-weight: 300;
    src: local('Roboto Condensed Light'), local('RobotoCondensed-Light'), url(/font/RobotoCondensed-Light.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: normal;
    font-weight: 400;
    src: local('Roboto Condensed Regular'), local('RobotoCondensed-Regular'), url(/font/RobotoCondensed-Regular.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: normal;
    font-weight: 700;
    src: local('Roboto Condensed Bold'), local('RobotoCondensed-Bold'), url(/font/RobotoCondensed-Bold.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: italic;
    font-weight: 300;
    src: local('Roboto Condensed Light Italic'), local('RobotoCondensed-LightItalic'), url(/font/RobotoCondensed-LightItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: italic;
    font-weight: 400;
    src: local('Roboto Condensed Italic'), local('RobotoCondensed-Italic'), url(/font/RobotoCondensed-Italic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Condensed';
    font-style: italic;
    font-weight: 700;
    src: local('Roboto Condensed Bold Italic'), local('RobotoCondensed-BoldItalic'), url(/font/RobotoCondensed-BoldItalic.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Slab';
    font-style: normal;
    font-weight: 100;
    src: local('Roboto Slab Thin'), local('RobotoSlab-Thin'), url(/font/RobotoSlab-Thin.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Slab';
    font-style: normal;
    font-weight: 300;
    src: local('Roboto Slab Light'), local('RobotoSlab-Light'), url(/font/RobotoSlab-Light.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Slab';
    font-style: normal;
    font-weight: 400;
    src: local('Roboto Slab Regular'), local('RobotoSlab-Regular'), url(/font/RobotoSlab-Regular.ttf) format('truetype');
}
@font-face {
    font-family: 'Roboto Slab';
    font-style: normal;
    font-weight: 700;
    src: local('Roboto Slab Bold'), local('RobotoSlab-Bold'), url(/font/RobotoSlab-Bold.ttf) format('truetype');
}

@font-face {
    font-family: 'Droid Sans Mono';
    font-style: normal;
    font-weight: 400;
    src: local('Droid Sans Mono'), local('DroidSansMono'), url(/font/DroidSansMono.ttf) format('truetype');
}


text:
module TownCrier
  class View
    attr_accessor :event

    def initialize(event)
      @event = event
    end

    def title
      "#{event.key} event"
    end

    def message
      "#{title} at #{Time.at(event.timestamp)}"
    end
  end
end


text:
cask 'oolite' do
  version '1.84'
  sha256 '8a10338202d46d6b1621e7ad86914c76c11f5ff5c08781fb5bc1f053c99e0e74'

  # github.com/OoliteProject/oolite was verified as official when first introduced to the cask
  url "https://github.com/OoliteProject/oolite/releases/download/#{version}/Oolite-#{version}.zip"
  appcast 'https://github.com/OoliteProject/oolite/releases.atom',
          checkpoint: 'e2043a4b70ccdce152a6c4f723bd7946656be29da56dccfeb3389066c462ba49'
  name 'oolite'
  homepage 'http://www.oolite.org/'

  app "Oolite #{version}/Oolite.app"
end


text:
'''
@author: davandev
'''

import logging
import os
import urllib
import urllib2
import traceback

from datetime import datetime
import davan.config.config_creator as configuration
import davan.util.constants as constants
import davan.util.helper_functions as helper
from davan.http.service.reoccuring_base_service import ReoccuringBaseService

class KeypadEvent():
    def __init__(self, name, ip):
        self.logger = logging.getLogger(os.path.basename(__file__))

        self.name = name
        self.ip = ip
        self.connected = False
        self.connected_at = ""
        self.disconnected_at = ""

    def toString(self):
        return "Name["+self.name+"] "\
            "IP["+self.ip+"] "\
            "Connected["+str(self.connected)+"] " \
            "Disconnected_at["+self.disconnected_at+"] " \
            "Connected_at["+self.connected_at+"]"

class KeypadAliveService(ReoccuringBaseService):
    '''
    Check if keypad is still running by sending a http request towards the keypad
    if there is no response from the keypad then a telegram message is sent.
    Re-occuring event every 5th minute
    '''

    def __init__(self, service_provider, config):
        '''
        Constructor
        '''
        ReoccuringBaseService.__init__(self, constants.KEYPAD_SERVICE_NAME, service_provider, config)
        self.logger = logging.getLogger(os.path.basename(__file__))
        self.keypads= []
        self.time_to_next_timeout = 600
        try:
            for name, ip in self.config['KEYPAD_IP_ADDRESSES'].iteritems():
                keypad = KeypadEvent(name, ip)
                self.logger.info(keypad.toString())
                self.keypads.append(keypad)
        except:
            self.logger.error(traceback.format_exc())

    def get_next_timeout(self):
        '''
        Return time to next timeout
        '''
        return self.time_to_next_timeout

    def handle_timeout(self):
        '''
        Timeout received, send a "ping" to key pad, send telegram message if failure.
        '''
        self.logger.info("Got a timeout, send keep alive")
        for keypad in self.keypads:
            try:
                self.logger.debug("Sending ping to keypad[" + keypad.name + "]")
                urllib.urlopen(self.config['KEYPAD_PING_URL'].replace('%IP%',keypad.ip))
                self.maybe_send_update(keypad, True)
            except:
                self.logger.warning("Failed to connect to keypad[" + keypad.name + "]")
                self.increment_errors()
                self.maybe_send_update(keypad, False)

    def get_log(self):
        self.logger.info("Fetch keypad logfile")
        try:
            log_file = urllib2.urlopen(self.config['KEYPAD_LOG_URL']).read()
            log_file = log_file.replace("
","\n")
            if os.path.exists(self.config["KEYPAD_LOG_FILE"]):
                os.remove(self.config["KEYPAD_LOG_FILE"])

            fd = open(self.config["KEYPAD_LOG_FILE"],'w')
            fd.write(log_file)
            fd.close()
            return self.config["KEYPAD_LOG_FILE"]
        except:
            self.increment_errors()
            self.logger.warning("Failed to fetch log file from keypad")
            return None

    def maybe_send_update(self, keypad, state):
        '''
        Send telegram message if state has changed
        @param state, current state of keypad
        '''
        #currentTime = time.strftime("%Y-%m-%d %H:%M", time.localtime())
        n = datetime.now()
        currentTime = format(n,"%Y-%m-%d %H:%M")

        if keypad.connected == True and state == False:
            self.logger.info("Keypad[ " + keypad.name + " ] state changed[Disconnected]")
            keypad.connected = False
            keypad.disconnected_at = currentTime
            str = constants.KEYPAD_NOT_ANSWERING.replace("%", keypad.name)
            self.raise_alarm(str,"Warning",str)

            helper.send_telegram_message(self.config, str)

        elif keypad.connected == False and state == True:
            self.logger.info("Keypad[" + keypad.name + "] state changed[Connected]")
            str = constants.KEYPAD_NOT_ANSWERING.replace("%", keypad.name)
            self.clear_alarm(str)

            keypad.connected = True
            keypad.connected_at = currentTime
            keypad.disconnected_at = ""
            str = constants.KEYPAD_ANSWERING.replace("%", keypad.name)
            helper.send_telegram_message(self.config, str)

    def has_html_gui(self):
        """
        Override if service has gui
        """
        return True

    def get_html_gui(self, column_id):
        """
        Override and provide gui
        """
        if not self.is_enabled():
            return ReoccuringBaseService.get_html_gui(self, column_id)

        column = constants.COLUMN_TAG.replace("<COLUMN_ID>", str(column_id))
        column = column.replace("<SERVICE_NAME>", self.service_name)
        html = ""
        for keypad in self.keypads:
            html += "
Name: " + str(keypad.name) + "
\n"
            html += "
Ip: " + str(keypad.ip) + "
\n"
            html += "
Connected: " + str(keypad.connected) + "
\n"
            html += "
Connected at: " + str(keypad.connected_at) + "
\n"
            html += "
Disconnected at: " + str(keypad.disconnected_at) + "
\n"
        column = column.replace("<SERVICE_VALUE>", html)
        return column

if __name__ == '__main__':
    from davan.util import application_logger as log_config
    import time

    config = configuration.create()
    log_config.start_logging(config['LOGFILE_PATH'],loglevel=3)

    test = KeypadAliveService()
    time.sleep(10)
    test.stop_service()


text:
#include <assert.h>
#include <cbmc_proof/cbmc_utils.h>
#include <cbmc_proof/make_common_datastructures.h>
#include <cbmc_proof/proof_allocators.h>

#include "api/s2n.h"
#include "stuffer/s2n_stuffer.h"

void s2n_stuffer_read_uint24_harness()
{
    struct s2n_stuffer *stuffer = cbmc_allocate_s2n_stuffer();
    __CPROVER_assume(s2n_stuffer_is_valid(stuffer));

    struct s2n_stuffer old_stuffer = *stuffer;
    uint32_t *         dest        = can_fail_malloc(sizeof(uint32_t *));

    /* Store a byte from the stuffer to compare after the read */
    struct store_byte_from_buffer old_byte_from_stuffer;
    save_byte_from_blob(&stuffer->blob, &old_byte_from_stuffer);

    if (s2n_stuffer_read_uint24(stuffer, dest) == S2N_SUCCESS) {
        assert(stuffer->read_cursor == old_stuffer.read_cursor + SIZEOF_UINT24);
        /* If successful, ensure uint was assembled correctly from stuffer */
        assert((( uint32_t )stuffer->blob.data[ old_stuffer.read_cursor ]) << 16
               | (( uint32_t )stuffer->blob.data[ old_stuffer.read_cursor + 1 ]) << 8
               | (( uint32_t )stuffer->blob.data[ old_stuffer.read_cursor + 2 ]) == *dest | *dest < (1 << (24 - 1)));
    } else {
        assert(stuffer->read_cursor == old_stuffer.read_cursor);
    }
    assert_stuffer_immutable_fields_after_read(stuffer, &old_stuffer, &old_byte_from_stuffer);
    assert(s2n_stuffer_is_valid(stuffer));
}


text:
{{ partial "header.html" . }}

{{if .Site.Params.cover}}
{{if or (eq (substr .Site.Params.cover 0 7) "http://") (eq (substr .Site.Params.cover 0 8) "https://")}}

  {{ else }}

  {{ end }}
{{else}}

{{end}}

        {{ if .Site.Params.logo }}

        {{end}}
        {{ if .Site.Menus.main }}
            ☰Menu
        {{else}}
            {{ if .Site.Params.RSSLink}}
                Subscribe
            {{else}}
                Subscribe
            {{end}}
        {{end}}

            {{ if .Site.Params.linkedinName }}

            {{end}}
            {{ if .Site.Params.githubName }}

            {{end}}
            {{ if .Site.Params.flickrName }}

            {{end}}
            {{ if .Site.Params.twitterName }}

            {{end}}
            {{ if .Site.Params.facebookName }}

            {{end}}
            {{ if .Site.Params.instagramName }}

            {{end}}
            {{ if .Site.Params.email }}

            {{end}}
            {{ if .Site.Params.pinterestName }}

            {{end}}
            {{ if .Site.Params.googlePlusName }}

            {{end}}

{{ .Site.Title }}

{{ .Site.Params.description }}

    Scroll Down

{{ partial "home-content.html" . }}

{{ partial "footer.html" . }}


text:
using DragonSpark.Commands;
using DragonSpark.ComponentModel;
using PostSharp.Patterns.Contracts;

namespace DragonSpark.Application
{
	public class RunProgramCommand : CommandBase<object>
	{
		[Service]
		public IProgram Program { [return: Required]get; set; }

		public override void Execute( object parameter ) => Program.Run( parameter );
	}
}