text:
/**
 * ### Contextmenu plugin
 *
 * Shows a context menu when a node is right-clicked.
 */
// TODO: move logic outside of function + check multiple move
/*globals jQuery, define, exports, require, document */
(function (factory) {
	"use strict";
	if (typeof define === 'function' && define.amd) {
		define('jstree.contextmenu', ['jquery','jstree'], factory);
	}
	else if(typeof exports === 'object') {
		factory(require('jquery'), require('jstree'));
	}
	else {
		factory(jQuery, jQuery.jstree);
	}
}(function ($, jstree, undefined) {
	"use strict";

	if($.jstree.plugins.contextmenu) { return; }

	/**
	 * stores all defaults for the contextmenu plugin
	 * @name $.jstree.defaults.contextmenu
	 * @plugin contextmenu
	 */
	$.jstree.defaults.contextmenu = {
		/**
		 * a boolean indicating if the node should be selected when the context menu is invoked on it. Defaults to `true`.
		 * @name $.jstree.defaults.contextmenu.select_node
		 * @plugin contextmenu
		 */
		select_node : true,
		/**
		 * a boolean indicating if the menu should be shown aligned with the node. Defaults to `true`, otherwise the mouse coordinates are used.
		 * @name $.jstree.defaults.contextmenu.show_at_node
		 * @plugin contextmenu
		 */
		show_at_node : true,
		/**
		 * an object of actions, or a function that accepts a node and returns an object of actions available for that node.
		 *
		 * Each action consists of a key (a unique name) and a value which is an object with the following properties:
		 *
		 * * `separator_before` - a boolean indicating if there should be a separator before this item
		 * * `separator_after` - a boolean indicating if there should be a separator after this item
		 * * `_disabled` - a boolean indicating if this action should be disabled
		 * * `label` - a string - the name of the action
		 * * `action` - a function to be executed if this item is chosen
		 *
		 * @name $.jstree.defaults.contextmenu.items
		 * @plugin contextmenu
		 */
		items : function (o) { // Could be an object directly
			return {
				"create" : {
					"separator_before"	: false,
					"separator_after"	: true,
					"_disabled"			: false, //(this.check("create_node", data.reference, {}, "last")),
					"label"				: "Create",
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.create_node(obj, {}, "last", function (new_node) {
							setTimeout(function () { inst.edit(new_node); },0);
						});
					}
				},
				"rename" : {
					"separator_before"	: false,
					"separator_after"	: false,
					"_disabled"			: false, //(this.check("rename_node", data.reference, this.get_parent(data.reference), "")),
					"label"				: "Rename",
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.edit(obj);
					}
				},
				"remove" : {
					"separator_before"	: false,
					"icon"				: false,
					"separator_after"	: false,
					"_disabled"			: false, //(this.check("delete_node", data.reference, this.get_parent(data.reference), "")),
					"label"				: "Delete",
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if(inst.is_selected(obj)) {
							inst.delete_node(inst.get_selected());
						}
						else {
							inst.delete_node(obj);
						}
					}
				},
				"ccp" : {
					"separator_before"	: true,
					"icon"				: false,
					"separator_after"	: false,
					"label"				: "Edit",
					"action"			: false,
					"submenu" : {
						"cut" : {
							"separator_before"	: false,
							"separator_after"	: false,
							"label"				: "Cut",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.cut(inst.get_selected());
								}
								else {
									inst.cut(obj);
								}
							}
						},
						"copy" : {
							"separator_before"	: false,
							"icon"				: false,
							"separator_after"	: false,
							"label"				: "Copy",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.copy(inst.get_selected());
								}
								else {
									inst.copy(obj);
								}
							}
						},
						"paste" : {
							"separator_before"	: false,
							"icon"				: false,
							"_disabled"			: !(this.can_paste()),
							"separator_after"	: false,
							"label"				: "Paste",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								inst.paste(obj);
							}
						}
					}
				}
			};
		}
	};

	$.jstree.plugins.contextmenu = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);

			this.element
				.on("contextmenu.jstree", "a", $.proxy(function (e) {
						e.preventDefault();
						if(!this.is_loading(e.currentTarget)) {
							this.show_contextmenu(e.currentTarget, e.pageX, e.pageY);
						}
					}, this))
				.on("click.jstree", "a", $.proxy(function (e) {
						if(this._data.contextmenu.visible) {
							$.vakata.context.hide();
						}
					}, this));
			$(document).on("context_hide.vakata", $.proxy(function () { this._data.contextmenu.visible = false; }, this));
		};
		this.teardown = function () {
			if(this._data.contextmenu.visible) {
				$.vakata.context.hide();
			}
			parent.teardown.call(this);
		};

		/**
		 * show the context menu for a node
		 * @name show_contextmenu(obj [, x, y])
		 * @param {mixed} obj the node
		 * @param {Number} x the x-coordinate relative to the document to show the menu at
		 * @param {Number} y the y-coordinate relative to the document to show the menu at
		 * @plugin contextmenu
		 * @trigger show_contextmenu.jstree
		 */
		this.show_contextmenu = function (obj, x, y) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			var s = this.settings.contextmenu,
				d = this.get_node(obj, true),
				a = d.children(".jstree-anchor"),
				o = false,
				i = false;
			if(s.show_at_node || x === undefined || y === undefined) {
				o = a.offset();
				x = o.left;
				y = o.top + this._data.core.li_height;
			}
			if(this.settings.contextmenu.select_node && !this.is_selected(obj)) {
				this.deselect_all();
				this.select_node(obj);
			}

			i = s.items;
			if($.isFunction(i)) { i = i.call(this, obj); }

			$(document).one("context_show.vakata", $.proxy(function (e, data) {
				var cls = 'jstree-contextmenu jstree-' + this.get_theme() + '-contextmenu';
				$(data.element).addClass(cls);
			}, this));
			this._data.contextmenu.visible = true;
			$.vakata.context.show(a, { 'x' : x, 'y' : y }, i);
			/**
			 * triggered when the contextmenu is shown for a node
			 * @event
			 * @name show_contextmenu.jstree
			 * @param {Object} node the node
			 * @param {Number} x the x-coordinate of the menu relative to the document
			 * @param {Number} y the y-coordinate of the menu relative to the document
			 * @plugin contextmenu
			 */
			this.trigger('show_contextmenu', { "node" : obj, "x" : x, "y" : y });
		};
	};

	// contextmenu helper
	(function ($) {
		var right_to_left = false,
			vakata_context = {
				element		: false,
				reference	: false,
				position_x	: 0,
				position_y	: 0,
				items		: [],
				html		: "",
				is_visible	: false
			};

		$.vakata.context = {
			settings : {
				hide_onmouseleave	: 0,
				icons				: true
			},
			_trigger : function (event_name) {
				$(document).triggerHandler("context_" + event_name + ".vakata", {
					"reference"	: vakata_context.reference,
					"element"	: vakata_context.element,
					"position"	: {
						"x" : vakata_context.position_x,
						"y" : vakata_context.position_y
					}
				});
			},
			_execute : function (i) {
				i = vakata_context.items[i];
				return i && !i._disabled && i.action ? i.action.call(null, {
							"item"		: i,
							"reference"	: vakata_context.reference,
							"element"	: vakata_context.element,
							"position"	: {
								"x" : vakata_context.position_x,
								"y" : vakata_context.position_y
							}
						}) : false;
			},
			_parse : function (o, is_callback) {
				if(!o) { return false; }
				if(!is_callback) {
					vakata_context.html		= "";
					vakata_context.items	= [];
				}
				var str = "",
					sep = false,
					tmp;

				if(is_callback) { str += "<"+"ul>"; }
				$.each(o, function (i, val) {
					if(!val) { return true; }
					vakata_context.items.push(val);
					if(!sep && val.separator_before) {
						str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + "> <"+"/a><"+"/li>";
					}
					sep = false;
					str += "<"+"li class='" + (val._class || "") + (val._disabled ? " vakata-contextmenu-disabled " : "") + "'>";
					str += "<"+"a href='#' rel='" + (vakata_context.items.length - 1) + "'>";
					if($.vakata.context.settings.icons) {
						str += "<"+"ins ";
						if(val.icon) {
							if(val.icon.indexOf("/") !== -1 || val.icon.indexOf(".") !== -1) { str += " style='background:url(\"" + val.icon + "\") center center no-repeat' "; }
							else { str += " class='" + val.icon + "' "; }
						}
						str += "> <"+"/ins><"+"span> <"+"/span>";
					}
					str += val.label + "<"+"/a>";
					if(val.submenu) {
						tmp = $.vakata.context._parse(val.submenu, true);
						if(tmp) { str += tmp; }
					}
					str += "<"+"/li>";
					if(val.separator_after) {
						str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + "> <"+"/a><"+"/li>";
						sep = true;
					}
				});
				str  = str.replace(/
<\/li\>$/,"");
				if(is_callback) { str += "
"; }
				if(!is_callback) { vakata_context.html = str; $.vakata.context._trigger("parse"); }
				return str.length > 10 ? str : false;
			},
			_show_submenu : function (o) {
				o = $(o);
				if(!o.length || !o.children("ul").length) { return; }
				var e = o.children("ul"),
					x = o.offset().left + o.outerWidth(),
					y = o.offset().top,
					w = e.width(),
					h = e.height(),
					dw = $(window).width() + $(window).scrollLeft(),
					dh = $(window).height() + $(window).scrollTop();
				// може да се спести е една проверка - дали няма някой от класовете вече нагоре
				if(right_to_left) {
					o[x - (w + 10 + o.outerWidth()) < 0 ? "addClass" : "removeClass"]("vakata-context-left");
				}
				else {
					o[x + w + 10 > dw ? "addClass" : "removeClass"]("vakata-context-right");
				}
				if(y + h + 10 > dh) {
					e.css("bottom","-1px");
				}
				e.show();
			},
			show : function (reference, position, data) {
				var o, e, x, y, w, h, dw, dh, cond = true;
				if(vakata_context.element && vakata_context.element.length) {
					vakata_context.element.width('');
				}
				switch(cond) {
					case (!position && !reference):
						return false;
					case (!!position && !!reference):
						vakata_context.reference	= reference;
						vakata_context.position_x	= position.x;
						vakata_context.position_y	= position.y;
						break;
					case (!position && !!reference):
						vakata_context.reference	= reference;
						o = reference.offset();
						vakata_context.position_x	= o.left + reference.outerHeight();
						vakata_context.position_y	= o.top;
						break;
					case (!!position && !reference):
						vakata_context.position_x	= position.x;
						vakata_context.position_y	= position.y;
						break;
				}
				if(!!reference && !data && $(reference).data('vakata_contextmenu')) {
					data = $(reference).data('vakata_contextmenu');
				}
				if($.vakata.context._parse(data)) {
					vakata_context.element.html(vakata_context.html);
				}
				if(vakata_context.items.length) {
					e = vakata_context.element;
					x = vakata_context.position_x;
					y = vakata_context.position_y;
					w = e.width();
					h = e.height();
					dw = $(window).width() + $(window).scrollLeft();
					dh = $(window).height() + $(window).scrollTop();
					if(right_to_left) {
						x -= e.outerWidth();
						if(x < $(window).scrollLeft() + 20) {
							x = $(window).scrollLeft() + 20;
						}
					}
					if(x + w + 20 > dw) {
						x = dw - (w + 20);
					}
					if(y + h + 20 > dh) {
						y = dh - (h + 20);
					}

					vakata_context.element
						.css({ "left" : x, "top" : y })
						.show()
						.find('a:eq(0)').focus().parent().addClass("vakata-context-hover");
					vakata_context.is_visible = true;
					$.vakata.context._trigger("show");
				}
			},
			hide : function () {
				if(vakata_context.is_visible) {
					vakata_context.element.hide().find("ul").hide().end().find(':focus').blur();
					vakata_context.is_visible = false;
					$.vakata.context._trigger("hide");
				}
			}
		};
		$(function () {
			right_to_left = $("body").css("direction") === "rtl";
			var to			= false,
				css_string	= '.vakata-context { display:none; _width:1px; } ' +
				'.vakata-context, ' +
				'.vakata-context ul { margin:0; padding:2px; position:absolute; background:#f5f5f5; border:1px solid #979797; ' +
				'	-moz-box-shadow:5px 5px 4px -4px #666666; -webkit-box-shadow:2px 2px 2px #999999; box-shadow:2px 2px 2px #999999; }'  +
				'.vakata-context ul { list-style:none; left:100%; margin-top:-2.7em; margin-left:-4px; } ' +
				'.vakata-context li.vakata-context-right ul { left:auto; right:100%; margin-left:auto; margin-right:-4px; } ' +
				'.vakata-context li { list-style:none; display:inline; }' +
				'.vakata-context li a { display:block; padding:0 2em 0 2em; text-decoration:none; width:auto; color:black; white-space:nowrap; line-height:2.4em; ' +
				'	-moz-text-shadow:1px 1px 0px white; -webkit-text-shadow:1px 1px 0px white; text-shadow:1px 1px 0px white; ' +
				'	-moz-border-radius:1px; -webkit-border-radius:1px; border-radius:1px; }' +
				'.vakata-context li a:hover { position:relative; background-color:#e8eff7; ' +
				'	-moz-box-shadow:0px 0px 2px #0a6aa1; -webkit-box-shadow:0px 0px 2px #0a6aa1; box-shadow:0px 0px 2px #0a6aa1; }' +
				'.vakata-context li.vakata-context-hover > a { position:relative; background-color:#e8eff7; ' +
				'	-moz-box-shadow:0px 0px 2px #0a6aa1; -webkit-box-shadow:0px 0px 2px #0a6aa1; box-shadow:0px 0px 2px #0a6aa1; }' +
				'.vakata-context li a.vakata-context-parent { background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw=="); background-position:right center; background-repeat:no-repeat; } ' +
				'.vakata-context li.vakata-context-separator a, ' +
				'.vakata-context li.vakata-context-separator a:hover { background:white; border:0; border-top:1px solid #e2e3e3; height:1px; min-height:1px; max-height:1px; padding:0; margin:0 0 0 2.4em; border-left:1px solid #e0e0e0; _overflow:hidden; ' +
				'	-moz-text-shadow:0 0 0 transparent; -webkit-text-shadow:0 0 0 transparent; text-shadow:0 0 0 transparent; ' +
				'	-moz-box-shadow:0 0 0 transparent; -webkit-box-shadow:0 0 0 transparent; box-shadow:0 0 0 transparent; ' +
				'	-moz-border-radius:0; -webkit-border-radius:0; border-radius:0; }' +
				'.vakata-context li.vakata-contextmenu-disabled a, .vakata-context li.vakata-contextmenu-disabled a:hover { color:silver; background-color:transparent; border:0; box-shadow:0 0 0; }' +
				'.vakata-context li a ins { text-decoration:none; display:inline-block; width:2.4em; height:2.4em; background:transparent; margin:0 0 0 -2em; } ' +
				'.vakata-context li a span { display:inline-block; width:1px; height:2.4em; background:white; margin:0 0.5em 0 0; border-left:1px solid #e2e3e3; _overflow:hidden; } ' +
				'.vakata-context-rtl ul { left:auto; right:100%; margin-left:auto; margin-right:-4px; } ' +
				'.vakata-context-rtl li a.vakata-context-parent { background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7"); background-position:left center; background-repeat:no-repeat; } ' +
				'.vakata-context-rtl li.vakata-context-separator a { margin:0 2.4em 0 0; border-left:0; border-right:1px solid #e2e3e3;} ' +
				'.vakata-context-rtl li.vakata-context-left ul { right:auto; left:100%; margin-left:-4px; margin-right:auto; } ' +
				'.vakata-context-rtl li a ins { margin:0 -2em 0 0; } ' +
				'.vakata-context-rtl li a span { margin:0 0 0 0.5em; border-left-color:white; background:#e2e3e3; } ';
			if(!$.jstree.no_css) {
				$('head').append('');
			}

			vakata_context.element = $("

");
			vakata_context.element
				.on("mouseenter", "li", function (e) {
					e.stopImmediatePropagation();

					if($.contains(this, e.relatedTarget)) {
						// премахнато заради delegate mouseleave по-долу
						// $(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
						return;
					}

					if(to) { clearTimeout(to); }
					vakata_context.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end();

					$(this)
						.siblings().find("ul").hide().end().end()
						.parentsUntil(".vakata-context", "li").addBack().addClass("vakata-context-hover");
					$.vakata.context._show_submenu(this);
				})
				// тестово - дали не натоварва?
				.on("mouseleave", "li", function (e) {
					if($.contains(this, e.relatedTarget)) { return; }
					$(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover");
				})
				.on("mouseleave", function (e) {
					$(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
					if($.vakata.context.settings.hide_onmouseleave) {
						to = setTimeout(
							(function (t) {
								return function () { $.vakata.context.hide(); };
							}(this)), $.vakata.context.settings.hide_onmouseleave);
					}
				})
				.on("click", "a", function (e) {
					e.preventDefault();
				})
				.on("mouseup", "a", function (e) {
					if(!$(this).blur().parent().hasClass("vakata-context-disabled") && $.vakata.context._execute($(this).attr("rel")) !== false) {
						$.vakata.context.hide();
					}
				})
				.on('keydown', 'a', function (e) {
						var o = null;
						switch(e.which) {
							case 13:
							case 32:
								e.type = "mouseup";
								e.preventDefault();
								$(e.currentTarget).trigger(e);
								break;
							case 37:
								if(vakata_context.is_visible) {
									vakata_context.element.find(".vakata-context-hover").last().parents("li:eq(0)").find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 38:
								if(vakata_context.is_visible) {
									o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first();
									if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last(); }
									o.addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 39:
								if(vakata_context.is_visible) {
									vakata_context.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 40:
								if(vakata_context.is_visible) {
									o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first();
									if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first(); }
									o.addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 27:
								$.vakata.context.hide();
								e.preventDefault();
								break;
							default:
								//console.log(e.which);
								break;
						}
					})
				.appendTo("body");

			$(document)
				.on("mousedown", function (e) {
					if(vakata_context.is_visible && !$.contains(vakata_context.element[0], e.target)) { $.vakata.context.hide(); }
				})
				.on("context_show.vakata", function (e, data) {
					vakata_context.element.find("li:has(ul)").children("a").addClass("vakata-context-parent");
					if(right_to_left) {
						vakata_context.element.addClass("vakata-context-rtl").css("direction", "rtl");
					}
					// also apply a RTL class?
					vakata_context.element.find("ul").hide().end();
				});
		});
	}($));
	// $.jstree.defaults.plugins.push("contextmenu");
}));


text:
#pragma once
LEARNER::base_learner* mwt_setup(vw& all);

redpajama_set_name: RedPajamaGithub


text:
/* */
"format cjs";
import warning from 'warning'
import invariant from 'invariant'
import { PUSH, POP } from './Actions'
import { canUseDOM } from './ExecutionEnvironment'
import { addEventListener, removeEventListener, getHashPath, replaceHashPath, supportsGoWithoutReloadUsingHash } from './DOMUtils'
import { saveState, readState } from './DOMStateStorage'
import createDOMHistory from './createDOMHistory'

function isAbsolutePath(path) {
  return typeof path === 'string' && path.charAt(0) === '/'
}

function ensureSlash() {
  let path = getHashPath()

  if (isAbsolutePath(path))
    return true

  replaceHashPath('/' + path)

  return false
}

function addQueryStringValueToPath(path, key, value) {
  return path + (path.indexOf('?') === -1 ? '?' : '&') + `${key}=${value}`
}

function stripQueryStringValueFromPath(path, key) {
  return path.replace(new RegExp(`[?&]?${key}=[a-zA-Z0-9]+`), '')
}

function getQueryStringValueFromPath(path, key) {
  let match = path.match(new RegExp(`\\?.*?\\b${key}=(.+?)\\b`))
  return match && match[1]
}

const DefaultQueryKey = '_k'

function createHashHistory(options={}) {
  invariant(
    canUseDOM,
    'Hash history needs a DOM'
  )

  let { queryKey } = options

  if (queryKey === undefined || !!queryKey)
    queryKey = typeof queryKey === 'string' ? queryKey : DefaultQueryKey

  function getCurrentLocation() {
    let path = getHashPath()

    let key, state
    if (queryKey) {
      key = getQueryStringValueFromPath(path, queryKey)
      path = stripQueryStringValueFromPath(path, queryKey)

      if (key) {
        state = readState(key)
      } else {
        state = null
        key = history.createKey()
        replaceHashPath(addQueryStringValueToPath(path, queryKey, key))
      }
    } else {
      key = state = null
    }

    return history.createLocation(path, state, undefined, key)
  }

  function startHashChangeListener({ transitionTo }) {
    function hashChangeListener() {
      if (!ensureSlash())
        return // Always make sure hashes are preceeded with a /.

      transitionTo(
        getCurrentLocation()
      )
    }

    ensureSlash()
    addEventListener(window, 'hashchange', hashChangeListener)

    return function () {
      removeEventListener(window, 'hashchange', hashChangeListener)
    }
  }

  function finishTransition(location) {
    let { basename, pathname, search, state, action, key } = location

    if (action === POP)
      return // Nothing to do.

    let path = (basename || '') + pathname + search

    if (queryKey)
      path = addQueryStringValueToPath(path, queryKey, key)

    if (path === getHashPath()) {
      warning(
        false,
        'You cannot %s the same path using hash history',
        action
      )
    } else {
      if (queryKey) {
        saveState(key, state)
      } else {
        // Drop key and state.
        location.key = location.state = null
      }

      if (action === PUSH) {
        window.location.hash = path
      } else { // REPLACE
        replaceHashPath(path)
      }
    }
  }

  let history = createDOMHistory({
    ...options,
    getCurrentLocation,
    finishTransition,
    saveState
  })

  let listenerCount = 0, stopHashChangeListener

  function listenBefore(listener) {
    if (++listenerCount === 1)
      stopHashChangeListener = startHashChangeListener(history)

    let unlisten = history.listenBefore(listener)

    return function () {
      unlisten()

      if (--listenerCount === 0)
        stopHashChangeListener()
    }
  }

  function listen(listener) {
    if (++listenerCount === 1)
      stopHashChangeListener = startHashChangeListener(history)

    let unlisten = history.listen(listener)

    return function () {
      unlisten()

      if (--listenerCount === 0)
        stopHashChangeListener()
    }
  }

  function pushState(state, path) {
    warning(
      queryKey || state == null,
      'You cannot use state without a queryKey it will be dropped'
    )

    history.pushState(state, path)
  }

  function replaceState(state, path) {
    warning(
      queryKey || state == null,
      'You cannot use state without a queryKey it will be dropped'
    )

    history.replaceState(state, path)
  }

  let goIsSupportedWithoutReload = supportsGoWithoutReloadUsingHash()

  function go(n) {
    warning(
      goIsSupportedWithoutReload,
      'Hash history go(n) causes a full page reload in this browser'
    )

    history.go(n)
  }

  function createHref(path) {
    return '#' + history.createHref(path)
  }

  // deprecated
  function registerTransitionHook(hook) {
    if (++listenerCount === 1)
      stopHashChangeListener = startHashChangeListener(history)

    history.registerTransitionHook(hook)
  }

  // deprecated
  function unregisterTransitionHook(hook) {
    history.unregisterTransitionHook(hook)

    if (--listenerCount === 0)
      stopHashChangeListener()
  }

  return {
    ...history,
    listenBefore,
    listen,
    pushState,
    replaceState,
    go,
    createHref,
    registerTransitionHook,
    unregisterTransitionHook
  }
}

export default createHashHistory


text:
/*
 * version.h - cleri version information.
 */
#ifndef CLERI_VERSION_H_
#define CLERI_VERSION_H_

#define CLERI_VERSION_MAJOR 1
#define CLERI_VERSION_MINOR 0
#define CLERI_VERSION_PATCH 0

#define VERSION__STRINGIFY(num) #num
#define VERSION___STR(major,minor,patch) \
        VERSION__STRINGIFY(major) "." \
        VERSION__STRINGIFY(minor) "." \
        VERSION__STRINGIFY(patch)
/* end helpers */

/* start auto generated from above */
#define LIBCLERI_VERSION VERSION___STR( \
        CLERI_VERSION_MAJOR, \
        CLERI_VERSION_MINOR, \
        CLERI_VERSION_PATCH)

/* public funtion */
#ifdef __cplusplus
extern "C" {
#endif

const char * cleri_version(void);

#ifdef __cplusplus
}
#endif

#endif /* CLERI_VERSION_H_ */


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  FlatList,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

const styles = StyleSheet.create({
  list: {
    paddingVertical: 8,
  },
  itemContainer: {
    alignItems: 'center',
    paddingHorizontal: 12,
  },
  itemIcon: {
    alignItems: 'center',
    backgroundColor: '#dbdbdb',
    borderColor: 'white',
    borderRadius: 10,
    borderWidth: 2,
    flexDirection: 'row',
    height: 20,
    justifyContent: 'center',
    position: 'absolute',
    right: -3,
    top: -3,
    width: 20,
  },
  itemImage: {
    borderRadius: 27,
    height: 54,
    width: 54,
  },
});

export class SelectedUserListItem extends Component {
  constructor(props) {
    super(props);

    this.remove = this.remove.bind(this);
  }

  remove() {
    this.props.remove(this.props.user);
  }

  render() {
    const { username } = this.props.user;

    return (
      <View
        style={styles.itemContainer}
      >
        <View>
          <Image
            style={styles.itemImage}
            source={{ uri: 'https://reactjs.org/logo-og.png' }}
          />
          <TouchableOpacity onPress={this.remove} style={styles.itemIcon}>
            <Icon
              color="white"
              name="times"
              size={12}
            />
          </TouchableOpacity>
        </View>
        <Text>{username}</Text>
      </View>
    );
  }
}
SelectedUserListItem.propTypes = {
  user: PropTypes.shape({
    id: PropTypes.number,
    username: PropTypes.string,
  }),
  remove: PropTypes.func,
};

class SelectedUserList extends Component {
  constructor(props) {
    super(props);

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

  keyExtractor = item => item.id.toString();

  renderItem({ item: user }) {
    return (
      <SelectedUserListItem user={user} remove={this.props.remove} />
    );
  }

  render() {
    return (
      <FlatList
        data={this.props.data}
        keyExtractor={this.keyExtractor}
        renderItem={this.renderItem}
        horizontal
        style={styles.list}
      />
    );
  }
}
SelectedUserList.propTypes = {
  data: PropTypes.arrayOf(PropTypes.object),
  remove: PropTypes.func,
};

export default SelectedUserList;


text:
This demo uses Parse Lite to populate a ListView in React Native.

### Try it yourself

You can set this app to point to your Parse Server, and run it yourself.

1. Run `npm install` from this directory to install the development dependencies.

2. Put your Parse Server info into `./src/RemoteData.js`. At the top, you'll find a line that initializes a new `App` object. Within its options parameter, set `host` to be the path to your Parse Server, and set `applicationId` to be the id of your app.
  ```js
  // INITIALIZE HERE
  const app = new App({
    host: 'my.parse.server/path',
    applicationId: 'abc123',
  });
  ```

3. Open `./ios/ListViewDemo.xcodeproj` with XCode, and build the app.

4. Run the app in the Simulator. Your app should load up and point to your Parse Server. Any changes you make should be persisted when you refresh the app.


text:
comments: true
date: 2011-02-21 12:54:58
layout: post
slug: firesheep-makes-it-to-the-nytimes-5-months-later
title: Firesheep makes it to the NYTimes.. 5 months later
wordpress_id: 533
categories:
- Code
- Current Events
- IT
- Security
- software
tags:
- blacksheep
- defcon
- firesheep
- security
- sheepsafe
- wall of sheep
---

> Until recently, only determined and knowledgeable hackers with fancy tools and lots of time on their hands could spy while you used your laptop or smartphone at Wi-Fi hot spots. But a free program called Firesheep, released in October, has made it simple to see what other users of an unsecured Wi-Fi network are doing and then log on as them at the sites they visited.

Without issuing any warnings of the possible threat, Web site administrators have since been scrambling to provide added protections.

"I released Firesheep to show that a core and widespread issue in Web site security is being ignored," said Eric Butler, a freelance software developer in Seattle who created the program. "It points out the lack of end-to-end encryption."

What he means is that while the password you initially enter on Web sites like [Facebook](http://topics.nytimes.com/top/news/business/companies/facebook_inc/index.html?inline=nyt-org),[Twitter](http://topics.nytimes.com/top/news/business/companies/twitter/index.html?inline=nyt-org), Flickr, [Amazon](http://topics.nytimes.com/top/news/business/companies/amazon_inc/index.html?inline=nyt-org), [eBay](http://topics.nytimes.com/top/news/business/companies/ebay_inc/index.html?inline=nyt-org) and The New York Times is encrypted, the Web browser's cookie, a bit of code that that identifies your computer, your settings on the site or other private information, is often not encrypted. Firesheep grabs that cookie, allowing nosy or malicious users to, in essence, be you on the site and have full access to your account.

via [New Hacking Tools Pose Bigger Threats to Wi-Fi Users - NYTimes.com](http://www.nytimes.com/2011/02/17/technology/personaltech/17basics.html).

Well, better late than never.

[Firesheep](http://codebutler.com/firesheep) is [really easy to use](http://codebutler.github.com/firesheep/).  I've had some fun at home stealing my wife's cookies and messaging myself back and forth in different browsers.  In seriousness, I haven't logged in to public wifi since this came out.  I did install [SheepSafe](https://github.com/nicksieger/sheepsafe) and ForceTLS, will try the [EFF software](http://www.eff.org/https-everywhere) though it is FireFox only, as is [BlackSheep](http://www.zscaler.com/blacksheep.html).

I'll note, and this is important that Firesheep actually steals insecure session cookies, not passwords.  That is, if you access any website with an insecure session cookie in public wifi, someone with Firesheep can make use of your session (i.e. be logged in as you).  You don't actually have to be logging in.

> It's extremely common for websites to protect your password by encrypting the initial login, but surprisingly uncommon for websites to encrypt everything else. This leaves the cookie (and the user) vulnerable. HTTP session hijacking (sometimes called "sidejacking") is when an attacker gets a hold of a user's cookie, allowing them to do anything the user can do on a particular website. On an open wireless network, cookies are basically shouted through the air, making these attacks extremely easy.

Also see [discussion on Slashdot when it came out in October 2010](http://news.slashdot.org/story/10/10/25/1031235/Firefox-Extension-Makes-Social-Network-ID-Spoofing-Trivial).

And for what it's worth, the term "firesheep" comes from "[Wall of Sheep](http://www.wallofsheep.com/)" at a hacker conference called Defcon that posted information of all the hackers at the conference making insecure use of the public wifi.


text:
<?php
Route::get('', [
	'as' => 'admin.dashboard',
	function () {
		$content = 'Define your dashboard here.';

		return AdminSection::view($content, 'Dashboard');
	}
]);

Route::get('information', [
	'as' => 'admin.information',
	function () {
		$content = 'Define your information here.';

		return AdminSection::view($content, 'Information');
	}
]);

Route::get('activate/{id}', [
	'as' => 'admin.schedule.activate',
	function ($id) {

		$errors = null;
		try {
			if (!$schedule = \App\Schedule::find($id)) {
				return false;
			}
			$schedule->activate();
		}
		catch (Exception $e) {
			return redirect(route('admin.model', [
				'adminModel' => 'schedules',
			]))->with('error_message', $e->getMessage());
		}

		return redirect(route('admin.model', [
			'adminModel' => 'schedules',
		]))->with('success_message', "Таблица обновлена");

	}
]);


text:
/**
 * Convert a file.
 * @function convertFile
 * @param {string} src - Source file path.
 * @param {string} dest - Destination file path.
 * @param {object} [options] - Optional settings.
 * @param {object} [options.rule={}] - Convert map.
 * @param {string} [options.mode='644'] - File mode to generate.
 * @param {boolean} [options.once=false] - Write only first time. Skip if already exists.
 * @returns {Promise}
 *
 */

'use strict'

const argx = require('argx')
const writeout = require('writeout')
const { existsAsync, readFileAsync } = require('asfs')
const convertString = require('./convert_string')

/** @lends convertFile */
async function convertFile(src, dest, options) {
  let args = argx(arguments)
  options = args.pop('object')
  src = args.shift('string')
  dest = args.shift('string')

  let rule = options.rule || {}
  let mode = options.mode || '644'
  let once = !!options.once

  let exists = await existsAsync(dest)
  let skip = exists && once
  if (skip) {
    return
  }
  let content = await readFileAsync(src)
  content = convertString(String(content), rule)
  return await writeout(dest, content, {
    mkdirp: true,
    force: true,
    mode
  })
}

module.exports = convertFile


text:
LICENSE = """Lizenz
============

Fuer die Nutzung dieser App musst du diesen Bedingungen zustimmen:

1. Garantie
Es wird nicht garantiert, dass die in dieser App angegebenen Daten korrekt oder
vollstaendig sind. ASapplications uebernimmt keine Haftung fuer jegliche Fehler.
Die Wahrscheinlichkeit einer Fehlinformation steigt, wenn sie keine aktuelle Version der App auf ihrem Mobiltelefon installiert haben.

2. Veraenderungen der App
Obgleich diese App kostenlos ist, ist es verboten diese App ohne Genehmigung von ASapplications zu verbreiten.

3. Angaben der Nutzer
Die Angaben der Nutzer werden unverschluesselt auf einem oeffentlichem FTP - Server gespeichert. Nutzen sie deshalb andere Passwoerter als bei anderen Accounts. Mit der Nutzung erklaeren sie sich mit der unverschluesselten Datenspeicherung einverstanden.

4. Netzwerkverkehr
Diese App laedt Vertrerungsdaten ueber das Internet herunter. Fuer anfallende Kosten der Mobilfunkbetreiber uebernimmt ASapplications keine Haftung.

5. Infos zu Services
Solange das App - Symbol in der Statusleiste vorhanden ist, werden sie bei bestehender Internetverbindung automatisch ueber Aenderungen informiert.

Der Eigentuemer dieser App ist ASapplications (R)
"""

from kivy.app import App
from kivy.animation import Animation
from kivy.uix.gridlayout import GridLayout
from kivy.uix.dropdown import DropDown
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.clock import Clock, mainthread
from kivy.uix.screenmanager import *
from kivy.uix.image import *
from kivy.uix.scrollview import ScrollView
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.properties import *
from kivy.uix.textinput import *
from kivy.uix.carousel import Carousel
from kivy.base import EventLoop
from kivy.uix.popup import Popup
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.actionbar import *
from kivy.uix.togglebutton import *
from kivy.graphics.instructions import Instruction, InstructionGroup
from kivy.core.window import Window
from kivy.uix.bubble import Bubble
from lxml import etree
import HTMLParser
import zipfile
import sys
import re
import os
import lxml.html
import ftplib
import threading
import time
import urllib
VPWEBSITE = "http://planung.schollgym.de/plaene/Anzeige-Homepage/Schueler-morgen/subst_001.htm"
NEWSSITE = "https://schollgym.lima-city.de/appdata/updates.html"
#VPWEBSITE = " http://vertretung.lornsenschule.de/schueler/f1/subst_001.htm"
#VPWEBSITE = "http://planung.schollgym.de/plaene/Anzeige-Homepage/Schueler-heute/subst_001.htm"
MAINWEBSITE = "http://www.schollgym.de"
ZOOMWEBSITE = "http://zeitung.schollgym.de"
threads = []
menopen = False
inprogress = False
platform = "android"

class dummys:
    def toast(msg):
        pass

def toast_android(msg):
    PythonActivity.toastError(msg)

if sys.platform == "win32":
    print("USING WINDOWS PLATFORM. ABORTING ANDROID STUFF")
    toast = dummys.toast
else:
    from jnius import autoclass
    PythonActivity = autoclass('org.renpy.android.PythonActivity')
    toast = toast_android

nums = "1234567890"
alphabet = "abcdefghijklmnopqrstuvwxyz"

def rotate(KEY=""):
    Window.rotation = 270

def clone(_from,to):
    global connectdone
    #connectdone = False
    file = open(to,"wb")
    server.retrbinary("RETR "+_from,file.write)
    file.close()
    file = open(to,"r")
    t = file.read().replace("\\n","\n")
    file.close()
    #connectdone = True
    return t
def store(name,text):
    f = open("tmp","w")
    f.write(text)
    f.close()
    file = open("tmp","r")
    server.storbinary("STOR "+name,file)
    file.close()
    os.remove("tmp")

def startftp(KEY=""):
    global server
    #printd("[FTP] Connecting to server...")
    server = ftplib.FTP("ftp.lima-city.de")
    #printd("[FTP] logging in to server...")
    server.login("schollgym","SchollGym15")

def log(msg,timestamp=True):
    f = open("/sdcard/.schollgymde/log","a")
    if timestamp:
        f.write(str(time.strftime("%Y/%m/%d$%H:%M:%S")) + " > " + msg + "\n")
    else:
        f.write(msg+"\n")
    f.close()

def exitapp(KEY=""):
    global threads
    for t in threads:
        try:
            t.stop()
        except:
            None
    sys.exit()

if os.path.isdir("/sdcard/.schollgymde") == False:
    os.makedirs("/sdcard/.schollgymde")

log("\n",False)
log("Started Schollgym.de")

class ScreenManagerExtended(ScreenManager):
    background_color = ObjectProperty(Color(1,1,1,1))
class ScreenEx(Screen):
    background_color = ObjectProperty(Color(1,1,1,1))

class NewScreen(Screen):

    def setbg(self,widget,clr=(1,1,1,1)):
            print("setting color...")
            with widget.canvas.before:
                Color(clr[0],clr[1],clr[2],clr[3])  # green; colors range from 0-1 not 0-255
                self.rect = Rectangle(size=widget.size, pos=widget.pos)
                print("doing")
                widget.bind(size=self._update_rect, pos=self._update_rect)
            print("END OF SETTING COLOR")
    def _update_rect(self,instance,value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size

def NewFloat(FloatLayout):
    def __init__(self, **kwargs):
        super(FloatLayoutNew, self).__init__(**kwargs)

class RootWidget(FloatLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(RootWidget, self).__init__(**kwargs)

        # let's add a Widget to this layout
    def setbg(self,widget,clr=(1,1,1,1)):
            print("setting color...")
            with widget.canvas.before:
                Color(clr[0],clr[1],clr[2],clr[3])  # green; colors range from 0-1 not 0-255
                self.rect = Rectangle(size=widget.size, pos=widget.pos)
                print("doing")
                widget.bind(size=self._update_rect, pos=self._update_rect)
            print("END OF SETTING COLOR")
    def _update_rect(self,instance,value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size

def sleep(time,todo):
    Clock.schedule_once(todo,time)

def clone(_from,to):
    global connectdone
    #connectdone = False
    file = open(to,"wb")
    server.retrbinary("RETR "+_from,file.write)
    file.close()
    file = open(to,"r")
    t = file.read().replace("\\n","\n")
    file.close()
    #connectdone = True
    return t
def openmen(KEY=""):
    global titleflow, menopen,sidebar
    if menopen == True:
        closemen()
        menopen = False
        return 0
    menopen = True
    startprog("Menu Open")
    am = Animation(size=(52,52),duration=.2,t="in_out_circ")
    am2 = Animation(pos_hint={"x":0,"y":0},duration=.2 ,t="in_out_circ")
    am2.start(sidebar)
    am.start(titleflow)

def closemen():
    global titleflow
    stopprog()
    am = Animation(size=(48,48),duration=.2 ,t="in_out_circ")
    am2 = Animation(pos_hint={"x":-.8,"y":0},duration=.2 ,t="in_out_circ")
    am2.start(sidebar)
    am.start(titleflow)
def goto_start(KEY=""):
    global sm, sc
    sc.size_hint = None,None
    sc.size = 48,48
    sc.pos_hint_x = None
    sc.pos_hint_y = None
    sc.pos = (int(winsize[0]/2)-24,int(winsize[1]/2)-24)
    am = Animation(size=(0,0))
    am &= Animation(pos=(winsize[0]/2,winsize[1]/2))
    am.start(sc)
    sleep(.8,goto_main)
def goto_main(KEY=""):
    global sm
    sm.current="mainscreen"
    sleep(.5,welcome)
def initfile(KEY=""):
    global threads
    """ This subprogram has to init all things """
    t = threading.Thread(target=vpthread)
    t.start()
    threads.append(t)

def vpthread():
    global done
    notshowp = False
    log("Fetching Data")
    #speedtest
    try:
        start = time.clock()
        urllib.urlretrieve(VPWEBSITE,"/sdcard/.schollgymde/vp")
        end = time.clock()
        if end - start < 2:
            notshowp = True
    except:
         startprog("Offline")
         log("Offline: Not fetched "+str(VPWEBSITE))
         sleep(2,stopprog)
         return 0
    #end speedtest
    if notshowp:
        startprog("Lade Daten")
    else:
        startprog("Lade\nVertretungsplan")
    try:
        os.remove("/sdcard/.schollgymde/vp")
        urllib.urlretrieve(VPWEBSITE,"/sdcard/.schollgymde/vp")
    except:
         startprog("Offline")
         log("Offline: Not fetched "+str(VPWEBSITE))
         sleep(2,stopprog)
         return 0
    if not notshowp:
        startprog("Lade\nHauptseite")
    try:
        urllib.urlretrieve(MAINWEBSITE,"/sdcard/.schollgymde/website")
    except:
        startprog("Offline")
        log("Offline: Not fetched "+str(MAINWEBSITE))
        sleep(2,stopprog)
        return 0
    if not notshowp:
        startprog("Lade\nZeitungsartikel")
    try:
        urllib.urlretrieve(ZOOMWEBSITE,"/sdcard/.schollgymde/newspaper")
    except:
         startprog("Offline")
         log("Offline: Not fetched "+str(ZOOMWEBSITE))
         sleep(2,stopprog)
         return 0
    if not notshowp:
        startprog("Lade\nNews")
    try:
        urllib.urlretrieve(NEWSSITE,"/sdcard/.schollgymde/news")
    except:
        startprog("Offline")
        log("Offline: Not fetched "+str(NEWSSITE))
        sleep(2,stopprog)
        return 0
    stopprog()
def parse():
    vpfile = open("/sdcard/.schollgymde/vp","r")
    vpt = vpfile.read().replace("\\n","\n")
    p = TableParser()
    p.feed(vpt)
    parsed = p.getres()
    log(str(p.getres()))
    parts = []
    formyclass = False
    subjcntr = 0
    nowsubj = []
    donotweekday = True
    endsubj = 10
    for subj in parsed:
        if subj == "Klasse "+CLASS:
            formyclass = True
            continue
        elif re.search("^Klasse ",subj):
                if formyclass:
                    print("Myclass")
                    if subjcntr < endsubj:
                        parts.append(nowsubj)
                        nowsubj = []
                        subjcntr = 0
                print("went out: "+subj+" my class: "+CLASS)
                formyclass = False
                continue
        if formyclass:
         subjcntr += 1
         nowsubj.append(subj)
         #print(subj)
         if subjcntr == endsubj:
                  parts.append(nowsubj)
                  nowsubj = []
                  subjcntr = 0
                  donotweekday = True
         if subj in ["Mo","Di","Mi","Do","Fr"]:
                if donotweekday == False:
                    nowsubj = nowsubj[:-1]
                    parts.append(nowsubj)
                    nowsubj = [subj]
                    subjcntr = 0
                else:
                    donotweekday = False
    log(str(parts))
    fillvp(parts)

def pressedvp(instance,value):
    global vpinf, vpdetail
    touse = vplist[int(value)]
    vpdetail.markup = True
    vpdetail.text = "[ref=Noname]"
    for i in range(8):
        try:
            if i == 0:
                continue
            if i == 1:
                vpdetail.text += "Aenderungstyp: "
            if i == 2:
                vpdetail.text += "Stunde: "
            if i == 3:
                continue
            if i == 4:
                vpdetail.text += "Bei Lehrer: "
            if i == 5:
                vpdetail.text += "Fach: "
            if i == 6:
                vpdetail.text += "in Raum: "
            if i == 7:
                vpdetail.text += "statt Fach: "
            vpdetail.text += touse[i] + "\n"
        except:
            None
    vpdetail.text += "[/ref]"
    am = Animation(pos_hint={"x":0,"y":2})
    am2 = Animation(pos_hint={"x":0,"y":0})
    am.start(vpinf)
    am2.start(vpdetail)
def pressedvpdetails(instance,value):
    global vpinf, vpdetail
    am = Animation(pos_hint={"x":0,"y":0})
    am2 = Animation(pos_hint={"x":3,"y":0})
    am.start(vpinf)
    am2.start(vpdetail)
def fillvp(l):
    global vpinf, vplist
    vplist = l
    vpinf.markup = True
    if len(l) != 0:
        vpinf.text = "" #remove no vp message
    itemcntr = 0
    for item in l:
         # one item is one part of vp
         print("INF: "+str(item))
         vpinf.text = vpinf.text + "[ref=" + str(itemcntr) +"]"+ str(item[2]) + ". Std: "+item[1] + ": "+item[5]+"[/ref]\n"
         itemcntr +=  1
    #readnews()

class TableParser(HTMLParser.HTMLParser):
     def __init__(self):
         HTMLParser.HTMLParser.__init__(self)
         self.endresult = []
         self.in_td = False
         self.in_div = False

     def handle_starttag(self, tag, attrs):
         if tag == 'td':
             self.in_td = True
         if tag == 'div':
             #print "hallo div"
             self.in_div = True

     def handle_data(self, data):
         global dayt
         if self.in_td:
             #print data
             self.endresult.append(data)
         if self.in_div:
             dayt = data

     def handle_endtag(self, tag):
         self.in_td = False
         self.in_div = False
     def getres(self):
         return self.endresult

def welcome(KEY=""):
    startprog("welcome")
    sleep(1,initfile)
    #sleep(3,welcome2)
def welcome2(KEY=""):
    startprog("Developer\nMode")
    sleep(3,stopprog)
def startprog(msg):
    global inprogress,proglabel,progmsg
    if inprogress:
        am = Animation(duration=.5,pos_hint={"x":.25,"y":1},color=(1,1,1,0),t="in_quad")
        am2 = Animation(duration=.5,pos_hint={"x":1.1,"y":.1},t="in_quad")
        am2.start(progimg)
        am.start(proglabel)
        sleep(.5,newprog)
        progmsg = msg
    else:
        proglabel.text = msg
        openprog()
    inprogress = True

def newprog(KEY=""):
    global proglabel,progmsg,progimg
    msg = progmsg
    proglabel.text = msg
    proglabel.pos_hint = {"x":.25,"y":-.4}
    progimg.pos_hint = {"x":1.1,"y":.1}
    openprog()
def openprog(KEY=""):
    global proglabel
    am = Animation(duration=.5,pos_hint={"x":.25,"y":0},color=(1,1,1,1),t="in_quad")
    am.start(proglabel)
    am2 = Animation(duration=.5,pos_hint={"x":.85,"y":.1},t="in_quad")
    am2.start(progimg)
def stopprog(KEY=""):
    global inprogress, proglabel
    sleep(1,readnews)
    inprogress = False
    am = Animation(duration=.5,pos_hint={"x":.25,"y":-.4},color=(1,1,1,0),t="in_quad")
    am.start(proglabel)
    am2 = Animation(duration=.5,pos_hint={"x":1.2,"y":0},t="in_quad")
    am2.start(progimg)
def openvp(KEY=""):
    global vpframe,vpopenbt,vpisopen, vpinf
    if vpisopen:
        am = Animation(duration=1,pos_hint={"x":1,"y":1},t="in_out_circ")
        am2 = Animation(duration=1,pos_hint={"x":.85,"y":.78},t="in_out_circ")
        am.start(vpframe)
        am2.start(vpopenbt)
        vpisopen = False
        return 0

    vpisopen = True
    if os.path.isfile("/sdcard/.schollgymde/vp"):
        try:
            parse()
        except Exception, e:
            vpinf.text = "Error while parsing\nContent:\n"+str(e)
    am = Animation(duration=1,pos_hint={"x":.3,"y":.3},t="in_out_circ")
    am2 = Animation(duration=1,pos_hint={"x":.15,"y":.18},t="in_out_circ")
    am.start(vpframe)
    am2.start(vpopenbt)

def acceptlic(KEY=""):
    global sm
    sm.current = "licscreen"
def licok(KEY=""):
    file = open("/sdcard/.schollgymde/licac","w")
    file.write("Accepted")
    file.close()
    if os.path.isfile("/sdcard/.schollgymde/sets"):
            sleep(1,goto_start)
    else:
             sm.add_widget(settingss)
             sm.current = "settings"
    #sleep(1,goto_start)
def licnok(key=""):
    exit()

def savesets(KEY=""):
    global sm
    startftp()
    usr = usrnorm = clone("/usr/index","r")
    usr = usr.split("\n")
    foundname = False
    for name in usr:
        if name == setname.text+":"+setname2.text:
            foundname = True
    if foundname:
        toast("Name schon vergeben")
        return 0
    store("/usr/index",usrnorm+setname.text+":"+setname2.text+"\n")
    server.mkd("/usr/"+setname.text+setname2.text)
    sdata("usrname",setname.text)
    sdata("usrname2",setname2.text)
    file = open("/sdcard/.schollgymde/sets","w")
    file.write(setclass.text)
    file.close()
    goto_start()

def data(name,notfound=False):
    if os.path.isfile("/sdcard/.schollgymde/"+name) == False:
        return notfound
    f = open("/sdcard/.schollgymde/"+name,"r")
    t = f.read()
    f.close()
    return t

def sdata(name,content):
    f = open("/sdcard/.schollgymde/"+name,"w")
    f.write(content)
    f.close()

def goto_secure(KEY=""):
    global sm
    rotate()
    sm.transition = NoTransition()
    sm.current = "secac"

def writets():
    global tstowrite, term
    for letter in tstowrite:
        term.text += letter
        time.sleep(tstowait)
def ts(text,wait=0.01):
    global sm, term, tstowrite, tstowait
    tstowait = wait
    tstowrite = text
    threading.Thread(target=writets).start()
    return len(text)*wait

def acdata(name,notfound=False):
    try:
        t = clone("/usr/"+usrid+"/"+name,"r")
        return t
    except:
        return notfound

def sacdata(name,content):
    store("/usr/"+usrid+"/"+name,content)

def showdeny():
    global secac, denyframe
    for i in range(2):
        secac.add_widget(denyframe)
        time.sleep(.5)
        secac.remove_widget(denyframe)
        time.sleep(.5)
    secac.add_widget(denyframe)
    time.sleep(1.5)
    secac.remove_widget(denyframe)

def ts2(text,wait=0):
    global term
    term.text += text

def firecmd(cmd):
    global sm, usrid, oldusrid
    oldusrid = usrid
    HELP = "\nhelp - Print this help\nlogout - Log out from the ADSAC\nexit - Exit the app\nusr [user id] - Set the current working account\nregister [name] [content: optional]\ncat [name]"
    if cmd == "logout":
        term.text = ""
        termin.text = "COMMAND INPUT"
        sm.current = "mainscreen"
    elif cmd == "help":
        ts2(HELP+"\n",0.00)
    elif cmd == "exit":
        exitapp()
    elif re.search("^usr ",cmd):
        usrid = cmd.replace("usr ","")
    elif re.search("^register ",cmd):
        cmd = cmd.split(" ")
        if len(cmd) < 2:
            ts2("Not enough arguments. Min. 1 expected\n",0.00)
            return 0
        if len(cmd) == 2:
            cmd.append("")
        sacdata(cmd[1],cmd[2])
    elif re.search("^cat ",cmd):
        cmd = cmd.split(" ")
        t = acdata(cmd[1])
        if t == False:
            ts2("IOError: No such file or directory\n",0.00)
        else:
            ts2("Content of specified file:\n-----------------------------\n"+str(t),0.00)

    ts2("ADSAC $ ",0.00)

def termcmd(KEY=""):
    cmd = termin.text
    termin.text = ""
    #towait = ts(cmd+"\n")
    term.text += cmd + "\n"
    #sleep(towait,lambda KEY: firecmd(cmd))
    firecmd(cmd)

def wronglogin(KEY=""):
    global sm
    sm.current = "secac"
    threading.Thread(target=showdeny).start()

def usrlogin(KEY=""):
    global usrid
    oldusrid = usrid
    usrid = secname.text+secpwd.text
    if acdata("dev") == False:
        sleep(1,wronglogin)
        usrid = oldusrid
        return 0
    usrid = oldusrid
    ts("\n\nWaiting for your commands\n\nFTP Server: / , local: ~  $")

def cmdftp(KEY=""):
    try:
       startftp()
       ts("\nServer connection: OK\n")
       sleep(2.5,usrlogin)
       #sleep(2.5,wronglogin)
    except Exception as e:
        ts("\nERROR: "+str(e)+"\n")
        sleep(5,wronglogin)

def termlogon(KEY=""):
    global sm
    # server things
    sm.transition = NoTransition()
    sm.current = "termscreen"
    ts("ASapplications Development Security Access Console ADSAC\nThis place is absolutely secure and blocked for all normal users.\nChecking User Credentials...")
    sleep(4,cmdftp)
    #sleep(5,wronglogin)

def readnews(KEY=""):
    global mainscroll, newsblocks, news, mainblock
    print("========================== READING NEWS ==============================")
    if os.path.isfile("/sdcard/.schollgymde/news") == False:
        print("NO NEWS")
        return 0
    news = []
    file = open("/sdcard/.schollgymde/news","r")
    for line in file:
        line = line[:-1]
        if re.search("^//",line):
            continue
        if line == "":
            continue
        line = line.split("::")
        news.append([line[0],line[1].replace("\\n","\n")])
    print(news)
    newscntr = 0
    count = False
    if len(news) > 5:
        count = True
    for new in news:
        newsblocks[newscntr] = RootWidget()
        newsblocks[newscntr].setbg(newsblocks[newscntr],(.98,.98,.98,1))
        headline = Label(text=new[0],pos_hint={"x":0,"y":.4},color=(0,0,0,1))
        top = .2
        if len(new[1].split("\n")) > 1:
            for i in range(len(new[1].split("\n"))):
                top = top - .1
        content = Label(text=new[1],markup=True,pos_hint={"x":0,"y":.2},halign="center",shorten=True,color=(0,0,0,1))
        newsblocks[newscntr].add_widget(headline)
        newsblocks[newscntr].add_widget(content)
        mainblock.add_widget(newsblocks[newscntr])
        newscntr += 1
        if count:
            if newscntr > 6:
                mainblock.size_hint = (1, float(mainblock.size_hint[1])+0.2)

vpisopen = False
winsize = (Window.width,Window.height)
sm = ScreenManagerExtended()

#news = [["SCHOLL","Gymnasium fuehrt App ein"],["JO","JO IST COOL"],["BLA","BLA CAR"],["1","1"],["2","2"],["3","3"],["4","4"]]
#for i in range(30):
#    news.append(["6","6"])

mainscroll = ScrollView(size_hint=(.9,.9),pos_hint={"x":.05,"y":0})
mainblock = GridLayout(size_hint=(1,1),spacing=3,pos_hint={"x":0,"y":0},cols=1)
mainscroll.add_widget(mainblock)
newsblocks = {}
#readnews()

denyframe = RootWidget()
denyframe.setbg(denyframe,(.2,0,0,1))
denyframe.add_widget(Label(text="! Access Denied !",color=(.9,0,0,1),font_size="40sp",pos_hint={"x":0,"y":0}))
denyframe.size_hint = .5,.13
denyframe.pos_hint = {"x":.25,"y":.5}

terms = NewScreen(name="termscreen")
term = TextInput(background_normal="",text="",background_color=(0,0,0,1),foreground_color=(0,.8,0,1),size_hint=(1,.92),pos_hint={"x":0,"y":.08})
terms.add_widget(term)
termin = TextInput(background_normal="",text="COMMAND INPUT",background_color=(0,0,0,1),foreground_color=(0,.8,0,1),size_hint=(1,.08),pos_hint={"x":0,"y":0},multiline=False)
terms.add_widget(termin)
termin.bind(on_text_validate=termcmd)
secac = NewScreen(name="secac")

seclog = Image(source="security.png")
seclog.size_hint = .4,.8
seclog.pos_hint = {"x":.05,"y":.1}

seclab = Label(text="ASapplications Security System Access\n\nYou are going to access the Security\nSystem now. This place is only opened\nfor verified Developers of ASapplications\nEnter your Credentials.",font_size="19sp",color=(0,0,.8,1))
seclab.pos_hint = {"x":.2,"y":.2}
secac.add_widget(seclab)

secgo = Button(text="Access",background_normal="",background_down="",background_color=(0,0,.9,1))
secgo.size_hint = .2,.08
secgo.pos_hint = {"x":.8,"y":.1}
secac.add_widget(secgo)
secgo.bind(on_release=termlogon)

secac.add_widget(seclog)

secname = TextInput(multiline=False,background_normal="",foreground_color=(1,1,1,1),text="Name",background_color=(0,0,.6,1))

secname.size_hint = .4, .08
secname.pos_hint = {"x":.6,"y":.4}
secac.add_widget(secname)

secpwd = TextInput(multiline=False,background_normal="",foreground_color=(1,1,1,1),text="123456",password=True,background_color=(0,0,.6,1))

secpwd.size_hint = .4, .08
secpwd.pos_hint = {"x":.6,"y":.3}
secac.add_widget(secpwd)

settingss = NewScreen(name="settings")
settingss.setbg(settingss,(1,1,1,1))

settitle = Label(text="Einstellungsassitent",font_size="20sp",color=(0,0,0,1),pos_hint={"x":0,"y":.45})
settingss.add_widget(settitle)

setclass = TextInput(text="Deine Klasse und Buchstabe (z.B. 8d)",multiline=False,size_hint=(.9,.1),pos_hint={"x":.05,"y":.8})
settingss.add_widget(setclass)

setname = TextInput(text="Vorname",multiline=False,pos_hint={"x":0,"y":.7},size_hint=(.5,.1))

setname2 = TextInput(text="Nachnahme (Nutze echte Angaben)",multiline=False,pos_hint={"x":.5,"y":.7},size_hint=(.5,.1))
settingss.add_widget(setname2)
settingss.add_widget(setname)

oksets = Button(text="Abspeichern",size_hint=(1,.1),pos_hint={"x":0,"y":0})
settingss.add_widget(oksets)

oksets.bind(on_release=savesets)

licscreen = NewScreen(name="licscreen")
licscreen.setbg(licscreen,(1,1,1,1))
liclabel = TextInput(background_color=(1,1,1,1),background="",font_size="11sp")
liclabel.size_hint = 1,.9
liclabel.pos_hint = {"x":0,"y":.1}
licscreen.add_widget(liclabel)
licyes = Button(text="Akzeptieren",size_hint=(.5,.1),pos_hint={"x":0,"y":0})
licscreen.add_widget(licyes)
licno = Button(text="Verweigern",size_hint=(.5,.1),pos_hint={"x":.5,"y":0})
licscreen.add_widget(licno)
licyes.bind(on_release=licok)
licno.bind(on_release=licnok)

liclabel.text = LICENSE

mainscreen = NewScreen(name="mainscreen")
mainscreen.setbg(mainscreen,(1,1,1,1))
mainscreen.add_widget(mainscroll)
logonscreen = NewScreen(name="logonscreen")
sc = Image(source="school_white.png")
sm.add_widget(logonscreen)
logonscreen.add_widget(sc)
titlebar = RootWidget()
titlebar.setbg(titlebar,(63.0/255.0,81.0/255.0,181.0/255.0,1))
titlebar.size_hint = 1, .1
titlebar.pos_hint = {"x":0,"y":0.9}
vpopenbt = Button(background_normal="bag.png",background_down="bag.png", pos_hint={"x":.85,"y":.78},size_hint=(.15,.12))
vpopenbt.bind(on_release=openvp)
vpframe = RootWidget()
vpframe.setbg(vpframe,(.9,.9,.9,1))
vpframe.size_hint = .7,.7
vpframe.pos_hint = {"x":1,"y":1}
vpinf = Label(text="KEIN\nVERTRETUNGSPLAN\nVORHANDEN",color=(0,0,0,1),font_size="20sp")
vpinf.pos_hint = {"x":0,"y":0}
vpinf.bind(on_ref_press=pressedvp)
vpdetail = Label(text="No Detais",color=(0,0,0,1),font_size="20sp")
vpdetail.pos_hint={"x":3,"y":0}
vpdetail.bind(on_ref_press=pressedvpdetails)
vpframe.add_widget(vpinf)
vpframe.add_widget(vpdetail)
mainscreen.add_widget(vpframe)
mainscreen.add_widget(vpopenbt)
titlelab = Label(text="SCHOLLGYM.de",font_size="20sp",color=(1,1,1,1))
proglabel = Label(text="None\nDeveloper",color=(1,1,1,0),font_size="13sp")
#proglabel.pos_hint_x = .2
#proglabel.pos_hint_y = 0
proglabel.pos_hint = {"x":.25,"y":-.4}
progimg = Image(source="loadingmat.gif",keep_ratio=False,allow_stretch=True,anim_delay=0.05)
progimg.size_hint = .14,.75
progimg.pos_hint ={"x":1.1,"y":.1}
progbg = RootWidget()
progbg.setbg(progbg,(1,1,1,1))
progbg.size_hinz = .15, 1
progbg.pos_hint = {"x":.85,"y":0}
titlebar.add_widget(progbg)
titlebar.add_widget(progimg)
titlebar.add_widget(proglabel)
titlelab.pos_hint = {"x":-.1,"y":0}
titlescat = ScatterLayout()
titlescat.size_hint = None,None
sidebar = RootWidget()
sidebar.setbg(sidebar,(.8,.8,.8,1))
sidebar.size_hint = .8,.9
sidebar.pos_hint = {"x":-.8,"y":0}
exitbt = Button(text="Beenden",background_color=(0,1,1,1))
exitbt.size_hint = 1,.1
exitbt.pos_hint = {"x":0,"y":0}
exitbt.bind(on_release=exitapp)
sidebar.add_widget(exitbt)
secbt = Button(text="Entwickler - Bereich",background_color=(0,0,0,1))
secbt.size_hint = 1,.1
secbt.pos_hint = {"x":0,"y":.8}
sm.add_widget(secac)
secbt.bind(on_release=goto_secure)
sidebar.add_widget(secbt)
sidetitle = Label(text="Optionen",font_size="25sp",color=(0,0,0,1))
sidetitle.pos_hint = {"x":0,"y":.45}
sidebar.add_widget(sidetitle)
titlescat.size = 48,48
titlescat.pos_hint = {"x":0.025,"y":.25}
mencanv = RootWidget()
mencanv.size_hint= .1,.6
mencanv.pos_hint = {"x":0.025,"y":.2}
#titlebar.add_widget(mencanv)
titlebar.add_widget(titlescat)
titleflow = Button(background_normal="school.png",background_down="school.png")
titleflow.size_hint = None,None
titleflow.size = 48,48
titleflow.pos_hint = {"x":0,"y":0}
titleflow.bind(on_release=openmen)
titlescat.add_widget(titleflow)
titlebar.add_widget(titlelab)
mainscreen.add_widget(titlebar)
sm.add_widget(mainscreen)
sm.add_widget(terms)
sm.current = "logonscreen"

logo = Image(source="school.png")
#mainscreen.add_widget(logo)
mainscreen.add_widget(sidebar)

us1 = data("usrname")
us2 = data("usrname2")

if us1:
    usrid = us1+us2

class MainApp(App):

    def build(self):
        global sm, CLASS
        if platform == 'android':
            if sys.platform != "win32":
                from android import AndroidService
                service = AndroidService('Vertretungsplan wird kontrolliert', 'Keine Benachrichtigung, Wenn Meldung weg ist.')
                service.start('service started')
                self.service = service
        if os.path.isfile("/sdcard/.schollgymde/licac"):
            if os.path.isfile("/sdcard/.schollgymde/sets"):
                clf = open( "/sdcard/.schollgymde/sets","r")
                CLASS = clf.read()
                clf.close()
                sleep(1,goto_start)
            else:
                sm.add_widget(settingss)
                sm.current = "settings"
        else:
            sm.add_widget(licscreen)
            sleep(1,acceptlic)
        return sm

if __name__ == "__main__":
    MainApp().run()


text:
require_relative "sampler/autoload"
require "active_support/core_ext/module/delegation"

# A prefix module for future Quick Sampler's sister libraries.
# For now just look at {Quick::Sampler} itself.
module Quick
  # A façade module with the main entry point: {.compile}
  module Sampler

    class << self

      # Main entry point of Quick Sampler. Compiles a definition into a sampler. The
      # "compilation" is only a metaphor here, since definition - which is given to `compile` as
      # a block - is simply executed in the context of a fresh {Quick::Sampler::DSL}
      # instance (where available syntax can be found).
      #
      # @example Compile a sampler
      #   chaos = Quick::Sampler.compile description: "a bit of everything" do
      #     one_of_weighted integer => 5,
      #                     boolean => 1,
      #                     pick_from(-10.0..10.0) => 10,
      #                     string(:alnum) => 15,
      #                     feed { Faker::Internet.email } => 3
      #   end
      #
      # @param [String] description sampler description which
      #   will be returned by `#inspect` as well as `#description`
      #
      # @param block sampler definition. Will be `instance_eval`ed in the context of an
      #   anonymous instance of {Quick::Sampler::DSL}.
      #
      # @return [Quick::Sampler] compiled sampler
      #
      # @!method compile(description: nil, &block)
      delegate :compile, to: Quick::Sampler::DSL

      # @api private
      #
      # Tests if `obj` is an instance of a known Quick Sampler sub-type.
      #
      # @param [Object] obj the object to test
      # @return [Boolean] true if the object is of a Quick Sampler sub-type
      def === obj
        Base === obj || DSL::Fluidiom === obj
      end
    end
  end
end


text:
<?php

namespace Thruway\Exception;

/**
 * Class InvalidRealmNameException
 * Throw this exception when using invalid realm name
 *
 * @package Thruway\Exception
 */

class InvalidRealmNameException extends \Exception
{

}


text:
jQuery(document).ready(function($){
	//update these values if you change these breakpoints in the style.css file (or _layout.scss if you use SASS)
	var MqM= 768,
		MqL = 1024;

	var faqsSections = $('.cd-faq-group'),
		faqTrigger = $('.cd-faq-trigger'),
		faqsContainer = $('.cd-faq-items'),
		faqsCategoriesContainer = $('.cd-faq-categories'),
		faqsCategories = faqsCategoriesContainer.find('a'),
		closeFaqsContainer = $('.cd-close-panel');

	//select a faq section
	faqsCategories.on('click', function(event){
		event.preventDefault();
		var selectedHref = $(this).attr('href'),
			target= $(selectedHref);
		if( $(window).width() < MqM) {
			faqsContainer.scrollTop(0).addClass('slide-in').children('ul').removeClass('selected').end().children(selectedHref).addClass('selected');
			closeFaqsContainer.addClass('move-left');
			$('body').addClass('cd-overlay');
		} else {
	        $('body,html').animate({ 'scrollTop': target.offset().top - 19}, 200);
		}
	});

	//close faq lateral panel - mobile only
	$('body').bind('click touchstart', function(event){
		if( $(event.target).is('body.cd-overlay') || $(event.target).is('.cd-close-panel')) {
			closePanel(event);
		}
	});
	faqsContainer.on('swiperight', function(event){
		closePanel(event);
	});

	//show faq content clicking on faqTrigger
	faqTrigger.on('click', function(event){
		event.preventDefault();
		$(this).next('.cd-faq-content').slideToggle(200).end().parent('li').toggleClass('content-visible');
	});

	//update category sidebar while scrolling
	$(window).on('scroll', function(){
		if ( $(window).width() > MqL ) {
			(!window.requestAnimationFrame) ? updateCategory() : window.requestAnimationFrame(updateCategory);
		}
	});

	// $(window).on('resize', function(){
	// 	if($(window).width() <= MqL) {
	// 		faqsCategoriesContainer.removeClass('is-fixed').css({
	// 			'-moz-transform': 'translateY(0)',
	// 		    '-webkit-transform': 'translateY(0)',
	// 			'-ms-transform': 'translateY(0)',
	// 			'-o-transform': 'translateY(0)',
	// 			'transform': 'translateY(0)',
	// 		});
	// 	}
	// 	if( faqsCategoriesContainer.hasClass('is-fixed') ) {
	// 		faqsCategoriesContainer.css({
	// 			'left': faqsContainer.offset().left,
	// 		});
	// 	}
	// });

	// function closePanel(e) {
	// 	e.preventDefault();
	// 	faqsContainer.removeClass('slide-in').find('li').show();
	// 	closeFaqsContainer.removeClass('move-left');
	// 	$('body').removeClass('cd-overlay');
	// }

	function updateCategory(){
	/** commented due to a bug in function	updateCategoryPosition(); */
		updateSelectedCategory();
	}

/*	function updateCategoryPosition() {
		var top = $('.cd-faq').offset().top,
			height = jQuery('.cd-faq').height() - jQuery('.cd-faq-categories').height(),
			margin = 20;
		if( top - margin <= $(window).scrollTop() && top - margin + height > $(window).scrollTop() ) {
			var leftValue = faqsCategoriesContainer.offset().left,
				widthValue = faqsCategoriesContainer.width();
			faqsCategoriesContainer.addClass('is-fixed').css({
				'left': leftValue,
				'top': margin,
				'-moz-transform': 'translateZ(0)',
			    '-webkit-transform': 'translateZ(0)',
				'-ms-transform': 'translateZ(0)',
				'-o-transform': 'translateZ(0)',
				'transform': 'translateZ(0)',
			});
		} else if( top - margin + height <= $(window).scrollTop()) {
			var delta = top - margin + height - $(window).scrollTop();
			faqsCategoriesContainer.css({
				'-moz-transform': 'translateZ(0) translateY('+delta+'px)',
			    '-webkit-transform': 'translateZ(0) translateY('+delta+'px)',
				'-ms-transform': 'translateZ(0) translateY('+delta+'px)',
				'-o-transform': 'translateZ(0) translateY('+delta+'px)',
				'transform': 'translateZ(0) translateY('+delta+'px)',
			});
		} else {
			faqsCategoriesContainer.removeClass('is-fixed').css({
				'left': 0,
				'top': 0,
			});
		}
	}*/

	function updateSelectedCategory() {
		faqsSections.each(function(){
			var actual = $(this),
				margin = parseInt($('.cd-faq-title').eq(1).css('marginTop').replace('px', '')),
				activeCategory = $('.cd-faq-categories a[href="#'+actual.attr('id')+'"]'),
				topSection = (activeCategory.parent('li').is(':first-child')) ? 0 : Math.round(actual.offset().top);

			if ( ( topSection - 20 <= $(window).scrollTop() ) && ( Math.round(actual.offset().top) + actual.height() + margin - 20 > $(window).scrollTop() ) ) {
				activeCategory.addClass('selected');
			}else {
				activeCategory.removeClass('selected');
			}
		});
	}
});


text:
<!doctype html>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Latvian Name Days Examples</title>

Latvian Name Days

<?php
    $file = file_get_contents('./examples.php');
    highlight_string($file);
?>


text:
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.elasticsearch.spark._

object esHadoopTest {
   def main(args: Array[String]) {
      val conf = new SparkConf();
      conf.set("spark.app.name", "ES-Hadoop-Test");
      conf.set("es.nodes", "es1.mkhome");
      val sc = new SparkContext(conf);

      val numbers = Map("one" -> 1, "two" -> 2, "three" -> 3);
      val airports = Map("arrival" -> "Otopeni", "SFO" -> "San Fran");

      sc.makeRDD(Seq(numbers,airports)).saveToEs("spark/docs");

   }
}


text:
title: "Graphite"
description: "Send metrics to the Graphite time-series database using the plaintext protocol."
product: "Sensu Enterprise"
version: "3.8"
weight: 17
menu:
  sensu-enterprise-3.8:
    parent: integrations
---
**ENTERPRISE: Built-in integrations are available for [Sensu Enterprise][1]
users only.**

- [Overview](#overview)
- [Configuration](#configuration)
  - [Example(s)](#examples)
  - [Integration Specification](#integration-specification)
    - [`graphite` attributes](#graphite-attributes)

## Overview

Send metrics to [Graphite][2], using the plaintext protocol over TCP. The
`graphite` enterprise handler is also capable of sending metrics to [Hosted
Graphite][3], using the `prefix` attribute to prefix metric names with the
Hosted Graphite API key. This handler uses the `output_format` mutator.

## Configuration

### Example(s) {#examples}

The following is an example global configuration for the `graphite` enterprise
handler (integration).

{{< code json >}}
{
  "graphite": {
    "host": "graphite.example.com",
    "port": 2003,
    "prefix_source": false,
    "prefix": "production"
  }
}
{{< /code >}}

### Integration Specification

#### `graphite` attributes

The following attributes are configured within the `{"graphite": {} }`
[configuration scope][4].

_PRO TIP: You can override `graphite` attributes on a per-contact basis using [contact routing][5]._

host         |
-------------|------
description  | The Graphite Carbon host address.
required     | false
type         | String
default      | `127.0.0.1`
example      | {{< code shell >}}"host": "carbon.hostedgraphite.com"{{< /code >}}

port         |
-------------|------
description  | The Graphite Carbon port.
required     | false
type         | Integer
default      | `2003`
example      | {{< code shell >}}"port": 3003{{< /code >}}

prefix_source |
--------------|------
description   | If the Sensu source (client name) should prefix (added to) the metric names.
required      | false
type          | Boolean
default       | `false`
example       | {{< code shell >}}"prefix_source": true{{< /code >}}

prefix       |
-------------|------
description  | A custom metric name prefix - this can be used to prefix the Hosted Graphite API key.
required     | false
type         | String
example      | {{< code shell >}}"prefix": "production"{{< /code >}}

retry_limit    |
---------------|------
description    | The number of times the integration will attempt to re-send metrics after encountering an error.
required       | false
type           | Integer
default        | `3`
example        | {{< code shell >}} "retry_limit": "3"{{< /code >}}

retry_delay    |
---------------|------
description    | How long the integration will wait between retries, in seconds.
required       | false
type           | Integer
default        | `1`
example        | {{< code shell >}} "retry_delay": "1"{{< /code >}}

[?]:  #
[1]:  /sensu-enterprise
[2]:  http://graphite.wikidot.com?ref=sensu-enterprise
[3]:  https://www.hostedgraphite.com?ref=sensu-enterprise
[4]:  /sensu-core/1.2/reference/configuration#configuration-scopes
[5]: ../../contact-routing


text:
@interface BKCurrencyTextField ()

@property (strong, nonatomic) NSNumberFormatter     *numberFormatter;
@property (strong, nonatomic) NSRegularExpression   *nonNumericRegularExpression;
@property (nonatomic, strong) NSCharacterSet        *numberCharacterSet;

@end

@implementation BKCurrencyTextField

- (void)commonInit
{
    [super commonInit];

    self.keyboardType = UIKeyboardTypeNumberPad;
    //self.textAlignment = NSTextAlignmentRight;

    _numberFormatter = [[NSNumberFormatter alloc] init];
    _numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;

    _nonNumericRegularExpression = [BKMoneyUtils nonNumericRegularExpression];
    _numberCharacterSet = [BKMoneyUtils numberCharacterSet];

    self.placeholder = [_numberFormatter stringFromNumber:@(0)];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([self.userDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
        if (NO == [self.userDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string]) {
            return NO;
        }
    }

    NSString *currentText = textField.text;

    NSCharacterSet *nonNumberCharacterSet = [self.numberCharacterSet invertedSet];

    if (string.length == 0 && [[currentText substringWithRange:range] stringByTrimmingCharactersInSet:nonNumberCharacterSet].length == 0) {
        // find non-whitespace character backward
        NSRange numberCharacterRange = [currentText rangeOfCharacterFromSet:self.numberCharacterSet
                                                                    options:NSBackwardsSearch
                                                                      range:NSMakeRange(0, range.location)];
        // adjust replace range
        if (numberCharacterRange.location != NSNotFound) {
            range = NSUnionRange(range, numberCharacterRange);
        }
    }

    NSString *newString = [currentText stringByReplacingCharactersInRange:range withString:string];

    NSString *digits = [self stringByRemovingNonNumericCharacters:newString];

    if (digits.length == 0) {
        return string.length == 0;
    }

    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:digits];

    if (self.numberFormatter.maximumFractionDigits > 0) {
        decimalNumber = [decimalNumber decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithMantissa:1 exponent:self.numberFormatter.maximumFractionDigits isNegative:NO]];
    }

    // get current cursor position
    UITextRange* selectedRange = [textField selectedTextRange];
    UITextPosition* start = textField.beginningOfDocument;
    NSInteger cursorOffset = [textField offsetFromPosition:start toPosition:selectedRange.start];
    NSUInteger currentLength = currentText.length;

    // update text field
    self.numberValue = decimalNumber;

    // if the cursor was not at the end of the string being entered, restore cursor position
    if (cursorOffset != currentLength) {
        NSInteger lengthDelta = newString.length - currentLength;
        NSInteger newCursorOffset = MAX(0, MIN(newString.length, cursorOffset + lengthDelta));
        UITextPosition* newPosition = [textField positionFromPosition:textField.beginningOfDocument offset:newCursorOffset];
        UITextRange* newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition];
        [textField setSelectedTextRange:newRange];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:self];
    [self sendActionsForControlEvents:UIControlEventEditingChanged];

    return NO;
}

#pragma mark - Private Methods

- (NSString *)stringByRemovingNonNumericCharacters:(NSString *)string
{
    return [self.nonNumericRegularExpression stringByReplacingMatchesInString:string
                                                                      options:0
                                                                        range:NSMakeRange(0, string.length)
                                                                 withTemplate:@""];
}

#pragma mark - Public Methods

- (void)setNumberValue:(NSDecimalNumber *)numberValue
{
    if (nil == numberValue || [numberValue compare:[NSDecimalNumber zero]] == NSOrderedSame || [numberValue compare:[NSDecimalNumber notANumber]] == NSOrderedSame) {
        self.text = nil;
    } else {
        self.text = [_numberFormatter stringFromNumber:numberValue];
    }
}

- (NSDecimalNumber *)numberValue
{
    if (self.text.length == 0) {
        return nil;
    }

    NSDecimal decimal = [_numberFormatter numberFromString:self.text].decimalValue;
    return [NSDecimalNumber decimalNumberWithDecimal:decimal];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: arch/mips/linux/hwrpb.hh File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

File List

File Members

arch/mips/linux/hwrpb.hh File Reference
#include "arch/mips/linux/aligned.hh"

Go to the source code of this file.

Namespaces

namespace  	Linux

Classes

struct  	Linux::pcb_struct

<address style="align: right;">
Generated on Fri Apr 17 12:39:03 2015 for gem5 by  doxygen 1.4.7</address>


text:
To run the application:

1. Right-click on the Application class in the org.magnum.mobilecloud.video
package, Run As->Java Application and then stop the application after it launches
(this is to have Eclipse create a run configuraiton for you).
2. Run->Run Configurations
3. Under Java Applications, select your run configuration for this app
4. Open the Arguments tab
5. In VM Arguments, provide the following information for your Amazon AWS account:

   -Damazon.aws.secretkey=your_secret_key -Damazon.aws.accesskey=your_access_key

   You will need to obtain the secret key and access key from Amazon by signing up
   for an AWS account.

To stop the application:

Open the Eclipse Debug Perspective (Window->Open Perspective->Debug), right-click on
the application in the "Debug" view (if it isn't open, Window->Show View->Debug) and
select Terminate

## Accessing the Service

To view a list of the videos that have been added, open your browser to the following
URL:

http://localhost:8080/video

To add a test video, run the VideoSvcClientApiTest by right-clicking on it in
Eclipse->Run As->JUnit Test (make sure that you run the application first!)

## What to Pay Attention to

In this version of the VideoSvc application, we are using DynamoDB to store data.
See the Video class for the annotation changes that this requires. See the Application
class for the configuration of your Amazon AWS credentials.


text:
using System;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
using LayoutSwitcher;
using Settings = LayoutSwitcher.Properties.Settings;

namespace LayoutSwitcher
{
    public class LayoutSwitcherModel: IDisposable, INotifyPropertyChanged
    {
        private ICommand _exitCommand;
        public ICommand ExitCommand
        {
            get
            {
                return _exitCommand ?? (_exitCommand = new DelegateCommand { CommandAction = o => Application.Current.Shutdown() });
            }
        }

        public ICommand ToggleMainWindowCommand
        {
            get
            {
                return new DelegateCommand {
                    CommandAction = o => {
                        if  (Application.Current.MainWindow.Visibility != Visibility.Visible)
                        {
                            Application.Current.MainWindow.Show();
                        }
                        else
                        {
                            Application.Current.MainWindow.Hide();
                        }
                    }
                };
            }
        }
        public ICommand CloseMainWindowCommand
        {
            get
            {
                return new DelegateCommand {
                    Predicate = o => Application.Current.MainWindow != null,
                    CommandAction = o => Application.Current.MainWindow.Close()
                };
            }
        }

        public KeyboardConfig Config { get; set; }

        public LayoutSwitcherModel()
        {

            Config = new KeyboardConfig(Settings.Default.RegistryKey);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Dispose()
        {
            Config.Dispose();
        }
    }
}


text:
%% Pattern Recognition Toolbox System Requirements
% Pattern Recognition Toolbox requires MATLAB(R)
%
% Copyright 2011 New Folder Consulting L.L.C.


text:
var Mousetrap = require('mousetrap'),
    getUrl = require('../lib/get-url.js'),
    $ = require('jquery'),
    log = require('log-with-style');

// TODO @palcu: DRY this fucking code

/**
 * Bind these keyboard shortcuts using mousetrap to different actions. Also,
 * I've added here the logic for showing when a monster is dead in battle.
 */
module.exports = {
  componentWillMount: function() {
    Mousetrap.bind('up', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'left'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('down', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'right'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('left', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'up'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('right', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'down'), this._parseMoveResponse);
    }.bind(this));

    Mousetrap.bind('w', function(e) {
      e.preventDefault();
      $.get(getUrl('dig', 'left', this.state.currentChar), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('a', function(e) {
      e.preventDefault();
      $.get(getUrl('dig', 'up', this.state.currentChar), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('s', function(e) {
      e.preventDefault();
      $.get(getUrl('dig', 'right', this.state.currentChar), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('d', function(e) {
      e.preventDefault();
      $.get(getUrl('dig', 'down', this.state.currentChar), this._parseMoveResponse);
    }.bind(this));

    Mousetrap.bind('i', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'upleft'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('o', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'downleft'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('k', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'upright'), this._parseMoveResponse);
    }.bind(this));
    Mousetrap.bind('l', function(e) {
      e.preventDefault();
      $.get(getUrl('move', this.state.currentChar, 'downright'), this._parseMoveResponse);
    }.bind(this));

    Mousetrap.bind('g', function(e) {
      e.preventDefault();
      $.get(getUrl('get', this.state.currentChar), function(resp) {
        console.log(resp);
      })
    }.bind(this));
    Mousetrap.bind('z', function(e) {
      e.preventDefault();
      $.get(getUrl('levelup', this.state.currentChar), function(resp) {
        console.log(resp);
      })
    }.bind(this));
    Mousetrap.bind('x', function(e) {
      e.preventDefault();
      $.get(getUrl('leveldown', this.state.currentChar), function(resp) {
        console.log(resp);
      })
    }.bind(this));

    Mousetrap.bind('p', function(e) {
      e.preventDefault();
      $.get(getUrl('planeshift', this.state.currentChar, 'sorting_puzzle_dimension'), function(resp) {
        console.log(resp);
      })
    }.bind(this));
  },

  _parseMoveResponse: function(response) {
    if ($.type(response.success) === 'object' && 'movedto' in response.success) {
      var coords = response.success.movedto;
      console.log('moved to (' + coords.x + ', ' + coords.y + ')');
    } else {
      var msg = JSON.stringify(response.success);
      if (msg && msg.indexOf('HP 0') > -1) {
        var re = /\[(.*?)\]/g;
        var info = [];
        while (text = re.exec(msg)) {
          info.push(text)
        }
        log('[c="font-family: \'Helvetica Neue\', Helvetica, Arial, sans-serif; color: #fff; font-size: 20px; padding: 15px 20px; background: #444; border-radius: 4px; line-height: 100px; text-shadow: 0 1px #000"]Dead[c]');
      }
      console.log(msg);
    }
  }
};


text:
DESTFILE = userman

ROOTFILE = umsroot

CHAPTERS = $(ROOTFILE).tex umsintro.tex umsterm.tex umsusing.tex umscompiler.tex \
	umssyntax.tex umsmodules.tex umsarith.tex umsio.tex umsexcept.tex \
	umsarrays.tex umsdebug.tex umsdeveltools.tex umsmemory.tex \
	umsopsys.tex umssocket.tex \
	umsmacros.tex extmeta.tex exthsusp.tex extsuspend.tex \
	umslanguage.tex \
	umsopers.tex umsstyle.tex \
	umserrors.tex umsbugs.tex

EPSFILES = boxmodel.eps resolv.eps dismat.eps dismat2.eps reexport.eps \
	tktop.eps xrefDavinci.eps

GENFILES = err1.tex err2.tex err3.tex err4.tex err5.tex err6.tex \
	err7.tex err8.tex err9.tex err10.tex

# the files that are touched by latex as a side effect
CHAPAUX = $(CHAPTERS:%.tex=%.aux) $(ROOTFILE).toc $(ROOTFILE).idx

all:	$(ROOTFILE).dvi $(ROOTFILE)/$(ROOTFILE).html
	@echo Do make install to install

install:	../../doc/$(DESTFILE).pdf $(ROOTFILE)/$(ROOTFILE).html
	rm -rf ../../doc/$(DESTFILE)
	mv $(ROOTFILE) ../../doc/$(DESTFILE)

../../doc/$(DESTFILE).pdf:	$(ROOTFILE).pdf
	cp $(ROOTFILE).pdf ../../doc/$(DESTFILE).pdf
	chmod 644 ../../doc/$(DESTFILE).pdf

$(ROOTFILE).dvi:	$(CHAPAUX) $(ROOTFILE).bbl $(ROOTFILE).ind
	@echo ======== UPDATE-PASS =========
	@for f in $(CHAPAUX); do \
		mv $$f $$f.old; cp $$f.old $$f; \
	    done
	latex $(ROOTFILE).tex
	# The touches below are supposed to work around nfs clock skew problems:
	# The latex run may leave the dvi file with a modification time in the
	# future. Touch it to make sure the time is right relative to the
	# subsequent touches of the aux files. Sleep in between to make sure
	# the dvi is strictly older than the touched aux files.
	touch $(ROOTFILE).dvi
	sleep 1
	@for f in $(CHAPAUX); do \
		if cmp -s $$f $$f.old; then mv $$f.old $$f; \
		else rm $$f.old; echo ==== $$f was modified ====; touch $$f; \
		fi \
	    done
	$(MAKE) $(ROOTFILE).dvi

$(CHAPTERS:%.tex=%.aux):	$(CHAPTERS) $(EPSFILES)
	@echo ======== PASS 1 =========
	latex $(ROOTFILE)

$(ROOTFILE).idx:	$(ROOTFILE).aux
	touch $(ROOTFILE).idx

$(ROOTFILE).bbl:	$(ROOTFILE).aux
	bibtex $(ROOTFILE)

$(ROOTFILE).ind:	$(ROOTFILE).idx
	-makeindex $(ROOTFILE)

$(ROOTFILE).pdf:	$(ROOTFILE).ps
	ps2pdf $(ROOTFILE).ps

$(ROOTFILE).ps:	$(ROOTFILE).dvi
	dvips -Ppdf -t a4 -o $(ROOTFILE).ps $(ROOTFILE)

$(ROOTFILE).ps.Z:	$(ROOTFILE).ps
	compress -f $(ROOTFILE).ps

genfiles:
	eclipse -e "[gen_error],gen_errors"

# This preprocesses all *.tex files
# to insert/update the hyperlinks to the bip pages
biprefs:
	eclipse -e "[makerefs],do" -- *.tex

$(ROOTFILE)/$(ROOTFILE).html:	$(CHAPTERS)
	mkdir -p $(ROOTFILE)
	hevea -fix underscore.hva url.hva $(ROOTFILE)
	# replace the hard link index.html -> $(ROOTFILE).html by a soft link
	# because of problems with tar on Windows
	hacha -tocbis $(ROOTFILE).html
        # copy the files needed for the html to $(ROOTFILE) directory
	cp $(ROOTFILE)[0-9]??.* $(ROOTFILE)/
	cp $(ROOTFILE).css $(ROOTFILE)/
	cp contents_motif.gif next_motif.gif previous_motif.gif $(ROOTFILE)
	cp index.html $(ROOTFILE)/$(ROOTFILE).html
	ln -s $(ROOTFILE).html $(ROOTFILE)/index.html

clean:
	rm -f *.bak *.idx *.ind *.bbl *.aux *.dvi *.toc *.log *.ilg *.blg
	rm -f *.hind *.haux *.hind *.htoc $(ROOTFILE).image.*
	rm -f $(ROOTFILE)[0-9]??.*
	rm -f $(ROOTFILE).ps $(ROOTFILE).ps.Z $(ROOTFILE).pdf $(ROOTFILE).html
	rm -rf $(ROOTFILE)


text:
{% extends "base.html" %}

{% block page_title %}
    Qiita:Clone
{% endblock %}
{% block navbar %}

{% endblock %}

{% block body_main %}

Qiita:Clone

Qloneは非公開情報共有サービスです.

                    <form class="form" data-bind="submit: Login" method="post">

                                <input name="identify" type="text" class="form-control input-sm"
                                       placeholder="ユーザ名またはメールアドレス" data-bind="value:identify"/>

                                <input name="password" type="password" class="form-control input-sm"
                                       placeholder="パスワード" data-bind="value: login_password"/>

                                <button type="submit" class="btn btn-primary btn-sm" >ログイン
                                </button>

                    </form>

                    {#

                        パスワードを忘れた場合

#}

                        または

アカウントを作成

                        する

                    <form class="form"  data-bind="submit: Create" action="#">

                            <input name="user_name" type="text" class="form-control input-sm" placeholder="ユーザ名"
                                   data-bind="value:user_name"/>

                            <input name="user_email" type="text" class="form-control input-sm" placeholder="メールアドレス"
                                   data-bind="value:user_email"/>

                            <input name="password" type="password" class="form-control input-sm" placeholder="パスワード"
                                   data-bind="value:password"/>

キャンセル

                                <button type='submit' class="btn btn-sm btn-primary">
                                    登録
                                </button>

                    </form>

{% endblock %}


text:
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CompaniesHouse.Tests
{
    public class TooManyRequestsHttpMessageHandler : HttpMessageHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return Task.FromResult(new HttpResponseMessage((HttpStatusCode)429)
            {
                Content = new StringContent("", Encoding.UTF8, "application/json")
            });
        }
    }
}