text:
// {namespace name=backend/swag_import_export/view/main}
// {block name="backend/swag_import_export/view/manager/manager"}
Ext.define('Shopware.apps.SwagImportExport.view.manager.Manager', {
    extend: 'Ext.container.Container',

    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     * @string
     */
    alias: 'widget.swag-import-export-manager-manager',
    height: 450,

    title: '{s name="swag_import_export/manager/manager/title"}Import / Export manager{/s}',
    layout: 'fit',
    style: {
        background: '#F0F2F4;'
    },

    initComponent: function() {
        var me = this;

        me.items = [
            me.createTabPanel()
        ];

        me.callParent(arguments);

        me.on('activate', function() {
            me.tabPanel.getActiveTab().fireEvent('activate', me.tabPanel.getActiveTab());
        });
    },

    /**
     * Creates the main tab Panel 'Import/Export Manager' (first tab)
     *
     * @returns Ext.tab.Panel
     */
    createTabPanel: function() {
        var me = this,
            aclItems = [];

        /* {if {acl_is_allowed privilege=export}} */
        aclItems.push(Ext.create('Shopware.apps.SwagImportExport.view.manager.Export', {
            itemId: 'exportmanager',
            border: false,
            sessionStore: me.sessionStore,
            listeners: {
                activate: {
                    buffer: 150,
                    fn: function(container) {
                        var combo = container.profileCombo,
                            store = combo.getStore();

                        store.filters.removeAtKey('search');
                        store.load({
                            callback: function() {
                                if (combo.isDirty() && !store.getById(combo.getValue())) {
                                    combo.clearValue();
                                }
                            }
                        });
                    }
                }
            }
        }));
        /* {/if} */

        /* {if {acl_is_allowed privilege=import}} */
        aclItems.push(Ext.create('Shopware.apps.SwagImportExport.view.manager.Import', {
            itemId: 'importManager',
            listeners: {
                activate: function(container) {
                    var combo = container.profileCombo,
                        store = combo.getStore();

                    store.filters.removeAtKey('search');
                    store.load({
                        callback: function() {
                            if (combo.isDirty() && !store.getById(combo.getValue())) {
                                combo.clearValue();
                            }
                        }
                    });
                }
            }
        }));
        /* {/if} */

        /* {if {acl_is_allowed privilege=export} OR {acl_is_allowed privilege=import}} */
        aclItems.push(Ext.create('Shopware.apps.SwagImportExport.view.manager.Session', {
            listeners: {
                activate: function(grid) {
                    grid.getStore().load();
                }
            }
        }));
        /* {/if} */

        me.tabPanel = Ext.create('Ext.tab.Panel', {
            name: 'manager-main-tab',
            items: aclItems
        });

        return me.tabPanel;
    }
});
// {/block}

redpajama_set_name: RedPajamaGithub


text:
(function () {
    var redirect = intellisense.redirectDefinition;

    var originalKeys = Object.keys;
    function baseKeys(o) {
        var values = Object.getOwnPropertyNames(o);
        for (var i = 0, len = values.length; i < len; ++i) {
            if (values[i].substr(0, 7) === "_$field") return values;
        }
        return originalKeys(o);
    }
    Object.keys = baseKeys;

    redirect(baseKeys, originalKeys);

    window._$originalAddEventListener = window.addEventListener;
    function addEventListener(type, handler, useCapture) {
        if (typeof (type) === "string" && (type === "pointerdown" || type === "keydown")) {
            handler = function () { };
        }
        return window._$originalAddEventListener(type, handler, useCapture);
    }
    window.addEventListener = addEventListener;

    redirect(addEventListener, window._$originalAddEventListener);
})();


text:
require 'digest/md5'

# postgresql_password.rb
module Puppet::Parser::Functions
  newfunction(:postgresql_password, type: :rvalue, doc: <<-EOS
    Returns the postgresql password hash from the clear text username / password.
    EOS
             ) do |args|

    if args.size != 2
      raise(Puppet::ParseError, 'postgresql_password(): Wrong number of arguments ' \
        "given (#{args.size} for 2)")
    end

    username = args[0]
    password = args[1]

    'md5' + Digest::MD5.hexdigest(password.to_s + username.to_s)
  end
end


text:
Event Infrastructure Change History
===================================

3.18.1
------

* No changes.

3.18.0
------

* No changes.

3.17.2
------

* No changes.

3.17.1
------

* No changes.

3.17.0
------

* No changes.

3.16.0
------

* Added the spacebar key mapping to ensure correct ARIA and WCAG compliance. ([#1642][]: @andrewnicols)

[#1642]: https://github.com/yui/yui3/issues/1642

3.15.0
------

* Reduced categories of certain noisy log events in the `event` module and added
  categories for those that were missing some. ([#1605][]: @andrewnicols)

* Fixed the `event.returnValue is deprecated` warning in chrome. ([#1460][]: @zhiyelee)

[#1605]: https://github.com/yui/yui3/issues/1605
[#1460]: https://github.com/yui/yui3/issues/1460

* Added support for W3C Pointer events in the `tap` event. This fixes an issue in IE11 where the `type` of pointer event objects was changed from 'MSPointerDown' to 'pointerdown' to comply with their proposed W3C standard.

3.14.1
------

* No changes.

3.14.0
------

* No changes.

3.13.0
------

* Delegated focus and blur events now behave the same way other events do when
  a delegate sub from a container closer to the target calls
  `e.stopPropagation()`. Delegate subs from containers higher in the parent
  axis are not notified. [#1145](https://github.com/yui/yui3/issues/1145)

3.12.0
------

* Fixed: YUI no longer breaks the browser back/forward cache by attaching an
  unnecessary `unload` event handler. [Ryan Grove]

* `event-tap` allows you to prevent default browser behavior on `tap` via
  `e.preventDefault()` [#682](https://github.com/yui/yui3/issues/682)

* `event-tap` now has a `sensitivity` property that can be passed as an option.
  This allows you to customize when `tap` fires, based on the difference in `px`
  between a the corresponding start and end event. [#631](https://github.com/yui/yui3/pull/631)

* `event-tap` has dual-listener support, and works properly on devices that support
  both mouse and touch input. [#683](https://github.com/yui/yui3/issues/683)

* `event-tap` works more reliably on Android 4.0.x (Ice cream sandwich).

3.11.0
------

* No changes.

3.10.3
------

* No changes.

3.10.2
------

* Fixed `nodelist.on()` for rare custom module use cases.

  In certain rare custom module loading circumstances [#2533242,
  https://github.com/yui/yui3/pull/689] dom-core is attached after
  event-base, which resulted in the `YDOM = Y.DOM` module level reference
  being undefined [1].

  This would break things like `nodelist.on()` which used the reference
  under the hood.

  [1] Added in 3.7.3, as part of the Win8 `isWindow()` fix.

* Fixed DOM event facade, when Y instance was set to emitFacade:true.

  With the Y instance's emitFacade set to true, DOM event subscriptions
  would receive a Y.EventFacade instance instead of a Y.DOMEventFacade
  instance, and as a result target and currentTarget would be set to
  the Y instance, instead of a Y.Node instance.

3.10.1
------

* No changes.

3.10.0
------

* No changes.

3.9.1
-----

* No changes.

3.9.0
-----

* `delegate()` now silences events originating from disabled form controls in
  IE, like it does natively in other browsers. [#2532677]

3.8.1
-----

* No changes.

3.8.0
-----

* No changes.

3.7.3
-----

* Changed onbeforeactivate feature test to account for Win 8 packaged Apps, which
  don't allow inline JS code in innerHTML.

  http://msdn.microsoft.com/en-us/library/windows/apps/hh465388.aspx

3.7.2
-----

* No changes.

3.7.1
-----

* No changes.

3.7.0
-----

* Changed event-synthetic, to support CustomEvent performance optimizations.

  Mainly the deprecation of CustomEvent subscribers and afters instance properties,
  which event-synthetic was referring to directly. The direct reference was replaced
  by a public API method call.

  See src/event-custom/HISTORY.md for more details about the deprecated properties.

* `event-tap` was migrated from Gallery and it supports "fast-click" on touch
  devices.

* Added try/catch around the internal window unload listener event-base adds,
  so that YUI works in Chrome Packaged Apps. They don't support unload,
  but still have a window.onunload, so no real way to feature test without
  a try/catch anyway.

3.6.0
-----

* No changes.

3.5.1
-----

  * No changes.

3.5.0
-----
  * `event-simulate` references to `window` replaced with `Y.config.win`
    [#2531223]
  * `event-resize` no longer throws an exception in IE [#2531310]
  * "avilable" and "contentready" handlers that throw exceptions no longer
    result in infinite polling [#2531375]
  * Added `event-touch`, `event-flick`, `event-move`, and `event-valuechange` to
    the `event` virtual rollup in accordance with the docs.
  * 'key' event does a better job parsing character filters. Uses `e.which`
    instead of `e.keyCode` or `e.charCode`.
  * `node.delegate('focus', fn, '.not-focusable')` now works.  Properly supports
    delegation where the filter matches non-focusable parent nodes of the
    focused target. Same for blur. [#2531334] (`event-focus`)
  * `node.delegate('focus', fn, filterThatMatchesNode); node.focus();` now
    works. [#2531734]

3.4.1
-----
  * Calling Y.on('syntheticEvent', callback) without a context/selector argument
    now defaults to `window` (or the global object) [Ticket #2530081]

  * event-resize, a.k.a. Y.on('windowresize', ...) migrated to synthetic event
    infrastructure. Now detachable, etc. Also properly throttles the resize
    event on newer Gecko engines. That browser sniff was old! [Ticket #2530805]

3.4.0
-----
  * `event-outside` added for "outside" events.

  * `Y.Event.define(name)` adds name to `DOM_EVENTS` whitelist. Accepts event
    name string or array of string names.

  * `event-hover` properly pulls in required module `event-mouseenter`.

  * DOM event subscriptions are now removed and objects cleaned up after last
    subscription is detached; same for synthetic events.

  * `key` synthetic event migrated to official synth infrastructure; and now
    supports delegation.

  * `key` event spec param now supports letters and named keys. E.g.:
    `'enter+ctrl' == '13+ctrl'`, `'up:a' == 'up:65'` and `'A' == '65+shift'`.

  * Added experimental config `YUI({ lazyEventFacade: true })` that triggers a
    mode for DOM EventFacades in IE8 to use getters to access event properties
    that involve any calculation, such as `e.target` and `e.currentTarget`; this
    should also improve performance.

  * `mouseenter` and `mouseleave` events now filter the native event rather than
    the generated `DOMEventFacades` for `mouseover`/`mouseout`. This results in
    fewer calls to `Y.one` (`e.target`, `currentTarget`, `relatedTarget`) as
    well, so should improve performance.

  * Added `onceAfter()` method to do a self-detaching `after()` subscription.
    [Ticket #2529464]

  * `Y.on(type, callback, HTMLElement[], COMPAT)` subscriptions to attach to
    multiple elements in one call now correctly use native DOM elements instead
    of Nodes for all subscriptions. [Ticket #2529807]

  * Plugged the leaked global `GLOBAL_ENV`. [Ticket #2530227]

  * Fixed synth architecture to properly resubscribe to synths that use
    `processArgs` if the target is not available at the time of subscription.
    [Ticket #2530293]

3.3.0
-----

  * Added support for `delegate({ click: fn, keyup: fn2 }, …)` and
    `delegate(['click', 'keyup'], fn, …)`.

  * Delegation containers are now potential matches for the filter.

  * Nested delegate matches will now have callback executed for all matching
    targets in bubbling order.

  * `e.stopPropagation()` in nested delegate matches now works as expected.

  * The raw DOM event is no longer double wrapped (i.e. was: `e._event._event`).

  * `event-focus` now uses XHTML-friendly feature test to fork for IE.

  * New `event-hover` module providing `node.on('hover', in, out)`.

  * `e.button`/`e.which` normalization.

  * `e.which` normalized for key operations as well.

  * Split out IE-specific code into `event-base-ie` conditional module.

3.2.0
-----

  * Added event and facade support for touch.

  * Synthetic event infrastructure rebuilt. Changes include:

    * Support for delegation.

    * Passing `DOMEventFacade` to `notifier.fire(e)` now recommended.

    * Fixed issue where firing the notifier from inside DOM event subs would
      result in duplicate synth sub execution if the same synth was subscribed
      multiple times on the same Node.

    * Synths can now be detached with `node.purge(t|f, 'synthName')`.

    * `Event.define(type, config, *force*)` third arg added to override existing
      events. Only use this if you really know what you're doing.

    * Changed `allowDups` to `preventDups`, `true` by default to mimic existing
      behavior elsewhere in the event system.

  * `delegate()` now defers to synthetic event def more intelligently.

  * Added support for passing filter function to delegate.

  * `delegate()` now executes callback for each filter match up the bubble path.

  * Added detach category support to `delegate()`.

  * Migrate `mouseenter`, `mouseleave`, `focus`, and `blur` to `Event.define`.

  * `focus` and `blur` now guarantee execution order of subs matches bubble
    order when multiple delegates are created from different levels.

  * `event-synthetic` added to 'event' rollup module.

3.1.1
-----

  * fired `fireOnce()` listeners are executed synchronously.

3.1.0
-----

  * Removed deprecated `delegate` custom event. As of 3.1.0 use the `delegate()`
    method on a `Node` instance or `Y` instance.

  * Updated the `event-focus` submodule so that the specialized `focus` and
    `blur` events that enable the `focus` and `blur` events to bubble do not
    apply when adding `focus` and `blur` events to the `window` object.

  * Synthetic event creation API added.

  * `delegate` enhancements.

  * `unload` event fix.

  * Compatibility with Firefox's untouchable anonymous `div`.

3.0.0
-----

  * Added `onreadystatechange` fork in `domready` to handle the event in IE when
    YUI is hosted in an `iframe`.

  * Added `mousewheel` support.

  * Added `Y.delegate()` function that is a bit easier to use than
    `Y.on('delegate', …)`.

  * Default scope of `mouseenter` and `mouseleave` events is the `Node` instance
    to which the listener is attached.

  * Default scope of delegated event listeners is the `Node` instance that
    matched the supplied CSS selector.

  * All special DOM event handlers (`focus`, `blur`, `mousewheel`, `resize`,
    `delegate`, etc.) are broken down into submodules. Core DOM event
    functionality is provided in event-base.js, and all of the functionality is
    rolled into event.js.

  * Additional Safari key remapping.

  * Special DOM events can now be routed through `delegate()`.

  * `Y.on()` can target `Node` and `NodeList` references correctly.

  * Fixed `onAvailable()` lazy DOM listener detach handles.

  * When configured to return a detach handle, a single object is always
    returned. Previously requests that resolved to multiple listeners returned
    an array.

3.0.0beta1
----------

  * DOM event, custom event, and simulate event moved to separate modules.

  * Added an event for DOM event delegation. It only fires if the target or its
    descendants match a supplied selector.

        Y.on('delegate', fn, el, 'click', 'selector', …)

    The event facade sets the following properties:

      * `target`: the target of the event.
      * `currentTarget`: the element that the selector matched.
      * `container`: the bound element (the delegation container).

  * Added `mouseenter`/`mouseleave` events:

    * `Y.on('mouseenter', fn, el, 'click', 'selector', …)`
    * `Y.on('mouseleave', fn, el, 'click', 'selector', …)`

  * Added `Y.on('windowresize', fn)`, which attempts to normalize when the event
    fires across all browsers (once at the end of the resize rather than
    continuously during the resize).

  * Fixed `unsubscribeAll()` return value.

  * Added ability to skip facade creation where performance is a concern.

  * Moved `DOMReady` core to `yui-base`.

  * Focus/blur abstraction works in Opera when the bound element is the target.

  * `purgeElement` only reads element guids, it does not create new ones for
    elements without one.

  * `Event.attach()` returns a single handle if the result from collection
    processing is a single item.

3.0.0pr2
--------

  * Fixed IE notification error when no arguments are supplied.

  * Added `event-simulate`.

  * `getListeners()` works when the element has no listeners defined.

  * `Event.addListener()` removed. Exists only in compat layer.

  * `addListerer()` triggers 2.x event behavior.

  * Removed extra undefined parameter passed to DOM event listeners.

  * Compat layer contains `Event.on()`.

  * Event adapter support added to `Y.on()`.

  * Added `focus` and `blur` event adaptors (support for propagation of these
    events.)

  * publish and subscribe support an object for the type, allowing for multiple
    events/subscriptions.

  * subscriber failures throw an error by default rather than log.

  * subscriber failures are not routed through `Y.fail` in order to improve the
    debug experience.

  * New facades created every `fire()`.

  * `before()` method re-added to `EventTarget`, which delegates to
    `Do.before()` or `subscribe()`.

  * `EventTarget.after()` will delegate to `Do.after()` if type is a function.

  * Added keylistener: `Y.on('key', fn, element, 'down:13,65+ctrl+shift')`.

  * `event:ready` event deprecated in favor of `domready`.

3.0.0pr1
--------

  * Initial Release.


text:
class UrbanWorld : public WorldType {
public:
	UrbanWorld();
	virtual ~UrbanWorld();

	virtual void		load();

};

#endif


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p387;

import org.gradle.test.performance.mediummonolithicjavaproject.p386.Production7736;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test7745 {
    Production7745 objectUnderTest = new Production7745();

    @Test
    public void testProperty0() {
        Production7736 value = new Production7736();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production7740 value = new Production7740();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production7744 value = new Production7744();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
using System.Collections.Generic;

namespace sharp_kcs
{
    interface IConnection
    {
        ICollection<IDevice> GetOutputDevices();
        ICollection<IDevice> GetInputDevices();
        void ChangeOutputDevice(IDevice outputDevice);
        void ChangeOutputDevice(string outputDeviceName);
        void ChangeInputDevice(IDevice inputDevice);
        void ChangeInputDevice(string inputDeviceName);
        void AttachTrack(ITrack track);
        void DetachTrack(ITrack track);
    }
}


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

<title>SlimListFragment (library 1.2 API)</title>
<meta name="date" content="2015-12-31">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.metova.slim

Class SlimListFragment

java.lang.Object

ListFragment

com.metova.slim.SlimListFragment

public class SlimListFragment
extends ListFragment

Constructor Summary

Constructors

Constructor and Description

SlimListFragment()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
onAttach(android.app.Activity activity)

void
onCreate(android.os.Bundle savedInstanceState)

android.view.View
onCreateView(android.view.LayoutInflater inflater,
            android.view.ViewGroup container,
            android.os.Bundle savedInstanceState)

void
onViewCreated(android.view.View view,
             android.os.Bundle savedInstanceState)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SlimListFragment

public SlimListFragment()

Method Detail

onAttach

public void onAttach(android.app.Activity activity)

onCreate

public void onCreate(android.os.Bundle savedInstanceState)

onCreateView

public android.view.View onCreateView(android.view.LayoutInflater inflater,
                                      android.view.ViewGroup container,
                                      android.os.Bundle savedInstanceState)

onViewCreated

public void onViewCreated(android.view.View view,
                          android.os.Bundle savedInstanceState)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!doctype html>

  <meta charset="UTF-8">
  <meta name="description"
    content="I craft code + content for the web, and write about software and amateur neuroscience. This is where you can find my whole eclectic collection of projects." />
  <meta name="author" content="Curiositry">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="MobileOptimized" content="320">
  <meta name="HandheldFriendly" content="True">

  <title>Curiositry • Code & Content</title>
  <link rel="stylesheet" href="css/main.min.css" media="screen" />
  <link rel="shortcut icon" href="https://cdn.autodidacts.io/img/gravatar-favicon.png" />
  <link rel="apple-touch-icon" href="https://cdn.autodidacts.io/img/gravatar-small.png" />

Curiositry

Code & Content

Good day, and thanks for stopping by! I write and build things. In
    this portfolio listicle you'll find some of my web & programming
    projects.

 My open-source code is on
    GitHub. You can follow @curiositry on Twitter for the occasional (gzipped) thought, or subscribe
    to The Autodidacts by
    email or RSS for longer
    essays.

Featured projects:

Autodidacts.io The blog of three thing-building, self-educating,
          voraciously-reading, computer-tinkering, music-playing brothers

Algebrarules.com The most useful rules of basic Algebra

NeuroBB.com The EEG, brain-computer interface, and biofeedback
          discussion forum.

Laminim
          Ghost Blog Theme A premium Ghost theme for serious bloggers.

Weblog
          Ghost Blog Theme A *seriously* old-school Ghost blog theme (premium).

Blog.txt The most minimal blogging platform in the known
          universe—or your money back! (WIP project/essay/joke…)

MNML Ghost Blog Theme A beautiful, responsive, and featureful
          blog theme with great typography.

Undefined Ghost Blog Theme A minimal
          starter theme for the Ghost blogging platform.

EEGrunt A Collection Python EEG Analysis Utilities for
          OpenBCI

Diaeresis.jsWield diæreses like Chuck Mary Norris

Older projects:

Automathic.org The Best Mathematical Forumlas on the Web

ReaDB ReaDB is your private digital bookshelf. Read.
          Review. Remember.

The Free & Open Science Class Fun, no-nonsense science
          projects that stimulate and inform

The Ghost Theme Directory Find the perfect theme for your
          blog

Wise Wallpapers A Collection of Minimalist
          Typographic Wallpapers From Quotes & Proverbs

Designs That Don't Suck A non sucky
          infographic explaining what it is that makes it not suck.

Bohemian Theme A free, responsive, open source, &
          typographically tasteful Pelican theme. Built to provide a great reading experience with minimal clutter

Responsive Microplate The bare essentials for any
          responsive website — halfway between Emmet's !tab and HTML5 Boilerplate

Clean Theme A minimalist theme for the Python static site
          generator Pelican.

Flexbox Functions A Simple PHP Script That
          Makes Flexbox Development Painless

    ©

       Twitter

       GitHub

        Email

     The Creation is the
      Citation


text:
<?php

class UsersController extends BaseController
{
    public function register()
    {
        if ($this->isPost) {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $password_confirm = $_POST['password_confirm'];
            $full_name = $_POST['full_name'];
            if (strlen($username) <= 1) {
                $this->setValidationError("username", "Невалидно потребителско име!");
            }
            if (strlen($password) <= 1) {
                $this->setValidationError("password", "Невалидна парола!");
            }
            if ($password != $password_confirm) {
                $this->setValidationError("password_confirm", "Паролата не съвпада!");
            }
            if ($this->formValid()) {
                $userId = $this->model->register($username, $password, $full_name);
                if ($userId !== false) {
                    $_SESSION['username'] = $username;
                    $_SESSION['user_id'] = $userId;
                    $this->addInfoMessage("Успешна регистрация!");
                    $this->redirect("");
                } else {
                    $this->addErrorMessage("Грешка по време на регистрацията!");
                }
            }
        }
    }

    public function login()
    {
        if ($this->isPost) {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $userId = $this->model->login($username, $password);
            if ($userId !== false) {
                $_SESSION['username'] = $username;
                $_SESSION['user_id'] = $userId;
                $this->addInfoMessage("Успешно влязохте!");
                $this->redirect("");
            } else {
                $this->addErrorMessage("Неуспешно влизане!");
            }
        }
    }

    public function logout()
    {
        session_destroy();
        $this->redirect("");
    }

    public function index()
    {
        $this->authorize();
        $this->users = $this->model->getAll();
    }
}


text:
name: Albertsons
address_1: 28090 S Western Ave
address_2: ''
city: San Pedro
state: CA
zip: '90732'
phone: (310) 831-1323
latitude: '33.764856'
longitude: '-118.309917'
category: Supermarket
website: 'http://www.albertsons.com/'
active: ''
daycode1: Mon
day1_open: '600'
day1_close: '2300'
daycode2: Tue
day2_open: '600'
day2_close: '2300'
daycode3: Wed
day3_open: '600'
day3_close: '2300'
daycode4: Thu
day4_open: '600'
day4_close: '2300'
daycode5: Fri
day5_open: '600'
day5_close: '2300'
daycode6: Sat
day6_open: '600'
day6_close: '2300'
daycode7: Sun
day7_open: '600'
day7_close: '2300'
title: 'Albertsons, Food Oasis Los Angeles'
uri: /supermarket/albertsons-28090-s-western-ave/
formatted_daycode1: Monday
formatted_day1_open: 6am
formatted_day1_close: 11pm
formatted_daycode2: Tuesday
formatted_day2_open: 6am
formatted_day2_close: 11pm
formatted_daycode3: Wednesday
formatted_day3_open: 6am
formatted_day3_close: 11pm
formatted_daycode4: Thursday
formatted_day4_open: 6am
formatted_day4_close: 11pm
formatted_daycode5: Friday
formatted_day5_open: 6am
formatted_day5_close: 11pm
formatted_daycode6: Saturday
formatted_day6_open: 6am
formatted_day6_close: 11pm
formatted_daycode7: Sunday
formatted_day7_open: 6am
formatted_day7_close: 11pm

---


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Bacidia antillarum B. de Lesd.

### Remarks
null


text:
create database cats_db;

use cats_db;

create table cats (
  cat_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  cat_name VARCHAR(32) NOT NULL,
  cat_age INT(10) UNSIGNED NOT NULL,
  cat_type VARCHAR(32) NOT NULL,
  PRIMARY KEY (cat_id),
  UNIQUE INDEX cat_name (cat_name)
);


text:
<?php

namespace Magento\Paypal\Test\TestStep;

use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\TestStep\TestStepInterface;
use Magento\Catalog\Test\Page\Product\CatalogProductView;
use Magento\Mtf\Fixture\FixtureInterface;

/**
 * Checkout with PayPal from product page.
 */
class CheckoutWithPaypalFromProductPageStep implements TestStepInterface
{
    /**
     * Detail fixture.
     *
     * @var FixtureInterface
     */
    protected $product;

    /**
     * Catalog product view frontend page.
     *
     * @var CatalogProductView
     */
    protected $catalogProductView;

    /**
     * Browser.
     *
     * @var BrowserInterface
     */
    protected $browser;

    /**
     * @constructor
     * @param CatalogProductView $catalogProductView
     * @param FixtureInterface $product
     * @param BrowserInterface $browser
     */
    public function __construct(
        CatalogProductView $catalogProductView,
        BrowserInterface $browser,
        FixtureInterface $product
    ) {
        $this->catalogProductView = $catalogProductView;
        $this->browser = $browser;
        $this->product = $product;
    }

    /**
     * Open product on frontend and click Checkout with PayPal button.
     *
     * @return void
     */
    public function run()
    {
        $this->browser->open($_ENV['app_frontend_url'] . $this->product->getUrlKey() . '.html');
        $this->catalogProductView->getViewBlock()->paypalCheckout();
    }
}


text:
package tech.gusavila92.apache.http.impl.io;

import java.io.IOException;
import java.io.InputStream;

import tech.gusavila92.apache.http.ConnectionClosedException;
import tech.gusavila92.apache.http.Header;
import tech.gusavila92.apache.http.HttpException;
import tech.gusavila92.apache.http.MalformedChunkCodingException;
import tech.gusavila92.apache.http.TruncatedChunkException;
import tech.gusavila92.apache.http.config.MessageConstraints;
import tech.gusavila92.apache.http.io.BufferInfo;
import tech.gusavila92.apache.http.io.SessionInputBuffer;
import tech.gusavila92.apache.http.util.Args;
import tech.gusavila92.apache.http.util.CharArrayBuffer;

/**
 * Implements chunked transfer coding. The content is received in small chunks.
 * Entities transferred using this input stream can be of unlimited length.
 * After the stream is read to the end, it provides access to the trailers,
 * if any.
 *

 * Note that this class NEVER closes the underlying stream, even when close
 * gets called.  Instead, it will read until the "end" of its chunking on
 * close, which allows for the seamless execution of subsequent HTTP 1.1
 * requests, while not requiring the client to remember to read the entire
 * contents of the response.
 *
 *
 * @since 4.0
 *
 */
public class ChunkedInputStream extends InputStream {

    private static final int CHUNK_LEN               = 1;
    private static final int CHUNK_DATA              = 2;
    private static final int CHUNK_CRLF              = 3;
    private static final int CHUNK_INVALID           = Integer.MAX_VALUE;

    private static final int BUFFER_SIZE = 2048;

    /** The session input buffer */
    private final SessionInputBuffer in;
    private final CharArrayBuffer buffer;
    private final MessageConstraints constraints;

    private int state;

    /** The chunk size */
    private long chunkSize;

    /** The current position within the current chunk */
    private long pos;

    /** True if we've reached the end of stream */
    private boolean eof = false;

    /** True if this stream is closed */
    private boolean closed = false;

    private Header[] footers = new Header[] {};

    /**
     * Wraps session input stream and reads chunk coded input.
     *
     * @param in The session input buffer
     * @param constraints Message constraints. If {@code null}
     *   {@link MessageConstraints#DEFAULT} will be used.
     *
     * @since 4.4
     */
    public ChunkedInputStream(final SessionInputBuffer in, final MessageConstraints constraints) {
        super();
        this.in = Args.notNull(in, "Session input buffer");
        this.pos = 0L;
        this.buffer = new CharArrayBuffer(16);
        this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT;
        this.state = CHUNK_LEN;
    }

    /**
     * Wraps session input stream and reads chunk coded input.
     *
     * @param in The session input buffer
     */
    public ChunkedInputStream(final SessionInputBuffer in) {
        this(in, null);
    }

    @Override
    public int available() throws IOException {
        if (this.in instanceof BufferInfo) {
            final int len = ((BufferInfo) this.in).length();
            return (int) Math.min(len, this.chunkSize - this.pos);
        } else {
            return 0;
        }
    }

    /**
     *
 Returns all the data in a chunked stream in coalesced form. A chunk
     * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
     * is detected.

     *
     *
 Trailer headers are read automatically at the end of the stream and
     * can be obtained with the getResponseFooters() method.

     *
     * @return -1 of the end of the stream has been reached or the next data
     * byte
     * @throws IOException in case of an I/O error
     */
    @Override
    public int read() throws IOException {
        if (this.closed) {
            throw new IOException("Attempted read from closed stream.");
        }
        if (this.eof) {
            return -1;
        }
        if (state != CHUNK_DATA) {
            nextChunk();
            if (this.eof) {
                return -1;
            }
        }
        final int b = in.read();
        if (b != -1) {
            pos++;
            if (pos >= chunkSize) {
                state = CHUNK_CRLF;
            }
        }
        return b;
    }

    /**
     * Read some bytes from the stream.
     * @param b The byte array that will hold the contents from the stream.
     * @param off The offset into the byte array at which bytes will start to be
     * placed.
     * @param len the maximum number of bytes that can be returned.
     * @return The number of bytes returned or -1 if the end of stream has been
     * reached.
     * @throws IOException in case of an I/O error
     */
    @Override
    public int read (final byte[] b, final int off, final int len) throws IOException {

        if (closed) {
            throw new IOException("Attempted read from closed stream.");
        }

        if (eof) {
            return -1;
        }
        if (state != CHUNK_DATA) {
            nextChunk();
            if (eof) {
                return -1;
            }
        }
        final int bytesRead = in.read(b, off, (int) Math.min(len, chunkSize - pos));
        if (bytesRead != -1) {
            pos += bytesRead;
            if (pos >= chunkSize) {
                state = CHUNK_CRLF;
            }
            return bytesRead;
        } else {
            eof = true;
            throw new TruncatedChunkException("Truncated chunk "
                    + "( expected size: " + chunkSize
                    + "; actual size: " + pos + ")");
        }
    }

    /**
     * Read some bytes from the stream.
     * @param b The byte array that will hold the contents from the stream.
     * @return The number of bytes returned or -1 if the end of stream has been
     * reached.
     * @throws IOException in case of an I/O error
     */
    @Override
    public int read (final byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    /**
     * Read the next chunk.
     * @throws IOException in case of an I/O error
     */
    private void nextChunk() throws IOException {
        if (state == CHUNK_INVALID) {
            throw new MalformedChunkCodingException("Corrupt data stream");
        }
        try {
            chunkSize = getChunkSize();
            if (chunkSize < 0L) {
                throw new MalformedChunkCodingException("Negative chunk size");
            }
            state = CHUNK_DATA;
            pos = 0L;
            if (chunkSize == 0L) {
                eof = true;
                parseTrailerHeaders();
            }
        } catch (final MalformedChunkCodingException ex) {
            state = CHUNK_INVALID;
            throw ex;
        }
    }

    /**
     * Expects the stream to start with a chunksize in hex with optional
     * comments after a semicolon. The line must end with a CRLF: "a3; some
     * comment\r\n" Positions the stream at the start of the next line.
     */
    private long getChunkSize() throws IOException {
        final int st = this.state;
        switch (st) {
        case CHUNK_CRLF:
            this.buffer.clear();
            final int bytesRead1 = this.in.readLine(this.buffer);
            if (bytesRead1 == -1) {
                throw new MalformedChunkCodingException(
                    "CRLF expected at end of chunk");
            }
            if (!this.buffer.isEmpty()) {
                throw new MalformedChunkCodingException(
                    "Unexpected content at the end of chunk");
            }
            state = CHUNK_LEN;
            //$FALL-THROUGH$
        case CHUNK_LEN:
            this.buffer.clear();
            final int bytesRead2 = this.in.readLine(this.buffer);
            if (bytesRead2 == -1) {
                throw new ConnectionClosedException("Premature end of chunk coded message body: " +
                        "closing chunk expected");
            }
            int separator = this.buffer.indexOf(';');
            if (separator < 0) {
                separator = this.buffer.length();
            }
            final String s = this.buffer.substringTrimmed(0, separator);
            try {
                return Long.parseLong(s, 16);
            } catch (final NumberFormatException e) {
                throw new MalformedChunkCodingException("Bad chunk header: " + s);
            }
        default:
            throw new IllegalStateException("Inconsistent codec state");
        }
    }

    /**
     * Reads and stores the Trailer headers.
     * @throws IOException in case of an I/O error
     */
    private void parseTrailerHeaders() throws IOException {
        try {
            this.footers = AbstractMessageParser.parseHeaders(in,
                    constraints.getMaxHeaderCount(),
                    constraints.getMaxLineLength(),
                    null);
        } catch (final HttpException ex) {
            final IOException ioe = new MalformedChunkCodingException("Invalid footer: "
                    + ex.getMessage());
            ioe.initCause(ex);
            throw ioe;
        }
    }

    /**
     * Upon close, this reads the remainder of the chunked message,
     * leaving the underlying socket at a position to start reading the
     * next response without scanning.
     * @throws IOException in case of an I/O error
     */
    @Override
    public void close() throws IOException {
        if (!closed) {
            try {
                if (!eof && state != CHUNK_INVALID) {
                    // read and discard the remainder of the message
                    final byte buff[] = new byte[BUFFER_SIZE];
                    while (read(buff) >= 0) {
                    }
                }
            } finally {
                eof = true;
                closed = true;
            }
        }
    }

    public Header[] getFooters() {
        return this.footers.clone();
    }

}


text:
using System;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
    internal abstract partial class AbstractMethodXmlBuilder
    {
        private class AutoTag : IDisposable
        {
            private readonly AbstractMethodXmlBuilder _xmlBuilder;
            private readonly string _name;

            public AutoTag(AbstractMethodXmlBuilder xmlBuilder, string name, AttributeInfo[] attributes)
            {
                _xmlBuilder = xmlBuilder;
                _name = name;

                _xmlBuilder.AppendOpenTag(name, attributes);
            }

            public void Dispose()
            {
                _xmlBuilder.AppendCloseTag(_name);
            }
        }
    }
}


text:
AI Notes
========

Note this page uses [tex the world](http://thewe.net/tex/) notation extensively.

Unit 18 - Computer Vision III
-----------------------------

## Structure from Motion Question ##

The idea of 'structure from motion' is to take a handheld camera, and move it around a 3d structure
and be able to recover or estimate the 3d coordinates of all the features in the world based on many
2d images, e.g.:-

## Projection Question ##

Nothing to note.

## Structure from Motion Models ##

Nothing to note.

## SFM Maths ##

The mathematics of structure from movement are involved. Don't want to go into too much detail.

Here is our original projection model:-

Once we take into account that we are viewing the object from an arbitrary angle, we end up with:-

We have to sum over i and j and work to find the minimum. This is very much non-trivial.

Non-linear methods have been used extensively to attempt to solve this non-linear least squares
problem (SFM) problem, e.g.:-

* Gradient Descent
* Conjugate Gradient
* Gauss-Newton
* Levenberg Marquardt
* Singular Value decomposition (affine, orthographic)

## Recovered Unknowns Question ##

With:-

* m camera poses (motion)
* n points (structure)

We have :-

* 2mn constraints due to having x and y coordinates for each point from each pose,
* 6m + 3n unknowns - each camera pose has a 6d unknown about the rotation and translation of the
  camera, and each point has 3 unknown dimensions.

We want:-

    [; 2mn \leq 6m + 3n ;]

To be able to solve this.

How many unknowns cannot be recovered?

There are 7 - the absolute location and orientation of the coordinate system which consist of 6 (3
times 2) of the parameters, but also cannot recover *scale* since perspective means a scaled up
scene looks the same as one which is not.

We care about this because it determines whether the problem is 'well-posed' such that we can solve
it.

## Conclusion ##

Nothing to note.


text:
using System.Linq;
using System.Text.RegularExpressions;
using AlephNote.Common.Settings;
using AlephNote.Common.Settings.Types;

namespace AlephNote.WPF.ScintillaUtil
{
	public class DefaultHighlighter : ScintillaHighlighter
	{
		private const int MAX_BACKTRACE = 512;
		private const int MAX_FORWARDTRACE = 512;

		public override void Highlight(ScintillaNET.Scintilla sci, int start, int end, AppSettings s)
		{
			bool startsWithNL = sci.GetCharAt(start) == '\n' || (start+1 < sci.TextLength && sci.GetCharAt(start) == '\r' && sci.GetCharAt(start+1) == '\n');
			bool endsWithNL   = sci.GetCharAt(end) == '\n' || (end-1 >= 0 && sci.GetCharAt(end-1) == '\n');

			// move back to start of line
			if (!startsWithNL)
			{
				for (int i = 0; i < MAX_BACKTRACE && start > 0; i++, start--)
				{
					if (start > 0 && sci.GetCharAt(start - 1) == '\n') break;
				}
			}

			// move forward to end of line
			if (!endsWithNL)
			{
				for (int i = 0; i < MAX_FORWARDTRACE && end < sci.TextLength; i++, end++)
				{
					if (end >= sci.TextLength || sci.GetCharAt(end) == '\n') break;
				}
			}

			var text = sci.GetTextRange(start, end - start);

			if (s.LinkMode != LinkHighlightMode.Disabled)
			{
				LinkHighlight(sci, start, text);
			}
			else
			{
				sci.StartStyling(start);
				sci.SetStyling(end-start, STYLE_DEFAULT);
			}
		}

		public override string GetClickedLink(string text, int pos)
		{
			var linedata = GetLine(text, pos); // (line, lineStart, lineLen)
			var line      = linedata.Item1;
			var lineStart = linedata.Item2;

			return GetURLMatchingRegex()
				.Matches(line)
				.OfType<Match>()
				.Where(m => lineStart + m.Index <= pos && pos <= lineStart + m.Index+m.Length)
				.Select(m => m.Groups[0].Value)
				.FirstOrDefault();
		}
	}
}


text:
"""Tests for catalog.py."""

__author__ = 'lschumacher@google.com (Lee Schumacher)'

import model
import perms
import test_utils

class CatalogTest(test_utils.BaseTest):
  """Tests for the catalog.py request handler."""

  def setUp(self):
    super(CatalogTest, self).setUp()
    self.map_object = test_utils.CreateMap('{"title": "test map"}')
    self.map_id = self.map_object.id
    perms.Grant('publisher', perms.Role.CATALOG_EDITOR, 'xyz.com')

  def testGet(self):
    """Tests the Catalog GET handler."""
    with test_utils.RootLogin():
      model.CatalogEntry.Create('xyz.com', 'label', self.map_object)
    with test_utils.Login('publisher'):
      response = self.DoGet('/xyz.com/.catalog')
      self.assertTrue('test map' in response.body, response.body)
      self.assertTrue('/root/xyz.com/label' in response.body, response.body)

  def testPost(self):
    """Tests the Catalog POST handler."""
    with test_utils.RootLogin():
      model.CatalogEntry.Create('xyz.com', 'label1', self.map_object)
      model.CatalogEntry.Create('xyz.com', 'label2', self.map_object)
    # Catalog entries are not listed in the Map Picker by default.
    self.assertFalse(model.CatalogEntry.Get('xyz.com', 'label1').is_listed)
    self.assertFalse(model.CatalogEntry.Get('xyz.com', 'label2').is_listed)
    with test_utils.Login('publisher'):
      self.DoPost('/xyz.com/.catalog', 'label1=True&xsrf_token=XSRF')
      self.assertTrue(model.CatalogEntry.Get('xyz.com', 'label1').is_listed)
      self.assertFalse(model.CatalogEntry.Get('xyz.com', 'label2').is_listed)

if __name__ == '__main__':
  test_utils.main()


text:
package com.chengjf.sparkdemo.module.wiki.model;

import com.chengjf.sparkdemo.model.IModel;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Wiki内容
 *
 * @author CHENGJIANFENG100
 * @date 2015-09-08
 */

@DatabaseTable(tableName = "text")
public class Text implements IModel {

	@DatabaseField(columnName = "text_id", canBeNull = false, id = true, index = true)
	private String textId;

	@DatabaseField(columnName = "text", canBeNull = false, dataType = DataType.LONG_STRING)
	private String text;

	@DatabaseField(columnName = "type", canBeNull = true)
	private String type;

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTextId() {
		return textId;
	}

	public void setTextId(String textId) {
		this.textId = textId;
	}

}


text:
__author__ = 'Christian Moeller' #MullerCorp
print("Welcome!")
userNameInput = raw_input("""Please enter your username
""") #Lets the user enter a name.
print("Hello", userNameInput) #greets the user.
if userNameInput == "Christian": #Checks if the user is "Christian" or not.
    print("Welcome back old chap!")
    pswdInput = raw_input("""Please enter your password
    """)
    if raw_input() == "1234":#Compares the entered password with the valid password.
        print("That's right! It's as if you designed this system!")
    else:
        print("Wrong password, Christian - or whomever you might be.")
    #Loop function intented in the future.
else:
    print("You're not Christian.")
    print("That's odd.")
#Pushtest1


text:
var listUsersSince = function(lastUserId) {
  let url = `https://api.github.com/users?since=${lastUserId}`;
  return fetch(url).then(response => response.json())
}

export { listUsersSince };


text:
apt-get install -y tiger
tiger


text:
require 'formula'

class Uriparser < Formula
  homepage 'http://uriparser.sourceforge.net/'
  url 'https://downloads.sourceforge.net/project/uriparser/Sources/0.8.0/uriparser-0.8.0.tar.bz2'
  sha1 '4bfe347220b00ff9cd3252e2b784d13e583282fb'

  depends_on 'pkg-config' => :build
  depends_on 'cpptest'

  conflicts_with 'libkml', :because => 'both install `liburiparser.dylib`'

  def install
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--disable-doc"
    system "make check"
    system "make install"
  end
end


text:
/**
 * Creates a notification instance.
 *
 * @-x-less Notification.less
 * @class tinymce.ui.Notification
 * @extends tinymce.ui.Container
 * @mixes tinymce.ui.Movable
 */
define(
  'tinymce.core.ui.Notification',
  [
    "tinymce.core.ui.Control",
    "tinymce.core.ui.Movable",
    "tinymce.core.ui.Progress",
    "tinymce.core.util.Delay"
  ],
  function (Control, Movable, Progress, Delay) {
    return Control.extend({
      Mixins: [Movable],

      Defaults: {
        classes: 'widget notification'
      },

      init: function (settings) {
        var self = this;

        self._super(settings);

        if (settings.text) {
          self.text(settings.text);
        }

        if (settings.icon) {
          self.icon = settings.icon;
        }

        if (settings.color) {
          self.color = settings.color;
        }

        if (settings.type) {
          self.classes.add('notification-' + settings.type);
        }

        if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) {
          self.closeButton = false;
        } else {
          self.classes.add('has-close');
          self.closeButton = true;
        }

        if (settings.progressBar) {
          self.progressBar = new Progress();
        }

        self.on('click', function (e) {
          if (e.target.className.indexOf(self.classPrefix + 'close') != -1) {
            self.close();
          }
        });
      },

      /**
       * Renders the control as a HTML string.
       *
       * @method renderHtml
       * @return {String} HTML representing the control.
       */
      renderHtml: function () {
        var self = this, prefix = self.classPrefix, icon = '', closeButton = '', progressBar = '', notificationStyle = '';

        if (self.icon) {
          icon = '';
        }

        if (self.color) {
          notificationStyle = ' style="background-color: ' + self.color + '"';
        }

        if (self.closeButton) {
          closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\u00d7</button>';
        }

        if (self.progressBar) {
          progressBar = self.progressBar.renderHtml();
        }

        return (
          '
' +
          icon +
          '
' + self.state.get('text') + '
' +
          progressBar +
          closeButton +
          '
'
        );
      },

      postRender: function () {
        var self = this;

        Delay.setTimeout(function () {
          self.$el.addClass(self.classPrefix + 'in');
        });

        return self._super();
      },

      bindStates: function () {
        var self = this;

        self.state.on('change:text', function (e) {
          self.getEl().childNodes[1].innerHTML = e.value;
        });
        if (self.progressBar) {
          self.progressBar.bindStates();
        }
        return self._super();
      },

      close: function () {
        var self = this;

        if (!self.fire('close').isDefaultPrevented()) {
          self.remove();
        }

        return self;
      },

      /**
       * Repaints the control after a layout operation.
       *
       * @method repaint
       */
      repaint: function () {
        var self = this, style, rect;

        style = self.getEl().style;
        rect = self._layoutRect;

        style.left = rect.x + 'px';
        style.top = rect.y + 'px';

        // Hardcoded arbitrary z-value because we want the
        // notifications under the other windows
        style.zIndex = 0xFFFF - 1;
      }
    });
  }
);


text:
var maxChats = 200;

Chat = new Meteor.Stream("chat");
ChatCollection = new Meteor.Collection(null);

var addChatMessage = function(message, username) {
  ChatCollection.insert({
    username: username,
    message: message,
    time: new Date()
  });
  if (!Session.equals("selectedTab", "chat")) {
    Session.set("missedChats", Session.get("missedChats") + 1);
  }
}

Chat.on("chat", function(message, username, boxname) {
  // only show the chats from the same box
  if (boxname.toLowerCase() === Meteor.user().profile.boxname.toLowerCase()) {
    addChatMessage(message, username);
  }
});

Template.chat.helpers({
  message: function() {
    return ChatCollection.find({}, {
      limit: maxChats,
      sort: [["time", "desc"], ["username", "asc"]]
    });
  },
});

Template.chatMessage.helpers({
  formattedTime: function() {
    return moment(this.time).format("H:mm");
  }
});

Template.chat.events({
  "submit .chat form": function(event) {
    event.preventDefault();

    var message = $(".chat form input");
    // don't do anything if the message is empty
    if (message.val()) {
      addChatMessage(message.val(), Meteor.user().username);
      Chat.emit("chat", message.val());
      message.val("");
    }
  }
});


text:
Please install the following software if not already installed:

* [Vagrant (tested with 1.9.3)](http://www.vagrantup.com/downloads.html)
* [Virtualbox >= 5.0](https://www.virtualbox.org/wiki/Downloads)
* [Vagrant docker-compose plugin](https://github.com/leighmcculloch/vagrant-docker-compose) (`vagrant plugin install vagrant-docker-compose`)

1.) Please follow the "Configuration" section from [docker Instructions](docker.md#step-3-configuration)
2.) Then run:
```bash
$: vagrant up
```

All dependencies will be downloaded. This may take a while ...

Now open [http://localhost:8080](http://localhost:8080/) and have fun.


text:
title: Package framed
subtitle: Default LaTeX style in knitr
date: '2012-02-29'
slug: framed
---

By default, **knitr** uses a LaTeX package named [framed](http://www.ctan.org/pkg/framed) for typesetting; the most obvious feature is the light gray shading. In this page, we introduce some tricks and known problems.

As listed in [FAQ's](../../faq/), you may see the output overflow the shading box, and you can set `options('width')` to a smaller value in this case.

## Overflow of elements

Besides text overflow, figures may also exceed the margin of the shading. If a figure is too wide, LaTeX may complain there is something wrong with the `kframe` environment, which is what **knitr** uses to wrap up the chunk output. A known case is about PNG graphics in [#154](https://github.com/yihui/knitr/issues/154). To make sure your figures do not exceed the page margin, **knitr** uses the following command in the LaTeX preamble:

```tex
%% maxwidth is the original width if it's less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother
```

The chunk option `out.width` is set to `'\\maxwidth'` by default if the output format is LaTeX.

## Padding of the shading box

This LaTeX command sets the padding to be 5mm if you feel the default layout is too parsimonious (no padding at all).

```tex
\setlength\fboxsep{5mm}
```

If you do not like this default style with the **framed** package, you are free to switch to other styles like [listings](../listings/) or even define your own output [hooks](../../hooks).

## Incompatible environments with **framed**

It does not work well with the `figure*` environment in two-column documents; see [knitr-twocolumn.pdf](https://github.com/yihui/knitr/releases/download/doc/knitr-twocolumn.pdf) for one approach to deal with this situation.

If you use the Tufte handout/book classes, the `fullwidth` environment does not work well with the **framed** package either; see discussion in [#222](https://github.com/yihui/knitr/issues/222) for possible solutions.

It does not work with the **lineno** package; see [Michael's post](http://groups.google.com/group/knitr/browse_thread/thread/b0d6723386371139) in the mailing list.


text:
[![GoDoc][1]][2] [![Build Status][3]][4] [![Go Report Card][5]][6] [![Coverage Statusd][7]][8] [![MIT licensed][9]][10]

[1]: https://godoc.org/github.com/xtaci/tcpraw?status.svg
[2]: https://godoc.org/github.com/xtaci/tcpraw
[3]: https://travis-ci.org/xtaci/tcpraw.svg?branch=master
[4]: https://travis-ci.org/xtaci/tcpraw
[5]: https://goreportcard.com/badge/github.com/xtaci/tcpraw
[6]: https://goreportcard.com/report/github.com/xtaci/tcpraw
[7]: https://codecov.io/gh/xtaci/tcpraw/branch/master/graph/badge.svg
[8]: https://codecov.io/gh/xtaci/tcpraw
[9]: https://img.shields.io/badge/license-MIT-blue.svg
[10]: LICENSE

# Introduction

A packet-oriented connection by simulating TCP protocol

## Features

0. Tiny
1. Support IPv4 and IPv6.
2. Realistic sliding window, NAT friendly.
3. Pure golang without cgo, available on all architecture.

## Documentation

For complete documentation, see the associated [Godoc](https://godoc.org/github.com/xtaci/tcpraw).

## Benchmark

```
goos: linux
goarch: amd64
pkg: github.com/xtaci/tcpraw
BenchmarkEcho-2   	   20000	     93036 ns/op	  11.01 MB/s	    6200 B/op	      62 allocs/op
PASS
ok  	github.com/xtaci/tcpraw	2.758s
```

## Status

Stable

## Who is using this

https://github.com/xtaci/kcptun


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:citrus="http://www.citrusframework.org/schema/config"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.citrusframework.org/schema/config http://www.citrusframework.org/schema/config/citrus-config.xsd">

  <context:annotation-config/>

  <!-- Default message validators -->
  <citrus:message-validators>
    <citrus:validator ref="defaultXmlMessageValidator"/>
    <citrus:validator ref="defaultXpathMessageValidator"/>
    <citrus:validator ref="defaultGroovyXmlMessageValidator"/>
    <citrus:validator class="com.consol.citrus.validation.text.PlainTextMessageValidator"/>
    <citrus:validator ref="defaultBinaryBase64MessageValidator"/>
    <citrus:validator ref="defaultGzipBinaryBase64MessageValidator"/>
    <citrus:validator ref="defaultJsonMessageValidator"/>
    <citrus:validator ref="defaultJsonPathMessageValidator"/>
    <citrus:validator ref="defaultMessageHeaderValidator"/>
    <citrus:validator ref="defaultGroovyJsonMessageValidator"/>
    <citrus:validator ref="defaultXhtmlMessageValidator"/>
  </citrus:message-validators>

  <bean id="defaultMessageHeaderValidator" class="com.consol.citrus.validation.DefaultMessageHeaderValidator"/>
  <bean id="defaultXmlMessageValidator" class="com.consol.citrus.validation.xml.DomXmlMessageValidator"/>
  <bean id="defaultXpathMessageValidator" class="com.consol.citrus.validation.xml.XpathMessageValidator"/>
  <bean id="defaultJsonMessageValidator" class="com.consol.citrus.validation.json.JsonTextMessageValidator"/>
  <bean id="defaultJsonPathMessageValidator" class="com.consol.citrus.validation.json.JsonPathMessageValidator"/>
  <bean id="defaultXhtmlMessageValidator" class="com.consol.citrus.validation.xhtml.XhtmlMessageValidator"/>
  <bean id="defaultBinaryBase64MessageValidator" class="com.consol.citrus.validation.text.BinaryBase64MessageValidator"/>
  <bean id="defaultGzipBinaryBase64MessageValidator" class="com.consol.citrus.validation.text.GzipBinaryBase64MessageValidator"/>

  <bean id="defaultGroovyXmlMessageValidator" class="com.consol.citrus.validation.script.GroovyXmlMessageValidator"/>
  <bean id="defaultGroovyJsonMessageValidator" class="com.consol.citrus.validation.script.GroovyJsonMessageValidator"/>

</beans>


text:
/**
 * @file
 * @brief Implementation of reading 3D scans in colored XYZ format (i.e., pure
 * 3D data points and RGB color information)
 * @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany.
 * @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany.
 */

#include "slam6d/scan_io_xyz_rgb.h"
#include "slam6d/globals.icc"
#include <fstream>
using std::ifstream;
#include <iostream>
using std::cerr;
using std::endl;

#include <algorithm>
using std::swap;

#ifdef _MSC_VER
#include <windows.h>
#endif

/**
 * Reads specified scans from given directory in the colored XYZ file format
 * (i.e., pure 3D data points and RGB color * information only)
 * It will be compiled as shared lib.
 *
 * @param start Starts to read with this scan
 * @param end Stops with this scan
 * @param dir The directory from which to read
 * @param maxDist Reads only Points up to this Distance
 * @param minDist Reads only Points from this Distance
 * @param euler Initital pose estimates (will not be applied to the points
 * @param ptss Vector containing the read points
 */
int ScanIO_xyz_rgb::readScans(int start, int end, string &dir, int maxDist, int minDist,
					 double *euler, vector<Point> &ptss)
{
  static int fileCounter = start;
  string scanFileName;

  ifstream scan_in, pose_in;
  double maxDist2 = sqr(maxDist);
  double minDist2 = sqr(minDist);

  if (end > -1 && fileCounter > end) return -1; // 'nuf read

  scanFileName = dir + to_string(fileCounter,3) + ".xyz";
  scan_in.open(scanFileName.c_str());
  // read 3D scan
  if (!scan_in.good()) { cerr << "ERROR: Missing file " << scanFileName << endl; exit(1); }
  cout << "Processing Scan " << scanFileName;

  char firstline[255];
  scan_in.getline(firstline, 255);

  euler[0] = 0.0;
  euler[1] = 0.0;
  euler[2] = 0.0;
  euler[3] = 0.0;
  euler[4] = 0.0;
  euler[5] = 0.0;

  while (scan_in.good()) {
    Point p;
    int r, g, b;
    scan_in >> p.x >> p.z >> p.y >> r >> g >> b;
    p.x *= 100;
    p.y *= 100;
    p.z *= 100;
    p.rgb[0] = (char)r;
    p.rgb[1] = (char)g;
    p.rgb[2] = (char)b;

    if (maxDist == -1 || sqr(p.x) + sqr(p.y) + sqr(p.z) < maxDist2)
      if (minDist == -1 || sqr(p.x) + sqr(p.y) + sqr(p.z) > minDist2)
        ptss.push_back(p);
  }

  cout << " done" << endl;

  scan_in.close();
  scan_in.clear();
  pose_in.close();
  pose_in.clear();
  fileCounter++;

  return 1;
}

/**
 * class factory for object construction
 *
 * @return Pointer to new object
 */
#ifdef _MSC_VER
extern "C" __declspec(dllexport) ScanIO* create()
#else
extern "C" ScanIO* create()
#endif
{
  return new ScanIO_xyz_rgb;
}

/**
 * class factory for object construction
 *
 * @return Pointer to new object
 */
#ifdef _MSC_VER
extern "C" __declspec(dllexport) void destroy(ScanIO *sio)
#else
extern "C" void destroy(ScanIO *sio)
#endif
{
  delete sio;
}

#ifdef _MSC_VER
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
	return TRUE;
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                                      http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Thorr\Nonce\Entity\Nonce" table="thorr_nonces">

        <field name="expirationDate" type="datetime" nullable="true"/>
        <field name="namespace" type="string" nullable="true" />

        <many-to-one target-entity="Thorr\Nonce\Entity\NonceOwnerInterface" field="owner">
            <join-column name="ownerUuid" referenced-column-name="uuid"  on-delete="CASCADE" on-update="CASCADE" />
        </many-to-one>

    </entity>

</doctrine-mapping>


text:
import "../../lib/jquery.resize"; // makes jquery resize work on all elements
import { BloomApi } from "../../utils/bloomApi";

// Enhance: this could be turned into a Typescript Module with only two public methods

import theOneLocalizationManager from "../../lib/localizationManager/localizationManager";

import { updateOverlayClass } from "./bubbleManager";

const kPlaybackOrderContainerSelector: string =
    ".bloom-playbackOrderControlsContainer";

// This appears to be constant even on higher dpi screens.
// (See http://www.w3.org/TR/css3-values/#absolute-lengths)
const kBrowserDpi = 96;

export function cleanupImages() {
    $(".bloom-imageContainer").css("opacity", ""); //comes in on img containers from an old version of myimgscale, and is a major problem if the image is missing
    $(".bloom-imageContainer").css("overflow", ""); //review: also comes form myimgscale; is it a problem?
}

export function SetupImagesInContainer(container) {
    $(container)
        .find(".bloom-imageContainer > img") // the ">" here prevents finding img's of ui affordances deep in comics
        .each(function() {
            SetupImage(this);
        });

    $(container)
        .find(".bloom-imageContainer")
        .each((index, element) => {
            SetupImageContainer(element as HTMLHtmlElement);
        });

    //todo: this had problems. Check out the later approach, seen in draggableLabel (e.g. move handle on the inside, using a background image on a div)
    $(container)
        .find(".bloom-draggable")
        .mouseenter(function() {
            $(this).prepend(
                "<button class='moveButton' title='Move'></button>"
            );
            $(this)
                .find(".moveButton")
                .mousedown(function(e) {
                    //reviewSlog added the <any>
                    $(this)
                        .parent()
                        .trigger(<any>e);
                });
        });
    $(container)
        .find(".bloom-draggable")
        .mouseleave(function() {
            $(this)
                .find(".moveButton")
                .each(function() {
                    $(this).remove();
                });
        });

    // Add the event listener to handle control/alt being pressed.
    // We have a pretty interesting way of listening for these keydown/keyup events.
    // I initially tried putting the event listeners on the bloom-imageContainer,
    // but that didn't work reliably.
    // Keyboard events don't fire for every element, but only certain valid ones.
    // For the short answer, divs with contenteditable=true meet the criteria.
    // (Although... I tested what happens with slapping contenteditable=true onto the bloom-imageContainer,
    // and I don't think it helped)
    // To get around this, I found the following strategy:
    // 1) place the keydown listener as broadly as we can... that's {document}.
    // 2) When a key is pressed, the listener will fire and some child element of the document will be the event target.
    // 3) Oddly enough however, the same trick doesn't work for "keyup" (if you put the listener on {document}, it doesn't fire).
    // 4) Instead, we put the "keyup" event listener on whatever element fired the "keydown" event,
    //    since whatever element that is should presumably be getting the keyup event too.
    //    This could be the main text box actually, and that's fine.
    //    It could also be the translation qtip way off screen (maybe only for pages without a text box?),
    //    but even that is sufficient for our purposes.
    document.addEventListener("keydown", ctrlAltKeyDownListener);

    $(container)
        .find("img")
        .each(function() {
            SetAlternateTextOnImages(this);
        });
}

export function SetupImage(image: JQuery) {
    // Remove any obsolete explicit image size and position left over from earlier versions of Bloom, before we had object-fit:contain.
    if (image.style) {
        // Note, in BL-9460 we had to return to having width and height in some cases.
        if (!$(image.parent).hasClass("bloom-scale-with-code")) {
            image.style.width = "";
            image.style.height = "";
        }
        image.style.marginLeft = "";
        image.style.marginTop = "";
    }
    if (image.removeAttribute) {
        if (image.getAttribute && image.getAttribute("style") === "") {
            image.removeAttribute("style");
        }
        image.removeAttribute("width");
        image.removeAttribute("height");
    }
}

/**
 * When the Ctrl or Alt key is pressed, hide the image editing buttons until the key is released.
 */
function ctrlAltKeyDownListener(event: KeyboardEvent) {
    if ((event.ctrlKey || event.altKey) && event.target) {
        event.target.addEventListener("keyup", ctrlAltKeyUpListener);

        // Note (paranoia): Add this class conservatively (ensure event.target is good first),
        // remove it liberally (regardless of event.target),
        // Since if it gets stuck on, the image editing buttons won't come back (unless SetupImageContainer is re-run)
        document
            .querySelectorAll(
                ".bloom-imageContainer:not(.ui-suppressImageButtons)"
            )
            .forEach(imageContainer => {
                imageContainer.classList.add("ui-suppressImageButtons");

                if (event.ctrlKey) {
                    imageContainer.classList.add("ui-ctrlDown");
                }
            });
    }
}

/**
 * When the last Ctrl or Alt key is released, show the image editing buttons again (if they still exist)
 */
function ctrlAltKeyUpListener(event: KeyboardEvent) {
    // event.ctrlKey/event.altKey are normally false when a single Control or Alt button is released
    // (unless the user pressed two ctrl/alt keys, and then released one of them).
    // We don't want to fire the event until all of the ctrl/alt keys are released.
    const isCtrlOrAltReleased = event.key === "Control" || event.key === "Alt";
    const areAnyOtherCtrlOrAltKeysDown = event.ctrlKey || event.altKey;

    if (isCtrlOrAltReleased && !areAnyOtherCtrlOrAltKeysDown) {
        document
            .querySelectorAll(".bloom-imageContainer.ui-suppressImageButtons")
            .forEach(imageContainer => {
                imageContainer.classList.remove("ui-suppressImageButtons");

                // Remember, for keyup events, you want to check event.key === "Control" instead of event.ctrlKey
                if (event.key === "Control") {
                    imageContainer.classList.remove("ui-ctrlDown");
                }
            });

        // De-register ourself as an event handler.
        // We're no longer needed until the next time ctrl/alt is pressed,
        // and the user could type a bunch of things in a text box, which we don't need to bother listening to.
        event.target?.removeEventListener("keyup", ctrlAltKeyUpListener);
    }
}

export function GetButtonModifier(container) {
    let buttonModifier = "";
    const imageButtonWidth = 87;
    const imageButtonHeight = 52;
    const $container = $(container);
    if ($container.height() < imageButtonHeight * 2) {
        buttonModifier = "smallButtonHeight";
    }
    if ($container.width() < imageButtonWidth * 2) {
        buttonModifier += " smallButtonWidth";
    }
    if ($container.width() < imageButtonWidth) {
        buttonModifier += " verySmallButtons";
    }
    return buttonModifier;
}

export function addImageEditingButtons(containerDiv: HTMLElement): void {
    if (!containerDiv || containerDiv.classList.contains("hoverUp")) {
        return;
    }
    let img = getImgFromContainer(this);
    if (img.length === 0)
        // This case is probably a left over from some previous Bloom where
        // we were using background images instead of <img>? But it does
        // no harm so I'm leaving it in.
        img = $(containerDiv); //using a backgroundImage

    const $containerDiv = $(containerDiv);
    if ($containerDiv.find(kPlaybackOrderContainerSelector).length > 0) {
        return; // Playback order controls are active, deactivate image container stuff.
    }
    const buttonModifier = GetButtonModifier($containerDiv);

    const addButtonHandler = (command: string) => {
        const button = $containerDiv.get(0)?.firstElementChild;
        button?.addEventListener("click", () => {
            const imgIndex = Array.from(
                document.getElementsByClassName("bloom-imageContainer")
            ).indexOf($containerDiv.get(0));
            BloomApi.postJson("editView/" + command + "Image", { imgIndex });
        });
    };

    $containerDiv.prepend(
        '<button class="miniButton cutImageButton imageOverlayButton disabled ' +
            buttonModifier +
            '" title="' +
            theOneLocalizationManager.getText("EditTab.Image.CutImage") +
            '"></button>'
    );
    addButtonHandler("cut");

    $containerDiv.prepend(
        '<button class="miniButton copyImageButton imageOverlayButton disabled ' +
            buttonModifier +
            '" title="' +
            theOneLocalizationManager.getText("EditTab.Image.CopyImage") +
            '"></button>'
    );
    addButtonHandler("copy");

    $containerDiv.prepend(
        '<button class="pasteImageButton imageButton imageOverlayButton ' +
            buttonModifier +
            '" title="' +
            theOneLocalizationManager.getText("EditTab.Image.PasteImage") +
            '"></button>'
    );
    addButtonHandler("paste");

    $containerDiv.prepend(
        '<button class="changeImageButton imageButton imageOverlayButton ' +
            buttonModifier +
            '" title="' +
            theOneLocalizationManager.getText("EditTab.Image.ChangeImage") +
            '"></button>'
    );
    addButtonHandler("change");

    // As part of BL-9976 JH decided to remove this button as users were getting confused.
    // if (
    //     // Only show this button if the toolbox is also offering it. It might not offer it
    //     // if it's experimental and that settings isn't on, or for Bloom Enterprise reasons, or whatever.
    //     getToolboxFrameExports()
    //         ?.getTheOneToolbox()
    //         .getToolIfOffered(ImageDescriptionAdapter.kToolID)
    // ) {
    //     $this.prepend(
    //         '<button class="imageDescriptionButton imageButton imageOverlayButton ' +
    //             buttonModifier +
    //             '" title="' +
    //             theOneLocalizationManager.getText(
    //                 "EditTab.Toolbox.ImageDescriptionTool" // not quite the "Show Image Description Tool", but... feeling parsimonious
    //             ) +
    //             '"></button>'
    //     );
    //     $this.find(".imageDescriptionButton").click(() => {
    //         getToolboxFrameExports()
    //             ?.getTheOneToolbox()
    //             .activateToolFromId(ImageDescriptionAdapter.kToolID);
    //     });
    // }

    SetImageTooltip(containerDiv);

    if (IsImageReal(img)) {
        const title = theOneLocalizationManager.getText(
            "EditTab.Image.EditMetadata"
        );
        const button = `<button class="editMetadataButton imageButton imageOverlayButton ${buttonModifier}" title="${title}"></button>`;
        $containerDiv.prepend(button);
        $containerDiv.find("button.editMetadataButton").attr(
            "onClick",
            // Originally, we tried to determine the imageUrl at setup time and put that string in the onClick handler string below.
            // However, it turns out that we must rely on the click handler knowing what element we clicked on ("this") at click time.
            // Otherwise, we can get an incorrect imageUrl. For example, a picture on picture might give the parent picture imageUrl.
            // We have to do this strange editTabBundle stuff because at the time of the click, we are in a context where that is all we can access.
            `(window.parent || window).editTabBundle.showCopyrightAndLicenseDialog(
                (window.parent || window).editTabBundle.getImageUrlFromImageButton(this));`
        );
        $containerDiv.find(".miniButton").each(function() {
            $(this).removeClass("disabled");
        });
    }

    $containerDiv.addClass("hoverUp");
}

/**
 * Gets a NodeListOf of the image editing button elements, which can be iterated through.
 * @param containerDiv: The .bloom-imageContainer which contains the image editing buttons.
 * @param options: An object with the following fields:
 *    skipProblemIndicator: true to omit the imgMetadataProblem element(s) from the list
 */
function getImageEditingButtons(
    containerDiv: Element,
    options: {
        skipProblemIndicator: boolean;
    }
): NodeListOf<Element> {
    // NOTE: imgMetadataProblem isn't actually an imageOverlayButton,
    // so strictly speaking, we don't need to do any special checks,
    // but let's check anyway just in case it ever receives the imageOverlayButton class in the future
    const selector =
        ".imageOverlayButton" +
        (options.skipProblemIndicator ? ":not(.imgMetadataProblem)" : "");
    return containerDiv.querySelectorAll(selector);
}

export function removeImageEditingButtons(containerDiv: Element): void {
    containerDiv.classList.remove("hoverUp");
    getImageEditingButtons(containerDiv, {
        skipProblemIndicator: true // leave the problem indicator visible
    }).forEach(button => {
        button.remove();
    });
}

export function tryRemoveImageEditingButtons(
    containerDiv: Element | undefined
): void {
    if (containerDiv) {
        removeImageEditingButtons(containerDiv);
    }
}

// Bloom "imageContainer"s are <div>'s which wrap an <img>, and automatically proportionally resize
// the img to fit the available space.
// Precondition: containerDiv must be just a single HTMLElement
function SetupImageContainer(containerDiv: HTMLElement) {
    // Initialize the value of the hoverUp class.
    // the hoverup class should be present whenever the mouse is over the containerDiv.
    // This is usually achieved by mouseenter/mouseleave event handlers,
    // but mouseenter won't trigger if the mouse starts off over the image container when the page is loaded
    // That case is extremely commonplace when adding comic bubbles, because that needs to reload the page.
    // (It is also possible to trigger even when opening up a new page, but probably less likely to happen accidentally)
    if (containerDiv.matches(":hover")) {
        containerDiv.classList.add("hoverUp");
    } else {
        containerDiv.classList.remove("hoverUp");
    }

    // Just in case, ensure prior state is cleaned up
    containerDiv.classList.remove("ui-suppressImageButtons");

    // Now that we can overlay things on top of images, we don't want to show the flower placeholder
    // if the image container contains an overlay.
    updateOverlayClass(containerDiv);

    // This will fix cover image on Kyrgyzstan books that we created before we switched to this
    // new border system. Going forward, say 5.1, we could remove this and just
    // rely on a call to SetImageDisplaySize() when the image is added.
    const img = $(containerDiv).find("img");
    SetImageDisplaySizeIfCalledFor($(containerDiv), img);

    $(containerDiv)
        .mouseenter(function() {
            addImageEditingButtons(this);
        })
        .mouseleave(function() {
            removeImageEditingButtons(this);
        });
}

export function getImageUrlFromImageButton(button: HTMLButtonElement): string {
    const imageContainer = button?.parentElement;
    if (!imageContainer) return "";
    return GetRawImageUrl(getImgFromContainer(imageContainer));
}

function getImgFromContainer(imageContainer: HTMLElement) {
    // FF60 doesn't seem to do this properly, so I'm punting and using jquery...
    // return imageContainer.querySelector(
    //     "img:not(.bloom-ui > img, .bloom-ui)"
    // );
    return $(imageContainer)
        .find("img")
        .not(".bloom-ui") // e.g. dragHandle.svg
        .not(".bloom-ui img"); // e.g. cog.svg
}

function SetImageTooltip(container: HTMLElement) {
    const containerJQ = $(container);
    const imgElement = $(container).find("img");

    if (!imgElement) {
        container.title = "";
        return;
    }
    const url = GetRawImageUrl(imgElement);
    // Don't try to go getting image info for a built in Bloom image (like cogGrey.svg).
    // It'll just throw an exception.
    if (url.startsWith("/bloom/")) {
        container.title = "";
        return;
    }

    const targetDpiWidth = Math.ceil((300 * containerJQ.width()) / kBrowserDpi);
    const targetDpiHeight = Math.ceil(
        (300 * containerJQ.height()) / kBrowserDpi
    );
    const isPlaceHolder = url.indexOf("placeHolder.png") > -1;

    BloomApi.getWithConfig("image/info", { params: { image: url } }, result => {
        const imageFileInfo: any = result.data;
        let linesAboutThisFile: string;
        const fileFound = imageFileInfo.bytes >= 0;
        let dpiLine = "";
        if (isPlaceHolder) {
            linesAboutThisFile = "";
        } else if (!fileFound) {
            linesAboutThisFile = `${imageFileInfo.name} not found\n`;
        } else {
            const dpi = getDpi(
                container,
                imageFileInfo.width,
                imageFileInfo.height
            );
            const bulletForDpi = dpi < 300 ? "⚠" : "✓";
            // removed because only devs care! Bit Depth: ${imageFileInfo.bitDepth.toString()}
            linesAboutThisFile = `Name: ${
                imageFileInfo.name
            } Size: ${getFileLengthString(imageFileInfo.bytes)} Dots: ${
                imageFileInfo.width
            } x ${imageFileInfo.height}\n\n`;
            if (!isPlaceHolder) {
                dpiLine = `${bulletForDpi} This image would print at ${dpi} DPI.\n`;
            }
        }

        const linesAboutThisContext =
            `For the current paper size:\n` +
            `  • The image container is ${containerJQ.width()} x ${containerJQ.height()} dots.\n` +
            `  • For print publications, you want between 300-600 DPI (Dots Per Inch).\n` +
            dpiLine +
            `  • An image with ${targetDpiWidth} x ${targetDpiHeight} dots would fill this container at 300 DPI.`;

        container.title = linesAboutThisFile + linesAboutThisContext;
    });
}
function getDpi(
    container: HTMLElement,
    imageWidth: number,
    imageHeight: number
): number {
    const containerJQ = $(container);

    const containerAspectRatio =
        containerJQ.width() / Math.max(1, containerJQ.height());
    const imageAspectRatio = imageWidth / Math.max(1, imageHeight);

    // Image is skinnier than the container, so the image will be
    // stretched/squeezed to fit the height of the container.
    if (imageAspectRatio < containerAspectRatio) {
        return Math.round(imageHeight / (containerJQ.height() / kBrowserDpi));
    }
    // Image is fatter than the container, so the image will be
    // stretched/squeezed to fit the width of the container.
    else {
        return Math.round(imageWidth / (containerJQ.width() / kBrowserDpi));
    }
}

function SetImageDisplaySizeIfCalledFor(container: JQuery, img: JQuery) {
    //const $container = $(containerDiv);
    // For Kyrgyzstan covers, we needed a white border around images.
    // object-fit:contain would leave the border of the image around the inside
    // of the parent, instead of around the fitted image. See
    // https://issues.bloomlibrary.org/youtrack/issue/BL-9460.
    // So this allows us to do things the old fashioned way, essentially
    // implementing object-fit ourselves, so that a style can be applied to add
    // a border that will fit snugly.

    if (container.hasClass("bloom-scale-with-code")) {
        const url = GetRawImageUrl(img);
        // Don't touch images for a built in Bloom image (like cogGrey.svg).
        if (url.startsWith("/bloom/")) {
            return;
        }
        BloomApi.getWithConfig(
            "image/info",
            { params: { image: GetRawImageUrl(img) } },
            result => {
                const imageInfo: any = result.data;
                const containerAspectRatio =
                    container.width() / Math.max(1, container.height());
                const imageAspectRatio =
                    imageInfo.width / Math.max(1, imageInfo.height);

                // image is skinnier than the container
                if (imageAspectRatio < containerAspectRatio) {
                    $(img).css(
                        "width",
                        `${container.height() * imageAspectRatio}px`
                    );
                    $(img).css("height", "100%");
                }
                // image is fatter than the container
                else {
                    $(img).css(
                        "height",
                        `${imageInfo.height *
                            (container.width() /
                                Math.max(1, imageInfo.width))}px`
                    );
                    $(img).css("width", "100%");
                }
                // This isn't actually needed once we have the height and width
                // here. However, when a new the book is previewed *before we've
                // had a chance to set this stuff*, it will look awful unless we
                // can put object-fit:contain on it. That won't make the border
                // fit tightly, but at least the image won't be distorted. So we
                // do set it that way in the stylesheet, and then overwrite that here once
                // we have the height and width set.
                $(img).css("object-fit", "cover");
            }
        );
    }
}

function getFileLengthString(bytes): String {
    const units = ["bytes", "kb", "mb"];
    for (let i = units.length; i-- > 0; ) {
        const unit = Math.pow(1024, i);
        if (bytes >= unit)
            //reviewSlog
            return (
                (Math.round((bytes / unit) * 100) / 100).toFixed(2).toString() +
                " " +
                units[i]
            );
        //return parseFloat(Math.round(bytes / unit * 100) / 100).toFixed(2) + ' ' + units[i];
    }
    return "";
}

// IsImageReal returns true if the img tag refers to a non-placeholder image
// If the image is a placeholder:
// - we don't want to offer to edit placeholder credits
// - we don't want to activate the minibuttons for cut/copy
function IsImageReal(img) {
    return (
        GetRawImageUrl(img)
            .toLowerCase()
            .indexOf("placeholder") == -1
    ); //don't offer to edit placeholder credits
}

// Gets the src attribute out of images, and the background-image:url() of everything else
function GetRawImageUrl(imgOrDivWithBackgroundImage): string {
    if ($(imgOrDivWithBackgroundImage).hasAttr("src")) {
        return $(imgOrDivWithBackgroundImage).attr("src");
    }
    //handle divs with background-image in an inline style attribute
    if ($(imgOrDivWithBackgroundImage).hasAttr("style")) {
        const style = $(imgOrDivWithBackgroundImage).attr("style");
        // see http://stackoverflow.com/questions/9723889/regex-to-match-urls-in-inline-styles-div-style-url
        //var result = (/url\(\s*(['"]?)(.*?)\1\s*\)/.exec(style) || [])[2];
        // Various things don't expect this to return null or undefined, which the regex just might do.
        return (/url\s*\(\s*(['"]?)(.*?)\1\s*\)/.exec(style) || [])[2] ?? "";
    }
    return "";
}

/* appears to be unused
export function SetImageElementUrl(imgOrDivWithBackgroundImage, url) {
    if (imgOrDivWithBackgroundImage.tagName.toLowerCase() === "img") {
        imgOrDivWithBackgroundImage.src = url;
    } else {
        imgOrDivWithBackgroundImage.style =
            "background-image:url('" + url + "')";
    }
}
*/

//While the actual metadata is embedded in the images (Bloom/palaso does that), Bloom sticks some metadata in data-* attributes
// so that we can easily & quickly get to the here.
export function SetOverlayForImagesWithoutMetadata(container) {
    $(container)
        .find("*[style*='background-image']")
        .each(function() {
            SetOverlayForImagesWithoutMetadataInner(this, this);
        });

    //Do the same for any img elements inside
    $(container)
        .find(".bloom-imageContainer")
        .each(function() {
            // BL-9976: now that we can have images on images, only look one level down from the container.
            const img = $(this).find("> img");
            SetOverlayForImagesWithoutMetadataInner($(img).parent(), img);
        });
}

function SetOverlayForImagesWithoutMetadataInner(container, img) {
    if (!IsImageReal(img)) {
        return;
    }

    UpdateOverlay(container, img);

    //and if the bloom program changes these values (i.e. the user changes them using bloom), I
    //haven't figured out a way (apart from polling) to know that. So for now I'm using a hack
    //where Bloom calls click() on the image when it wants an update, and we detect that here.
    $(img).click(() => {
        UpdateOverlay(container, img);
    });
}

function UpdateOverlay(container, img) {
    $(container)
        .find("button.imgMetadataProblem")
        .each(function() {
            $(this).remove();
        });

    //review: should we also require copyright, illustrator, etc? In many contexts the id of the work-for-hire illustrator isn't available
    const copyright = $(img).attr("data-copyright");
    if (!copyright || copyright.length === 0) {
        const buttonClasses = `editMetadataButton imageButton imgMetadataProblem ${GetButtonModifier(
            container
        )}`;
        const englishText =
            "Image is missing information on Credits, Copyright, or License";
        theOneLocalizationManager
            .asyncGetText(
                "EditTab.Image.MissingInfo",
                englishText,
                "tooltip text"
            )
            .done(translation => {
                const title = translation.replace(/'/g, "'");
                $(container).prepend(
                    `<button class='${buttonClasses}' title='${title}'></button>`
                );
            })
            .fail(() => {
                $(container).prepend(
                    `<button class='${buttonClasses}' title='${englishText}'></button>`
                );
            });
    }
}

// Instead of "missing", we want to show it in the right ui language. We also want the text
// to indicate that it might not be missing, just didn't load (this happens on slow machines)
function SetAlternateTextOnImages(element) {
    if (GetRawImageUrl(element).length > 0) {
        //don't show this on the empty license image when we don't know the license yet
        const englishText =
            "This picture, {0}, is missing or was loading too slowly."; // Also update HtmlDom.cs::IsPlaceholderImageAltText
        const nameWithoutQueryString = GetRawImageUrl(element).split("?")[0];
        const decodedName = decodeURI(nameWithoutQueryString);
        theOneLocalizationManager
            .asyncGetText(
                "EditTab.Image.AltMsg",
                englishText,
                "message displayed when the picture image cannot be displayed",
                decodedName
            )
            .done(translation => {
                $(element).attr("alt", translation);
            })
            .fail(() => {
                $(element).attr(
                    "alt",
                    theOneLocalizationManager.simpleFormat(englishText, [
                        decodedName
                    ])
                );
            });
    } else {
        $(element).attr("alt", ""); //don't be tempted to show something like a '?' unless you fix the result when you have a custom book license on top of that '?'
    }
}

export function SetupResizableElement(element) {
    $(element)
        .mouseenter(function() {
            $(this).addClass("ui-mouseOver");
        })
        .mouseleave(function() {
            $(this).removeClass("ui-mouseOver");
        });
    const childImgContainer = $(element).find(".bloom-imageContainer");
    // A Picture Dictionary Word-And-Image
    if ($(childImgContainer).length > 0) {
        /* The case here is that the thing with this class actually has an
         inner image, as is the case for the Picture Dictionary.
         The key, non-obvious, difficult requirement is keeping the text below
         a picture dictionary item centered underneath the image.  I'd be
         surprised if this wasn't possible in CSS, but I'm not expert enough.
         So, I switched from having the image container be resizable, to having the
         whole div (image+headwords) be resizable, then use the "alsoResize"
         parameter to make the imageContainer resize.  Then, in order to make
         the image resize in real-time as you're dragging, I use the "resize"
         event to scale the image up proportionally (and centered) inside the
         newly resized container.
         */
        const img = $(childImgContainer).find("img");
        $(element).resizable({
            handles: "nw, ne, sw, se",
            containment: "parent",
            alsoResize: childImgContainer
        });
    }
    //An Image Container div (which must have an inner <img>
    else if ($(element).hasClass("bloom-imageContainer")) {
        const img = $(element).find("img");
        $(element).resizable({
            handles: "nw, ne, sw, se",
            containment: "parent"
        });
    }
    // some other kind of resizable
    else {
        $(element).resizable({
            handles: "nw, ne, sw, se",
            containment: "parent",
            stop: ResizeUsingPercentages,
            start: (e, ui) => {
                if (
                    $(ui.element).css("top") == "0px" &&
                    $(ui.element).css("left") == "0px"
                ) {
                    $(ui.element).data("doRestoreRelativePosition", "true");
                }
            }
        });
    }
}

//jquery resizable normally uses pixels. This makes it use percentages, which are mor robust across page size/orientation changes
function ResizeUsingPercentages(e, ui) {
    const parent = ui.element.parent();
    ui.element.css({
        width: (ui.element.width() / parent.width()) * 100 + "%",
        height: (ui.element.height() / parent.height()) * 100 + "%"
    });

    //after any resize jquery adds an absolute position, which we don't want unless the user has resized
    //so this removes it, unless we previously noted that the user had moved it
    if ($(ui.element).data("doRestoreRelativePosition")) {
        ui.element.css({
            position: "",
            top: "",
            left: ""
        });
    }
    $(ui.element).removeData("hadPreviouslyBeenRelocated");
}


text:
Mern and I have been obsessed with this game on our phones, so I decided to write a solver for it.

The program uses an installation of Android Debug Bridge (`adb`) to pull a screenshot from my phone. The program then runs
some image processing on the screenshot to determine the locations of all of the vials and colored balls. Once the program
has that information, it runs a depth first search to determine the fewest number of moves required to solve the level.
Then the program is able to use `adb` to automate the clicks required to solve the level, using my phone.

The image processing step of this process is probably trash, but I had a lot of fun making this.

No guarentees that it works on your particular phone. The image processing was designed around my old Samsung S8+, though
it was designed to handle levels with any number of vials with any number of balls.

Enjoy!

![](./images/Color%20Sort%20Puzzle%20Solver%20Example.gif)


text:
/**
 * Created by tal on 3/13/15.
 */

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = new Schema({
    _id: {type:Number, unique:true, required:true},
    center_id: { type: Number, ref: 'Center'},
    date: { type: Date },
    isActive: { type: Boolean, default: true }
});

schema.path('date').get(function (d) {
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    return curr_date + "-" + curr_month + "-" + curr_year;
});

schema.set('toJSON', { getters: true, virtuals: true });

module.exports = mongoose.model('Date', schema);