<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, window, setTimeout */

/**
 * Resizer is a Module utility to inject resizing capabilities to any element
 * inside Brackets.
 *
 * On initialization, Resizer discovers all nodes tagged as "vert-resizable"
 * and "horz-resizable" to add the resizer handler. Additionally, "top-resizer",
 * "bottom-resizer", "left-resizer" and "right-resizer" classes control the
 * position of the resizer on the element.
 *
 * An element can be made resizable at any time using the `makeResizable` API
 *
 * The resizable elements trigger a panelResizeStart, panelResizeUpdate and panelResizeEnd
 * event that can be used to create performance optimizations (such as hiding/showing elements
 * while resizing), custom or internal resizes and save the final resized value into local
 * storage for example.
 *
 * A resizable element can be collapsed/expanded using the `show`, `hide` and `toggle` APIs
 *
 * The resizable elements trigger a panelCollapsed and panelExpanded event when the panel toggles
 * between visible and invisible
 */
define(function (require, exports, module) {
    "use strict";

    var DIRECTION_VERTICAL = "vert";
    var DIRECTION_HORIZONTAL = "horz";

    var POSITION_TOP = "top";
    var POSITION_BOTTOM = "bottom";
    var POSITION_LEFT = "left";
    var POSITION_RIGHT = "right";

    // Minimum size (height or width) for autodiscovered resizable panels
    var DEFAULT_MIN_SIZE = 100;

    // Load dependent modules
    var AppInit                 = require("utils/AppInit"),
        EditorManager           = require("editor/EditorManager");

    var $mainView;

    /**
     * Shows a resizable element.
     * @param {DOMNode} element Html element to show if possible
     */
    function show(element) {
        var showFunc = $(element).data("show");
        if (showFunc) {
            showFunc.apply(element);
        }
    }

    /**
     * Hides a resizable element.
     * @param {DOMNode} element Html element to hide if possible
     */
    function hide(element) {
        var hideFunc = $(element).data("hide");
        if (hideFunc) {
            hideFunc.apply(element);
        }
    }

    /**
     * Changes the visibility state of a resizable element. The toggle
     * functionality is added when an element is made resizable.
     * @param {DOMNode} element Html element to toggle
     */
    function toggle(element) {
        if ($(element).is(":visible")) {
            hide(element);
        } else {
            show(element);
        }
    }

    /**
     * Adds resizing capabilities to a given html element.
     *
     * Resizing can be configured in two directions:
     *  - Vertical ("vert"): Resizes the height of the element
     *  - Horizontal ("horz"): Resizes the width of the element
     *
     * Resizer handlers can be positioned on the element at:
     *  - Top ("top") or bottom ("bottom") for vertical resizing
     *  - Left ("left") or right ("right") for horizontal resizing
     *
     * A resizable element triggers the following events while resizing:
     *  - panelResizeStarts: When the resize starts
     *  - panelResizeUpdate: When the resize gets updated
     *  - panelResizeEnds: When the resize ends
     *  - panelCollapsed: When the panel gets collapsed (or hidden)
     *  - panelExpanded: When the panel gets expanded (or shown)
     *
     * @param {DOMNode} element Html element which should be made resizable.
     * @param {string} direction The direction of the resize action. Must be "horz" or "vert".
     * @param {string} position The position of the resizer on the element. Can be "top" or "bottom"
     *                          for vertical resizing and "left" or "right" for horizontal resizing.
     * @param {int} minSize Minimum size (width or height) of the element.
     * @param {boolean} collapsable True indicates the panel is collapsable on double click
     *                              on the resizer.
     */
    function makeResizable(element, direction, position, minSize, collapsable) {

        var $resizer            = $('

'),
            $element            = $(element),
            $resizableElement   = $($element.find(".resizable-content:first")[0]),
            $body               = $(window.document.body),
            animationRequest    = null,
            directionProperty   = direction === DIRECTION_HORIZONTAL ? "clientX" : "clientY",
            elementSizeFunction = direction === DIRECTION_HORIZONTAL ? $element.width : $element.height,
            resizerCSSPosition  = direction === DIRECTION_HORIZONTAL ? "left" : "top",
            contentSizeFunction = null;

        minSize = minSize || 0;
        collapsable = collapsable || false;

        $element.prepend($resizer);

        $element.data("show", function () {
            $element.show();

            if (collapsable) {
                $element.prepend($resizer);
                $resizer.css(resizerCSSPosition, "");
            }

            EditorManager.resizeEditor();
            $element.trigger("panelExpanded");
            $element.trigger("panelResizeEnd", [elementSizeFunction.apply($element)]);
        });

        $element.data("hide", function () {
            var elementOffset   = $element.offset(),
                elementSize     = elementSizeFunction.apply($element);

            $element.hide();
            if (collapsable) {
                $resizer.insertBefore($element).css(resizerCSSPosition, elementOffset[resizerCSSPosition] + elementSize);
            }

            EditorManager.resizeEditor();
            $element.trigger("panelCollapsed");
        });

        $resizer.on("mousedown", function (e) {
            var $resizeCont     = $("
"),
                startPosition   = e[directionProperty],
                startSize       = $element.is(":visible") ? elementSizeFunction.apply($element) : 0,
                newSize         = startSize,
                baseSize        = 0,
                doResize        = false,
                isMouseDown     = true;

            $body.append($resizeCont);

            $element.trigger("panelResizeStart", [elementSizeFunction.apply($element)]);

            if ($resizableElement !== undefined) {
                $element.children().not(".horz-resizer, .vert-resizer, .resizable-content").each(function (index, child) {
                    if (direction === DIRECTION_HORIZONTAL) {
                        baseSize += $(child).outerWidth();
                    } else {
                        baseSize += $(child).outerHeight();
                    }
                });

                contentSizeFunction = direction === DIRECTION_HORIZONTAL ? $resizableElement.width : $resizableElement.height;
            }

            animationRequest = window.webkitRequestAnimationFrame(function doRedraw() {
                // only run this if the mouse is down so we don't constantly loop even
                // after we're done resizing.
                if (!isMouseDown) {
                    return;
                }

                if (doResize) {
                    // resize the main element to the new size
                    if ($element.is(":visible")) {
                        elementSizeFunction.apply($element, [newSize]);

                        // if there is a content element, its size is the new size
                        // minus the size of the non-resizable elements
                        if ($resizableElement !== undefined) {
                            contentSizeFunction.apply($resizableElement, [newSize - baseSize]);
                        }

                        if (newSize < 10) {
                            toggle($element);
                        }
                    } else if (newSize > 10) {
                        elementSizeFunction.apply($element, [newSize]);
                        toggle($element);
                        $element.trigger("panelResizeStart", [elementSizeFunction.apply($element)]);
                    }

                    EditorManager.resizeEditor();
                }

                animationRequest = window.webkitRequestAnimationFrame(doRedraw);
            });

            $resizeCont.on("mousemove", function (e) {
                doResize = true;
                // calculate newSize adding to startSize the difference
                // between starting and current position, capped at minSize
                newSize = Math.max(startSize + (startPosition - e[directionProperty]), minSize);
                $element.trigger("panelResizeUpdate", [newSize]);
                e.preventDefault();
            });

            // If the element is marked as collapsable, check for double click
            // to toggle the element visibility
            if (collapsable) {
                $resizeCont.on("mousedown", function (e) {
                    toggle($element);
                });
            }

            function endResize(e) {
                if (isMouseDown) {
                    isMouseDown = false;
                    $element.trigger("panelResizeEnd", [elementSizeFunction.apply($element)]);

                    // We wait 100ms to remove the resizer container to capture a mousedown
                    // on the container that would account for double click
                    setTimeout(function () {
                        $resizeCont.off("mousemove");
                        $resizeCont.off("mousedown");
                        $resizeCont.remove();
                    }, 100);
                }
            }

            $resizeCont.one("mouseup", endResize);
            $resizeCont.mouseleave(endResize);

            e.preventDefault();
        });
    }

    // Scan DOM for horz-resizable and vert-resizable classes and make them resizable
    AppInit.htmlReady(function () {
        $mainView = $(".main-view");

        $(".vert-resizable").each(function (index, element) {

            if ($(element).hasClass("top-resizer")) {
                makeResizable(element, DIRECTION_VERTICAL, POSITION_TOP, DEFAULT_MIN_SIZE, $(element).hasClass("collapsable"));
            }

            //if ($(element).hasClass("bottom-resizer")) {
            //    makeResizable(element, DIRECTION_VERTICAL, POSITION_BOTTOM, DEFAULT_MIN_SIZE);
            //}
        });

        $(".horz-resizable").each(function (index, element) {

            //if ($(element).hasClass("left-resizer")) {
            //    makeResizable(element, DIRECTION_HORIZONTAL, POSITION_LEFT, DEFAULT_MIN_SIZE);
            //}

            //if ($(element).hasClass("right-resizer")) {
            //    makeResizable(element, DIRECTION_HORIZONTAL, POSITION_RIGHT, DEFAULT_MIN_SIZE);
            //}
        });
    });

    exports.makeResizable = makeResizable;
    exports.toggle = toggle;
    exports.show = show;
    exports.hide = hide;
});<commit_msg>Review changes<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, window, setTimeout */

/**
 * Resizer is a Module utility to inject resizing capabilities to any element
 * inside Brackets.
 *
 * On initialization, Resizer discovers all nodes tagged as "vert-resizable"
 * and "horz-resizable" to add the resizer handler. Additionally, "top-resizer",
 * "bottom-resizer", "left-resizer" and "right-resizer" classes control the
 * position of the resizer on the element.
 *
 * An element can be made resizable at any time using the `makeResizable` API
 *
 * The resizable elements trigger a panelResizeStart, panelResizeUpdate and panelResizeEnd
 * event that can be used to create performance optimizations (such as hiding/showing elements
 * while resizing), custom or internal resizes and save the final resized value into local
 * storage for example.
 *
 * A resizable element can be collapsed/expanded using the `show`, `hide` and `toggle` APIs
 *
 * The resizable elements trigger a panelCollapsed and panelExpanded event when the panel toggles
 * between visible and invisible
 */
define(function (require, exports, module) {
    "use strict";

    var DIRECTION_VERTICAL = "vert";
    var DIRECTION_HORIZONTAL = "horz";

    var POSITION_TOP = "top";
    var POSITION_BOTTOM = "bottom";
    var POSITION_LEFT = "left";
    var POSITION_RIGHT = "right";

    // Minimum size (height or width) for autodiscovered resizable panels
    var DEFAULT_MIN_SIZE = 100;

    // Load dependent modules
    var AppInit                 = require("utils/AppInit"),
        EditorManager           = require("editor/EditorManager");

    var $mainView;

    /**
     * Shows a resizable element.
     * @param {DOMNode} element Html element to show if possible
     */
    function show(element) {
        var showFunc = $(element).data("show");
        if (showFunc) {
            showFunc.apply(element);
        }
    }

    /**
     * Hides a resizable element.
     * @param {DOMNode} element Html element to hide if possible
     */
    function hide(element) {
        var hideFunc = $(element).data("hide");
        if (hideFunc) {
            hideFunc.apply(element);
        }
    }

    /**
     * Changes the visibility state of a resizable element. The toggle
     * functionality is added when an element is made resizable.
     * @param {DOMNode} element Html element to toggle
     */
    function toggle(element) {
        if ($(element).is(":visible")) {
            hide(element);
        } else {
            show(element);
        }
    }

    /**
     * Adds resizing capabilities to a given html element.
     *
     * Resizing can be configured in two directions:
     *  - Vertical ("vert"): Resizes the height of the element
     *  - Horizontal ("horz"): Resizes the width of the element
     *
     * Resizer handlers can be positioned on the element at:
     *  - Top ("top") or bottom ("bottom") for vertical resizing
     *  - Left ("left") or right ("right") for horizontal resizing
     *
     * A resizable element triggers the following events while resizing:
     *  - panelResizeStart: When the resize starts
     *  - panelResizeUpdate: When the resize gets updated
     *  - panelResizeEnds: When the resize ends
     *  - panelCollapsed: When the panel gets collapsed (or hidden)
     *  - panelExpanded: When the panel gets expanded (or shown)
     *
     * @param {DOMNode} element Html element which should be made resizable.
     * @param {string} direction The direction of the resize action. Must be "horz" or "vert".
     * @param {string} position The position of the resizer on the element. Can be "top" or "bottom"
     *                          for vertical resizing and "left" or "right" for horizontal resizing.
     * @param {int} minSize Minimum size (width or height) of the element.
     * @param {boolean} collapsable True indicates the panel is collapsable on double click
     *                              on the resizer.
     */
    function makeResizable(element, direction, position, minSize, collapsable) {

        var $resizer            = $('

'),
            $element            = $(element),
            $resizableElement   = $($element.find(".resizable-content:first")[0]),
            $body               = $(window.document.body),
            animationRequest    = null,
            directionProperty   = direction === DIRECTION_HORIZONTAL ? "clientX" : "clientY",
            elementSizeFunction = direction === DIRECTION_HORIZONTAL ? $element.width : $element.height,
            resizerCSSPosition  = direction === DIRECTION_HORIZONTAL ? "left" : "top",
            contentSizeFunction = null;

        minSize = minSize || 0;
        collapsable = collapsable || false;

        $element.prepend($resizer);

        $element.data("show", function () {
            $element.show();

            if (collapsable) {
                $element.prepend($resizer);
                $resizer.css(resizerCSSPosition, "");
            }

            EditorManager.resizeEditor();
            $element.trigger("panelExpanded");
        });

        $element.data("hide", function () {
            var elementOffset   = $element.offset(),
                elementSize     = elementSizeFunction.apply($element);

            $element.hide();
            if (collapsable) {
                $resizer.insertBefore($element).css(resizerCSSPosition, elementOffset[resizerCSSPosition] + elementSize);
            }

            EditorManager.resizeEditor();
            $element.trigger("panelCollapsed");
        });

        $resizer.on("mousedown", function (e) {
            var $resizeCont     = $("
"),
                startPosition   = e[directionProperty],
                startSize       = $element.is(":visible") ? elementSizeFunction.apply($element) : 0,
                newSize         = startSize,
                baseSize        = 0,
                doResize        = false,
                isMouseDown     = true;

            $body.append($resizeCont);

            $element.trigger("panelResizeStart", [elementSizeFunction.apply($element)]);

            if ($resizableElement !== undefined) {
                $element.children().not(".horz-resizer, .vert-resizer, .resizable-content").each(function (index, child) {
                    if (direction === DIRECTION_HORIZONTAL) {
                        baseSize += $(child).outerWidth();
                    } else {
                        baseSize += $(child).outerHeight();
                    }
                });

                contentSizeFunction = direction === DIRECTION_HORIZONTAL ? $resizableElement.width : $resizableElement.height;
            }

            animationRequest = window.webkitRequestAnimationFrame(function doRedraw() {
                // only run this if the mouse is down so we don't constantly loop even
                // after we're done resizing.
                if (!isMouseDown) {
                    return;
                }

                if (doResize) {
                    // resize the main element to the new size
                    if ($element.is(":visible")) {
                        elementSizeFunction.apply($element, [newSize]);

                        // if there is a content element, its size is the new size
                        // minus the size of the non-resizable elements
                        if ($resizableElement !== undefined) {
                            contentSizeFunction.apply($resizableElement, [newSize - baseSize]);
                        }

                        if (newSize < 10) {
                            toggle($element);
                        }
                    } else if (newSize > 10) {
                        elementSizeFunction.apply($element, [newSize]);
                        toggle($element);
                        $element.trigger("panelResizeStart", [elementSizeFunction.apply($element)]);
                    }

                    EditorManager.resizeEditor();
                }

                animationRequest = window.webkitRequestAnimationFrame(doRedraw);
            });

            $resizeCont.on("mousemove", function (e) {
                doResize = true;
                // calculate newSize adding to startSize the difference
                // between starting and current position, capped at minSize
                newSize = Math.max(startSize + (startPosition - e[directionProperty]), minSize);
                $element.trigger("panelResizeUpdate", [newSize]);
                e.preventDefault();
            });

            // If the element is marked as collapsable, check for double click
            // to toggle the element visibility
            if (collapsable) {
                $resizeCont.on("mousedown", function (e) {
                    toggle($element);
                });
            }

            function endResize(e) {
                if (isMouseDown) {
                    isMouseDown = false;
                    $element.trigger("panelResizeEnd", [elementSizeFunction.apply($element)]);

                    // We wait 100ms to remove the resizer container to capture a mousedown
                    // on the container that would account for double click
                    setTimeout(function () {
                        $resizeCont.off("mousemove");
                        $resizeCont.off("mousedown");
                        $resizeCont.remove();
                    }, 100);
                }
            }

            $resizeCont.one("mouseup", endResize);
            $resizeCont.mouseleave(endResize);

            e.preventDefault();
        });
    }

    // Scan DOM for horz-resizable and vert-resizable classes and make them resizable
    AppInit.htmlReady(function () {
        $mainView = $(".main-view");

        $(".vert-resizable").each(function (index, element) {

            if ($(element).hasClass("top-resizer")) {
                makeResizable(element, DIRECTION_VERTICAL, POSITION_TOP, DEFAULT_MIN_SIZE, $(element).hasClass("collapsable"));
            }

            //if ($(element).hasClass("bottom-resizer")) {
            //    makeResizable(element, DIRECTION_VERTICAL, POSITION_BOTTOM, DEFAULT_MIN_SIZE);
            //}
        });

        $(".horz-resizable").each(function (index, element) {

            //if ($(element).hasClass("left-resizer")) {
            //    makeResizable(element, DIRECTION_HORIZONTAL, POSITION_LEFT, DEFAULT_MIN_SIZE);
            //}

            //if ($(element).hasClass("right-resizer")) {
            //    makeResizable(element, DIRECTION_HORIZONTAL, POSITION_RIGHT, DEFAULT_MIN_SIZE);
            //}
        });
    });

    exports.makeResizable = makeResizable;
    exports.toggle = toggle;
    exports.show = show;
    exports.hide = hide;
});<|endoftext|>


<commit_before><commit_msg>use replyTo instead of from when email<commit_after><|endoftext|>


<commit_before>const currentDate = new Date();
const webExperienceYears =  currentDate.getFullYear() - 2012;
export const name = 'Kevin To';
export const role = 'UI Engineering Team Lead';
export const work = 'NurtureCloud in Sydney, AU';
export const about = `

    My previous roles include Front-end Engineer at Upside, Lead Front-end Developer at Okendo and Front-end Developer, Team Lead at Freelancer.com.

  I build stuff for the web and iOS with a background in design — I studied and worked as a Graphic Designer for about 6 years and now enjoy building accessible and maintainable web and iOS apps.

  I've been working with the web for about ${webExperienceYears} years with a heavy focus on Angular, TypeScript and RxJS. And for the past year and a bit, iOS using Swift and SwiftUI along with RxSwift and Combine.

    You can find some of my stuff on CodePen and GitHub.

    When I’m not sat in front of the computer screen, I build and fly drones, tinker with 3D printing and electronics projects, work on my 4WD, go camping, take photos, and travel!

    Feel free to say g’day at hello@kevinto.me or connect with me on LinkedIn.

`;
<commit_msg>Only wrap link around "photo"<commit_after>const currentDate = new Date();
const webExperienceYears =  currentDate.getFullYear() - 2012;
export const name = 'Kevin To';
export const role = 'UI Engineering Team Lead';
export const work = 'NurtureCloud in Sydney, AU';
export const about = `

    My previous roles include Front-end Engineer at Upside, Lead Front-end Developer at Okendo and Front-end Developer, Team Lead at Freelancer.com.

  I build stuff for the web and iOS with a background in design — I studied and worked as a Graphic Designer for about 6 years and now enjoy building accessible and maintainable web and iOS apps.

  I've been working with the web for about ${webExperienceYears} years with a heavy focus on Angular, TypeScript and RxJS. And for the past year and a bit, iOS using Swift and SwiftUI along with RxSwift and Combine.

    You can find some of my stuff on CodePen and GitHub.

    When I’m not sat in front of the computer screen, I build and fly drones, tinker with 3D printing and electronics projects, work on my 4WD, go camping, take photos, and travel!

    Feel free to say g’day at hello@kevinto.me or connect with me on LinkedIn.

`;
<|endoftext|>


<commit_before><commit_msg>deleted empty line<commit_after><|endoftext|>


<commit_before><commit_msg>Update index.js<commit_after><|endoftext|>


<commit_before>/* global window */
import axios from 'axios'
import qs from 'qs'
import jsonp from 'jsonp'
import cloneDeep from 'lodash.clonedeep'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import { YQL, CORS } from './config'

const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options

  const cloneData = cloneDeep(data)

  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      [domin] = url.match(/[a-zA-z]+:\/\/[^/]*/)
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put':
      return axios.put(url, cloneData)
    case 'patch':
      return axios.patch(url, cloneData)
    default:
      return axios(options)
  }
}

export default function request (options) {
  if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`
    if (window.location.origin !== origin) {
      if (CORS && CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (YQL && YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }

  return fetch(options).then((response) => {
    const { statusText, status } = response
    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }
    return Promise.resolve({
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    })
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status
      msg = data.message || statusText
    } else {
      statusCode = 600
      msg = error.message || 'Network Error'
    }

    /* eslint-disable */
    return Promise.reject({ success: false, statusCode, message: msg })
  })
}
<commit_msg>Rename variable name  domin  to domain<commit_after>/* global window */
import axios from 'axios'
import qs from 'qs'
import jsonp from 'jsonp'
import cloneDeep from 'lodash.clonedeep'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import { YQL, CORS } from './config'

const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options

  const cloneData = cloneDeep(data)

  try {
    let domain = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      [domain] = url.match(/[a-zA-z]+:\/\/[^/]*/)
      url = url.slice(domain.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domain + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put':
      return axios.put(url, cloneData)
    case 'patch':
      return axios.patch(url, cloneData)
    default:
      return axios(options)
  }
}

export default function request (options) {
  if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`
    if (window.location.origin !== origin) {
      if (CORS && CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (YQL && YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }

  return fetch(options).then((response) => {
    const { statusText, status } = response
    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }
    return Promise.resolve({
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    })
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status
      msg = data.message || statusText
    } else {
      statusCode = 600
      msg = error.message || 'Network Error'
    }

    /* eslint-disable */
    return Promise.reject({ success: false, statusCode, message: msg })
  })
}
<|endoftext|>


<commit_before><commit_msg>Added number support<commit_after><|endoftext|>


<commit_before>/* eslint-disable max-len */
/*
 * From: http://www.unicode.org/Public/emoji/1.0//emoji-data.txt
 *
 * Copy first column
 * const codes = `PASTE HERE`
 * const ints = codes.split("\n").map(c => parseInt(c, 16)).filter(int => int >= 8986)
 * const ranges = ints.sort((a,b) => a - b).reduce((arr, code) => (code - (arr[arr.length - 1] || {}).end <= 1) ? (arr[arr.length-1].end = code) && arr : arr.concat({start:code, end:code}), [])
 * ranges.map(range => range.start === range.end ? range.start.toString(16) : `${range.start.toString(16)}..${range.end.toString(16)}`).join(",").toUpperCase()
 * */

const emojiCodes = '231A..231B,2328,23CF,23E9..23F3,23F8..23FA,24C2,25AA..25AB,25B6,25C0,25FB..25FE,2600..2604,260E,2611,2614..2615,2618,261D,2620,2622..2623,2626,262A,262E..262F,2638..263A,2648..2653,2660,2663,2665..2666,2668,267B,267F,2692..2694,2696..2697,2699,269B..269C,26A0..26A1,26AA..26AB,26B0..26B1,26BD..26BE,26C4..26C5,26C8,26CE..26CF,26D1,26D3..26D4,26E9..26EA,26F0..26F5,26F7..26FA,26FD,2702,2705,2708..270D,270F,2712,2714,2716,271D,2721,2728,2733..2734,2744,2747,274C,274E,2753..2755,2757,2763..2764,2795..2797,27A1,27B0,27BF,2934..2935,2B05..2B07,2B1B..2B1C,2B50,2B55,3030,303D,3297,3299,1F004,1F0CF,1F170..1F171,1F17E..1F17F,1F18E,1F191..1F19A,1F1E6..1F1FF,1F201..1F202,1F21A,1F22F,1F232..1F23A,1F250..1F251,1F300..1F321,1F324..1F393,1F396..1F397,1F399..1F39B,1F39E..1F3F0,1F3F3..1F3F5,1F3F7..1F4FD,1F4FF..1F53D,1F549..1F54E,1F550..1F567,1F56F..1F570,1F573..1F579,1F587,1F58A..1F58D,1F590,1F595..1F596,1F5A5,1F5A8,1F5B1..1F5B2,1F5BC,1F5C2..1F5C4,1F5D1..1F5D3,1F5DC..1F5DE,1F5E1,1F5E3,1F5EF,1F5F3,1F5FA..1F64F,1F680..1F6C5,1F6CB..1F6D0,1F6E0..1F6E5,1F6E9,1F6EB..1F6EC,1F6F0,1F6F3,1F910..1F918,1F980..1F984,1F9C0'
const emojiList = emojiCodes.split(',').reduce((arr, range) => {
  const matches = /(\w+)\.\.(\w+)/.exec(range)
  if (matches) {
    const from = parseInt(matches[1], 16)
    const to = parseInt(matches[2], 16)
    return arr.concat(...Array((to - from) + 1).fill()
      .map((_, i) => from + i))
  } else {
    return arr.concat(parseInt(range, 16))
  }
}, [])

/* Some high number, usually 9-digit base-10. Map it to base-😎 */
const toEmoji = code => {
  const lastDigit = String.fromCodePoint(emojiList[code % emojiList.length])
  return code > emojiList.length ? `${toEmoji(Math.floor(code / emojiList.length))}${String.fromCodePoint(0x2006)}${lastDigit}` : lastDigit
}

export default toEmoji
<commit_msg>removing the emoji generator<commit_after><|endoftext|>


<commit_before><commit_msg>Options made optional in most API.<commit_after><|endoftext|>


<commit_before><commit_msg>fix MIME correction in File for 'text/...'<commit_after><|endoftext|>


<commit_before>import { STRING, INTEGER } from 'sequelize'

function create (database) {
  return database.define('boleto', {
    instructions: {
      type: STRING,
      allowNull: false
    },

    barcode: {
      type: INTEGER,
      allowNull: false
    }
  })
}

export default { create }
<commit_msg>Add boleto model<commit_after>import { STRING, INTEGER, ENUM, TEXT, DATE } from 'sequelize'
import { defaultCuidValue } from '../lib/cuid'

function create (database) {
  return database.define('boleto', {
    id: {
      type: STRING,
      primaryKey: true,
      allowNull: false,
      defaultValue: defaultCuidValue('bol_')
    },

    queue_id: {
      type: INTEGER,
      allowNull: false
    },

    status: {
      type: ENUM,
      allowNull: false,
      values: ['pending_registration', 'registered'],
      defaultValue: 'pending_registration'
    },

    expiration_date: {
      type: DATE,
      allowNull: false
    },

    amount: {
      type: INTEGER,
      allowNull: false
    },

    paid_amount: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0
    },

    instructions: {
      type: TEXT
    },

    issuer: {
      type: STRING,
      allowNull: false
    },

    issuer_id: {
      type: STRING
    },

    title_id: {
      type: INTEGER,
      allowNull: false,
      autoIncrement: true
    },

    payer_name: {
      type: STRING,
      allowNull: false
    },

    payer_document_type: {
      type: ENUM,
      allowNull: false,
      values: ['cpf', 'cnpj'],
      defaultValue: 'cpf'
    },

    payer_document_number: {
      type: STRING,
      allowNull: false
    }
  }, {
    indexes: [
      { fields: ['queue_id'] },
      { fields: ['status'] }
    ]
  })
}

function associate (boleto, { queue }) {
  boleto.belongsTo(queue)
}

export default {
  associate,
  create
}
<|endoftext|>


<commit_before>/** ---------------------------------------------------------------------------
 *  SonosJS
 *  Copyright 2013 Dennis Alund
 *  http://github.com/oddbit/sonosjs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ------------------------------------------------------------------------- */

define(function (require) {
        "use strict";

        var xmlParser = require("utils/xml");

        function device(opts) {
            opts = opts || {};
            var that = opts;

            var lastUpdated = Date.now();
            var address; // Only IP and port
            var infoUrl; // Full URL to the service

            that.address = "";

            that.getUniqueServiceName = function () {
                return [that.id, that.device.type].join("::");
            };

            that.getLastUpdated = function () {
                return lastUpdated;
            };

            that.getInfoUrl = function () {
                return infoUrl;
            };

            that.setInfoUrl = function (deviceInfoUrl) {
                infoUrl = deviceInfoUrl || "";
                address = extractHostFromUrl(infoUrl);
                that.address = address;
            };

            that.getMediaStateUrl = function () {
                return formatServiceUrl("/MediaRenderer/AVTransport/Control");
            };

            function extractHostFromUrl(url) {
                return url.replace(/http[s]?:\/\/([^\/]+).*/g, "$1");
            }

            function formatServiceUrl(serviceUri) {
                return ["http://", address,  serviceUri].join("");
            }

            return that;
        }

        device.fromXml = function (xml) {
            var xmlDocument = xmlParser.document(xml);
            var opts = {
                id: xmlDocument.getValue("UDN"),
                displayName: xmlDocument.getValue("displayName"),
                speakerSize: xmlDocument.getValue("internalSpeakerSize"),
                device: {
                    type: xmlDocument.getValue("deviceType"),
                    icons: xmlDocument.getValueList("iconList.url")
                },
                room: {
                    name: xmlDocument.getValue("roomName")
                }
            };

            return device(opts);
        };

        return device;
    }
)
;
<commit_msg>Renaming "room" to more generic name "group"<commit_after>/** ---------------------------------------------------------------------------
 *  SonosJS
 *  Copyright 2013 Dennis Alund
 *  http://github.com/oddbit/sonosjs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ------------------------------------------------------------------------- */

define(function (require) {
        "use strict";

        var xmlParser = require("utils/xml");

        function device(opts) {
            opts = opts || {};
            var that = opts;

            var lastUpdated = Date.now();
            var address; // Only IP and port
            var infoUrl; // Full URL to the service

            that.address = "";

            that.getUniqueServiceName = function () {
                return [that.id, that.device.type].join("::");
            };

            that.getLastUpdated = function () {
                return lastUpdated;
            };

            that.getInfoUrl = function () {
                return infoUrl;
            };

            that.setInfoUrl = function (deviceInfoUrl) {
                infoUrl = deviceInfoUrl || "";
                address = extractHostFromUrl(infoUrl);
                that.address = address;
            };

            that.getMediaStateUrl = function () {
                return formatServiceUrl("/MediaRenderer/AVTransport/Control");
            };

            function extractHostFromUrl(url) {
                return url.replace(/http[s]?:\/\/([^\/]+).*/g, "$1");
            }

            function formatServiceUrl(serviceUri) {
                return ["http://", address,  serviceUri].join("");
            }

            return that;
        }

        device.fromXml = function (xml) {
            var xmlDocument = xmlParser.document(xml);
            var opts = {
                id: xmlDocument.getValue("UDN"),
                displayName: xmlDocument.getValue("displayName"),
                speakerSize: xmlDocument.getValue("internalSpeakerSize"),
                device: {
                    type: xmlDocument.getValue("deviceType"),
                    icons: xmlDocument.getValueList("iconList.url")
                },
                group: {
                    name: xmlDocument.getValue("roomName")
                }
            };

            return device(opts);
        };

        return device;
    }
)
;
<|endoftext|>


<commit_before>import glob from 'glob'
import Router from 'koa-router'
import convert from 'koa-convert'

exports = module.exports = function initModules(app) {
  glob(`${__dirname}/*`, { ignore: '**/index.js' }, (err, matches) => {
    if (err) { throw err }

    matches.forEach((mod) => {
      const routerConfig = require(`${mod}/router`).default
      const router = new Router({ prefix: routerConfig.base })

      for (const [key, props] of Object.entries(routerConfig)) {
        if (key === 'base') { continue }

        const {
          method = '',
          route = '',
          middleware = [],
          controller
        } = props

        router[method.toLowerCase()](route, ...middleware, controller)

        app
          .use(router.routes())
          .use(router.allowedMethods())
      }
    })
  })
}
<commit_msg>Update router generation with `handlers`<commit_after>import glob from 'glob'
import Router from 'koa-router'

exports = module.exports = function initModules(app) {
  glob(`${__dirname}/*`, { ignore: '**/index.js' }, (err, matches) => {
    if (err) { throw err }

    matches.forEach((mod) => {
      const routerConfig = require(`${mod}/router`).default
      const router = new Router({ prefix: routerConfig.base })

      for (const [key, props] of Object.entries(routerConfig)) {
        if (key === 'base') { continue }

        const {
          method = '',
          route = '',
          handlers = []
        } = props

        router[method.toLowerCase()](route, ...handlers)

        app
          .use(router.routes())
          .use(router.allowedMethods())
      }
    })
  })
}
<|endoftext|>


<commit_before>export {all}          from './list/all';
export {any}          from './list/any';
export {append}       from './list/append';
export {concat}       from './list/concat';
export {contains}     from './list/contains';
export {difference}   from './list/difference';
export {filter}       from './list/filter';
export {head}         from './list/head';
export {indexOf}      from './list/indexOf';
export {init}         from './list/init';
export {intersection} from './list/intersection';
export {groupBy}      from './list/groupBy';
export {map}          from './list/map';
export {none}         from './list/none';
export {last}         from './list/last';
export {prepend}      from './list/prepend';
export {pluck}        from './list/pluck';
export {range}        from './list/range';
export {reduced}      from './list/reduced';
export {reject}       from './list/reject';
export {remove}       from './list/remove';
export {reduce}       from './list/reduce';
export {reduceRight}  from './list/reduceRight';
export {repeat}       from './list/repeat';
export {reverse}      from './list/reverse';
export {scan}         from './list/scan';
export {slice}        from './list/slice';
export {sort}         from './list/sort';
export {splitEvery}   from './list/splitEvery';
export {tail}         from './list/tail';
export {times}        from './list/times';
export {take}         from './list/take';
export {takeLast}     from './list/takeLast';
export {takeLastWhile}from './list/takeLastWhile';
export {takeWhile}    from './list/takeWhile';
export {transduce}    from './list/transduce';
export {unfold}       from './list/unfold';
export {uniq}         from './list/uniq';
export {uniqBy}       from './list/uniqBy';
export {uniqWith}     from './list/uniqWith';
export {unnest}       from './list/unnest';
export {update}       from './list/update';
export {without}      from './list/without';
export {xprod}        from './list/xprod';
export {zip}          from './list/zip';
export {zipObj}       from './list/zipObj';
export {zipWith}      from './list/zipWith';
<commit_msg>refactor(): reorder imports<commit_after>export {all}          from './list/all';
export {any}          from './list/any';
export {append}       from './list/append';
export {concat}       from './list/concat';
export {contains}     from './list/contains';
export {difference}   from './list/difference';
export {filter}       from './list/filter';
export {head}         from './list/head';
export {indexOf}      from './list/indexOf';
export {init}         from './list/init';
export {intersection} from './list/intersection';
export {groupBy}      from './list/groupBy';
export {map}          from './list/map';
export {none}         from './list/none';
export {last}         from './list/last';
export {pluck}        from './list/pluck';
export {prepend}      from './list/prepend';
export {range}        from './list/range';
export {reduced}      from './list/reduced';
export {reject}       from './list/reject';
export {remove}       from './list/remove';
export {reduce}       from './list/reduce';
export {reduceRight}  from './list/reduceRight';
export {repeat}       from './list/repeat';
export {reverse}      from './list/reverse';
export {scan}         from './list/scan';
export {slice}        from './list/slice';
export {sort}         from './list/sort';
export {splitEvery}   from './list/splitEvery';
export {tail}         from './list/tail';
export {times}        from './list/times';
export {take}         from './list/take';
export {takeLast}     from './list/takeLast';
export {takeLastWhile}from './list/takeLastWhile';
export {takeWhile}    from './list/takeWhile';
export {transduce}    from './list/transduce';
export {unfold}       from './list/unfold';
export {uniq}         from './list/uniq';
export {uniqBy}       from './list/uniqBy';
export {uniqWith}     from './list/uniqWith';
export {unnest}       from './list/unnest';
export {update}       from './list/update';
export {without}      from './list/without';
export {xprod}        from './list/xprod';
export {zip}          from './list/zip';
export {zipObj}       from './list/zipObj';
export {zipWith}      from './list/zipWith';
<|endoftext|>


<commit_before>(function(window) {
    'use strict';
    var Monaco = window.Monaco = (window.Monaco || {});

    /* -- ROUTER ----------------------------------------------------------- */
    Monaco.Router.prototype = _.extend(Monaco.Router.prototype, {
        // return the regexp option of the specific router if available
        // otherwhise undefined will be returned
        _routeConstraints : function(route) {
            var value = this._routes[route];
            if (value && _.isArray(value) && value.length > 1 && _.isObject(value[1])) {
                return value[1].regexp;
            }
            return void 0;
        },

        // override the original Backbone method to deal with the regex constraints
        _routeToRegExp : function(route)
            var constraints = this._routeConstraints(route);
            route = route.replace(escapeRegExp, '\\$&')
                         .replace(optionalParam, '(?:$1)?')
                         .replace(namedParam, function(match, optional){
                            // this `if` is the only difference from the original method from Backbone
                            // todo: find a way of getting the route regexp constranits
                            if (constraints && constraints[match.substr(1)]) {
                                var reStr = constraints[match.substr(1)].toString();
                                return reStr.slice(1, reStr.lastIndexOf('/'));
                            }
                            return optional ? match : '([^\/]+)';
                         })
                         .replace(splatParam, '(.*?)');
            return new RegExp('^' + route + '$');
        },

        // internal list of filters
        _filters : [],

        // adds a filter method to list of filters
        addFilter : function(name, callback) {
            var filter = {};
            filter[name] = callback;
            // todo: verify if the filter already exists on the array and throw an error
            this._filters.push(filter);
        },

        // wraps one or more controllers into one or more filters
        // use this method to execute post processing and pre processing code
        applyFilter: function(filters, controllers) {
            var originalController;

            // wrapp each controller with the list of filters provided
            for (var i = 0, l = controllers.length; i < l; i++) {
                for (var a=0, b=filters.length; a < b; a++) {
                    originalController = this.prototype[controllers[i]];
                    this.prototype[controllers[i]] = function() {
                        return this.prototype._filters[filters[a]].call(this, originalController, arguments);
                    }
                }
            }
        },

        // returns the original route definition based on the url name informed
        _getByName: function(name) {
            var possibleRoutes = _.map(this._routes, function(options, route) {
                if (_.isArray(options) && options.length > 1) {
                    if ((_.isString(options[1]) && options[1] === name) ||
                        (_.isObject(options[1]) && options.name === name)) {
                        return route;
                    }
                }
                return null;
            });

            route = _.compact(possibleRoutes);
            if (route.length > 0) {
                return route[0];
            }
            return false;
        },

        // returns a reverse url based on the url name and parameters passed to it.
        // This url won't be validated against the regexp contrains even if available.
        // Neighter it will validate if you provided enough parameters, the missing
        // parameters will be displayed as the original url definition.
        reverse: function(name, params) {
            var url = '';
            params = params || {};
            if (!name) {
                throw new Error('required `name` parameter for `reverse` method');
            }

            url = this._getByName(name);
            _.each(params, function(value, key) {
                url = url.replace(':'+key, value);
            });

            return url;
        }
    };
}(window));<commit_msg>fixed issues with monaco router<commit_after>(function(window, _, Backbone) {
    'use strict';
    var Monaco = window.Monaco = (window.Monaco || {});

    /* -- ROUTER ----------------------------------------------------------- */
    // Cached regular expressions for matching named param parts and splatted
    // parts of route strings.
    var optionalParam = /\((.*?)\)/g;
    var namedParam    = /(\(\?)?:\w+/g;
    var splatParam    = /\*\w+/g;
    var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

    // Monaco.Router.prototype = _.extend(Monaco.Router.prototype, {
    _.extend(Monaco.Router.prototype, {
        // return the regexp option of the specific router if available
        // otherwhise undefined will be returned
        _routeConstraints : function(routeKey) {
            // var value = this._routes[route];
            var route = _.find(this._routes, function(route) {
                return route.key === routeKey;
            });
            if (route && route.value && _.isArray(route.value) && route.value.length > 1 && _.isObject(route.value[1])) {
                return route.value[1].regexp;
            }
            return void 0;
        },

        // override the original Backbone method to deal with the regex constraints
        _routeToRegExp : function(route) {
            var constraints = this._routeConstraints(route);
            route = route.replace(escapeRegExp, '\\$&')
                         .replace(optionalParam, '(?:$1)?')
                         .replace(namedParam, function(match, optional){
                            // this `if` is the only difference from the original method from Backbone
                            if (constraints && constraints[match.substr(1)]) {
                                var reStr = constraints[match.substr(1)].toString();
                                return '(' + reStr.slice(1, reStr.lastIndexOf('/')) + ')';
                            }
                            return optional ? match : '([^\/]+)';
                         })
                         .replace(splatParam, '(.*?)');
            return new RegExp('^' + route + '$');
        },

        filter : function(filters, controller) {
            for (var i = (filters.length - 1) , l = 0; i >= l; i-- ) {
                var next = controller;
                controller = this._wrapFilter(filters[i], next);
            }

            return controller;
        },

        // internal list of filters
        _filters : {},

        _wrapFilter: function(filter, next) {
            return _.bind(function() {
                this._filters[filter].call(this, next, arguments);
            }, this);
        },

        // adds a filter method to list of filters
        addFilter : function(name, callback) {
            if (this._filters[name]) {
                throw new Error('This filter alread exists: ' + name);
            }
            this._filters[name] = callback;
        },

        // returns the original route definition based on the url name informed
        _getByName: function(name) {
            var possibleRoutes = _.map(this._routes, function(options, route) {
                if (_.isArray(options) && options.length > 1) {
                    if ((_.isString(options[1]) && options[1] === name) ||
                        (_.isObject(options[1]) && options.name === name)) {
                        return route;
                    }
                }
                return null;
            });

            route = _.compact(possibleRoutes);
            if (route.length > 0) {
                return route[0];
            }
            return false;
        },

        // returns a reverse url based on the url name and parameters passed to it.
        // This url won't be validated against the regexp contrains even if available.
        // Neighter it will validate if you provided enough parameters, the missing
        // parameters will be displayed as the original url definition.
        reverse: function(name, params) {
            var url = '';
            params = params || {};
            if (!name) {
                throw new Error('required `name` parameter for `reverse` method');
            }

            url = this._getByName(name);
            _.each(params, function(value, key) {
                url = url.replace(':'+key, value);
            });

            return url;
        }
    });
}(window, window._, window.Backbone));<|endoftext|>


<commit_before>'use strict';

angular.module('mgcrea.ngStrap.navbar', [])

  .provider('$navbar', function() {

    var defaults = this.defaults = {
      activeClass: 'active',
      routeAttr: 'data-match-route',
      strict: false
    };

    this.$get = function() {
      return {defaults: defaults};
    };

  })

  .directive('bsNavbar', function($window, $location, $navbar) {

    var defaults = $navbar.defaults;

    return {
      restrict: 'A',
      link: function postLink(scope, element, attr, controller) {

        // Directive options
        var options = angular.copy(defaults);
        angular.forEach(Object.keys(defaults), function(key) {
          if(angular.isDefined(attr[key])) options[key] = attr[key];
        });

        // Watch for the $location
        scope.$watch(function() {

          return $location.path();

        }, function(newValue, oldValue) {

          var liElements = element[0].querySelectorAll('li[' + options.routeAttr + ']');

          angular.forEach(liElements, function(li) {

            var liElement = angular.element(li);
            var pattern = liElement.attr(options.routeAttr).replace('/', '\\/');
            if(options.strict) {
              pattern = '^' + pattern + '$';
            }
            var regexp = new RegExp(pattern, ['i']);

            if(regexp.test(newValue)) {
              liElement.addClass(options.activeClass);
            } else {
              liElement.removeClass(options.activeClass);
            }

          });

        });

      }

    };

  });
<commit_msg>fix(navbar): use string for RegExp flags (fixes #1547)<commit_after>'use strict';

angular.module('mgcrea.ngStrap.navbar', [])

  .provider('$navbar', function() {

    var defaults = this.defaults = {
      activeClass: 'active',
      routeAttr: 'data-match-route',
      strict: false
    };

    this.$get = function() {
      return {defaults: defaults};
    };

  })

  .directive('bsNavbar', function($window, $location, $navbar) {

    var defaults = $navbar.defaults;

    return {
      restrict: 'A',
      link: function postLink(scope, element, attr, controller) {

        // Directive options
        var options = angular.copy(defaults);
        angular.forEach(Object.keys(defaults), function(key) {
          if(angular.isDefined(attr[key])) options[key] = attr[key];
        });

        // Watch for the $location
        scope.$watch(function() {

          return $location.path();

        }, function(newValue, oldValue) {

          var liElements = element[0].querySelectorAll('li[' + options.routeAttr + ']');

          angular.forEach(liElements, function(li) {

            var liElement = angular.element(li);
            var pattern = liElement.attr(options.routeAttr).replace('/', '\\/');
            if(options.strict) {
              pattern = '^' + pattern + '$';
            }
            var regexp = new RegExp(pattern, 'i');

            if(regexp.test(newValue)) {
              liElement.addClass(options.activeClass);
            } else {
              liElement.removeClass(options.activeClass);
            }

          });

        });

      }

    };

  });
<|endoftext|>


<commit_before>JSM.Viewer = function ()
{
	this.camera = null;
	this.renderer = null;
	this.navigation = null;
	this.cameraLight = null;
};

JSM.Viewer.prototype.Init = function (canvas, camera)
{
	if (!this.InitRenderer (canvas)) {
		return false;
	}

	if (!this.InitNavigation (camera)) {
		return false;
	}

	return true;
};

JSM.Viewer.prototype.Reset = function ()
{
	this.RemoveBodies ();
	this.RemoveLights ();
	this.SetAmbientLight (new JSM.RenderAmbientLight (0x7f7f7f));
	this.EnableCameraLight ();
};

JSM.Viewer.prototype.InitRenderer = function (canvas)
{
	this.renderer = new JSM.Renderer ();
	if (!this.renderer.Init (canvas)) {
		return false;
	}
	return true;
};

JSM.Viewer.prototype.InitNavigation = function (camera)
{
	this.camera = JSM.ValueOrDefault (camera, new JSM.Camera ());
	if (!this.camera) {
		return false;
	}

	this.navigation = new JSM.Navigation ();
	if (!this.navigation.Init (this.renderer.canvas, this.camera, this.Draw.bind (this), this.Resize.bind (this))) {
		return false;
	}

	this.SetAmbientLight (new JSM.RenderAmbientLight (0x7f7f7f));
	this.EnableCameraLight ();
	return true;
};

JSM.Viewer.prototype.SetClearColor = function (red, green, blue)
{
	this.renderer.SetClearColor (red, green, blue);
};

JSM.Viewer.prototype.EnableCameraLight = function ()
{
	if (this.cameraLight !== null) {
		return;
	}
	this.cameraLight = new JSM.RenderDirectionalLight (0x7f7f7f, 0xffffff, new JSM.Vector (1.0, 0.0, 0.0));
	this.AddLight (this.cameraLight);
};

JSM.Viewer.prototype.DisableCameraLight = function ()
{
	if (this.cameraLight === null) {
		return;
	}
	this.RemoveLight (this.cameraLight);
	this.cameraLight = null;
};

JSM.Viewer.prototype.GetCameraLight = function ()
{
	return this.cameraLight;
};

JSM.Viewer.prototype.SetAmbientLight = function (light)
{
	this.renderer.SetAmbientLight (light);
};

JSM.Viewer.prototype.AddLight = function (light)
{
	this.renderer.AddLight (light);
};

JSM.Viewer.prototype.RemoveLight = function (light)
{
	this.renderer.RemoveLight (light);
};

JSM.Viewer.prototype.RemoveLights = function ()
{
	this.renderer.RemoveLights ();
	this.cameraLight = null;
};

JSM.Viewer.prototype.AddBody = function (renderBody)
{
	this.renderer.AddBody (renderBody, this.Draw.bind (this));
};

JSM.Viewer.prototype.AddBodies = function (renderBodies)
{
	this.renderer.AddBodies (renderBodies, this.Draw.bind (this));
};

JSM.Viewer.prototype.RemoveBody = function (body)
{
	this.renderer.RemoveBody (body);
};

JSM.Viewer.prototype.RemoveBodies = function ()
{
	this.renderer.RemoveBodies ();
};

JSM.Viewer.prototype.FitInWindow = function ()
{
	var sphere = this.GetBoundingSphere ();
	this.navigation.FitInWindow (sphere.GetCenter (), sphere.GetRadius ());
};

JSM.Viewer.prototype.GetCenter = function ()
{
	var boundingBox = this.GetBoundingBox ();
	return boundingBox.GetCenter ();
};

JSM.Viewer.prototype.GetBoundingBox = function ()
{
	var min = new JSM.Coord (JSM.Inf, JSM.Inf, JSM.Inf);
	var max = new JSM.Coord (-JSM.Inf, -JSM.Inf, -JSM.Inf);

	this.renderer.EnumerateBodies (function (body) {
		var transformation = body.GetTransformation ();
		body.EnumerateMeshes (function (mesh) {
			var i, vertex;
			for (i = 0; i < mesh.VertexCount (); i++) {
				vertex = mesh.GetTransformedVertex (i, transformation);
				min.x = JSM.Minimum (min.x, vertex.x);
				min.y = JSM.Minimum (min.y, vertex.y);
				min.z = JSM.Minimum (min.z, vertex.z);
				max.x = JSM.Maximum (max.x, vertex.x);
				max.y = JSM.Maximum (max.y, vertex.y);
				max.z = JSM.Maximum (max.z, vertex.z);
			}
		});
	});

	return new JSM.Box (min, max);
};

JSM.Viewer.prototype.GetBoundingSphere = function ()
{
	var center = this.GetCenter ();
	var radius = 0.0;

	this.renderer.EnumerateBodies (function (body) {
		var transformation = body.GetTransformation ();
		body.EnumerateMeshes (function (mesh) {
			var i, vertex, distance;
			for (i = 0; i < mesh.VertexCount (); i++) {
				vertex = mesh.GetTransformedVertex (i, transformation);
				distance = center.DistanceTo (vertex);
				if (JSM.IsGreater (distance, radius)) {
					radius = distance;
				}
			}
		});
	});

	var sphere = new JSM.Sphere (center, radius);
	return sphere;
};

JSM.Viewer.prototype.FindObjects = function (screenX, screenY)
{
	return this.renderer.FindObjects (this.camera, screenX, screenY);
};

JSM.Viewer.prototype.Resize = function ()
{
	this.renderer.Resize ();
};

JSM.Viewer.prototype.Draw = function ()
{
	var camera = this.camera;
	var cameraLight = this.GetCameraLight ();
	if (cameraLight !== null) {
		cameraLight.direction = JSM.CoordSub (camera.center, camera.eye).Normalize ();
	}
	this.renderer.Render (camera);
};
<commit_msg>Add InitLights function.<commit_after>JSM.Viewer = function ()
{
	this.camera = null;
	this.renderer = null;
	this.navigation = null;
	this.cameraLight = null;
};

JSM.Viewer.prototype.Init = function (canvas, camera)
{
	if (!this.InitRenderer (canvas)) {
		return false;
	}

	if (!this.InitNavigation (camera)) {
		return false;
	}

	if (!this.InitLights ()) {
		return false;
	}

	return true;
};

JSM.Viewer.prototype.Reset = function ()
{
	this.RemoveBodies ();
	this.RemoveLights ();
	this.SetAmbientLight (new JSM.RenderAmbientLight (0x7f7f7f));
	this.EnableCameraLight ();
};

JSM.Viewer.prototype.InitRenderer = function (canvas)
{
	this.renderer = new JSM.Renderer ();
	if (!this.renderer.Init (canvas)) {
		return false;
	}
	return true;
};

JSM.Viewer.prototype.InitNavigation = function (camera)
{
	this.camera = JSM.ValueOrDefault (camera, new JSM.Camera ());
	if (!this.camera) {
		return false;
	}

	this.navigation = new JSM.Navigation ();
	if (!this.navigation.Init (this.renderer.canvas, this.camera, this.Draw.bind (this), this.Resize.bind (this))) {
		return false;
	}

	return true;
};

JSM.Viewer.prototype.InitLights = function ()
{
	this.SetAmbientLight (new JSM.RenderAmbientLight (0x7f7f7f));
	this.EnableCameraLight ();
	return true;
};

JSM.Viewer.prototype.SetClearColor = function (red, green, blue)
{
	this.renderer.SetClearColor (red, green, blue);
};

JSM.Viewer.prototype.EnableCameraLight = function ()
{
	if (this.cameraLight !== null) {
		return;
	}
	this.cameraLight = new JSM.RenderDirectionalLight (0x7f7f7f, 0xffffff, new JSM.Vector (1.0, 0.0, 0.0));
	this.AddLight (this.cameraLight);
};

JSM.Viewer.prototype.DisableCameraLight = function ()
{
	if (this.cameraLight === null) {
		return;
	}
	this.RemoveLight (this.cameraLight);
	this.cameraLight = null;
};

JSM.Viewer.prototype.GetCameraLight = function ()
{
	return this.cameraLight;
};

JSM.Viewer.prototype.SetAmbientLight = function (light)
{
	this.renderer.SetAmbientLight (light);
};

JSM.Viewer.prototype.AddLight = function (light)
{
	this.renderer.AddLight (light);
};

JSM.Viewer.prototype.RemoveLight = function (light)
{
	this.renderer.RemoveLight (light);
};

JSM.Viewer.prototype.RemoveLights = function ()
{
	this.renderer.RemoveLights ();
	this.cameraLight = null;
};

JSM.Viewer.prototype.AddBody = function (renderBody)
{
	this.renderer.AddBody (renderBody, this.Draw.bind (this));
};

JSM.Viewer.prototype.AddBodies = function (renderBodies)
{
	this.renderer.AddBodies (renderBodies, this.Draw.bind (this));
};

JSM.Viewer.prototype.RemoveBody = function (body)
{
	this.renderer.RemoveBody (body);
};

JSM.Viewer.prototype.RemoveBodies = function ()
{
	this.renderer.RemoveBodies ();
};

JSM.Viewer.prototype.FitInWindow = function ()
{
	var sphere = this.GetBoundingSphere ();
	this.navigation.FitInWindow (sphere.GetCenter (), sphere.GetRadius ());
};

JSM.Viewer.prototype.GetCenter = function ()
{
	var boundingBox = this.GetBoundingBox ();
	return boundingBox.GetCenter ();
};

JSM.Viewer.prototype.GetBoundingBox = function ()
{
	var min = new JSM.Coord (JSM.Inf, JSM.Inf, JSM.Inf);
	var max = new JSM.Coord (-JSM.Inf, -JSM.Inf, -JSM.Inf);

	this.renderer.EnumerateBodies (function (body) {
		var transformation = body.GetTransformation ();
		body.EnumerateMeshes (function (mesh) {
			var i, vertex;
			for (i = 0; i < mesh.VertexCount (); i++) {
				vertex = mesh.GetTransformedVertex (i, transformation);
				min.x = JSM.Minimum (min.x, vertex.x);
				min.y = JSM.Minimum (min.y, vertex.y);
				min.z = JSM.Minimum (min.z, vertex.z);
				max.x = JSM.Maximum (max.x, vertex.x);
				max.y = JSM.Maximum (max.y, vertex.y);
				max.z = JSM.Maximum (max.z, vertex.z);
			}
		});
	});

	return new JSM.Box (min, max);
};

JSM.Viewer.prototype.GetBoundingSphere = function ()
{
	var center = this.GetCenter ();
	var radius = 0.0;

	this.renderer.EnumerateBodies (function (body) {
		var transformation = body.GetTransformation ();
		body.EnumerateMeshes (function (mesh) {
			var i, vertex, distance;
			for (i = 0; i < mesh.VertexCount (); i++) {
				vertex = mesh.GetTransformedVertex (i, transformation);
				distance = center.DistanceTo (vertex);
				if (JSM.IsGreater (distance, radius)) {
					radius = distance;
				}
			}
		});
	});

	var sphere = new JSM.Sphere (center, radius);
	return sphere;
};

JSM.Viewer.prototype.FindObjects = function (screenX, screenY)
{
	return this.renderer.FindObjects (this.camera, screenX, screenY);
};

JSM.Viewer.prototype.Resize = function ()
{
	this.renderer.Resize ();
};

JSM.Viewer.prototype.Draw = function ()
{
	var camera = this.camera;
	var cameraLight = this.GetCameraLight ();
	if (cameraLight !== null) {
		cameraLight.direction = JSM.CoordSub (camera.center, camera.eye).Normalize ();
	}
	this.renderer.Render (camera);
};
<|endoftext|>


<commit_before>// We need a vue instance to handle reactivity
var vm = null;

// The plugin
const VueTranslate = {

    // Install the method
    install(Vue) {
        const version = Vue.version[0];

        if (!vm) {
            vm = new Vue({
                data() {
                    return {
                        current: '',
                        locales: {}
                    };
                },

                computed: {
                    // Current selected language
                    lang() {
                        return this.current;
                    },

                    // Current locale values
                    locale() {
                        if (!this.locales[this.current])
                            return null;

                        return this.locales[this.current];
                    }
                },

                methods: {
                    // Set a language as current
                    setLang(val) {
                        if (this.current !== val) {
                            if (this.current === '') {
                                this.$emit('language:init', val);
                            } else {
                                this.$emit('language:changed', val);
                            }
                        }

                        this.current = val;

                        this.$emit('language:modified', val);
                    },

                    // Set a locale tu use
                    setLocales(locales) {
                        if (!locales)
                            return;

                        let newLocale = Object.create(this.locales);

                        for (let key in locales) {
                            if (!newLocale[key])
                                newLocale[key] = {};

                            Vue.util.extend(newLocale[key], locales[key]);
                        }

                        this.locales = Object.create(newLocale);

                        this.$emit('locales:loaded', locales);
                    },

                    text(t) {
                        if (!this.locale || !this.locale[t]) {
                            return t;
                        }

                        return this.locale[t];
                    },

                    textWithParams(t, params = null) {
                        if (!this.locale || !this.locale[t]) {
                            return t;
                        }

                        if (!this.params || this.params === null || typeof this.params === 'undefined') {
                            return t;
                        }

                        Object.keys(params).forEach((key) => {
                            t = t.replace(`%${key}%`, params[key]);
                        });

                        return t;
                    }
                }
            });

            Vue.prototype.$translate = vm;
        }

        // Mixin to read locales and add the translation method and directive
        Vue.mixin({
            [version === '1' ? 'init' : 'beforeCreate']() {
                this.$translate.setLocales(this.$options.locales);
            },

            methods: {
                // An alias for the .$translate.text method
                t(t) {
                    return this.$translate.text(t);
                },

                tWithParams(t, params) {
                    return this.$translate.text(t, params);
                }
            },

            directives: {
                translate: function (el) {
                    if (!el.$translateKey)
                        el.$translateKey = el.innerText;

                    let text = this.$translate.text(el.$translateKey);

                    el.innerText = text;
                }.bind(vm)
            }
        });

        // Global method for loading locales
        Vue.locales = (locales) => {
            vm.$translate.setLocales(locales);
        };

        // Global method for setting languages
        Vue.lang = (lang) => {
            vm.$translate.setLang(lang);
        };
    }
};

if (typeof exports === 'object') {
    module.exports = VueTranslate; // CommonJS
} else if (typeof define === 'function' && define.amd) {
    define([], function () { return VueTranslate; }); // AMD
} else if (window.Vue) {
    window.VueTranslate = VueTranslate; // Browser (not required options)
    Vue.use(VueTranslate);
}
<commit_msg>fix multiple textWithParams issues<commit_after>// We need a vue instance to handle reactivity
var vm = null;

// The plugin
const VueTranslate = {

    // Install the method
    install(Vue) {
        const version = Vue.version[0];

        if (!vm) {
            vm = new Vue({
                data() {
                    return {
                        current: '',
                        locales: {}
                    };
                },

                computed: {
                    // Current selected language
                    lang() {
                        return this.current;
                    },

                    // Current locale values
                    locale() {
                        if (!this.locales[this.current])
                            return null;

                        return this.locales[this.current];
                    }
                },

                methods: {
                    // Set a language as current
                    setLang(val) {
                        if (this.current !== val) {
                            if (this.current === '') {
                                this.$emit('language:init', val);
                            } else {
                                this.$emit('language:changed', val);
                            }
                        }

                        this.current = val;

                        this.$emit('language:modified', val);
                    },

                    // Set a locale tu use
                    setLocales(locales) {
                        if (!locales)
                            return;

                        let newLocale = Object.create(this.locales);

                        for (let key in locales) {
                            if (!newLocale[key])
                                newLocale[key] = {};

                            Vue.util.extend(newLocale[key], locales[key]);
                        }

                        this.locales = Object.create(newLocale);

                        this.$emit('locales:loaded', locales);
                    },

                    text(t) {
                        if (t in this.locale) {
                            t = this.locale[t];
                        }

                        return t;
                    },

                    textWithParams(t, params = null) {
                        if (t in this.locale) {
                            t = this.locale[t];
                        }

                        if (!params || params === null || typeof params === 'undefined') {
                            return t;
                        }

                        Object.keys(params).forEach((key) => {
                            t = t.replace(`%${key}%`, params[key]);
                        });

                        return t;
                    }
                }
            });

            Vue.prototype.$translate = vm;
        }

        // Mixin to read locales and add the translation method and directive
        Vue.mixin({
            [version === '1' ? 'init' : 'beforeCreate']() {
                this.$translate.setLocales(this.$options.locales);
            },

            methods: {
                // An alias for the .$translate.text method
                t(t, params) {
                    return this.$translate.textWithParams(t, params);
                },

                // backwards compatibility
                tWithParams(t, params) {
                    return this.$translate.textWithParams(t, params);
                }
            },

            directives: {
                translate: function (el) {
                    if (!el.$translateKey)
                        el.$translateKey = el.innerText;

                    let text = this.$translate.text(el.$translateKey);

                    el.innerText = text;
                }.bind(vm)
            }
        });

        // Global method for loading locales
        Vue.locales = (locales) => {
            vm.$translate.setLocales(locales);
        };

        // Global method for setting languages
        Vue.lang = (lang) => {
            vm.$translate.setLang(lang);
        };
    }
};

if (typeof exports === 'object') {
    module.exports = VueTranslate; // CommonJS
} else if (typeof define === 'function' && define.amd) {
    define([], function () { return VueTranslate; }); // AMD
} else if (window.Vue) {
    window.VueTranslate = VueTranslate; // Browser (not required options)
    Vue.use(VueTranslate);
}
<|endoftext|>


<commit_before>// ============================================================================
// Fermat.js | Number Theory
// (c) 2015 Mathigon
// ============================================================================

import { isInteger } from 'types';
import { unique } from 'arrays';

const smallPrimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
    73,79,83,89,97];

export function gcd(first, ...rest) {
    if (rest.length > 1) {
        return gcd(first, gcd(...rest));
    }

    let mod;
    let a = Math.abs(first);
    let b = Math.abs(rest[0]);

    while (b) {
        mod = a % b;
        a = b;
        b = mod;
    }

    return a;
}

export function lcm(first, ...rest) {
    if (rest.length > 1) {
        return lcm(first, lcm(...rest));
    }

    let a = Math.abs(first);
    let b = Math.abs(rest[0]);

    return Math.abs(a * b) / gcd(a, b);
}

function isPrime(n) {
    if (n <= 1 || !isInteger(n)) return false;
    if (n < 101) return (smallPrimes.indexOf(n) >= 0);
    if (n % 2 === 0) return false;

    let sqrt = Math.sqrt(n);
    for (let i = 3; i <= sqrt; i += 2) {
        if (n % i === 0) return false;
    }

    return true;
}

export function primeFactorisation(n) {
    if (n === 1) return [];
    if (isPrime(n)) return [n];

    var maxf = Math.sqrt(n);
    for (let f = 2; f <= maxf; ++f) {
        if (n % f === 0) return primeFactorisation(f).concat(primeFactorisation(n / f));
    }
}

export function primeFactors(n) {
    return unique(primeFactorisation(n));
}

export function listPrimes(n = 100) {
    if (n < 2) return [];
    let result = [2];

    for (let i = 3; i <= n; i++) {
        let notMultiple = false;
        for (let r of result) {
            notMultiple = notMultiple || (0 === i % r);
        }
        if (!notMultiple) result.push(i);
    }

    return result;
}
<commit_msg>new prime checking, generation and goldbach functions<commit_after>// ============================================================================
// Fermat.js | Number Theory
// (c) 2015 Mathigon
// ============================================================================

import { isInteger } from 'types';
import { unique } from 'arrays';

const smallPrimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
    73,79,83,89,97];

export function gcd(first, ...rest) {
    if (rest.length > 1) return gcd(first, gcd(...rest));

    let a = Math.abs(first);
    let b = Math.abs(rest[0]);

    while (b) [a, b] = [b, a % b];
    return a;
}

export function lcm(first, ...rest) {
    if (rest.length > 1) return lcm(first, lcm(...rest));

    return Math.abs(first * rest[0]) / gcd(first, rest[0]);
}

// Contains no dependencies, so that this function can easily be stringified
// and run in a web worker.
export function isPrime(n) {
    if (n % 1 !== 0 || n < 2) return false;

    if (n % 2 === 0) return (n == 2);
    if (n % 3 === 0) return (n == 3);

    let m = Math.sqrt(n);
    for (let i = 5;i <= m;i += 6) {
        if (n % i === 0)     return false;
        if (n % (i+2) === 0) return false;
    }

    return true;
}

export function primeFactorisation(n) {
    if (n === 1) return [];
    if (isPrime(n)) return [n];

    var maxf = Math.sqrt(n);
    for (let f = 2; f <= maxf; ++f) {
        if (n % f === 0) return primeFactorisation(f).concat(primeFactorisation(n / f));
    }
}

export function primeFactors(n) {
    return unique(primeFactorisation(n));
}

export function listPrimes(n = 100) {
    if (n < 2) return [];
    let result = [2];

    for (let i = 3; i <= n; i++) {
        let notMultiple = false;
        for (let r of result) {
            notMultiple = notMultiple || (0 === i % r);
        }
        if (!notMultiple) result.push(i);
    }

    return result;
}

// Contains no dependencies, so that this function can easily be stringified
// and run in a web worker. Number of digits 2 <= d <= 16.
export function generatePrime(d) {
    if (d < 2 || d > 16) throw new Error('Invalid number of digits.');

    let lastDigit = [1, 3, 7, 9];
    function randomInt(d) {
        let pow = Math.pow(10, d - 2);
        let n = Math.floor(Math.random() * 9 * pow) + pow;
        return 10 * n + lastDigit[Math.floor(4 * Math.random())];
    }

    function isPrime(n) {
        let sqrt = Math.sqrt(n);
        for (let i = 3; i <= sqrt; i += 2) if (n % i === 0) return false;
        return true;
    }

    let x;
    do { x = randomInt(d); } while (!isPrime(x));
    return x;
}

// Contains no dependencies, so that this function can easily be stringified
// and run in a web worker.
export function goldbach(x) {

    function isPrime(n) {
        let sqrt = Math.sqrt(n);
        for (let i = 3; i <= sqrt; i += 2) if (n % i === 0) return false;
        return true;
    }

    let a = x / 2;
    let b = x / 2;

    if (a % 2 === 0){
        a--;
        b++;
    }

    while (a >= 3){
        if (isPrime(a) && isPrime(b)) return [a, b];
        a -= 2;
        b += 2;
    }
}
<|endoftext|>


<commit_before>class RacerPhysics {
  constructor(x,y, racer, trackinfo){
        this.x = x;
        this.y = y;
        this.racer = racer
        this.trackinfo = trackinfo;
        this.velocity     = new Phaser.Point(0, 0);
        this.acceleration = new Phaser.Point(0, 0);
        this.max_acceleration = 25;
        this.last_checkpoint    = null;
        this.last_checkpoint_id = null;
  }

  set_acceleration(acceleration) {
      var mag = acceleration.getMagnitude();
      if (mag > this.max_acceleration) {
          acceleration.setMagnitude(this.max_acceleration);
      }
      this.acceleration = acceleration;
  }

  move() {
      let prev_pos = new Phaser.Point(this.x, this.y);

      this.velocity.add(this.acceleration.x, this.acceleration.y);
      this.x += this.velocity.x;
      this.y += this.velocity.y;

      let cur_pos = new Phaser.Point(prev_pos.x, prev_pos.y);
      let mag = this.velocity.getMagnitude();
      let step = new Phaser.Point(this.velocity.x, this.velocity.y);
      step.setMagnitude(1.0);
      let i;
      let new_checkpoint = null;
      let new_checkpoint_id = null;
      let glitched = false;
      for (i = 0; i <= mag; i++) {
          if (i > mag) {
              cur_pos.x = this.pos.x;
              cur_pos.y = this.pos.y;
          }
          else {
              cur_pos.add(step.x, step.y);
          }

          let pixel = this.trackinfo.get_map(Math.round(cur_pos.x), Math.round(cur_pos.y));

          // check if we went past a checkpoint
          if (new_checkpoint == null) {
              let is_checkpoint = this.trackinfo.is_on_check_point(pixel);
              if (is_checkpoint) {
                  new_checkpoint = new Phaser.Point(cur_pos.x, cur_pos.y);
                  new_checkpoint_id = is_checkpoint;
              }
          }

          // check for glitching
          if (!this.trackinfo.is_on_track(pixel) && this.last_checkpoint != null) {
              if(this.racer) this.racer.previous_positions = [];
              this.x = this.last_checkpoint.x;
              this.y = this.last_checkpoint.y;
              this.velocity.x = 0.0;
              this.velocity.y = 0.0;
              glitched = true;
              break;
          }
      }
      if (!glitched && new_checkpoint != null) {
          this.last_checkpoint    = new_checkpoint;
          this.last_checkpoint_id = new_checkpoint_id;
      }
  }
}

class Racer extends Phaser.Graphics {
    constructor(game, x, y, trackinfo) {
        super(game, x, y);

        this.physics = new RacerPhysics(x,y, this, trackinfo)
        this.previous_positions = [];
        this.history_length = 7;

        this.render();
        this.game.world.add(this);
    }

    fork_physics(){
      let res = new Racer(this.game, this.x, this.y, this.trackinfo)
      res.velocity = this.velocity.clone();
      res.acceleration = this.acceleration.clone();
      res.last_checkpoint = this.last_checkpoint.clone();
      res.last_checkpoint_id = this.last_checkpoint_id();
      res.max_acceleration = this.max_acceleration.clone();
    }

    set_acceleration(accel){
      this.physics.set_acceleration(accel)
    }

    move(){
      let prev_pos = new Phaser.Point(this.physics.x, this.physics.y);
      this.previous_positions.push(prev_pos);
      this.physics.move()
      this.x = this.physics.x
      this.y = this.physics.y
    }

    update() {
        this.x = this.physics.x;
        this.y = this.physics.y;
        this.render();
    }

    render() {
        this.clear();

        // draw stuff at our current position
        this.beginFill(0xffffff, 0.5);
        this.drawCircle(0, 0, 20);
        this.endFill();

        // the path up to here
        this.lineStyle(2, 0xffffff);
        if (this.previous_positions.length >= 1) {
            this.moveTo(0, 0);
            let last_idx = Math.max(this.previous_positions.length - this.history_length, 0);

            // paint line path
            for (var i = this.previous_positions.length; i > last_idx; i--) {
                var point_x = this.previous_positions[i-1].x-this.x;
                var point_y = this.previous_positions[i-1].y-this.y;

                this.lineTo(point_x, point_y);
            }

            // paint points on the path
            for (var i = this.previous_positions.length; i > last_idx; i--) {
                var point_x = this.previous_positions[i-1].x-this.x;
                var point_y = this.previous_positions[i-1].y-this.y;

                this.beginFill(0x00ff00);
                this.drawRect(point_x-2, point_y-2, 4, 4);
                this.endFill();
            }
        }
    }
}

export default Racer;
<commit_msg>Fix whitespace<commit_after>class RacerPhysics {
  constructor(x, y, racer, trackinfo) {
        this.x = x;
        this.y = y;
        this.racer = racer
        this.trackinfo = trackinfo;
        this.velocity     = new Phaser.Point(0, 0);
        this.acceleration = new Phaser.Point(0, 0);
        this.max_acceleration = 25;
        this.last_checkpoint    = null;
        this.last_checkpoint_id = null;
  }

  set_acceleration(acceleration) {
      var mag = acceleration.getMagnitude();
      if (mag > this.max_acceleration) {
          acceleration.setMagnitude(this.max_acceleration);
      }
      this.acceleration = acceleration;
  }

  move() {
      let prev_pos = new Phaser.Point(this.x, this.y);

      this.velocity.add(this.acceleration.x, this.acceleration.y);
      this.x += this.velocity.x;
      this.y += this.velocity.y;

      let cur_pos = new Phaser.Point(prev_pos.x, prev_pos.y);
      let mag = this.velocity.getMagnitude();
      let step = new Phaser.Point(this.velocity.x, this.velocity.y);
      step.setMagnitude(1.0);
      let i;
      let new_checkpoint = null;
      let new_checkpoint_id = null;
      let glitched = false;
      for (i = 0; i <= mag; i++) {
          if (i > mag) {
              cur_pos.x = this.pos.x;
              cur_pos.y = this.pos.y;
          }
          else {
              cur_pos.add(step.x, step.y);
          }

          let pixel = this.trackinfo.get_map(Math.round(cur_pos.x), Math.round(cur_pos.y));

          // check if we went past a checkpoint
          if (new_checkpoint == null) {
              let is_checkpoint = this.trackinfo.is_on_check_point(pixel);
              if (is_checkpoint) {
                  new_checkpoint = new Phaser.Point(cur_pos.x, cur_pos.y);
                  new_checkpoint_id = is_checkpoint;
              }
          }

          // check for glitching
          if (!this.trackinfo.is_on_track(pixel) && this.last_checkpoint != null) {
              if(this.racer) this.racer.previous_positions = [];
              this.x = this.last_checkpoint.x;
              this.y = this.last_checkpoint.y;
              this.velocity.x = 0.0;
              this.velocity.y = 0.0;
              glitched = true;
              break;
          }
      }
      if (!glitched && new_checkpoint != null) {
          this.last_checkpoint    = new_checkpoint;
          this.last_checkpoint_id = new_checkpoint_id;
      }
  }
}

class Racer extends Phaser.Graphics {
    constructor(game, x, y, trackinfo) {
        super(game, x, y);

        this.physics = new RacerPhysics(x, y, this, trackinfo)
        this.previous_positions = [];
        this.history_length = 7;

        this.render();
        this.game.world.add(this);
    }

    fork_physics() {
      let res = new Racer(this.game, this.x, this.y, this.trackinfo)
      res.velocity = this.velocity.clone();
      res.acceleration = this.acceleration.clone();
      res.last_checkpoint = this.last_checkpoint.clone();
      res.last_checkpoint_id = this.last_checkpoint_id();
      res.max_acceleration = this.max_acceleration.clone();
    }

    set_acceleration(accel) {
      this.physics.set_acceleration(accel)
    }

    move() {
      let prev_pos = new Phaser.Point(this.physics.x, this.physics.y);
      this.previous_positions.push(prev_pos);
      this.physics.move()
      this.x = this.physics.x
      this.y = this.physics.y
    }

    update() {
        this.x = this.physics.x;
        this.y = this.physics.y;
        this.render();
    }

    render() {
        this.clear();

        // draw stuff at our current position
        this.beginFill(0xffffff, 0.5);
        this.drawCircle(0, 0, 20);
        this.endFill();

        // the path up to here
        this.lineStyle(2, 0xffffff);
        if (this.previous_positions.length >= 1) {
            this.moveTo(0, 0);
            let last_idx = Math.max(this.previous_positions.length - this.history_length, 0);

            // paint line path
            for (var i = this.previous_positions.length; i > last_idx; i--) {
                var point_x = this.previous_positions[i-1].x - this.x;
                var point_y = this.previous_positions[i-1].y - this.y;

                this.lineTo(point_x, point_y);
            }

            // paint points on the path
            for (var i = this.previous_positions.length; i > last_idx; i--) {
                var point_x = this.previous_positions[i-1].x - this.x;
                var point_y = this.previous_positions[i-1].y - this.y;

                this.beginFill(0x00ff00);
                this.drawRect(point_x - 2, point_y - 2, 4, 4);
                this.endFill();
            }
        }
    }
}

export default Racer;
<|endoftext|>