text:
import contextlib
import mock
import testtools

from neutron.callbacks import exceptions
from neutron.callbacks import registry
from neutron import context
from neutron.db import common_db_mixin
from neutron.db import securitygroups_db
from neutron.extensions import securitygroup
from neutron.tests.unit import testlib_api

class SecurityGroupDbMixinImpl(securitygroups_db.SecurityGroupDbMixin,
                               common_db_mixin.CommonDbMixin):
    pass

class SecurityGroupDbMixinTestCase(testlib_api.SqlTestCase):

    def setUp(self):
        super(SecurityGroupDbMixinTestCase, self).setUp()
        self.ctx = context.get_admin_context()
        self.mixin = SecurityGroupDbMixinImpl()

    def test_create_security_group_conflict(self):
        with mock.patch.object(registry, "notify") as mock_notify:
            mock_notify.side_effect = exceptions.CallbackFailure(Exception())
            secgroup = {'security_group': mock.ANY}
            with testtools.ExpectedException(
                securitygroup.SecurityGroupConflict):
                self.mixin.create_security_group(self.ctx, secgroup)

    def test_delete_security_group_in_use(self):
        with contextlib.nested(
            mock.patch.object(self.mixin, '_get_port_security_group_bindings'),
            mock.patch.object(self.mixin, '_get_security_group'),
            mock.patch.object(registry, "notify"),
        ) as (_, _, mock_notify):
            mock_notify.side_effect = exceptions.CallbackFailure(Exception())
            with testtools.ExpectedException(
                securitygroup.SecurityGroupInUse):
                self.mixin.delete_security_group(self.ctx, mock.ANY)

    def test_update_security_group_conflict(self):
        with mock.patch.object(registry, "notify") as mock_notify:
            mock_notify.side_effect = exceptions.CallbackFailure(Exception())
            secgroup = {'security_group': mock.ANY}
            with testtools.ExpectedException(
                securitygroup.SecurityGroupConflict):
                self.mixin.update_security_group(self.ctx, 'foo_id', secgroup)

    def test_create_security_group_rule_conflict(self):
        with mock.patch.object(self.mixin, '_validate_security_group_rule'),\
                mock.patch.object(self.mixin,
                                  '_check_for_duplicate_rules_in_db'),\
                mock.patch.object(registry, "notify") as mock_notify:
            mock_notify.side_effect = exceptions.CallbackFailure(Exception())
            with testtools.ExpectedException(
                securitygroup.SecurityGroupConflict):
                self.mixin.create_security_group_rule(
                    self.ctx, mock.MagicMock())

    def test_delete_security_group_rule_in_use(self):
        with mock.patch.object(registry, "notify") as mock_notify:
            mock_notify.side_effect = exceptions.CallbackFailure(Exception())
            with testtools.ExpectedException(
                securitygroup.SecurityGroupRuleInUse):
                self.mixin.delete_security_group_rule(self.ctx, mock.ANY)

    def test_delete_security_group_rule_raise_error_on_not_found(self):
        with testtools.ExpectedException(
            securitygroup.SecurityGroupRuleNotFound):
            self.mixin.delete_security_group_rule(self.ctx, 'foo_rule')


text:
<html>
<head>
<meta http-equiv="refresh" content="0; url=https://developers.liveperson.com/account-configuration-automatic-messages-get-automatic-messages.html" />
</head>
</html>

redpajama_set_name: RedPajamaGithub


text:
package com.orientechnologies.orient.core.iterator.object;

import java.util.Iterator;

/**
 * @author luca.molino
 *
 */
public interface OObjectIteratorClusterInterface<T> extends Iterator<T>, Iterable<T> {

}


text:
 * Context menu for mpv using Tcl/Tk. Mostly proof of concept.
 * Avi Halachmi (:avih) https://github.com/avih
 *
 * Features:
 * - Simple construction: ["<some text>", "<mpv-command>"] is a complete menu item.
 * - Possibly dynamic menu items and commands, disabled items, separators.
 * - Possibly keeping the menu open after clicking an item (via re-launch).
 * - Hacky pseudo sub menus. Really, this is an ugly hack.
 * - Reasonably well behaved/integrated considering it's an external application.
 *
 * TODO-ish:
 * - Proper sub menus (TBD protocol, tk relaunch), tooltips, other widgets (not).
 * - Possibly different menus for different bindings or states.
 *
 * Setup:
 * - Make sure Tcl/Tk is installed and `wish` is accessible and works.
 *   - Alternatively, configure `interpreter` below to `tclsh`, which may work smoother.
 *   - For windows, download a zip from http://www.tcl3d.org/html/appTclkits.html
 *     extract and then rename to wish.exe and put it at the path or at the mpv.exe dir.
 *     - Or, tclsh/wish from git/msys2(mingw) works too - set `interpreter` below.
 * - Put context.lua (this file) and context.tcl at the mpv scripts dir.
 * - Add a key/mouse binding at input.conf, e.g. "MOUSE_BTN2 script_message contextmenu"
 * - Once it works, configure the context_menu items below to your liking.
 *
 * 2017-02-02 - Version 0.1 - initial version
 *
 ***************************************************************
--]]

--[[ ************ CONFIG: start ************ ]]--

-- context_menu is an array of items, where each item is an array of:
-- - Display string or a function which returns such string, or "-" for separator.
-- - Command string or a function which is executed on click. Empty to disable/gray.
-- - Optional re-launch: a submenu array, or true to "keep" the same menu open.

function noop() end
local prop_native = mp.get_property_native

local context_menu = {
    {function() return prop_native("mute") and "Un-mute" or "Mute" end, "cycle mute"},
    {"* Volume Up",   "add volume  10", true},
    {"* Volume Down", "add volume -10", true},
    {function() return "[ Volume: " .. tostring(math.floor(prop_native("volume"))) .. " ]" end},
    {"-"},
    {"* Size: orig / 2", "set window-scale 0.5", true},
    {"* Size: orig 1:1", "set window-scale 1.0", true},
    {"* Size: orig x 2", "set window-scale 2.0", true},
    {"-"},
    {"Pseudo sub-menu -->", noop, {
        {"* Press space with the mouse!", "keypress SPACE", true},
        {"GOTO 0", "set time-pos 0"},
        {"Another pseudo sub-menu -->", noop, {
            {"Yay!", "show_text Yay!"},
            {"* Yay+!", function() mp.osd_message("Yay! " .. tostring(math.random())) end, true},
        }},
    }},
    {"-"},
    {"Quit watch-later", "quit-watch-later"},
    {"Quit", "quit"},
    {"-"},
    {"Dismiss", noop},
}

local verbose = false  -- true -> dump console messages also without -v
local interpreter = "wish";  -- tclsh/wish/full-path
local menuscript = mp.find_config_file("scripts/context.tcl")

--[[ ************ CONFIG: end ************ ]]--

function info(x) mp.msg[verbose and "info" or "verbose"](x) end
local utils = require 'mp.utils'

local function do_menu(items, x, y)
    local args = {interpreter, menuscript, tostring(x), tostring(y)}
    for i = 1, #items do
        local item = items[i]
        args[#args+1] = (type(item[1]) == "string") and item[1] or item[1]()
        args[#args+1] = item[2] and tostring(i) or ""
    end
    local ret = utils.subprocess({
        args = args,
        cancellable = true
    })

    if (ret.status ~= 0) then
        mp.osd_message("Something happened ...")
        return
    end

    info("ret: " .. ret.stdout)
    local res = utils.parse_json(ret.stdout)
    x = tonumber(res.x)
    y = tonumber(res.y)
    res.rv = tonumber(res.rv)
    if (res.rv == -1) then
        info("Context menu cancelled")
        return
    end

    local item = items[res.rv]
    if (not (item and item[2])) then
        mp.msg.error("Unknown menu item index: " .. tostring(res.rv))
        return
    end

    -- run the command
    if (type(item[2]) == "string") then
        mp.command(item[2])
    else
        item[2]()
    end

    -- re-launch
    if (item[3]) then
        if (type(item[3]) ~= "boolean") then
            items = item[3]  -- sub-menu, launch at mouse position
            x = -1
            y = -1
        end
        -- Break direct recursion with async, stack overflow can come quick.
        -- Also allow to un-congest the events queue.
        mp.add_timeout(0, function() do_menu(items, x, y) end)
    end
end

mp.register_script_message("contextmenu", function()
    do_menu(context_menu, -1, -1)
end)


text:
import math
from modules.tools.plot_planning.record_reader import RecordItemReader
from modules.tools.plot_planning.imu_speed_acc import ImuSpeedAcc

class ImuSpeedJerk:

    def __init__(self, is_lateral=False):
        self.timestamp_list = []
        self.jerk_list = []
        self.imu_speed_acc = ImuSpeedAcc(is_lateral)

    def add(self, location_est):
        self.imu_speed_acc.add(location_est)
        acc_timestamp_list = self.imu_speed_acc.get_timestamp_list()
        if len(acc_timestamp_list) <= 0:
            return

        index_500ms = len(acc_timestamp_list) - 1
        found_index_500ms = False
        last_timestamp = acc_timestamp_list[-1]
        while index_500ms >= 0:
            current_timestamp = acc_timestamp_list[index_500ms]
            if (last_timestamp - current_timestamp) >= 0.5:
                found_index_500ms = True
                break
            index_500ms -= 1

        if found_index_500ms:
            acc_list = self.imu_speed_acc.get_acc_list()
            jerk = (acc_list[-1] - acc_list[index_500ms]) / \
                (acc_timestamp_list[-1] - acc_timestamp_list[index_500ms])
            self.jerk_list.append(jerk)
            self.timestamp_list.append(acc_timestamp_list[-1])

    def get_jerk_list(self):
        return self.jerk_list

    def get_timestamp_list(self):
        return self.timestamp_list

    def get_lastest_jerk(self):
        if len(self.jerk_list) > 0:
            return self.jerk_list[-1]
        else:
            return None

    def get_lastest_timestamp(self):
        if len(self.timestamp_list) > 0:
            return self.timestamp_list[-1]
        else:
            return None

if __name__ == "__main__":
    import sys
    import matplotlib.pyplot as plt
    import numpy as np
    from os import listdir
    from os.path import isfile, join

    folders = sys.argv[1:]
    fig, ax = plt.subplots(1, 1)
    colors = ["g", "b", "r", "m", "y"]
    markers = ["o", "o", "o", "o"]
    for i in range(len(folders)):
        x = []
        y = []
        folder = folders[i]
        color = colors[i % len(colors)]
        marker = markers[i % len(markers)]
        fns = [f for f in listdir(folder) if isfile(join(folder, f))]
        fns.sort()
        for fn in fns:
            reader = RecordItemReader(folder+"/"+fn)
            processor = ImuSpeedJerk(True)
            last_pose_data = None
            last_chassis_data = None
            topics = ["/apollo/localization/pose"]
            for data in reader.read(topics):
                if "pose" in data:
                    last_pose_data = data["pose"]
                    processor.add(last_pose_data)

            data_x = processor.get_timestamp_list()
            data_y = processor.get_jerk_list()

            x.extend(data_x)
            y.extend(data_y)

        if len(x) <= 0:
            continue
        ax.scatter(x, y, c=color, marker=marker, alpha=0.4)
        #ax.plot(x, y, c=color, alpha=0.4)

        ax.set_xlabel('Timestamp')
        ax.set_ylabel('Jerk')

    plt.show()


text:
Toyz.namespace('Toyz.Astro.Viewer');

// Check to see if all of the API's dependencies have loaded
// If not, return false
Toyz.Astro.Viewer.dependencies_loaded = function(){
    return false;
};
// Load any dependencies of the tile
Toyz.Astro.Viewer.load_dependencies = function(callback){
    // Check to see if ace loaded from the server
    if(!Toyz.Astro.Viewer.dependencies_loaded()){
        console.log('Loading Template dependencies');
        Toyz.Core.load_dependencies(
            {
                js:[
                    "/toyz/static/astrotoyz/astro.js",
                    "/toyz/static/astrotoyz/catalog.js",
                    "/toyz/static/astrotoyz/spectrum.js", // 3rd party color picker
                ],
                css: [
                    "/toyz/static/astrotoyz/astro.css",
                    "/toyz/static/astrotoyz/spectrum.css"
                ]
            },
            function(){
                console.log('Astro-Toyz Viewer dependencies loaded');
                callback();
            }
        );
    };
};

Toyz.Astro.Viewer.Controls = function(options){
    this.physical_coords = {
        type: 'lbl',
        lbl: 'Physical Coords: ',
        input_class: 'viewer-ctrl-info-btn viewer-ctrl-info-coord-div',
        events: {
            mousemove: function(event){
                var ctrls = this.ctrl_panel.gui.params;
                var $input = ctrls.physical_coords.$input;
                var file_info = this.frames[this.viewer_frame].file_info;
                if(file_info!==undefined && file_info.hasOwnProperty('frame') &&
                    file_info.images[file_info.frame].hasOwnProperty('height')
                ){
                    var img_info = file_info.images[file_info.frame];
                    var xy = this.extract_coords(event, img_info);
                    var x = xy[0]/img_info.scale;
                    var y = xy[1]/img_info.scale;
                    if(img_info.hasOwnProperty('coord_range')){
                        x = x + img_info.coord_range.x[0];
                        y = y + img_info.coord_range.y[0];
                    };
                    var coords =
                        (Math.round(x*10)/10).toString()+','
                        +(Math.round(y*10)/10).toString();
                    $input.text(coords);
                };
            }.bind(options.parent)
        }
    };
    this.ra = {
        type: 'lbl',
        lbl: 'RA: ',
        input_class: 'viewer-ctrl-info-btn viewer-ctrl-info-coord-div',
        events: {
            rx_datapoint: function(event){
                var ra;
                if(!isNaN(event.ra) && !isNaN(event.dec)){
                    var wcs = new Toyz.Astro.Utils.World(event.ra, event.dec);
                    ra = wcs.get_ra();
                }else{
                    ra = '';
                };
                this.ctrl_panel.gui.params.ra.$input.text(ra);
            }.bind(options.parent)
        }
    };
    this.dec = {
        type: 'lbl',
        lbl: 'DEC: ',
        input_class: 'viewer-ctrl-info-btn viewer-ctrl-info-coord-div',
        events: {
            rx_datapoint: function(event){
                var dec;
                if(!isNaN(event.ra) && !isNaN(event.dec)){
                    var wcs = new Toyz.Astro.Utils.World(event.ra, event.dec);
                    dec = wcs.get_dec();
                }else{
                    dec = '';
                };
                this.ctrl_panel.gui.params.dec.$input.text(dec);
            }.bind(options.parent)
        }
    };
    this.wcs_align = {
        input_class: 'viewer-ctrl-button viewer-ctrl-viewer-btn astro-viewer-ctrl-align',
        func: {
            click: function(){
                var viewer_frame = this.viewer_frame;
                var file_info = $.extend(true, {}, this.frames[viewer_frame].file_info);
                var img_info = $.extend(true, {}, file_info.images[file_info.frame]);
                delete file_info.images;
                delete img_info.tiles;
                console.log('viewer_frame,x,y',
                    viewer_frame,img_info.viewer.x_center,img_info.viewer.y_center);
                    console.log('viewer filepath', file_info.filepath);
                websocket.send_task({
                    task: {
                        module: 'astrotoyz.tasks',
                        task: 'get_img_data',
                        parameters: {
                            file_info: file_info,
                            img_info: img_info,
                            x: img_info.viewer.x_center,
                            y: img_info.viewer.y_center,
                            data_type: 'datapoint'
                        }
                    },
                    callback: function(viewer_frame, scale, result){
                        console.log('img_data result:', result);
                        for(var i=0; i< this.frames.length; i++){
                            if(i!=viewer_frame){
                                console.log('i', i);
                                console.log('viewer frame', viewer_frame);
                                var file_info = $.extend(true, {},
                                    this.frames[i].file_info);
                                var img_info = $.extend(true, {},
                                    file_info.images[file_info.frame]);
                                    console.log('frame filepath', file_info.filepath);
                                if(img_info.scale!=scale){
                                    this.set_scale(i, scale);
                                };
                                websocket.send_task({
                                    task:{
                                        module: 'astrotoyz.tasks',
                                        task: 'wcs2px',
                                        parameters: {
                                            file_info: file_info,
                                            img_info: img_info,
                                            ra: result.ra,
                                            dec: result.dec
                                        },
                                    },
                                    callback: function(viewer_frame, result){
                                        console.log('i viewerframe', viewer_frame);
                                        console.log('wcs2px result', result);
                                        var file_info = this.frames[viewer_frame].file_info;
                                        var img_info = file_info.images[file_info.frame];
                                        var left = result.x-Math.round(img_info.viewer.width/2);
                                        var top = result.y-Math.round(img_info.viewer.height/2);
                                        console.log('left', left, 'top', top);
                                        this.set_window(viewer_frame, left, top);
                                        console.log('new center',
                                            img_info.viewer.x_center, img_info.viewer.y_center);
                                    }.bind(this, i)
                                });
                                console.log('sent');
                            };
                        };
                    }.bind(this, viewer_frame, img_info.scale)
                })
            }.bind(options.parent)
        },
        prop: {
            type: 'image',
            title: 'align images based on wcs',
            src: '/toyz/static/astrotoyz/icons/align.png'
        },
    };
    this.hist = {
        input_class: 'viewer-ctrl-button viewer-ctrl-tools-btn',
        func: {
            click: function(event){
                this.change_active_tool('hist', event.currentTarget);
                Toyz.Workspace.load_api_dependencies(
                    'highcharts',
                    'Toyz.API.Highcharts',
                    '/static/web/static/api/highcharts.js',
                    function(){
                        if(!this.hasOwnProperty('hist_dialog')){
                            var file_info = this.frames[this.viewer_frame].file_info;
                            var img_info = file_info.images[file_info.frame];
                            this.hist_dialog = new Toyz.Astro.Viewer.HistogramDialog({
                                parent: this,
                                cursor: {
                                    x: img_info.x_center,
                                    y: img_info.y_center
                                }
                            })
                        };
                    }.bind(this)
                )
            }.bind(options.parent)
        },
        prop: {
            type: 'image',
            title: 'get histogram',
            src: '/static/web/static/button_icons/histogram.png'
        },
        events: {
            mousedown: function(event){
                if(this.tools.active_tool=='hist'){
                    var file_info = this.frames[this.viewer_frame].file_info;
                    var img_info = file_info.images[file_info.frame];
                    var x = event.target.offsetLeft+event.offsetX;
                    var y = event.target.offsetTop+event.offsetY;
                    var xy = this.extract_coords(event, img_info);
                    var x = xy[0];
                    var y = xy[1];
                    this.hist_dialog.update({
                        cursor: {
                            x: x,
                            y: y
                        }
                    });
                };
            }.bind(options.parent)
        }
    };
    this.surface = {
        input_class: 'viewer-ctrl-button viewer-ctrl-tools-btn',
        func: {
            click: function(event){
                this.change_active_tool('surface', event.currentTarget);
                Toyz.Core.load_dependencies(
                    {
                        js: [
                            "http://www.google.com/jsapi",
                            "/third_party/graph_3d/graph3d.js"
                        ]
                    },
                    function(){
                        console.log('loaded');
                        google.load('visualization', '1.0', {
                            callback: function() {
                                console.log('all loaded');
                                if(!this.hasOwnProperty('surface_dialog')){
                                    var file_info = this.frames[this.viewer_frame].file_info;
                                    var img_info = file_info.images[file_info.frame];
                                    this.surface_dialog = new Toyz.Astro.Viewer.SurfaceDialog({
                                        parent: this,
                                        cursor: {
                                            x: img_info.x_center,
                                            y: img_info.y_center
                                        }
                                    })
                                };
                            }.bind(this)
                        });
                    }.bind(this)
                );
            }.bind(options.parent)
        },
        prop: {
            type: 'image',
            title: 'get surface plot',
            src: '/static/web/static/button_icons/surface.png'
        },
        events: {
            mousedown: function(event){
                if(this.tools.active_tool=='surface'){
                    var file_info = this.frames[this.viewer_frame].file_info;
                    var img_info = file_info.images[file_info.frame];
                    var x = event.target.offsetLeft+event.offsetX;
                    var y = event.target.offsetTop+event.offsetY;
                    var xy = this.extract_coords(event, img_info);
                    var x = xy[0];
                    var y = xy[1];
                    this.surface_dialog.update({
                        cursor: {
                            x: x,
                            y: y
                        }
                    });
                };
            }.bind(options.parent)
        }
    };
    this.select_star = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn ',
        func: {
            click: function(event){
                this.change_active_tool('select_star', event.currentTarget);
            }.bind(options.parent)
        },
        prop: {
            type: 'image',
            title: 'select catalog source',
            src: '/toyz/static/astrotoyz/icons/selectstar.png'
        }
    },
    this.add_star = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn',
        prop: {
            type: 'image',
            title: 'add point source to catalog',
            src: '/toyz/static/astrotoyz/icons/addstar.png'
        },
        func: {
            click: function(event){
                this.change_active_tool('add_star', event.currentTarget);
            }.bind(options.parent)
        },
        events: {
            mousedown: function(event){
                if(this.tools.active_tool=='add_star'){
                    var catalog = this.catalog_dialog.get_current_catalog();
                    if(catalog!==undefined){
                        var file_info = this.frames[this.viewer_frame].file_info;
                        var img_info = file_info.images[file_info.frame];
                        var x = event.target.offsetLeft+event.offsetX;
                        var y = event.target.offsetTop+event.offsetY;
                        var xy = this.extract_coords(event, img_info);
                        var x = xy[0]/img_info.scale;
                        var y = xy[1]/img_info.scale;
                        console.log('x',x,'y',y);
                        websocket.send_task({
                            task: {
                                module: 'astrotoyz.tasks',
                                task: 'add_src',
                                parameters: {
                                    file_info: file_info,
                                    src_info: {
                                        x: x,
                                        y: y,
                                    },
                                    fit_type: 'elliptical_moffat',
                                    cid: catalog.cid
                                }
                            },
                            callback: function(catalog, result){
                                if(result.status=='success'){
                                    // If the source has an ra amd dec then convert those
                                    // into strings
                                    if(result.src.hasOwnProperty('ra') &&
                                        result.src.hasOwnProperty('dec')
                                    ){
                                        var wcs = new
                                            Toyz.Astro.Utils.World(result.src.ra, result.src.dec);
                                        result.src.ra = wcs.get_ra();
                                        result.src.dec = wcs.get_dec();
                                    };
                                    console.log('catalog before update', catalog);
                                    catalog.add_src(result.src);
                                }else{
                                    alert(result.status)
                                };
                            }.bind(this, catalog)
                        })
                    };
                };
            }.bind(options.parent)
        }
    };
    this.delete_star = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn',
        prop: {
            type: 'image',
            title: 'delete point source from catalog',
            src: '/toyz/static/astrotoyz/icons/deletestar.png'
        },
        func: {
            click: function(event){
                var catalog = this.catalog_dialog.get_current_catalog();
                if(catalog.selected!==undefined){
                    websocket.send_task({
                        task: {
                            module: 'astrotoyz.tasks',
                            task: 'delete_src',
                            parameters: {
                                cid: catalog.cid,
                                src_info: catalog.selected.src_info
                            }
                        },
                        callback: function(selected, result){
                            if(result.status=='success'){
                                this.catalog_dialog.get_current_catalog().delete_src(selected);
                            }else{
                                alert(result.status);
                            };
                        }.bind(this, catalog.selected)
                    })
                };
            }.bind(options.parent)
        }
    };
    this.catalog = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn astro-viewer-ctrl-catalog',
        prop: {
            type: 'image',
            title: 'Open catalog dialog',
            src: '/toyz/static/astrotoyz/icons/catalog.png'
        },
        func: {
            click: function(){
                this.catalog_dialog.$div.dialog('open');
            }.bind(options.parent)
        }
    };
    this.detect_stars = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn',
        prop: {
            type: 'image',
            title: 'detect point sources',
            src: '/toyz/static/astrotoyz/icons/detect.png'
        },
        func: {
            click: function(){
                //this.detect_dialog.$div.dialog('open');
                var file_info = $.extend(true,{},this.frames[this.viewer_frame].file_info);
                var img_info = file_info.images[file_info.frame];
                file_info = {
                    filepath: file_info.filepath,
                    frame: file_info.frame
                };
                // Make room for the new catalog
                //var cid = 'cat-'+this.catalog_dialog.cat_idx;
                //this.catalog_dialog.catalog_idx++;
                this.catalog_dialog.gui.params.catalogs.buttons.add.$input.click();

                //return
                var catalog = this.catalog_dialog.get_current_catalog();
                var cid = catalog.cid;
                // Detect sources and create a catalog
                console.log('cid', cid);
                websocket.send_task({
                    task: {
                        module: 'astrotoyz.tasks',
                        task: 'detect_sources',
                        parameters: {
                            file_info: file_info,
                            cid: cid,
                            settings: {
                                aperture_type: 'radius',
                                maxima_size: 5,
                                maxima_sigma: 2,
                                aperture_radii: [5],
                                threshold: 19,
                                saturate: 40000,
                                fit_method: 'elliptical_moffat'
                            }
                        }
                    },
                    callback: function(cid, result){
                        console.log('detect result', result);
                        var catalog = new Toyz.Astro.Catalog.Catalog({
                            cid: cid,
                            settings: result.settings,
                            sources: result.sources.data,
                            viewer: this
                        });
                        this.catalog_dialog.catalogs[cid] = catalog;
                    }.bind(this, cid)
                })
            }.bind(options.parent)
        }
    };
    this.refresh = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn',
        prop: {
            type: 'image',
            title: 'refresh the src catalog',
            src: '/toyz/static/astrotoyz/icons/refresh.png'
        },
        func: {
            click: function(){
                this.catalog_dialog.get_current_catalog().refresh();
            }.bind(options.parent)
        }
    };
    this.redraw = {
        input_class: 'viewer-ctrl-button astro-viewer-ctrl-astro-btn',
        prop: {
            type: 'image',
            title: 'redraw the src catalog',
            src: '/toyz/static/astrotoyz/icons/redraw.png'
        },
        func: {
            click: function(){
                this.catalog_dialog.get_current_catalog().redraw();
            }.bind(options.parent)
        }
    };
    this.astrometry = {
        input_class: 'viewer-ctrl-button ',
        prop: {
            type: 'image',
            title: 'calculate astrometric solution',
            src: ''
        },
        func: {
            click: function(){

            }
        }
    };
}

Toyz.Astro.Viewer.contextMenu_items = function(workspace, tile_contents, options){
    var items = $.extend(true,{
        controls: {
            name: 'Control Panel',
            callback: function(){
                this.ctrl_panel.$div.dialog('open');
            }.bind(tile_contents)
        },
        img_sep: "--------------"
    },options, Toyz.Workspace.tile_contextMenu_items(workspace));
    return items;
};

Toyz.Astro.Viewer.Contents = function(params){
    if(!params.hasOwnProperty('groups')){
        params.groups = {
            Image: ['load_img', 'first_frame', 'previous_frame',
                'input_frame', 'next_frame', 'last_frame'],
            Viewer: ['add_viewer_frame', 'remove_viewer_frame', 'first_viewer_frame',
                'previous_viewer_frame', 'input_viewer_frame', 'next_viewer_frame',
                'last_viewer_frame', 'wcs_align'],
            Zoom: ['zoom_out', 'zoom_in', 'zoom_bestfit', 'zoom_fullsize', 'zoom_input'],
            Tools: ['rect', 'center', 'hist', 'surface', 'colormap'],
            'Catalog Tools': [
                'catalog', 'detect_stars', 'select_star', 'add_star', 'delete_star',
                'refresh', 'redraw' // TODO: Fix updating images events to eliminate these btns
            ],
            'Image Info': ['img_coords', 'physical_coords', 'ra', 'dec', 'pixel_val']
        }
    };
    if(!params.hasOwnProperty('controls')){
        params.controls = new Toyz.Astro.Viewer.Controls({
            parent: this
        });
    };
    Toyz.Viewer.Contents.call(this, params);
    this.type = 'astro_viewer';
    this.dialog_options = $.extend(true, {
        workspace: this.workspace,
        viewer: this
    }, this.dialog_options);
    this.catalog_dialog = new Toyz.Astro.Catalog.Dialog(this.dialog_options);
};
Toyz.Astro.Viewer.Contents.prototype = new Toyz.Viewer.Contents();
Toyz.Astro.Viewer.Contents.prototype.onmousemove = function(event){
    // Update the pixel value every 200ms
    var ctrl = this.ctrl_panel.gui.params;
    clearTimeout(this.mousemove_timeout);
    this.mousemove_timeout = setTimeout(function(event){
        this.mousemove_timeout = undefined;
        var file_info = this.frames[this.viewer_frame].file_info;
        if(file_info!==undefined && file_info.file_type=='img_array'){
            var img_info = file_info.images[file_info.frame];
            var xy = this.extract_coords(event, img_info);
            var x = Math.round(xy[0]/img_info.scale);
            var y = Math.round(xy[1]/img_info.scale);
            websocket.send_task({
                task: {
                    module: 'astrotoyz.tasks',
                    task: 'get_img_data',
                    parameters: {
                        data_type: 'datapoint',
                        file_info: file_info,
                        img_info: img_info,
                        x: x,
                        y: y
                    }
                },
                callback: function(result){
                    this.rx_datapoint(result);
                }.bind(this)
            });
        };
    }.bind(this, event), 100);
};
Toyz.Astro.Viewer.Contents.prototype.get_img_tiles = function(viewer_frame, file_frame, tiles){
    var file_info = $.extend(true, {}, this.frames[viewer_frame].file_info);
    var img_info = file_info.images[file_frame];
    // If this is the first time accessing the image data load Astro-Toyz specific
    // image information
    if(!img_info.hasOwnProperty('coord_range')){
        websocket.send_task({
            task: {
                module: 'astrotoyz.tasks',
                task: 'get_img_info',
                parameters: {
                    file_info: file_info,
                    img_info: img_info
                }
            },
            callback: function(viewer_frame, file_frame, tiles, result){
                var file_info = this.frames[viewer_frame].file_info;
                file_info.images[file_frame] = result.img_info;
                var temp = new Toyz.Viewer.Contents();
                temp.get_img_tiles.call(this, viewer_frame, file_frame, tiles);
            }.bind(this, viewer_frame, file_frame, tiles)
        })
    }else{
        var temp = new Toyz.Viewer.Contents();
        temp.get_img_tiles.call(this, viewer_frame, file_frame, tiles);
    };
};

Toyz.Astro.Viewer.Histogram = function(options){
    if(!options.hasOwnProperty('settings')){
        options = {settings: options};
    };
    options = $.extend(true,{
        settings: {
            chart: {
                type: 'column',
                width: 400,
                height: 300
            },
            title: {
                text: 'Pixel values'
            },
            xAxis: {
                text: 'Pixel value',
                labels: {
                    rotation: -45
                }
            },
            yAxis: {
                text: 'Number of Points'
            },
            series: [{}]
        },
        bin_type: 'columns',
        columns: 20,
    }, options);
    this.$div = $('<div/>').addClass('viewer-hist-div');
    for(var opt in options){
        this[opt] = options[opt];
    };
    this.$div.highcharts(this.settings);
};
Toyz.Astro.Viewer.Histogram.prototype.update = function(update){
    for(var u in update){
        this[u] = update[u];
    };
    this.build_histogram();
    this.$div.highcharts(this.settings);
};
Toyz.Astro.Viewer.Histogram.prototype.build_histogram = function(){
    var bins = [];
    if(this.bin_type == 'columns'){
        var range = this.dataset.max-this.dataset.min;
        bins = new Array(this.columns);
        this.settings.xAxis.categories = new Array(this.columns);
        for(var i=0; i<bins.length; i++){
            bins[i]=0;
        };
        for(var i=0; i<this.dataset.data.length; i++){
            for(var j=0; j<this.dataset.data[i].length; j++){
                var bin = Math.round(this.columns*(this.dataset.data[i][j]-this.dataset.min)/range);
                if(bin<0){
                    bin = 0;
                }else if(bin>bins.length-1){
                    bin = bins.length-1;
                };
                bins[bin]+=1;
            }
        };
        this.settings.series[0].data = [];
        for(var i=0; i<bins.length; i++){
            var bin_value = Math.round(i*range/this.columns+this.dataset.min);
            this.settings.series[0].data.push([bin_value, bins[i]]);
        };
    }else{
        throw Error("Bin type is not supported yet");
    };
    return bins;
};

Toyz.Astro.Viewer.HistogramDialog = function(options){
    if(!options.hasOwnProperty('parent')){
        throw Error("HistogramDialog must be initialized with a parent viewer");
    };
    this.parent = options.parent;
    options = $.extend(true, {
        min: 1,
        max: 100,
        step: 1,
        value: 10,
        chart: {
            settings:{},
            bin_type: 'columns',
            columns: 20,
            width: 400,
            height: 300
        },
        cursor: {
            x: 0,
            y: 0
        }
    }, options);
    this.cursor = options.cursor;

    this.$div = $('<div/>');

    var elements = {
        type: 'div',
        params: {
            hist: new Toyz.Astro.Viewer.Histogram(options.chart),
            width: {
                lbl: 'area width',
                prop: {
                    value: options.value,
                    type: 'Number'
                },
                func: {
                    change: function(event){
                        this.update({
                            width: Number(event.currentTarget.value)
                        })
                    }.bind(this)
                }
            },
            bins: {
                lbl: 'number of bins',
                prop: {
                    type: 'Number',
                    value: options.chart.columns
                },
                func: {
                    change: function(event){
                        this.update({
                            hist: {
                                columns: Number(event.currentTarget.value)
                            }
                        })
                    }.bind(this)
                }
            },
            stats: {
                type: 'div',
                legend: 'Stats',
                params: {
                    mean: {
                        lbl: 'mean',
                        type: 'lbl'
                    },
                    std_dev: {
                        lbl: '\u03C3',
                        type: 'lbl'
                    },
                    median: {
                        lbl: 'median',
                        type: 'lbl'
                    },
                    min: {
                        lbl: 'min',
                        type: 'lbl'
                    },
                    max: {
                        lbl: 'max',
                        type: 'lbl'
                    }
                }
            }
        }
    };

    this.gui = new Toyz.Gui.Gui({
        params: elements,
        $parent: this.$div
    });

    this.$div.dialog($.extend(true, {
        resizable: true,
        draggable: true,
        autoOpen: false,
        modal: false,
        width: 'auto',//options.chart.width+20,
        title: 'Pixel Values',
        maxHeight: $(window).height(),
        position: {
            my: "left top",
            at: "left top",
            of: $(window)
        },
        buttons: {}
    },options.dialog)).css("font-size", "12px");
};
Toyz.Astro.Viewer.HistogramDialog.prototype.update = function(update){
    var update_hist = false;
    var update_data = false;
    if(update.hasOwnProperty('width') || update.hasOwnProperty('data')){
        update_data = true;
    };
    if(update.hasOwnProperty('hist')){
        this.gui.params.hist.update(update.hist)
    }else if(update_hist){
        this.gui.params.hist.update({});
    };
    if(update.hasOwnProperty('cursor')){
        this.cursor = update.cursor;
        this.$div.dialog('open');
        update_data = true;
    };
    if(update_data===true){
        var file_info = $.extend(true, {},this.parent.frames[this.parent.viewer_frame].file_info);
        var img_info = $.extend(true, {}, file_info.images[file_info.frame]);
        delete file_info.images;
        delete img_info.tiles;
        var width = this.gui.get().width;
        websocket.send_task({
            task: {
                module: 'toyz.web.tasks',
                task: 'get_img_data',
                parameters: {
                    file_info: file_info,
                    img_info: img_info,
                    data_type: 'data',
                    x: this.cursor.x/img_info.viewer.scale,
                    y: this.cursor.y/img_info.viewer.scale,
                    width: width,
                    height: width
                }
            },
            callback: function(result){
                console.log('result', result);
                this.gui.params.hist.update({
                    dataset: $.extend(true,{}, result)
                });
                delete result.data
                delete result.id
                // Update the statistics
                this.gui.set_params({
                    change: false,
                    values: result
                });
            }.bind(this)
        })
    };
};

// Initialize an interactive surface plot and functions to modify and update it
// Note: for now this requires the use of Google Visualization API but in the future
// this will be switched to d3.js
Toyz.Astro.Viewer.SurfacePlot = function(options){
    options = $.extend(true,{
        settings: {
            width: '300px',
            height: '300px',
            style: "surface",
            showPerspective: true,
            showGrid: true,
            showShadow: false,
            keepAspectRatio: true,
            verticalRatio: 1
        }
    }, options);

    this.data = undefined;
    this.$div = $('<div/>');
    this.plot = new links.Graph3d(this.$div[0]);
    for(var opt in options){
        this[opt] = options[opt]
    };
};
Toyz.Astro.Viewer.SurfacePlot.prototype.update = function(update){
    if(update.hasOwnProperty('data')){
        // We must convert the data into a form that Google visualization wants
        this.data = new google.visualization.DataTable();
        this.data.addColumn('number', 'x');
        this.data.addColumn('number', 'y');
        this.data.addColumn('number', 'value');
        for(var i=0; i<update.data.length; i++){
            for(var j=0; j<update.data[i].length; j++){
                this.data.addRow([j,i,update.data[i][j]]);
            }
        };
    };
    if(update.hasOwnProperty('settings')){
        this.settings = $.extend(true, this.settings, update.settings);
    };
    if(this.data!==undefined){
        this.draw();
    };
};
Toyz.Astro.Viewer.SurfacePlot.prototype.draw = function(){
    console.log('data', this.data);
    console.log('settings', this.settings);
    this.plot.draw(this.data, this.settings);
};

Toyz.Astro.Viewer.SurfaceDialog = function(options){
    if(!options.hasOwnProperty('parent')){
        throw Error("HistogramDialog must be initialized with a parent viewer");
    };
    this.parent = options.parent;
    options = $.extend(true, {
        plot: {},
        cursor: {
            x: 0,
            y: 0
        },
        plot_width: 10,
        fit_type: 'circular_gaussian'
    }, options);
    this.cursor = options.cursor;
    this.plot_width = options.plot_width

    this.$div = $('<div/>').css({
        height: '400px',
        width: '400px',
        'min-height': '400px',
    });
    this.plot = new Toyz.Astro.Viewer.SurfacePlot(options.plot);
    this.$div.append(this.plot.$div);
    this.$div[0].width = 400;
    this.$div[0].height = 1000;
    var elements = {
        type: 'div',
        params: {
            plot_width: {
                lbl: 'plot area width',
                prop: {
                    type: 'Number',
                    value: options.plot_width
                },
                func: {
                    change: function(event){
                        this.update({
                            plot_width: Number(event.currentTarget.value)
                        })
                    }.bind(this)
                }
            },
            fit_type: {
                type: 'conditional',
                selector:{
                    fit_type: {
                        type: 'select',
                        options: {
                            circular_gaussian: 'circular gaussian',
                            elliptical_gaussian: 'elliptical gaussian',
                            circular_moffat: 'circular moffat',
                            elliptical_moffat: 'elliptical moffat'
                        },
                        default_val: options.fit_type,
                        func: {
                            change: function(event){
                                this.update({
                                    fit_type: event.currentTarget.value
                                });
                            }.bind(this)
                        }
                    }
                },
                param_sets: {
                    circular_gaussian: {
                        type: 'div',
                        legend: 'Circular gaussian fit',
                        params: {
                            coords: {
                                type: 'lbl',
                                lbl: 'coords'
                            },
                            ra: {
                                type: 'lbl',
                                lbl: 'RA'
                            },
                            dec: {
                                type: 'lbl',
                                lbl: 'DEC'
                            },
                            std_dev: {
                                type: 'lbl',
                                lbl: '\u03C3'
                            },
                            amplitude: {
                                type: 'lbl',
                                lbl: 'amplitude'
                            },
                            floor: {
                                type: 'lbl',
                                lbl: 'floor'
                            }
                        }
                    },
                    elliptical_gaussian: {
                        type: 'div',
                        legend: 'Elliptical gaussian fit',
                        params: {
                            coords: {
                                type: 'lbl',
                                lbl: 'coords'
                            },
                            ra: {
                                type: 'lbl',
                                lbl: 'RA'
                            },
                            dec: {
                                type: 'lbl',
                                lbl: 'DEC'
                            },
                            std_x: {
                                type: 'lbl',
                                lbl: '\u03C3_x'
                            },
                            std_y: {
                                type: 'lbl',
                                lbl: '\u03C3_y'
                            },
                            angle: {
                                type: 'lbl',
                                lbl: '\u03B8'
                            },
                            amplitude: {
                                type: 'lbl',
                                lbl: 'amplitude'
                            },
                            floor: {
                                type: 'lbl',
                                lbl: 'floor'
                            }
                        }
                    },
                    circular_moffat: {
                        type: 'div',
                        legend: 'Circular moffat fit',
                        params: {
                            coords: {
                                type: 'lbl',
                                lbl: 'coords'
                            },
                            ra: {
                                type: 'lbl',
                                lbl: 'RA'
                            },
                            dec: {
                                type: 'lbl',
                                lbl: 'DEC'
                            },
                            fwhm: {
                                type: 'lbl',
                                lbl: 'fwhm1'
                            },
                            beta: {
                                type: 'lbl',
                                lbl: '\u03B2'
                            },
                            amplitude: {
                                type: 'lbl',
                                lbl: 'amplitude'
                            },
                            floor: {
                                type: 'lbl',
                                lbl: 'floor'
                            }
                        }
                    },
                    elliptical_moffat: {
                        type: 'div',
                        legend: 'Elliptical moffat fit',
                        params: {
                            coords: {
                                type: 'lbl',
                                lbl: 'coords'
                            },
                            ra: {
                                type: 'lbl',
                                lbl: 'RA'
                            },
                            dec: {
                                type: 'lbl',
                                lbl: 'DEC'
                            },
                            fwhm1: {
                                type: 'lbl',
                                lbl: 'fwhm1'
                            },
                            fwhm2: {
                                type: 'lbl',
                                lbl: 'fwhm2'
                            },
                            beta: {
                                type: 'lbl',
                                lbl: '\u03B2'
                            },
                            angle: {
                                type: 'lbl',
                                lbl: '\u03B8'
                            },
                            amplitude: {
                                type: 'lbl',
                                lbl: 'amplitude'
                            },
                            floor: {
                                type: 'lbl',
                                lbl: 'floor'
                            }
                        }
                    }
                }
            }
        }
    };

    this.gui = new Toyz.Gui.Gui({
        params: elements,
        $parent: this.$div
    });

    this.$div.dialog($.extend(true, {
        resizable: true,
        draggable: true,
        autoOpen: false,
        modal: false,
        width: 'auto',
        title: 'Surface Plot',
        maxHeight: $(window).height(),
        position: {
            my: "left top",
            at: "left top",
            of: $(window)
        },
        buttons: {}
    },options.dialog)).css("font-size", "12px");
};
Toyz.Astro.Viewer.SurfaceDialog.prototype.update = function(update){
    var update_plot = false;
    var update_data = false;
    if(update.hasOwnProperty('plot_width') || update.hasOwnProperty('data') ||
        update.hasOwnProperty('fit_type')
    ){
        update_data = true;
    };
    for(var u in update){
        this[u] = update[u]
    };
    if(update.hasOwnProperty('plot')){
        this.gui.params.plot.update(update.plot);
    };
    if(update.hasOwnProperty('cursor')){
        this.cursor = update.cursor;
        this.$div.dialog('open');
        update_data = true;
    };
    if(update_data===true){
        var file_info = $.extend(true, {},this.parent.frames[this.parent.viewer_frame].file_info);
        var img_info = $.extend(true, {}, file_info.images[file_info.frame]);
        delete file_info.images;
        delete img_info.tiles;
        var params = this.gui.get();
        var width = this.plot_width;
        websocket.send_task({
            task: {
                module: 'astrotoyz.tasks',
                task: 'get_img_data',
                parameters: {
                    file_info: file_info,
                    img_info: img_info,
                    data_type: 'data',
                    fit_type: params.conditions.fit_type,
                    x: this.cursor.x/img_info.viewer.scale,
                    y: this.cursor.y/img_info.viewer.scale,
                    width: width,
                    height: width
                }
            },
            callback: function(result){
                console.log('surface result', result);
                this.plot.update({
                    data: result.data
                });
                delete result.data
                delete result.id
                // Update the statistics
                if(result.hasOwnProperty('ra') && result.hasOwnProperty('dec')){
                    var wcs = new Toyz.Astro.Utils.World(result.ra, result.dec);
                    result.ra = wcs.get_ra();
                    result.dec = wcs.get_dec();
                };
                this.gui.set_params({
                    change: false,
                    values: result
                });
            }.bind(this)
        })
    };
}

console.log('Astro Toyz Viewer loaded');


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.osmdroid.google.overlay (OSMdroid Third Party 5.0.1 API)</title>
<meta name="date" content="2015-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.osmdroid.google.overlay

Classes

GoogleItemizedOverlay

GooglePolylineOverlay

GoogleTilesOverlay


text:
package org.cipres.treebase.domain.study;

import java.util.List;

import org.cipres.treebase.domain.DomainHome;

/**
 * Interface algorithm home.
 *
 * @author madhu
 *
 */
public interface AlgorithmHome extends DomainHome {

	/**
	 * Find all defined unique algorithm descriptions.
	 */
	List<String> findAllUniqueAlgorithmDescriptions();

	/**
	 * Find all defined unique "other" algorithm descriptions.
	 */
	List<String> findAllUniqueOtherAlgorithmDescriptions(String pPartialValue);

	/**
	 * Find the algorithm based on the description. The search is not case sensitive.
	 *
	 * Returns null if there is no match.
	 *
	 * @param pDesc
	 * @return
	 */
	// Algorithm findByDescription(String pDesc);
}


text:
'use strict';

var handleError = require(__dirname + '/handle_error');
var File = require(__dirname + '/../models/file');
var responseHandler = require(__dirname + '/response_handler');

module.exports = function(req, res) {
  File.findOne({_id: req.params.id}, function(err, file) {
    if (err) return handleError.err404(err, res);
    responseHandler.send200(res, file);
  });
};


text:
<?php

namespace Vich\Sf2TweetsBundle\Form\Handler;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Form;
use Vich\Sf2TweetsBundle\Entity\TweetManager;

/**
 * TweetFormHandler.
 *
 * @author Dustin Dobervich <ddobervich@gmail.com>
 */
class TweetFormHandler
{
    /**
     * @var Request $request
     */
    protected $request;

    /**
     * @var TweetManager $manager
     */
    protected $manager;

    /**
     * @var Form $form
     */
    protected $form;

    /**
     * Gets the form.
     *
     * @return Form The form.
     */
    public function getForm()
    {
        return $this->form;
    }

    /**
     * Gets the tweet.
     *
     * @return Tweet The tweet.
     */
    public function getTweet()
    {
        return $this->form->getData();
    }

    /**
     * Constructs a new instance of TweetFormHandler.
     *
     * @param Request $request The request.
     */
    public function __construct(Request $request, TweetManager $manager, Form $form)
    {
        $this->request = $request;
        $this->manager = $manager;
        $this->form = $form;
    }

    /**
     * Processes the form.
     *
     * @return boolean True if processed successfully, false otherwise.
     */
    public function handle()
    {
        if ('POST' === $this->request->getMethod()) {
            $this->form->bindRequest($this->request);
            if ($this->form->isValid()) {
                $tweet = $this->form->getData();
                $this->manager->updateTweet($tweet);

                return true;
            }
        }

        return false;
    }
}


text:
/**
 * @author Steffen Meschkat (mesch@google.com)
 *
 * @fileoverview Core functions that are used to manage Ajax application
 * state with the URL fragment identifier method.
 *
 * These functions use functions defined in example.js.
 */

/**
 * This variable contains the current state of the application in its
 * external representation, i.e.  as URL parameters. It is used by the
 * history detection function to detect history navigation: If the
 * fragment identifier of the URL of the page is different that the
 * value stored in this object, then a history navigation event
 * occurred and the application is notified. It is global in order to
 * share it with the function that updates the page URL to reflect
 * changed application state: this must not be mistaken for history
 * navigation.
 */
var currentHash = null;

/**
 * Map that says which state elements dominate which other. The keys
 * are the dominant elements, the values are arrays of properties that
 * are recessive against that element. If an element changes, all
 * state elements that are dominated by it are deleted.
 */
var dominatedElements = null;

/**
 * Obtains the initial state of the application based on the URL it
 * was loaded from.
 *
 * @param {Function} loader A function that takes a state Object as
 * argument adnd resets the applications into the state represented by
 * that object.
 *
 * @param {Object} dominate Initializer for dominatedElements.
 */
function applyInitialState(loader, dominate) {
  dominatedElements = dominate;
  currentHash = document.location.hash;
  var state = decode(currentHash.substring(1));
  loader(state);
  detectHistoryNavigation(loader);
}

/**
 * Records the value of a state element in the hard or soft state part
 * of the application state.
 *
 * This uses the global variable currentHash. This function updates
 * the page URL, but we don't want the function that detects history
 * navigation to false consider this a history navigation
 * event. Therefore, we update the URL that the
 * detectHistoryNavigation() function expects to see as the current
 * URL of the page. This is accomplished by sharing the value through
 * this object.
 *
 * @param {String} name The name of the state element.
 *
 * @param {String} value The value of the state element.
 *
 * @param {Boolean} hard If true, the state change is hard, i.e. it
 * creates a new browser history step.
 */
function recordState(name, value, hard) {
  setTimeout(function() {
    recordStateImpl_(name, value, hard);
  }, 10);
}

function recordStateImpl_(name, value, hard) {
  if (typeof console != 'undefined') {
    console.log(name + ' ' + value);
  }
  var state = decode(location.hash.substring(1));
  state[name] = value;

  var dominated = dominatedElements[name] || [];
  for (var i = 0; i < dominated.length; ++i) {
    delete state[dominated[i]];
  }

  var stateUrl = encode(state);
  currentHash = "#" + stateUrl;

  // Internet Explorer will not create a history entry for a changed
  // fragment identifier if there is no anchor in the page that
  // corresponds to it. So we have to create one. Because the browser
  // will scroll to it, we also have to position it at the top of
  // screen.
  var a = document.createElement('A');
  a.style.position = 'absolute';
  a.style.top = getScrollTop(window) + 'px';
  a.name = stateUrl;

  document.body.appendChild(a);
  if (hard) {
    location.href = currentHash;
  } else {
    location.replace(currentHash);
  }
  document.body.removeChild(a);
}

/**
 * Computes the vertical position on the page of the top edge of the
 * browser window.
 *
 * @param {Window} win The window of which to compute the scroll
 * position.
 *
 * @return {Number} The vertical scroll position of the window in
 * pixels.
 */
function getScrollTop(win) {
  if (typeof win.scrollY != 'undefined') {
    return win.scrollY;
  } else if (typeof win.documentElement != 'undefined' &&
    typeof win.documentElement.scrollTop != 'undefined') {
    return win.documentElement.scrollTop + win.document.body.scrollTop;
  } else {
    return win.document.body.scrollTop;
  }
}

/**
 * Initializes history navigation detection. Sets up a function that
 * polls the current URL and detects if it changes. If it does,
 * invokes a callback with the new application state decoded from the
 * new URL.
 *
 * This function uses the global variable currentHash. The last seen
 * state is stored in the property hash of this object. This allows to
 * share the current value with recordState(), so that the load()
 * callback is not invoked when the application updates the state.
 *
 * @param {Function} load A function that is invoked when the page URL
 * chnages. Receives the new application state decoded from the new
 * page URL as argument.
 */
function detectHistoryNavigation(load) {
  window.setInterval(function() {
    if (location.hash != currentHash) {
      if (typeof console != 'undefined') {
        console.log(location.hash + ' <- ' + currentHash);
      }
      currentHash = location.hash;
      var state = decode(location.hash.substr(1));
      load(state);
    }
  }, 50);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<snippet filetemplate="false" extension="cfm">
<name>mxunitAntTaskExample</name>
<help></help>
<starttext><![CDATA[<?xml version="1.0" encoding="ISO-8859-1"?>

<project name="Sample" basedir="." default="runtests">

	<target name="init">
		<!-- what's the directory name of your application? this value will be used throughout this build file; if you don't want that, just replace the references to ${application.name} with your desired values -->
		<property name="application.name" value="MyAppName" />

		<!-- where do your tests live, relative to this build file? -->
		<!-- if running from hudson, simply set this property in the hudson configuration; for example:
		test.dir=c:/inetpub/wwwroot/myapp/test

		if running against network paths on windows, you'll need to escape slashes in the hudson configuration, for example:
		\\\\server\\some\\dir\\webapps\\myapp\\test
		 -->
		<property name="test.dir" location="test" />
		<!-- what is the cfc dot-notation path to that directory, as ColdFusion sees it? -->
		<property name="test.cfcpath" value="${application.name}.test" />
		<!-- what "runner" URL should the tests hit. -->
		<property name="test.runner" value="/${application.name}/test/HttpAntRunner.cfc" />
		<!-- what server and port should your tests run against? -->
		<property name="test.server" value="localhost" />
		<property name="test.serverport" value="80" />

		<!-- where does the mxunit ant jar file live? it's easiest to copy it out of the mxunit install and put it into your app;
		you can include other jars in that directory as well... svn jars for the svnant task, for example-->
		<path id="project.classpath">
			<fileset dir="lib">
				<include name="**/*.jar" />
			</fileset>
		</path>

		<!-- this is where the xml and html will live for the report generator -->
		<property name="test.output" location="test/testresults" />
		<property name="test.output.tmp" location="${test.output}/tmp" />
		<property name="test.junitoutput" location="${test.output}/html" />

		<!-- where the zip file for deployment will live -->
		<property name="dist.dir" location="deploy" />
		<!-- what to call it -->
		<property name="dist.zip" value="${application.name}.zip" />
		<!-- what to start the "path" in the zip with -->
		<property name="dist.prefixInZip" value="${application.name}" />

		<!-- dump the properties -->
		<echoproperties prefix="test" />
		<echoproperties prefix="dist" />
	</target>

	<target name="clean" depends="init">
		<delete dir="{test.output}" failonerror="false" />
		<delete dir="{dist.dir}" failonerror="false" />
		<mkdir dir="${test.output.tmp}" />
		<mkdir dir="${test.junitoutput}" />
		<mkdir dir="${dist.dir}" />
	</target>

	<target name="svn.update" depends="init">
		<typedef resource="org/tigris/subversion/svnant/svnantlib.xml" classpathref="project.classpath" />
		<echo message="updating ${test.dir}" />
		<svn svnkit="true">
			<update dir="${test.dir}" />
		</svn>
	</target>

	<target name="runtests" description="Make output directories and run the MXUnit task" depends="init,clean">
		<taskdef name="mxunittask" classname="org.mxunit.ant.MXUnitAntTask" classpath="${test.mxunit.jar}" />
		<mxunittask server="${test.server}" port="${test.serverport}" defaultrunner="${test.runner}" outputdir="${test.output.tmp}" verbose="true">
			<directory path="${test.dir}" recurse="true" packageName="${test.cfcpath}" componentPath="${test.cfcpath}" />
		</mxunittask>

		<!-- generate pretty reports -->
		<antcall target="junitreport" />
	</target>

	<target name="junitreport" depends="init,clean" description="Runs the report without running the tests">
		<junitreport todir="${test.junitoutput}">
			<fileset dir="${test.output.tmp}">
				<include name="*.xml" />
			</fileset>
			<report format="frames" todir="${test.junitoutput}" />
		</junitreport>
	</target>

	<target name="dist" depends="init,clean" description="Builds the zip file for deployment">
		<zip destfile="${dist.dir}/${dist.zip}">
			<zipfileset dir="." excludes="test/, deploy/, lib/, .apptacular/, .project, build.xml, settings.xml, .settings" prefix="${dist.prefixInZip}" casesensitive="false" />
		</zip>
	</target>

</project>]]></starttext>
<endtext><![CDATA[]]></endtext>
</snippet>


text:
package org.visallo.web.routes.search;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.visallo.core.exception.VisalloException;
import org.visallo.core.exception.VisalloResourceNotFoundException;
import org.visallo.core.model.search.SearchRepository;
import org.visallo.core.user.User;
import org.visallo.web.clientapi.model.ClientApiSearch;

import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SearchDeleteTest {
    private SearchDelete searchDelete;

    @Mock
    private SearchRepository searchRepository;

    @Mock
    private User user;

    @Before
    public void setUp() {
        searchDelete = new SearchDelete(searchRepository);
    }

    @Test
    public void testDeleteExists() throws Exception {
        String id = "1234";
        ClientApiSearch savedSearch = new ClientApiSearch();

        when(searchRepository.getSavedSearch(eq(id), eq(user))).thenReturn(savedSearch);

        searchDelete.handle(id, user);

        verify(searchRepository).deleteSearch(id, user);
    }

    @Test
    public void testDeleteNotExists() throws Exception {
        String id = "1234";

        when(searchRepository.getSavedSearch(eq(id), eq(user))).thenReturn(null);

        try {
            searchDelete.handle(id, user);
            throw new VisalloException("Should have thrown not found");
        } catch (VisalloResourceNotFoundException ex) {
            // OK
        }
    }
}


text:
typedef struct syscall_policy {
	char name[MAX_BUFF];
	char logname[MAX_BUFF];
	int cnt;
	int *syscalls;
} policy;

policy *proc_policy;
int monitor_ctr;
char logname[MAX_BUFF];
char cmdline[MAX_BUFF];

void list_syscalls();
void gridbox_trace_setup();
int check_syscall(int syscall);
void extract_cmdline(char *pid);
#endif


text:
/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  View,
  ActivityIndicator,
  FlatList,
  Dimensions,
  Platform,
} from 'react-native';
import { ButtonGroup } from 'react-native-elements';
import { SafeAreaView } from 'react-navigation';

import {
  ViewContainer,
  RepositoryListItem,
  UserListItem,
  LoadingContainer,
  SearchBar,
} from 'components';
import styled from 'styled-components';
import { colors, fonts, normalize, getHeaderForceInset } from 'config';
import { t } from 'utils';
import { RestClient } from 'api';

const NAV_QUERY_PARAM = 'q';
const SearchTypes = {
  REPOS: 0,
  USERS: 1,
};

const mapStateToProps = (state, ownProps) => {
  const {
    auth: { locale },
    pagination: { SEARCH_REPOS, SEARCH_USERS },
    entities: { repos, users },
  } = state;

  const searchQuery = ownProps.navigation.getParam(NAV_QUERY_PARAM);

  const reposSearchResultsPagination = SEARCH_REPOS[searchQuery] || {
    ids: [],
    isFetching: false,
  };
  const reposSearchResults = reposSearchResultsPagination.ids.map(
    id => repos[id]
  );

  const usersSearchResultsPagination = SEARCH_USERS[searchQuery] || {
    ids: [],
    isFetching: false,
  };
  const usersSearchResults = usersSearchResultsPagination.ids.map(
    id => users[id]
  );

  return {
    locale,
    reposSearchResultsPagination,
    reposSearchResults,
    usersSearchResultsPagination,
    usersSearchResults,
    searchQuery,
  };
};

const mapDispatchToProps = {
  searchRepos: RestClient.search.repos,
  searchUsers: RestClient.search.users,
};

const StyledSafeAreaView = styled(SafeAreaView).attrs({
  forceInset: getHeaderForceInset('Search'),
})`
  background-color: ${colors.white};
`;

const SearchBarWrapper = styled.View`
  flex-direction: row;
`;

const SearchContainer = styled.View`
  width: ${Dimensions.get('window').width};
  background-color: ${colors.white};
  flex: 1;
  height: 55;
  justify-content: center;
`;

const ListContainer = styled.View`
  border-top-color: ${colors.greyLight};
  border-top-width: ${props => (props.noBorderTopWidth ? 0 : 1)};
  margin-bottom: 105;
`;

const TextContainer = styled.View`
  flex: 1;
  align-items: center;
  justify-content: center;
`;

const SearchInfoText = styled.Text`
  font-size: ${normalize(18)};
  text-align: center;
  ${fonts.fontPrimary};
`;

const StyledButtonGroup = styled(ButtonGroup).attrs({
  textStyle: { ...fonts.fontPrimaryBold },
  selectedTextStyle: { color: colors.black },
  containerStyle: {
    height: 30,
    ...Platform.select({
      ios: {
        marginTop: 0,
        marginBottom: 10,
      },
      android: {
        marginTop: 5,
        marginBottom: 12,
      },
    }),
  },
})``;

class Search extends Component {
  props: {
    searchRepos: Function,
    searchUsers: Function,
    usersSearchResults: Array,
    usersSearchResultsPagination: Object,
    reposSearchResults: Array,
    reposSearchResultsPagination: Object,
    locale: string,
    navigation: Object,
  };

  state: {
    query: string,
    searchType: number,
    searchStart: boolean,
    searchFocus: boolean,
  };

  constructor(props) {
    super(props);

    this.state = {
      query: '',
      currentQuery: {},
      searchType: SearchTypes.REPOS,
      searchStart: false,
      searchFocus: false,
    };

    this.switchQueryType = this.switchQueryType.bind(this);
    this.search = this.search.bind(this);
    this.renderItem = this.renderItem.bind(this);
  }

  getNoResultsFound = (type = this.state.searchType) => {
    const { locale } = this.props;

    switch (type) {
      case SearchTypes.REPOS:
        return t('No repositories found :(', locale);
      case SearchTypes.USERS:
        return t('No users found :(', locale);
      default:
        return null;
    }
  };

  getSearchPagination = (type = this.state.searchType) => {
    switch (type) {
      case SearchTypes.REPOS:
        return this.props.reposSearchResultsPagination;

      case SearchTypes.USERS:
        return this.props.usersSearchResultsPagination;

      default:
        return null;
    }
  };

  getSearchResults = (type = this.state.searchType) => {
    switch (type) {
      case SearchTypes.REPOS:
        return this.props.reposSearchResults;

      case SearchTypes.USERS:
        return this.props.usersSearchResults;

      default:
        return null;
    }
  };

  getSearcher = (type = this.state.searchType) => {
    switch (type) {
      case SearchTypes.REPOS:
        return this.props.searchRepos;

      case SearchTypes.USERS:
        return this.props.searchUsers;

      default:
        return null;
    }
  };

  search(query, selectedType = null) {
    const selectedSearchType =
      selectedType !== null ? selectedType : this.state.searchType;

    if (query.trim() !== '') {
      const searchedQuery = query.toLowerCase();

      this.setState({
        searchStart: true,
        currentQuery: {
          ...this.state.currentQuery,
          [selectedSearchType]: searchedQuery,
        },
        query: searchedQuery,
      });
      this.props.navigation.setParams({ [NAV_QUERY_PARAM]: searchedQuery });

      this.getSearcher(selectedSearchType)(searchedQuery);
    }
  }

  switchQueryType(selectedType) {
    if (this.state.searchType !== selectedType) {
      this.setState({
        searchType: selectedType,
      });
      if (this.state.currentQuery[selectedType] !== this.state.query) {
        this.search(this.state.query, selectedType);
      }
    }
  }

  keyExtractor = item => {
    return item.id;
  };

  renderItem = ({ item }) => {
    switch (this.state.searchType) {
      case SearchTypes.REPOS:
        return (
          <RepositoryListItem
            repository={item}
            navigation={this.props.navigation}
          />
        );

      case SearchTypes.USERS:
        return <UserListItem user={item} navigation={this.props.navigation} />;

      default:
        return null;
    }
  };

  renderFooter = isPendingSearch => {
    if (isPendingSearch) {
      return null;
    }

    if (this.getSearchPagination().nextPageUrl === null) {
      return null;
    }

    return (
      <View
        style={{
          paddingVertical: 20,
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    );
  };

  render() {
    const { locale } = this.props;

    const isPendingSearch =
      this.getSearchResults().length === 0 &&
      this.getSearchPagination().isFetching;

    const { query, searchType, searchStart } = this.state;

    const noResults =
      this.getSearchResults().length === 0 &&
      !this.getSearchPagination().isFetching;

    return (
      <ViewContainer>
        <StyledSafeAreaView />

        <SearchBarWrapper>
          <SearchContainer>
            <SearchBar
              textColor={colors.primaryDark}
              textFieldBackgroundColor={colors.greyLight}
              showsCancelButton={this.state.searchFocus}
              onFocus={() => this.setState({ searchFocus: true })}
              onCancelButtonPress={() =>
                this.setState({ searchStart: false, query: '' })
              }
              onSearchButtonPress={text => {
                this.search(text);
              }}
              hideBackground
            />
          </SearchContainer>
        </SearchBarWrapper>

        <StyledButtonGroup
          onPress={this.switchQueryType}
          selectedIndex={this.state.searchType}
          buttons={[t('Repositories', locale), t('Users', locale)]}
        />

        {isPendingSearch && (
          <LoadingContainer
            animating={isPendingSearch}
            text={t('Searching for {query}', locale, {
              query,
            })}
          />
        )}

        {searchStart &&
          !noResults && (
            <ListContainer noBorderTopWidth={isPendingSearch}>
              <FlatList
                data={this.getSearchResults()}
                onRefresh={() =>
                  this.getSearcher()(query, {
                    forceRefresh: true,
                  })
                }
                refreshing={isPendingSearch}
                onEndReached={() =>
                  this.getSearcher()(query, { loadMore: true })
                }
                onEndReachedThreshold={0.5}
                ListFooterComponent={() => this.renderFooter(isPendingSearch)}
                keyExtractor={this.keyExtractor}
                renderItem={this.renderItem}
              />
            </ListContainer>
          )}

        {!searchStart && (
          <TextContainer>
            <SearchInfoText>
              {t('Search for any {type}', locale, {
                type:
                  searchType === SearchTypes.REPOS
                    ? t('repository', locale)
                    : t('user', locale),
              })}
            </SearchInfoText>
          </TextContainer>
        )}

        {searchStart &&
          !isPendingSearch &&
          this.getSearchResults().length === 0 && (
            <TextContainer>
              <SearchInfoText>{this.getNoResultsFound()}</SearchInfoText>
            </TextContainer>
          )}
      </ViewContainer>
    );
  }
}

export const SearchScreen = connect(mapStateToProps, mapDispatchToProps)(
  Search
);


text:
Here is a list of things which could be useful, when added to your issue:

- description
- TL;DR (short description)
- [pastebin](https://pastebin.com) link to your preset
	- found in `preset.json` in the `.zip` download
	- alternatively use the [Preset Viewer](https://projects.dodekeract.com/manta/#/presets/view)
- code or autoexec samples (format like <code>\`this\`</code>)

### Useful Resources
- [how to write markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
- [submit code or presets](https://pastebin.com)

## Pull Requests

Please try to use the same code-style. Including, but not limited to:

- indentation with tabs
- alignment with spaces
- write `if`s like this:
```javascript
if (condition) {
	code;
} else if (condition) {
	code;
} else {
	code;
}
```


text:
[:hungary:](#hu)   [:uk:](#en)

## Maintenance of WordPress websites on a cloud server and technical support

My main activity is **proactive** maintenance of existing websites and
[web applications](/webserver/PHP-development.md).
These experiences could mean valuable feedback for your developer/s.
Traffic light example :vertical_traffic_light: a developer sees the green light,
[I see red](/webserver/WordPress-security.md) and amber.

### Proactive maintenance features

- Choosing service providers based on [measurements](https://github.com/szepeviktor/wordpress-speedtest)
- Modern OS and software on your server
- Server and website [monitoring](/monitoring/README.md) by functional tests and integrity checks
- Monitoring of 3rd-parties too
- Log analysis, alerts
- Software updates by reading changelogs
- Intelligent backup
- **Reporting issues** to editors and developers
- User management, user support over the phone, in email or chat
  and [how-to videos](https://www.youtube.com/user/szepeviktor) EN/HU
- Developing monitoring, **performance and security** [tools](https://github.com/szepeviktor/)
- Handmade [WordPress plugins](https://profiles.wordpress.org/szepeviktor#content-plugins)
- WordPress theme developer [tools](https://github.com/szepeviktor/wordpress-plugin-construction),
  plugin blacklist and suggestions
- Image optimization
- [Email delivery](/mail/README.md)

### Benefits

- **Stable operation**
- Fast page loads
- Website security
- Better UX for visitors and editors also
- Higher Google Search ranking
- Fewer **unexpected** situations

Contact me: viktor@szepe.net

### Webserver stack

Essentially keep every operation in memory!

- Modern CPU, high *memory* bandwidth as WordPress is mainly memory copying,
  sub-msec disk access time, use [UpCloud](https://www.upcloud.com/register/?promo=U29Q8S)
- Thin virtualization layer, use UpCloud, stay away from popular, non-enterprise providers
- Fast operating system: No systemd, Enough entropy, IRQ balance, Low memory usage
- Block hammering attackers: Fail2ban, permanently block hostile networks
- Anycast DNS
- Quick webserver: Apache with Event MPM
- Parallel connection CDN with RAM-like speeds (Amazon CloudFront)
- [High speed SSL](https://istlsfastyet.com/): ECDSA certificate, Entropy source,
  TLS1.2, Ciphersuites for AES-NI, SSL session cache, OCSP stapling, HTTP/2
- Modern PHP with OPcache, FastCGI connected through UDS
- Lean WordPress installation: minimal and audited plugins only
- Redis in-memory object cache
- TokuDB (fractal tree) MariaDB engine
- Static resource optimization
- Cut on JavaScripts
- Continuous monitoring (Monit, Pingdom, HetrixTools)

### Infrastructure layers

- Choose a datacenter (location, power, cooling, security)
- Choose carriers (network)
- Set up an AS (Autonomous system)
- Set up redundant networking
- Set up SAN (Storage area network)
- Set up servers (power supply, fans, CPU, memory, chipsets)
- Install virtualization software
- Install network services (DNS resolvers, NTP, OS mirror)
- Monitor all of above (e.g. disk health, voltages, fan speeds, temperatures)
- Keep away spammer and hacker neighbors

* OS (Operating system: time, IRQ, entropy)
* Firewall (known hostile networks, individual attackers)
* MTA (Mail transfer agent)
* System backup
* Server software (webserver, database, in-memory cache, language interpreter)
* Monitoring (filesystem, clock, networking, processes, files)

- Application (code, static files)
- Package managers
- CLI (command line) tools
- Third parties (DNS, CDN, SSL OCSP, external monitoring, trackers, video platform, map, ESP)

## WordPress üzemeltetés cloud szerveren és műszaki támogatás

[![Honlap műszaki háttere](/Application-infrastructure.png)
Videó egy honlap műszaki hátteréről (HU)](https://www.youtube.com/watch?v=dGi6O9naiN8)

Létező honlapok **proaktív** üzemeltetésével foglalkozok.
Olyan dolgokkal, amelyek nem látszanak a képernyőn,
amiről sokan azt hisszük, hogy rendben vannak, tehát a hibák **váratlanul** jönnek elő.

Olyan helyen veszi hasznomat, ahol nehezen tolerálható az üzemszünet és az üzemzavar.

A **fejlesztésbe** technológiai tanácsokkal és konkrét kivitelezéssel segítek be a tapasztalataim alapján.
A közlekedési jelzőlámpa példával élve :vertical_traffic_light:
a fejlesztők a zöldet látják, én a sárgát és a pirosat.
A figyelmem az üzembiztonságon, a [sérülékenységen](/webserver/WordPress-security.md) és a sebességen van.

### Hogyan előzöm meg a hibákat?

- Megfelelő szolgáltató választás [mérések alapján](https://github.com/szepeviktor/wordpress-speedtest)
- Modern operációs rendszer és szoftver installálás a szerverére
- Ellenőrzött környezet felállítása a honlaphoz
- Szerver, honlap és külső szolgáltatók [monitorozás](/monitoring/README.md) (EN)
  funkcionális tesztekkel és integritás ellenőrzéssel
- Reggelente/óránként hibanaplók elemzése
- Szoftver frissítés changelog-ok olvasása alapján
- Intelligens biztonsági mentés heti rotációval
- **Hibajegy nyitás** a szerkesztőknek és a fejlesztőknek
- Felhasználó menedzsment, és felhasználó támogatás telefonon, emailben, chat-en
  és [videókkal](https://www.youtube.com/user/szepeviktor) (EN/HU)
- Monitorozó programok, **teljesítmény növelő és biztonsági**
  [eszközök fejlesztése](https://github.com/szepeviktor/)
- Gondosan készített [WordPress bővítmények](https://profiles.wordpress.org/szepeviktor#content-plugins)
- [Fejlesztői eszközök](https://github.com/szepeviktor/wordpress-plugin-construction)
  gyártása WordPress sablon készítéshez, bővítmény fekete-lista és javasolt bővítmények
- Kép fájl optimalizálás
- [Email kézbesítés](/mail/README.md) (EN)

### Előnyök

- **Stabil üzem**
- Gyors oldal betöltés
- Honlap sérülékenységek kiküszöbölése
- Jobb felhasználói élmény (UX) a látogatóknak és a szerkesztőknek is
- Jobb helyezés a Google Keresőben
- Kevesebb **váratlan** incidens

Keressen meg: viktor@szepe.net

### más: Honlap tervezés

Ezekről a csapatokról **hallottam** olyat, hogy képesnek arra, hogy hatékony, konverziót hozó honlapot,
[webáruházat](https://www.ocado.com/) tervezzenek.

- https://www.voov.hu/ - Laravel
- https://hacky.hu/
- https://www.upsolution.hu/ - Laravel
- https://splendex.io/
- https://neeed.us/
- https://www.pwstudio.hu/ - :fire: CodeIgniter
- https://netpeople.hu/

* https://www.finetune.hu/
* https://www.rblmarketing.hu/
* http://maarsk.com/
* http://www.surmanngyula.hu/

### más: WordPress fejlesztő keresés

- https://iamgergo.com/about/
- https://webikon.sk/
- https://www.bluechip.at/de/ueber-uns/leitung-team/
- https://www.towa-digital.com/wordpress/

* https://kinsta.com/blog/hire-wordpress-developer/
* https://jobs.wordpress.net/post-a-job/


text:
package org.culturegraph.mf.stream.pipe;

import org.culturegraph.mf.framework.DefaultObjectPipe;
import org.culturegraph.mf.framework.ObjectReceiver;
import org.culturegraph.mf.framework.annotations.Description;
import org.culturegraph.mf.framework.annotations.In;
import org.culturegraph.mf.framework.annotations.Out;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logs the string representation of every object.
 *
 * @param <T> object type
 * @deprecated use {@link ObjectExceptionLogger} instead.
 * @author Christoph Böhme
 *
 */
@Description("logs objects with the toString method")
@In(Object.class)
@Out(Object.class)
@Deprecated
public final class ObjectExceptionLogger<T>
		extends DefaultObjectPipe<T, ObjectReceiver<T>> {

	private static final Logger LOG = LoggerFactory.getLogger(ObjectExceptionLogger.class);

	private final String logPrefix;

	public ObjectExceptionLogger() {
		this("");
	}

	public ObjectExceptionLogger(final String logPrefix) {
		super();
		this.logPrefix = logPrefix;
	}

	@Override
	public void process(final T obj) {

		try{
			getReceiver().process(obj);
		}catch(Exception e){
			// NO CHECKSTYLE IllegalCatch FOR -1 LINES:
			// This module is supposed to intercept _all_ exceptions
			// thrown by downstream modules. Hence, we have to catch
			// Exception.
			LOG.error(logPrefix, e);
		}

	}

	@Override
	protected void onResetStream() {
		LOG.debug("{}resetStream", logPrefix);
	}

	@Override
	protected void onCloseStream() {
		LOG.debug("{}closeStream", logPrefix);
	}

}


text:
from sklearn_explain.tests.skl_datasets_reg import skl_datasets_test as skltest

skltest.test_reg_dataset_and_model("diabetes" , "SVR_poly_8")


text:
"""
Send alerts about about NCSO concessions.
"""

import datetime
import logging

from django.core.management import BaseCommand

from common.alert_utils import EmailErrorDeferrer
from frontend.models import EmailMessage, NCSOConcessionBookmark
from frontend.views import bookmark_utils

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument("--date", help="Date that concessions were imported")

    def handle(self, *args, **options):
        date = options["date"] or datetime.date.today().strftime("%Y-%m-%d")
        send_alerts(date)

def send_alerts(date):
    """Send unsent alerts for given date."""

    bookmarks = get_unsent_bookmarks(date)

    for bookmark in bookmarks:
        with EmailErrorDeferrer() as error_deferrer:
            error_deferrer.try_email(send_alert, bookmark, date)

    print("Sent {} alerts".format(bookmarks.count()))

def get_unsent_bookmarks(date):
    """Find unsent bookmarks for given date.

    Alerts should only be sent to active users.
    """

    return NCSOConcessionBookmark.objects.filter(user__is_active=True).exclude(
        user__emailmessage__tags__contains=["ncso_concessions", date]
    )

def send_alert(bookmark, date):
    """Send alert for bookmark for given date."""

    try:
        msg = bookmark_utils.make_ncso_concession_email(bookmark, tag=date)
        msg = EmailMessage.objects.create_from_message(msg)
        msg.send()
        logger.info("Sent concession alert to %s about %s" % (msg.to, bookmark.id))
    except bookmark_utils.BadAlertImageError as e:
        logger.exception(e)


text:
A simple angular directive for integrating Naver Maps

[![Bower version](https://badge.fury.io/bo/angular-naver-maps.svg)](https://badge.fury.io/bo/angular-naver-maps) [![npm version](https://badge.fury.io/js/angular-naver-maps.svg)](https://badge.fury.io/js/angular-naver-maps)

Use `<ng-naver-map>` for embedding a Naver map into your html

You can see a [live demo here](https://dreidev.github.io/angular-naver-maps)

The full Naver Map API is still unsupported, currently only the following features are supported (which should cover most use cases).

##How to use

Create a Naver map API key https://developers.naver.com/register

include

```html
<script src="https://openapi.map.naver.com/openapi/v2/maps.js?clientId=YOURKEY"></script>
```

get module using bower or npm
- using bower `bower install angular-naver-maps`
- using npm `npm install angular-naver-maps`

then add it before you app.js
- if installed using bower
  ```
  <script src="bower_components/angular-naver-maps/angular-naver-maps.js"></script>
  ```
- if installed using npm
  ```
  <script src="node_modules/angular-naver-maps/angular-naver-maps.js"></script>
  ```

Add the module to your angular app

```js
angular.module('App', ['NaverMaps']);
```

Use available directives (this is taken from the demo)

```html
<ng-naver-map
  zoom="11"
  center="'current-location'"
  zoom-control="true"
  zoom-control-options='{position:{right: 10,left: 10}}'
  size="['width', 400]"
  enable-wheel-zoom="false"
  on-center-changed="centerChanged(coord)">

    <ng-naver-map-marker
        ng-repeat="item in items"
        model="item"
        position='[37.5675451, 126.9773356]'
        on-click="log(model)"
        title="item.name">
    </ng-naver-map-marker>

</ng-naver-map>
```

##Documentation

For the `<ng-naver-map>` directive

- **zoom** Number refers to the zoom level the map should start with
- **min-max-level** Array define zoom range (default:`[1,14]`)
- **center** can take 2 type of values to center the map
  + String `'current-location'` use the geolocation api to get current location
  + Array `[37.5675451, 126.9773356]` latitudinal and longitudinal values
  + If omitted the map defaults to Soul
- **zoom-control-true** Boolean to show the zoom controls (default:false)
- **zoom-control-options** Object zoom controls options such as position
- **size** indicating the size of the map in the form of an array
  + `['width', 400]` set map with `100%` of its container width and `400px` height
  + `['width', 'height']` create a responsive map that scales to the width and height of its container
  + `[800, 400]` create a static map with width `800px` and height `400px`
- **enable-wheel-zoom** Boolean (default:true)
- **enable-drag-pan** Boolean (default:true)
- **enable-dbl-click-zoom** Boolean (default:false)
- **map-mode** Number takes one of three values 0, 1, 2 (default:0)
- **activate-traffic-map** Boolean (default:false)
- **activate-bicycle-map** Boolean (default:false)
- **on-center-changed** is fired whenever center is changed
  + an object coord is passed to the function with the new center position

It is possible to place a marker on the map using `<ng-naver-map-marker>` directive

- **title** String to display on hover
- **position** Array with latitudinal and longitudinal values
- **model** Object to pass on click
- **on-click** function to call on click, passes model as an argument

---

It is possible to place an information window on the map using `<ng-naver-map-infowindow>` directive (uses transclusion)

- **index** Integer to identify the window for future control
- **position** Array with latitudinal and longitudinal values
- **model** Object to pass on click
- **on-click** function to call on click, passes model as an argument

To add HTML to the info window, simply transclude your HTML in the directive.

---
# For additional feature requests submit an issue


text:
/* global describe, beforeEach, it, expect */

import deepFreeze from 'deep-freeze'
import { channelsReducer, currentWeatherReducer, forecastReducer } from '../reducer'

describe('Weather channels reducer', function () {
  it('adds channel to channels list when data received', function () {
    var stateBefore = [1, 2, 3]
    var stateAfter = [1, 2, 3, 4]
    var action = {
      type: 'RECEIVED_WEATHER_DATA',
      payload: {
        id: 4
      }
    }
    deepFreeze(stateBefore)

    var result = channelsReducer(stateBefore, action)
    expect(result).toEqual(stateAfter)
  })

  it('does not duplicate channels in channels\' list when data received', function () {
    var stateBefore = [1, 2, 3]
    var stateAfter = [1, 2, 3, 4]
    var action = {
      type: 'RECEIVED_WEATHER_DATA',
      payload: {
        id: 4
      }
    }
    deepFreeze(stateBefore)

    var result1 = channelsReducer(stateBefore, action)
    deepFreeze(result1)
    var result2 = channelsReducer(result1, action)

    expect(result2).toEqual(stateAfter)
  })
})

describe('Current weather reducer', function () {
  var stateBefore
  beforeEach(function () {
    stateBefore = {
      1: {
        isLoading: false
      },
      2: {
        isLoading: true
      },
      9: {
        isLoading: true
      }
    }
  })

  it('sets current weather\'s loading state to true when data requested', function () {
    var stateAfter = {
      1: {
        isLoading: false
      },
      2: {
        isLoading: true
      },
      9: {
        isLoading: true
      },
      isLoading: true
    }

    var action = {
      type: 'REQUEST_WEATHER',
      payload: {
        id: 10
      }
    }

    deepFreeze(stateBefore)

    var result = currentWeatherReducer(stateBefore, action)

    expect(result).toEqual(stateAfter)
  })

  it('sets loading state to false for given id when data received', function () {
    deepFreeze(stateBefore)

    var action = {
      type: 'RECEIVED_WEATHER_DATA',
      payload: {
        id: 2,
        weather: [ {id: 800} ]
      }
    }

    var result = currentWeatherReducer(stateBefore, action)
    expect(result['2'].isLoading).toBeFalsy()
  })

  it('sets data state to payload for given id when data received', function () {
    var stateAfter = {
      id: 2,
      weather: [ {id: 800} ]
    }

    deepFreeze(stateBefore)

    var action = {
      type: 'RECEIVED_WEATHER_DATA',
      payload: {
        id: 2,
        weather: [ {id: 800} ]
      }
    }

    var result = currentWeatherReducer(stateBefore, action)
    console.log(result)
    action = {
      type: 'RECEIVED_WEATHER_DATA',
      payload: {
        id: 3,
        weather: [ {id: 900} ]
      }
    }
    deepFreeze(result)

    var result1 = currentWeatherReducer(result, action)

    expect(result1['2'].data).toEqual({
      id: 2,
      weather: [ {id: 800} ]
    })
    expect(result1['3'].data).toEqual({
      id: 3,
      weather: [ {id: 900} ]
    })
  })

  it('sets loading state to false, error to true when failed receiving data', function () {
    deepFreeze(stateBefore)

    var action = {
      type: 'FAILED_RECEIVING_WEATHER_DATA',
      payload: {
        id: 2
      }
    }
    var result = currentWeatherReducer(stateBefore, action)
    expect(result['2'].isLoading).toBeFalsy()
    expect(result['2'].error).toBeTruthy()
  })
})


text:
import DS from 'ember-data';

export default DS.ModelFragment.extend({
    CorsRule: DS.hasManyFragments('corsRule')
});


text:
import { createAction } from "redux-actions";

export default createAction("WINDOW_RESIZE", ({ width, height }) => ({
  width,
  height
}));