code
stringlengths
2
1.05M
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } __export(require("./responsiveTable.component")); //# sourceMappingURL=index.js.map
// Karma configuration // Generated on Fri Jun 20 2014 11:30:56 GMT-0700 (US Mountain Standard Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ // libraries 'app/lib/jquery/dist/jquery.min.js', 'app/lib/underscore/underscore-min.js', 'app/lib/angular/angular.min.js', 'app/lib/angular-route/angular-route.min.js', 'app/lib/angular-mocks/angular-mocks.js', // application files 'app/js/*.js', // test files 'test/unit/*.js', // templates 'app/partials/*.html' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['dots'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
// All code points in the Deseret block as per Unicode v4.0.1: [ 0x10400, 0x10401, 0x10402, 0x10403, 0x10404, 0x10405, 0x10406, 0x10407, 0x10408, 0x10409, 0x1040A, 0x1040B, 0x1040C, 0x1040D, 0x1040E, 0x1040F, 0x10410, 0x10411, 0x10412, 0x10413, 0x10414, 0x10415, 0x10416, 0x10417, 0x10418, 0x10419, 0x1041A, 0x1041B, 0x1041C, 0x1041D, 0x1041E, 0x1041F, 0x10420, 0x10421, 0x10422, 0x10423, 0x10424, 0x10425, 0x10426, 0x10427, 0x10428, 0x10429, 0x1042A, 0x1042B, 0x1042C, 0x1042D, 0x1042E, 0x1042F, 0x10430, 0x10431, 0x10432, 0x10433, 0x10434, 0x10435, 0x10436, 0x10437, 0x10438, 0x10439, 0x1043A, 0x1043B, 0x1043C, 0x1043D, 0x1043E, 0x1043F, 0x10440, 0x10441, 0x10442, 0x10443, 0x10444, 0x10445, 0x10446, 0x10447, 0x10448, 0x10449, 0x1044A, 0x1044B, 0x1044C, 0x1044D, 0x1044E, 0x1044F ];
const { runSidebarTests } = require('./test-utils') const sidebar = require('../../content/_data/sidebar.json') runSidebarTests(sidebar.faq)
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } (function ($) { $.fn.SearchProducts = function (options) { var defaults = { resultDiv: '#resultDiv', progressDiv: '#progress', sourceUrl: '/', loginUrl: '/login', errorHandler: null, completeHandler: null, noMoreInfoHandler: null, priceRangeInputId: null, groupsListDivId: null, searchInputId: null, btnSearchId: null, showStockProductsOnlyId: null, pagerSortById: null, pagerSortOrderId: null, pageSizeId: null, paginationId: null, mainNonAjaxContentDivId: "#mainNonAjaxContent", paramName: "", pageName: "صفحه" }; options = $.extend(defaults, options); var showProgress = function () { $(options.progressDiv).fadeIn(); } var hideProgress = function () { $(options.progressDiv).fadeOut(); } var clearArea = function () { $(options.moreInfoDiv).html(""); $(options.mainNonAjaxContentDivId).html(""); window.scrollTo(0, 0); } return this.each(function () { var title = document.title; var updatePath = function () { if (!$(options.pagerSortById).val()) { return; } var selectedGroups = ""; $(options.groupsListDivId + " input:checked").each(function () { selectedGroups += $(this).val() + "-"; }); selectedGroups = selectedGroups.substr(0, selectedGroups.length - 1); var path = "#/page/" + (selectedGroups || "all") + "/" + ($(options.searchInputId).val() || "empty") + "/" + (currentPage) + "/" + $(options.pagerSortById).val() + "/" + $(options.pagerSortOrderId).val() + "/" + $(options.pageSizeId).val() + "/" + $(options.showStockProductsOnlyId).is(":checked") + "/" + $(options.priceRangeInputId).slider("values", 0) + "/" + $(options.priceRangeInputId).slider("values", 1); try { history.pushState({}, "", path); } catch (ex) { window.location.hash = path; } document.title = title + " / " + options.pageName + " " + (page); } var currentPage = 1; var submitData = function (pageNumber) { if (pageNumber == null) { pageNumber = currentPage; } else { currentPage = pageNumber; } showProgress(); var pagerSortBy = $(options.pagerSortById).val(); var pagerSortOrder = $(options.pagerSortOrderId).val(); var pagerPageSize = $(options.pageSizeId).val(); var showStockProductsOnly = $(options.showStockProductsOnlyId).is(':checked'); var minPrice = $(options.priceRangeInputId).slider("values", 0); var maxPrice = $(options.priceRangeInputId).slider("values", 1); var searchTerm = $(options.searchInputId).val(); var selectedGroups = []; $(options.groupsListDivId + " input:checked").each(function () { selectedGroups.push($(this).val()); }); updatePath(); if (minPrice == values[0] && maxPrice == values[values.length - 1]) { minPrice = maxPrice = null; } $.ajax({ type: "POST", url: options.sourceUrl, data: JSON.stringify( { pageNumber: pageNumber, pageSize: pagerPageSize, sortBy: pagerSortBy, sortOrder: pagerSortOrder, showStockProductsOnly: showStockProductsOnly, minPrice: minPrice, maxPrice: maxPrice, selectedCategories: selectedGroups, searchTerm: searchTerm, name: options.paramName } ), contentType: "application/json; charset=utf-8", dataType: "json", complete: function (xhr, status) { hideProgress(); var data = xhr.responseText; if (options.completeHandler) options.completeHandler(appendEl, $boxes); if (xhr.status == 403) { window.location = options.loginUrl; } else if (status === 'error' || !data) { if (options.errorHandler) options.errorHandler(this); } else { if (data == "no-more-info") { if (options.noMoreInfoHandler) options.noMoreInfoHandler(this); } else { var $boxes = $(data); var appendEl; $(options.resultDiv).fadeOut(function () { appendEl = $(options.resultDiv).html(data); $(options.resultDiv).fadeIn(); $(options.paginationId + " a").on("click", function (event) { event.preventDefault(); var $this = $(this); var href = $this.attr("href"); if (href === null || href === undefined) return; var pageNumber = getParameterByName(href, "page"); $('html,body').animate({ scrollTop: 0 }); submitData(pageNumber); }); }); } } } }); } Path.map("#/page(/:groups)(/:searchTerm)(/:page)(/:sortby)(/:order)(/:pageSize)(/:showStockProductsOnly)(/:minPrice)(/:maxPrice)").to(function () { var sortBy = this.params['sortby'] || 'ViewNumber'; var order = this.params['order'] || 'desc'; var pageSize = this.params['pageSize'] || +$(options.pageSizeId).val(); var searchTerm = (this.params['searchTerm'] === "empty") ? "" : this.params['searchTerm']; var minPrice = this.params['minPrice']; var maxPrice = this.params['maxPrice']; var showStockProductsOnly = this.params['showStockProductsOnly']; var urlPage = 1; if (isNumeric(this.params['page'])) { urlPage = parseInt(this.params['page'], 10); } $(options.pagerSortById).val(sortBy); $(options.pagerSortOrderId).val(order); $(options.pageSizeId).val(pageSize); $(options.searchInputId).val(decodeURIComponent(searchTerm || "")); if (showStockProductsOnly == "true") { $(options.showStockProductsOnlyId).attr('checked', 'checked'); } var $slider = $(options.priceRangeInputId); if (isNumeric(minPrice) && isNumeric(maxPrice)) { $slider.slider("values", 0, minPrice); $slider.slider("values", 1, maxPrice); $("#priceMinVal").html(formatCurrency($slider.slider('values', 0))); $("#priceMaxVal").html(formatCurrency($slider.slider('values', 1))); } var groups = this.params['groups'] || 'all'; var groupsList = []; groupsList = groups.split("-"); $(options.groupsListDivId + " input[type='checkbox']").each(function () { for (var i = 0; i < groupsList.length; i++) { if (groupsList[i] === $(this).val()) { $(this).attr('checked', 'checked'); break; } } }); page = urlPage; submitData(page); }); //Path.root("#/page/all/1/date/desc/24/false"); if ($(options.pagerSortById).val()) { Path.listen(); } $(options.pagerSortById + "," + options.pagerSortOrderId + "," + options.showStockProductsOnlyId + "," + options.groupsListDivId + " input[type='checkbox']").change(function () { submitData(); }); $(options.pageSizeId).change(function () { submitData(1); }); $(options.priceRangeInputId).on("slidechange", function (event, ui) { submitData(); }); $(options.btnSearchId).on("click", function (event) { submitData(); }); function getParameterByName(url, name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } }); }; })(jQuery); function formatCurrency(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } $(function () { $("#priceMinVal").html(formatCurrency(values[0])); $("#priceMaxVal").html(formatCurrency(values[values.length - 1])); var slider = $("#priceRange").slider({ orientation: 'horizontal', range: true, isRTL: true, animate: false, min: values[0], max: values[values.length - 1], values: [values[0], values[values.length - 1]], slide: function (event, ui) { var includeLeft = event.keyCode != $.ui.keyCode.RIGHT; var includeRight = event.keyCode != $.ui.keyCode.LEFT; var value = findNearest(includeRight, includeLeft, ui.value); if (ui.value == ui.values[0]) { slider.slider('values', 0, value); } else { slider.slider('values', 1, value); } $("#priceMinVal").html(formatCurrency(slider.slider('values', 0))); $("#priceMaxVal").html(formatCurrency(slider.slider('values', 1))); return false; }, change: function (event, ui) { //getHomeListings(); } }); function findNearest(includeLeft, includeRight, value) { var nearest = null; var diff = null; for (var i = 0; i < values.length; i++) { if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) { var newDiff = Math.abs(value - values[i]); if (diff == null || newDiff < diff) { nearest = values[i]; diff = newDiff; } } } return nearest; } }); $("#priceRange").on("slidecreate", function (event, ui) { $("#searchProductFrm").SearchProducts({ resultDiv: '#resultDiv', progressDiv: '#progress', sourceUrl: sourceUrl, loginUrl: '/login', errorHandler: null, completeHandler: null, noMoreInfoHandler: null, priceRangeInputId: "#priceRange", groupsListDivId: "#groupsList", searchInputId: "#searchTerm", btnSearchId: "#btnSearchProdcut", showStockProductsOnlyId: "#AvailableProducts", pagerSortById: "#pagerSortBy", pagerSortOrderId: "#pagerSortOrder", pageSizeId: "#pagerPageSize", paginationId: "#paginationDiv", mainNonAjaxContentDivId: "#mainNonAjaxContent", paramName: "", pageName: "صفحه" }); });
var m = require('mithril'); var chessground = require('chessground'); var classSet = require('chessground').util.classSet; var defined = require('./util').defined; var empty = require('./util').empty; var game = require('game').game; var partial = require('chessground').util.partial; var renderStatus = require('game').view.status; var mod = require('game').view.mod; var treePath = require('./path'); var control = require('./control'); var actionMenu = require('./actionMenu').view; var renderPromotion = require('./promotion').view; var pgnExport = require('./pgnExport'); function renderEval(e) { e = Math.round(e / 10) / 10; return (e > 0 ? '+' : '') + e; } function renderEvalTag(e) { return { tag: 'span', attrs: { class: 'eval' }, children: [e] }; } function autoScroll(movelist) { var plyEl = movelist.querySelector('.active') || movelist.querySelector('.turn:first-child'); if (plyEl) movelist.scrollTop = plyEl.offsetTop - movelist.offsetHeight / 2 + plyEl.offsetHeight / 2; } var emptyMove = m('em.move.empty', '...'); function renderMove(ctrl, move, path) { if (!move) return emptyMove; var pathStr = treePath.write(path); return { tag: 'a', attrs: { class: 'move' + (pathStr === ctrl.vm.pathStr ? ' active' : ''), 'data-path': pathStr, 'href': '#' + path[0].ply }, children: [ defined(move.eval) ? renderEvalTag(renderEval(move.eval)) : ( defined(move.mate) ? renderEvalTag('#' + move.mate) : null ), move.san ] }; } function plyToTurn(ply) { return Math.floor((ply - 1) / 2) + 1; } function renderVariation(ctrl, variation, path, klass) { return m('div', { class: 'variation' + (klass ? ' ' + klass : '') }, renderVariationContent(ctrl, variation, path)); } function renderVariationNested(ctrl, variation, path) { return m('span.variation', [ '(', renderVariationContent(ctrl, variation, path), ')' ]); } function renderVariationContent(ctrl, variation, path) { var turns = []; if (variation[0].ply % 2 === 0) { variation = variation.slice(0); var move = variation.shift(); turns.push({ turn: plyToTurn(move.ply), black: move }); } for (i = 0, nb = variation.length; i < nb; i += 2) turns.push({ turn: plyToTurn(variation[i].ply), white: variation[i], black: variation[i + 1] }); return turns.map(function(turn) { return renderVariationTurn(ctrl, turn, path); }); } function renderVariationMeta(ctrl, move, path) { if (!move || empty(move.variations)) return; return move.variations.map(function(variation, i) { return renderVariationNested(ctrl, variation, treePath.withVariation(path, i + 1)); }); } function renderVariationTurn(ctrl, turn, path) { var wPath = turn.white ? treePath.withPly(path, turn.white.ply) : null; var wMove = wPath ? renderMove(ctrl, turn.white, wPath) : null; var wMeta = renderVariationMeta(ctrl, turn.white, wPath); var bPath = turn.black ? treePath.withPly(path, turn.black.ply) : null; var bMove = bPath ? renderMove(ctrl, turn.black, bPath) : null; var bMeta = renderVariationMeta(ctrl, turn.black, bPath); if (wMove) { if (wMeta) return [ renderIndex(turn.turn + '.'), wMove, wMeta, bMove ? [ bMove, bMeta ] : null ]; return [renderIndex(turn.turn + '.'), wMove, (bMove ? [' ', bMove, bMeta] : '')]; } return [renderIndex(turn.turn + '...'), bMove, bMeta]; } function renderOpening(ctrl, opening) { return m('div.comment.opening', opening.code + ': ' + opening.name); } function renderMeta(ctrl, move, path) { if (!ctrl.vm.comments) return; var opening = ctrl.data.game.opening; opening = (move && opening && opening.size == move.ply) ? renderOpening(ctrl, opening) : null; if (!move || (!opening && empty(move.comments) && empty(move.variations))) return; var children = []; if (opening) children.push(opening); var colorClass = move.ply % 2 === 0 ? 'black ' : 'white '; var commentClass; if (!empty(move.comments)) move.comments.forEach(function(comment) { if (comment.indexOf('Inaccuracy.') === 0) commentClass = 'inaccuracy'; else if (comment.indexOf('Mistake.') === 0) commentClass = 'mistake'; else if (comment.indexOf('Blunder.') === 0) commentClass = 'blunder'; children.push(m('div', { class: 'comment ' + colorClass + commentClass }, comment)); }); if (!empty(move.variations)) move.variations.forEach(function(variation, i) { if (empty(variation)) return; children.push(renderVariation( ctrl, variation, treePath.withVariation(path, i + 1), i === 0 ? colorClass + commentClass : null )); }); return m('div', { class: 'meta' }, children); } function renderIndex(txt) { return { tag: 'span', attrs: { class: 'index' }, children: [txt] }; } function renderTurnDiv(children) { return { tag: 'div', attrs: { class: 'turn', }, children: children }; } function renderTurn(ctrl, turn, path) { var index = renderIndex(turn.turn); var wPath = turn.white ? treePath.withPly(path, turn.white.ply) : null; var wMove = wPath ? renderMove(ctrl, turn.white, wPath) : null; var wMeta = renderMeta(ctrl, turn.white, wPath); var bPath = turn.black ? treePath.withPly(path, turn.black.ply) : null; var bMove = bPath ? renderMove(ctrl, turn.black, bPath) : null; var bMeta = renderMeta(ctrl, turn.black, bPath); if (wMove) { if (wMeta) return [ renderTurnDiv([index, wMove, emptyMove]), wMeta, bMove ? [ renderTurnDiv([index, emptyMove, bMove]), bMeta ] : null, ]; return [ renderTurnDiv([index, wMove, bMove]), bMeta ]; } return [ renderTurnDiv([index, emptyMove, bMove]), bMeta ]; } function renderTree(ctrl, tree) { var turns = []; var initPly = ctrl.analyse.firstPly(); if (initPly % 2 === 0) for (var i = 1, nb = tree.length; i < nb; i += 2) turns.push({ turn: Math.floor((initPly + i) / 2) + 1, white: tree[i], black: tree[i + 1] }); else { turns.push({ turn: Math.floor(initPly / 2) + 1, white: null, black: tree[1] }); for (var i = 2, nb = tree.length; i < nb; i += 2) turns.push({ turn: Math.floor((initPly + i) / 2) + 1, white: tree[i], black: tree[i + 1] }); } var path = treePath.default(); var tags = []; for (var i = 0, len = turns.length; i < len; i++) tags.push(renderTurn(ctrl, turns[i], path)); return tags; } function renderAnalyse(ctrl) { var result; if (ctrl.data.game.status.id >= 30) switch (ctrl.data.game.winner) { case 'white': result = '1-0'; break; case 'black': result = '0-1'; break; default: result = '½-½'; } var tree = renderTree(ctrl, ctrl.analyse.tree); if (result) { tree.push(m('div.result', result)); var winner = game.getPlayer(ctrl.data, ctrl.data.game.winner); tree.push(m('div.status', [ renderStatus(ctrl), winner ? ', ' + ctrl.trans(winner.color == 'white' ? 'whiteIsVictorious' : 'blackIsVictorious') : null ])); } return m('div.analyse', { onmousedown: function(e) { var path = e.target.getAttribute('data-path') || e.target.parentNode.getAttribute('data-path'); if (path) { e.preventDefault(); ctrl.userJump(treePath.read(path)); } }, onclick: function(e) { return false; } }, tree); } function wheel(ctrl, e) { if (e.deltaY > 0) control.next(ctrl); else if (e.deltaY < 0) control.prev(ctrl); m.redraw(); e.preventDefault(); return false; } function inputs(ctrl) { if (!ctrl.data.userAnalysis) return null; return m('div.copyables', [ m('label.name', 'FEN'), m('input.copyable[readonly][spellCheck=false]', { value: ctrl.vm.step.fen }), m('div.pgn', [ m('label.name', 'PGN'), m('textarea.copyable[readonly][spellCheck=false]', { value: pgnExport(ctrl) }) ]) ]); } function visualBoard(ctrl) { return m('div.lichess_board_wrap', m('div.lichess_board.' + ctrl.data.game.variant.key, { config: function(el, isUpdate) { if (!isUpdate) el.addEventListener('wheel', function(e) { return wheel(ctrl, e); }); } }, chessground.view(ctrl.chessground), renderPromotion(ctrl))); } function blindBoard(ctrl) { return m('div.lichess_board_blind', [ m('div.textual', { config: function(el, isUpdate) { if (!isUpdate) blind.init(el, ctrl); } }), chessground.view(ctrl.chessground) ]); } function buttons(ctrl) { return [ m('div.game_control', [ m('div.jumps.hint--bottom', [ ['first', 'W', control.first, ], ['prev', 'Y', control.prev], ['next', 'X', control.next], ['last', 'V', control.last] ].map(function(b) { return { tag: 'a', attrs: { class: 'button ' + b[0] + ' ' + classSet({ disabled: ctrl.broken, glowed: ctrl.vm.late && b[0] === 'last' }), 'data-icon': b[1], onclick: partial(b[2], ctrl) } }; })), ctrl.data.inGame ? null : m('a.button', { onclick: ctrl.actionMenu.toggle, class: ctrl.actionMenu.open ? 'active' : '' }, m('span', { 'data-icon': '[' })) ]) ]; } module.exports = function(ctrl) { return [ m('div.top', [ m('div.lichess_game', { config: function(el, isUpdate, context) { if (isUpdate) return; $('body').trigger('lichess.content_loaded'); } }, [ ctrl.data.blind ? blindBoard(ctrl) : visualBoard(ctrl), m('div.lichess_ground', ctrl.actionMenu.open ? actionMenu(ctrl) : m('div.replay', { config: function(el, isUpdate) { autoScroll(el); if (!isUpdate) setTimeout(partial(autoScroll, el), 100); } }, renderAnalyse(ctrl)), buttons(ctrl)) ]) ]), m('div.underboard', [ m('div.center', inputs(ctrl)), m('div.right') ]) ]; };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ describe('Store', () => { let React; let ReactDOM; let agent; let act; let getRendererID; let store; let withErrorsOrWarningsIgnored; beforeEach(() => { agent = global.agent; store = global.store; React = require('react'); ReactDOM = require('react-dom'); const utils = require('./utils'); act = utils.act; getRendererID = utils.getRendererID; withErrorsOrWarningsIgnored = utils.withErrorsOrWarningsIgnored; }); it('should not allow a root node to be collapsed', () => { const Component = () => <div>Hi</div>; act(() => ReactDOM.render(<Component count={4} />, document.createElement('div')), ); expect(store).toMatchSnapshot('1: mount'); expect(store.roots).toHaveLength(1); const rootID = store.roots[0]; expect(() => store.toggleIsCollapsed(rootID, true)).toThrow( 'Root nodes cannot be collapsed', ); }); it('should properly handle a root with no visible nodes', () => { const Root = ({children}) => children; const container = document.createElement('div'); act(() => ReactDOM.render(<Root>{null}</Root>, container)); expect(store).toMatchSnapshot('1: mount'); act(() => ReactDOM.render(<div />, container)); expect(store).toMatchSnapshot('2: add host nodes'); }); describe('collapseNodesByDefault:false', () => { beforeEach(() => { store.collapseNodesByDefault = false; }); it('should support mount and update operations', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const container = document.createElement('div'); act(() => ReactDOM.render(<Grandparent count={4} />, container)); expect(store).toMatchSnapshot('1: mount'); act(() => ReactDOM.render(<Grandparent count={2} />, container)); expect(store).toMatchSnapshot('2: update'); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchSnapshot('3: unmount'); }); it('should support mount and update operations for multiple roots', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const containerA = document.createElement('div'); const containerB = document.createElement('div'); act(() => { ReactDOM.render(<Parent key="A" count={3} />, containerA); ReactDOM.render(<Parent key="B" count={2} />, containerB); }); expect(store).toMatchSnapshot('1: mount'); act(() => { ReactDOM.render(<Parent key="A" count={4} />, containerA); ReactDOM.render(<Parent key="B" count={1} />, containerB); }); expect(store).toMatchSnapshot('2: update'); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store).toMatchSnapshot('3: unmount B'); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store).toMatchSnapshot('4: unmount A'); }); it('should filter DOM nodes from the store tree', () => { const Grandparent = () => ( <div> <div> <Parent /> </div> <Parent /> </div> ); const Parent = () => ( <div> <Child /> </div> ); const Child = () => <div>Hi!</div>; act(() => ReactDOM.render( <Grandparent count={4} />, document.createElement('div'), ), ); expect(store).toMatchSnapshot('1: mount'); }); it('should display Suspense nodes properly in various states', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? ( <SuspendingComponent /> ) : ( <Component key="Inside" /> )} </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => ReactDOM.render(<Wrapper shouldSuspense={true} />, container)); expect(store).toMatchSnapshot('1: loading'); act(() => { ReactDOM.render(<Wrapper shouldSuspense={false} />, container); }); expect(store).toMatchSnapshot('2: resolved'); }); it('should support nested Suspense nodes', () => { const Component = () => null; const Loading = () => <div>Loading...</div>; const Never = () => { throw new Promise(() => {}); }; const Wrapper = ({ suspendFirst = false, suspendSecond = false, suspendParent = false, }) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading key="Parent Fallback" />}> <Component key="Unrelated at Start" /> <React.Suspense fallback={<Loading key="Suspense 1 Fallback" />}> {suspendFirst ? ( <Never /> ) : ( <Component key="Suspense 1 Content" /> )} </React.Suspense> <React.Suspense fallback={<Loading key="Suspense 2 Fallback" />}> {suspendSecond ? ( <Never /> ) : ( <Component key="Suspense 2 Content" /> )} </React.Suspense> <React.Suspense fallback={<Loading key="Suspense 3 Fallback" />}> <Never /> </React.Suspense> {suspendParent && <Never />} <Component key="Unrelated at End" /> </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('1: third child is suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('2: first and third child are suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={true} />, container, ), ); expect(store).toMatchSnapshot('3: second and third child are suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('4: first and third child are suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={true} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('5: parent is suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={true} />, container, ), ); expect(store).toMatchSnapshot('6: all children are suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('7: only third child is suspended'); const rendererID = getRendererID(); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(4), rendererID, forceFallback: true, }), ); expect(store).toMatchSnapshot('8: first and third child are suspended'); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(2), rendererID, forceFallback: true, }), ); expect(store).toMatchSnapshot('9: parent is suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={true} />, container, ), ); expect(store).toMatchSnapshot('10: parent is suspended'); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(2), rendererID, forceFallback: false, }), ); expect(store).toMatchSnapshot('11: all children are suspended'); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(4), rendererID, forceFallback: false, }), ); expect(store).toMatchSnapshot('12: all children are suspended'); act(() => ReactDOM.render( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchSnapshot('13: third child is suspended'); }); it('should display a partially rendered SuspenseList', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <React.unstable_SuspenseList revealOrder="forwards" tail="collapsed"> <Component key="A" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? <SuspendingComponent /> : <Component key="B" />} </React.Suspense> <Component key="C" /> </React.unstable_SuspenseList> </React.Fragment> ); const container = document.createElement('div'); const root = ReactDOM.unstable_createRoot(container); act(() => { root.render(<Wrapper shouldSuspense={true} />); }); expect(store).toMatchSnapshot('1: loading'); act(() => { root.render(<Wrapper shouldSuspense={false} />); }); expect(store).toMatchSnapshot('2: resolved'); }); it('should support collapsing parts of the tree', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; act(() => ReactDOM.render( <Grandparent count={2} />, document.createElement('div'), ), ); expect(store).toMatchSnapshot('1: mount'); const grandparentID = store.getElementIDAtIndex(0); const parentOneID = store.getElementIDAtIndex(1); const parentTwoID = store.getElementIDAtIndex(4); act(() => store.toggleIsCollapsed(parentOneID, true)); expect(store).toMatchSnapshot('2: collapse first Parent'); act(() => store.toggleIsCollapsed(parentTwoID, true)); expect(store).toMatchSnapshot('3: collapse second Parent'); act(() => store.toggleIsCollapsed(parentOneID, false)); expect(store).toMatchSnapshot('4: expand first Parent'); act(() => store.toggleIsCollapsed(grandparentID, true)); expect(store).toMatchSnapshot('5: collapse Grandparent'); act(() => store.toggleIsCollapsed(grandparentID, false)); expect(store).toMatchSnapshot('6: expand Grandparent'); }); it('should support reordering of children', () => { const Root = ({children}) => children; const Component = () => null; const Foo = () => [<Component key="0" />]; const Bar = () => [<Component key="0" />, <Component key="1" />]; const foo = <Foo key="foo" />; const bar = <Bar key="bar" />; const container = document.createElement('div'); act(() => ReactDOM.render(<Root>{[foo, bar]}</Root>, container)); expect(store).toMatchSnapshot('1: mount'); act(() => ReactDOM.render(<Root>{[bar, foo]}</Root>, container)); expect(store).toMatchSnapshot('3: reorder children'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), true)); expect(store).toMatchSnapshot('4: collapse root'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchSnapshot('5: expand root'); }); }); describe('collapseNodesByDefault:true', () => { beforeEach(() => { store.collapseNodesByDefault = true; }); it('should support mount and update operations', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const container = document.createElement('div'); act(() => ReactDOM.render( <React.Fragment> <Parent count={1} /> <Parent count={3} /> </React.Fragment>, container, ), ); expect(store).toMatchSnapshot('1: mount'); act(() => ReactDOM.render( <React.Fragment> <Parent count={2} /> <Parent count={1} /> </React.Fragment>, container, ), ); expect(store).toMatchSnapshot('2: update'); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchSnapshot('3: unmount'); }); it('should support mount and update operations for multiple roots', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const containerA = document.createElement('div'); const containerB = document.createElement('div'); act(() => { ReactDOM.render(<Parent key="A" count={3} />, containerA); ReactDOM.render(<Parent key="B" count={2} />, containerB); }); expect(store).toMatchSnapshot('1: mount'); act(() => { ReactDOM.render(<Parent key="A" count={4} />, containerA); ReactDOM.render(<Parent key="B" count={1} />, containerB); }); expect(store).toMatchSnapshot('2: update'); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store).toMatchSnapshot('3: unmount B'); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store).toMatchSnapshot('4: unmount A'); }); it('should filter DOM nodes from the store tree', () => { const Grandparent = () => ( <div> <div> <Parent /> </div> <Parent /> </div> ); const Parent = () => ( <div> <Child /> </div> ); const Child = () => <div>Hi!</div>; act(() => ReactDOM.render( <Grandparent count={4} />, document.createElement('div'), ), ); expect(store).toMatchSnapshot('1: mount'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchSnapshot('2: expand Grandparent'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(1), false)); expect(store).toMatchSnapshot('3: expand Parent'); }); it('should display Suspense nodes properly in various states', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? ( <SuspendingComponent /> ) : ( <Component key="Inside" /> )} </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => ReactDOM.render(<Wrapper shouldSuspense={true} />, container)); expect(store).toMatchSnapshot('1: loading'); // This test isn't meaningful unless we expand the suspended tree act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(2), false)); expect(store).toMatchSnapshot('2: expand Wrapper and Suspense'); act(() => { ReactDOM.render(<Wrapper shouldSuspense={false} />, container); }); expect(store).toMatchSnapshot('2: resolved'); }); it('should support expanding parts of the tree', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; act(() => ReactDOM.render( <Grandparent count={2} />, document.createElement('div'), ), ); expect(store).toMatchSnapshot('1: mount'); const grandparentID = store.getElementIDAtIndex(0); act(() => store.toggleIsCollapsed(grandparentID, false)); expect(store).toMatchSnapshot('2: expand Grandparent'); const parentOneID = store.getElementIDAtIndex(1); const parentTwoID = store.getElementIDAtIndex(2); act(() => store.toggleIsCollapsed(parentOneID, false)); expect(store).toMatchSnapshot('3: expand first Parent'); act(() => store.toggleIsCollapsed(parentTwoID, false)); expect(store).toMatchSnapshot('4: expand second Parent'); act(() => store.toggleIsCollapsed(parentOneID, true)); expect(store).toMatchSnapshot('5: collapse first Parent'); act(() => store.toggleIsCollapsed(parentTwoID, true)); expect(store).toMatchSnapshot('6: collapse second Parent'); act(() => store.toggleIsCollapsed(grandparentID, true)); expect(store).toMatchSnapshot('7: collapse Grandparent'); }); it('should support expanding deep parts of the tree', () => { const Wrapper = ({forwardedRef}) => ( <Nested depth={3} forwardedRef={forwardedRef} /> ); const Nested = ({depth, forwardedRef}) => depth > 0 ? ( <Nested depth={depth - 1} forwardedRef={forwardedRef} /> ) : ( <div ref={forwardedRef} /> ); const ref = React.createRef(); act(() => ReactDOM.render( <Wrapper forwardedRef={ref} />, document.createElement('div'), ), ); expect(store).toMatchSnapshot('1: mount'); const deepestedNodeID = agent.getIDForNode(ref.current); act(() => store.toggleIsCollapsed(deepestedNodeID, false)); expect(store).toMatchSnapshot('2: expand deepest node'); const rootID = store.getElementIDAtIndex(0); act(() => store.toggleIsCollapsed(rootID, true)); expect(store).toMatchSnapshot('3: collapse root'); act(() => store.toggleIsCollapsed(rootID, false)); expect(store).toMatchSnapshot('4: expand root'); const id = store.getElementIDAtIndex(1); act(() => store.toggleIsCollapsed(id, true)); expect(store).toMatchSnapshot('5: collapse middle node'); act(() => store.toggleIsCollapsed(id, false)); expect(store).toMatchSnapshot('6: expand middle node'); }); it('should support reordering of children', () => { const Root = ({children}) => children; const Component = () => null; const Foo = () => [<Component key="0" />]; const Bar = () => [<Component key="0" />, <Component key="1" />]; const foo = <Foo key="foo" />; const bar = <Bar key="bar" />; const container = document.createElement('div'); act(() => ReactDOM.render(<Root>{[foo, bar]}</Root>, container)); expect(store).toMatchSnapshot('1: mount'); act(() => ReactDOM.render(<Root>{[bar, foo]}</Root>, container)); expect(store).toMatchSnapshot('3: reorder children'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchSnapshot('4: expand root'); act(() => { store.toggleIsCollapsed(store.getElementIDAtIndex(2), false); store.toggleIsCollapsed(store.getElementIDAtIndex(1), false); }); expect(store).toMatchSnapshot('5: expand leaves'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), true)); expect(store).toMatchSnapshot('6: collapse root'); }); it('should not add new nodes when suspense is toggled', () => { const SuspenseTree = () => { return ( <React.Suspense fallback={<Fallback>Loading outer</Fallback>}> <Parent /> </React.Suspense> ); }; const Fallback = () => null; const Parent = () => <Child />; const Child = () => null; act(() => ReactDOM.render(<SuspenseTree />, document.createElement('div')), ); expect(store).toMatchSnapshot('1: mount'); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(1), false)); expect(store).toMatchSnapshot('2: expand tree'); const rendererID = getRendererID(); const suspenseID = store.getElementIDAtIndex(1); act(() => agent.overrideSuspense({ id: suspenseID, rendererID, forceFallback: true, }), ); expect(store).toMatchSnapshot('3: toggle fallback on'); act(() => agent.overrideSuspense({ id: suspenseID, rendererID, forceFallback: false, }), ); expect(store).toMatchSnapshot('4: toggle fallback on'); }); }); describe('getIndexOfElementID', () => { beforeEach(() => { store.collapseNodesByDefault = false; }); it('should support a single root with a single child', () => { const Grandparent = () => ( <React.Fragment> <Parent /> <Parent /> </React.Fragment> ); const Parent = () => <Child />; const Child = () => null; act(() => ReactDOM.render(<Grandparent />, document.createElement('div')), ); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); it('should support multiple roots with one children each', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => { ReactDOM.render(<Grandparent />, document.createElement('div')); ReactDOM.render(<Grandparent />, document.createElement('div')); }); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); it('should support a single root with multiple top level children', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => ReactDOM.render( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ), ); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); it('should support multiple roots with multiple top level children', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => { ReactDOM.render( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ); ReactDOM.render( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ); }); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); }); it('detects and updates profiling support based on the attached roots', () => { const Component = () => null; const containerA = document.createElement('div'); const containerB = document.createElement('div'); expect(store.supportsProfiling).toBe(false); act(() => ReactDOM.render(<Component />, containerA)); expect(store.supportsProfiling).toBe(true); act(() => ReactDOM.render(<Component />, containerB)); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store.supportsProfiling).toBe(true); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store.supportsProfiling).toBe(false); }); it('should properly serialize non-string key values', () => { const Child = () => null; // Bypass React element's automatic stringifying of keys intentionally. // This is pretty hacky. const fauxElement = Object.assign({}, <Child />, {key: 123}); act(() => ReactDOM.render([fauxElement], document.createElement('div'))); expect(store).toMatchSnapshot('1: mount'); }); it('should show the right display names for special component types', async done => { const MyComponent = (props, ref) => null; const ForwardRefComponent = React.forwardRef(MyComponent); const MyComponent2 = (props, ref) => null; const ForwardRefComponentWithAnonymousFunction = React.forwardRef(() => ( <MyComponent2 /> )); const MyComponent3 = (props, ref) => null; const ForwardRefComponentWithCustomDisplayName = React.forwardRef( MyComponent3, ); ForwardRefComponentWithCustomDisplayName.displayName = 'Custom'; const MyComponent4 = (props, ref) => null; const MemoComponent = React.memo(MyComponent4); const MemoForwardRefComponent = React.memo(ForwardRefComponent); const FakeHigherOrderComponent = () => null; FakeHigherOrderComponent.displayName = 'withFoo(withBar(Baz))'; const MemoizedFakeHigherOrderComponent = React.memo( FakeHigherOrderComponent, ); const ForwardRefFakeHigherOrderComponent = React.forwardRef( FakeHigherOrderComponent, ); const App = () => ( <React.Fragment> <MyComponent /> <ForwardRefComponent /> <ForwardRefComponentWithAnonymousFunction /> <ForwardRefComponentWithCustomDisplayName /> <MemoComponent /> <MemoForwardRefComponent /> <FakeHigherOrderComponent /> <MemoizedFakeHigherOrderComponent /> <ForwardRefFakeHigherOrderComponent /> <React.unstable_Cache /> </React.Fragment> ); const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => ReactDOM.render(<App />, container)); await Promise.resolve(); // Render again after it resolves act(() => ReactDOM.render(<App />, container)); expect(store).toMatchSnapshot(); done(); }); describe('Lazy', () => { async function fakeImport(result) { return {default: result}; } const LazyInnerComponent = () => null; const App = ({renderChildren}) => { if (renderChildren) { return ( <React.Suspense fallback="Loading..."> <LazyComponent /> </React.Suspense> ); } else { return null; } }; let LazyComponent; beforeEach(() => { LazyComponent = React.lazy(() => fakeImport(LazyInnerComponent)); }); it('should support Lazy components (legacy render)', async done => { const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => ReactDOM.render(<App renderChildren={true} />, container)); expect(store).toMatchSnapshot('1: mounted + loading'); await Promise.resolve(); // Render again after it resolves act(() => ReactDOM.render(<App renderChildren={true} />, container)); expect(store).toMatchSnapshot('2: mounted + loaded'); // Render again to unmount it act(() => ReactDOM.render(<App renderChildren={false} />, container)); expect(store).toMatchSnapshot('3: unmounted'); done(); }); it('should support Lazy components in (createRoot)', async done => { const container = document.createElement('div'); const root = ReactDOM.unstable_createRoot(container); // Render once to start fetching the lazy component act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchSnapshot('1: mounted + loading'); await Promise.resolve(); // Render again after it resolves act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchSnapshot('2: mounted + loaded'); // Render again to unmount it act(() => root.render(<App renderChildren={false} />)); expect(store).toMatchSnapshot('3: unmounted'); done(); }); it('should support Lazy components that are unmounted before they finish loading (legacy render)', async done => { const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => ReactDOM.render(<App renderChildren={true} />, container)); expect(store).toMatchSnapshot('1: mounted + loading'); // Render again to unmount it before it finishes loading act(() => ReactDOM.render(<App renderChildren={false} />, container)); expect(store).toMatchSnapshot('2: unmounted'); done(); }); it('should support Lazy components that are unmounted before they finish loading in (createRoot)', async done => { const container = document.createElement('div'); const root = ReactDOM.unstable_createRoot(container); // Render once to start fetching the lazy component act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchSnapshot('1: mounted + loading'); // Render again to unmount it before it finishes loading act(() => root.render(<App renderChildren={false} />)); expect(store).toMatchSnapshot('2: unmounted'); done(); }); }); describe('inline errors and warnings', () => { it('during render are counted', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example rerender={1} />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ `); }); it('during layout get counted', () => { function Example() { React.useLayoutEffect(() => { console.error('test-only: layout error'); console.warn('test-only: layout warning'); }); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example rerender={1} />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ `); }); // This is not great, but it seems safer than potentially flushing between commits. // Our logic for determining how to handle e.g. suspended trees or error boundaries // is built on the assumption that we're evaluating the results of a commit, not an in-progress render. it('during passive get counted (but not until the next commit)', () => { function Example() { React.useEffect(() => { console.error('test-only: passive error'); console.warn('test-only: passive warning'); }); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example />, container)); }); expect(store).toMatchInlineSnapshot(` [root] <Example> `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<Example rerender={1} />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchInlineSnapshot(``); }); it('from react get counted', () => { const container = document.createElement('div'); function Example() { return [<Child />]; } function Child() { return null; } withErrorsOrWarningsIgnored( ['Warning: Each child in a list should have a unique "key" prop'], () => { act(() => ReactDOM.render(<Example />, container)); }, ); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] ▾ <Example> ✕ <Child> `); }); it('can be cleared for the whole app', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); store.clearErrorsAndWarnings(); // flush events to the renderer jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` [root] <Example> <Example> `); }); it('can be cleared for particular Fiber (only warnings)', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); store.clearWarningsForElement(2); // Flush events to the renderer. jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 1 [root] <Example> ✕⚠ <Example> ✕ `); }); it('can be cleared for a particular Fiber (only errors)', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); store.clearErrorsForElement(2); // Flush events to the renderer. jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Example> ✕⚠ <Example> ⚠ `); }); it('are updated when fibers are removed from the tree', () => { function ComponentWithWarning() { console.warn('test-only: render warning'); return null; } function ComponentWithError() { console.error('test-only: render error'); return null; } function ComponentWithWarningAndError() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <ComponentWithError /> <ComponentWithWarning /> <ComponentWithWarningAndError /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <ComponentWithError> ✕ <ComponentWithWarning> ⚠ <ComponentWithWarningAndError> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <ComponentWithWarning /> <ComponentWithWarningAndError /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <ComponentWithWarning> ⚠ <ComponentWithWarningAndError> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render( <React.Fragment> <ComponentWithWarning /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] <ComponentWithWarning> ⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => ReactDOM.render(<React.Fragment />, container)); }); expect(store).toMatchInlineSnapshot(`[root]`); expect(store.errorCount).toBe(0); expect(store.warningCount).toBe(0); }); }); });
/** * hexo-tag-bilibili * https://github.com/Z4Tech/hexo-tag-bilibili.git * Copyright (c) 2015, Z4Tech * Licensed under the MIT license. * Syntax: * {% bilibili [av_id] %} or {% bilibili [av_id] [page] %} */ var bili_convert = require('bilibili-embed-convert'); hexo.extend.tag.register('bilibili', function(args){ var av_id = parseInt(args[0]); var page = parseInt(args[1]) || 1; var config = hexo.config.bilibili || {}; config.width = config.width || 452; config.height = config.height || 544; var bili_video = new bili_convert(av_id, page); return '<div class="bili_video">' + bili_video.embedAddr(config.width, config.height) + '</div>'; });
import express from 'express' import path from 'path' import favicon from 'serve-favicon' import logger from 'morgan' import cookieParser from 'cookie-parser' import bodyParser from 'body-parser' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import router from './router' import admin from './admin' import config from '../../webpack.config' const app = express() // view engine setup app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))) app.use(logger('dev')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser('dexiao')) app.use(express.static(path.join(__dirname, 'public'))) const compiler = webpack(config) app.use(webpackDevMiddleware(compiler, { publicPath: config.output.publicPath, stats: { colors: true } })) app.use(webpackHotMiddleware(compiler)) app.use('/', router) app.use('/admin', admin) // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found') err.status = 404 next(err) }) // error handler // will print stacktrace app.use(function(err, req, res, next) { res.status(err.status || 500) res.render('error', { message: err.message, error: err }) }) app.listen(4000) export default app
import { EventEmitter } from 'events'; import dispatcher from '../dispatcher'; class BlogStore extends EventEmitter { constructor() { super(); this.blogs = []; this.login_response = {}; } getAll() { return this.blogs; } createBlog(text) { const id = Date.now(); this.blogs.push({ id, text}); this.emit('change'); } handleActions(action) { console.log('BlogStore received an action ', action); switch(action.type) { case 'CREATE_BLOG': { this.createBlog(action.text); break; } case 'LOADED_BLOG': { this.blogs = action.blogs; this.emit('change'); break; } case 'LOGIN_RESPONSE': { this.login_response = action.response; this.emit('login_response'); break; } } } } const blogStore = new BlogStore(); dispatcher.register(blogStore.handleActions.bind(blogStore)); global.bss = blogStore; export default blogStore;
g_ws = new WebSocket(evt.data.url); g_ws.onopen = (event) => { g_isConnect = true; postMessage({ type: "open" }); }; g_ws.onmessage = (event) => { let fileReader = new FileReader(); fileReader.onload = (e) => { if (!(e.target?.result instanceof ArrayBuffer)) return; let packet = new Packet(); packet.initWithArrayBuffer(e.target.result); const protocolId = packet.getUint32(); const packetId = packet.getUint32(); let dispatcher = g_dispatchers.find( (p) => p.protocolId == protocolId ); if (!dispatcher) { return; } dispatcher.dispatch(null, g_ws, packet, g_handlers); }; fileReader.readAsArrayBuffer(event.data); }; g_ws.onerror = (event) => { postMessage({ type: "error" }); }; g_ws.onclose = (event) => { g_isConnect = false; postMessage({ type: "close" }); }; } break; case "close": if (g_ws) g_ws.close(); g_handlers = []; g_dispatchers = []; break; case "send": if (!g_isConnect) return; sendPacket(g_ws, evt.data.protocolId, evt.data.packetId, evt.data.packet); break; case "sendBinary": if (!g_isConnect) return; sendPacketBinary( g_ws, evt.data.protocolId, evt.data.packetId, evt.data.packet, evt.data.packetLen ); break; } };
import Ember from 'ember'; export default Ember.Controller.extend({ volume: 100, isPlaying: false, isRecording: false, isLooping: false, isCountIn: false, isMetronome: true });
/** * Emerging Citizens * Developed by Engagement Lab, 2016 * ============== * Moderator view controller. * * Help: http://keystonejs.com/docs/getting-started/#routesviews-firstview * * @class group * @static * @author Johnny Richardson * * ========== */ var keystone = require('keystone'), LessonPlan = keystone.list('LessonPlan'), GameConfig = keystone.list('GameConfig'), ContentCategory = keystone.list('ContentCategory'); exports = module.exports = function(req, res) { // Check if game type specified if(!req.params.game_type) return res.notfound('Game type not specified!', 'Sorry, but a game type needs to be specified.'); var view = new keystone.View(req, res); var locals = res.locals; var configGameType = req.params.game_type; var gameCode; locals.viewType = 'landing'; locals.section = configGameType.toUpperCase(); // locals.section is used to set the currently selected // item in the header navigation. view.on('init', function(next) { // // WWDMM = Meme Punk // if(configGameType === 'mememachine') // configGameType = 'wwdmm'; locals.categories = []; locals.lessonPlans = []; locals.whichGame = configGameType.toUpperCase(); var queryContent = ContentCategory.model.find({}); var queryPlan = LessonPlan.model.find({ 'enabled':true }) .populate('relatedGame') .populate('category'); var queryGame = GameConfig.model.findOne({ 'enabled':true, 'gameType':new RegExp('^'+locals.whichGame+'$', "i") }); queryPlan.exec(function (err, plans) { _.each(plans, function(plan, index){ plan.relatedGame.gameType = plan.relatedGame.gameType.toUpperCase(); }); locals.lessonPlans = plans; queryContent.exec(function (err, category) { locals.categories = category; queryGame.exec(function (err, game) { locals.game = game; next(err); }); }); }); // LessonPlan.model.find({ relatedGame: gameType }, {}, function (err, plans) { // locals.gameType = gameType; // locals.lessonPlans = plans; // console.log(plans); // // }); }); // Render the view view.render('group/game'); };
import fs from 'fs'; import path from 'path'; import readlineSync from 'readline-sync'; import cheerio from 'cheerio'; import beautify from 'js-beautify'; import mkdirp from 'mkdirp'; import postcss from 'postcss'; import { util } from './utils'; import { getMessages } from './messages'; class CreateComponent { constructor() { this.cwd = process.cwd(); this.cfgFile = `${this.cwd}/.bem2ngrc`; this.options = this.validateConfig(); if (!this.options) { let _languages = util.readDIR(__dirname + '/dict/langs/'); this.lang = ~_languages.indexOf(util.locale.LANG) ? util.locale.LANG : 'en'; this.MS = getMessages(this.lang); this.prompt(); this.options = this.readConfig(); } this.tech = this.options.tech_ng2; this.sym = this.tech === 'dart' ? '_' : '.'; this.config(this.options); } make(program, action) { let block, component; const optionGS = program.globalStyle || program.moveGlobalStyle; this.PB = program.block; if (action && optionGS && !this.PB) { this.moveGlobalStyle(optionGS); return; } else if (action && !this.PB) { console.error(this.MS.omittedBlockOption); return; } else { this.PB = this.PB.replace(/-/g, '_'); block = path.join(this.bemRoot, program.block); component = path.join(this.ng2Root, this.PB); } if (fs.existsSync(block)) { const blockStyle = `${block}/${program.block}.${this.styleExtension}`; const componentTech = `${component}/${this.PB + this.sym}component.${this.tech}`; const componentStyle = `${component}/${this.PB + this.sym}component.css`; const componentTemplate = `${component}/${this.PB + this.sym}component.html`; if (action === 'create') { if (fs.existsSync(component)) { console.error(this.MS.componentExist, this.PB, this.ng2Root); return; } mkdirp(component, err => { if (err) { console.error(util.chalk.red(err)); return; } console.info(this.MS.componentCreated, this.PB); this.createTech(componentTech); this.createStyle(blockStyle, componentStyle); this.createTemplate(componentTemplate); }); } if (action === 'update') { if (!fs.existsSync(component)) { console.warn(this.MS.componentNotExist, this.PB, this.ng2Root); return; } if (program.style && !program.all) { this.createStyle(blockStyle, componentStyle, this.MS.styleUpdated); } else if (program.template && !program.all) { this.createTemplate(componentTemplate, this.MS.templateUpdated); } else if (program.all) { this.createStyle(blockStyle, componentStyle, this.MS.styleUpdated); this.createTemplate(componentTemplate, this.MS.templateUpdated); } } } else { console.error(this.MS.blockNotExist, this.PB, this.bemRoot); } } createTech(toPath) { fs.readFile(__dirname + `/../src/template/${this.tech}`, 'utf-8', (err, data) => { if (err) { console.error(util.chalk.red(err)); return; } let formated, className = ''; this.PB.split('_').forEach(item => { className += util.capitalize(item); }); formated = util.format(data, ...util.repeatArg(this.PB, 2), this.sym, this.PB, this.sym, className); fs.writeFile(toPath, formated, 'utf-8', err => { if (err) { console.error(util.chalk.red(err)); return; } console.info(this.MS.techCreated, this.PB, this.sym, this.tech); }); }); } createStyle(fromPath, toPath, message) { if (fs.existsSync(fromPath)) { fs.readFile(fromPath, 'utf-8', (err, data) => { if (err) { console.error(util.chalk.red(err)); return; } const css = postcss(this.postcssPlugins).process(data, { parser: this.postcssParser }).css; fs.writeFile(toPath, css, err => { if (err) { console.error(util.chalk.red(err)); return; } message ? console.info(message, this.PB, this.sym) : console.info(this.MS.styleCreated, this.PB, this.sym); }); }); } else { if (fs.existsSync(toPath) && fs.statSync(toPath).size !== 0) { console.error(this.MS.styleNotRewrite); return; } fs.writeFile(toPath, '', err => { if (err) { console.error(util.chalk.red(err)); return; } message ? console.info(message, this.PB, this.sym) : console.warn(this.MS.styleEmpty, this.PB, this.sym, this.PB); }); } } createTemplate(toPath, message) { const loop = {}; fs.readdir(this.bemOutput, (err, files) => { if (err) { console.error(util.chalk.red(err)); return; } files.forEach(item => { const file = path.join(this.bemOutput, item); const stats = fs.statSync(file); if(loop.break) return; if (stats.isDirectory()) { const html = fs.readFileSync(`${file}/index.html`, 'utf-8'); const $ = cheerio.load(html); const block = $(`.${this.PB}`); if (block.attr('class') === this.PB && (loop.break = true)) { const blockHTML = beautify.html(cheerio.html(block)); fs.writeFileSync(toPath, blockHTML, 'utf-8'); message ? console.info(message, this.PB, this.sym) : console.info(this.MS.templateCreated, this.PB, this.sym); } } }); }); } moveGlobalStyle(pgs) { pgs = typeof pgs === 'string' ? pgs : ''; const conf = this.readConfig(); const style = path.join(this.cwd, conf.out_bem, 'index.min.css'); const dest = path.join(this.cwd, conf.src_ng2, pgs, 'styles.css'); fs .createReadStream(style) .pipe(fs.createWriteStream(dest)); console.info(this.MS.globalStyleCreated, dest); } prompt() { const options = {}; const configLang = util.format(this.MS.configLang, this.lang); const required = (fn, message, options) => { while (!result) { var result = fn(message, options); if (result) break; console.error(this.MS.configRequired); } return result; }; console.info(this.MS.configInfo); options.lang = readlineSync.question(configLang, {defaultInput: this.lang}); if (options.lang !== this.lang) this.MS = getMessages(options.lang); options.src_ng2 = required(readlineSync.question, this.MS.configNg2Src); readlineSync.setDefaultOptions({limit: ['dart', 'ts'], limitMessage: this.MS.configNg2TechErr}); options.tech_ng2 = readlineSync.question(this.MS.configNg2Tech).toLowerCase(); readlineSync.setDefaultOptions({limit: false}); options.src_bem = required(readlineSync.question, this.MS.configBemSrc); options.out_bem = required(readlineSync.question, this.MS.configBemOut); console.info(this.MS.configPostCSSInfo); options.postcss_plugins = readlineSync.question(this.MS.configPostCSSPlugin); options.postcss_parser = readlineSync.question(this.MS.configPostCSSParser); options.css_extension = required(readlineSync.question, this.MS.configPostCSSExtension); fs.writeFileSync(this.cfgFile, beautify.js(JSON.stringify(options))); console.info(this.MS.configSuccess, '\n'); } config(options) { if (options && Object.keys(options).length) { Object.assign(this.options, options); } this.ng2Root = path.join(this.cwd, this.options.src_ng2); this.bemRoot = path.join(this.cwd, this.options.src_bem); this.bemOutput = path.join(this.cwd, this.options.out_bem); this.MS = getMessages(this.options.lang); } readConfig() { let str = fs.readFileSync(this.cfgFile, 'utf-8'); try { return JSON.parse(str); } catch(e) { str = str.replace(/\'/g, '"'); str = str.replace(/(\w*[^\"])\s*\:/g, '"$1": '); str = str.replace(/\,(?!\s*[\{\[\"\w])/g, ''); fs.writeFileSync( this.cfgFile, beautify.js(str), 'utf-8' ); return JSON.parse(str); } } validateConfig() { const required = [ 'lang', 'src_ng2', 'tech_ng2', 'src_bem', 'out_bem', 'css_extension' ]; const config = this.readConfig(); let keys, bool = true; if (!config) return; keys = Object.keys(config); required.forEach(item => { if(!bool) return; if (!~keys.indexOf(item)) bool = false; }); return bool ? config : bool; } get postcssPlugins() { const plugins = this.options.postcss_plugins.split(','); return plugins.map(item => require(item.trim())); } get postcssParser() { return require(this.options.postcss_parser); } get styleExtension() { return this.options.css_extension.replace('.', ''); } } const bem2ng = new CreateComponent(); export { bem2ng };
describe('sidebar', function() { // Load the module that contains the `sidebar` component before each test beforeEach(module('sidebar')); // Test the controller });
/** * Copyright (c) 2015, Coder by Blood, Inc. All rights reserved. */ 'use strict'; /** * @module solos */ const services = require('./services'); const d = require('debug'); const ns = 'solos:'; const logs = {}; const log = { debug: { init: d(`${ns}init`), beforeall: d(`${ns}beforeall`), afterall: d(`${ns}afterall`), }, trace: { init: d(`${ns}init:trace`), beforeall: d(`${ns}beforeall:trace`), afterall: d(`${ns}afterall:trace`), }, }; /** * The default configuration for the init function * 1. `directory: process.cwd()` - the full path to the directory to scan * for solos files, defaults to current working directory * 2. `globby: {...}` - the configuration passed to globby module - see * their docs: * 1. `{globs: ['**`&#8205;`/*.solos.js', '!node_modules/**`&#8205;`/*'], absolute: true}` * the default is all solos.js files in subdirectories with absolute file names * 3. `hooks:{...}` has two properties `before` and `after` * 1. `before: ['receive', 'validate', 'authorize', 'before', ]` the * callback **before** hooks, in the order called * 2. `after: ['after', ]` the callback **after** hook, in the * order called */ const defaultConfig = { directory: process.cwd(), globby: { globs: ['**/*.solos.js', '!**/node_modules/**/*'], absolute: true, }, services: {}, hooks: { before: ['receive', 'validate', 'authorize', 'before'], after: ['after'], }, }; const calls = ['remove', 'get', 'find', 'patch', 'create', 'update']; const beforecalls = []; const aftercalls = []; /** * Configures debug module for all of the hook combinations: * - receive * - receive_[remove|get|find|patch|create|update] * - validate * - validate_[remove|get|find|patch|create|update] * - authorize * - authorize_[remove|get|find|patch|create|update] * - before * - before_[remove|get|find|patch|create|update] * - after * - after_[remove|get|find|patch|create|update] * * The namespace is: * - 'solos:hook:{hook}' - for debugging * - 'solos:hook:{hook}:trace' - for tracing function calls * * @param {object} conf **required** Configuration holding the hook names - * see `init()` docs for more details */ function setupLogs(conf) { beforecalls.length = 0; aftercalls.length = 0; conf.hooks.before.forEach((hook) => { beforecalls.push(hook); logs[hook] = { debug: d(`${ns}hook:${hook}`), trace: d(`${ns}hook:${hook}:trace`), }; calls.forEach((call) => { const beforecall = `${hook}_${call}`; beforecalls.push(beforecall); logs[beforecall] = { debug: d(`${ns}hook:${beforecall}`), trace: d(`${ns}hook:${beforecall}:trace`), }; }); }); conf.hooks.after.forEach((hook) => { aftercalls.push(hook); logs[hook] = { debug: d(`${ns}hook:${hook}`), trace: d(`${ns}hook:${hook}:trace`), }; calls.forEach((call) => { const aftercall = `${hook}_${call}`; aftercalls.push(aftercall); logs[aftercall] = { debug: d(`${ns}hook:${aftercall}`), trace: d(`${ns}hook:${aftercall}:trace`), }; }); }); } module.exports = { /** * Finds all solos.js files in subdirectories and registers them as featherjs * services with before and after callback hooks. * * #### The required configuration is: #### * 1. NONE * * #### The optional configuration is: #### * 1. See the docs for `defaultConfig` on this page for details * * @param {object} app **required** Featherjs app - services are registered here * @param {object} config **optional** The configuration * @param {function} toModule **optional** `function(path)` that returns * a service - defaults to `require` * @param {function} toURI **optional** `function(filepath, basepath)` * that returns a URI endpoint for the service */ async init(app, config, toModule, toURI) { log.trace.init({ enter: 'init', args: { app, config, toModule, toURI } }); const conf = Object.assign({}, defaultConfig, config); log.debug.init({ conf }); const files = await services.glob(conf.directory, conf.globby); files.base = conf.directory; log.debug.init({ files }); const endpoints = services.process(files, conf.services, toModule, toURI); log.debug.init({ endpoints }); setupLogs(conf); log.debug.init({ beforecalls }); log.debug.init({ aftercalls }); endpoints.forEach((endpoint) => { const end = /[_]([^_]+$)/; app.use(endpoint.path, endpoint.solos); app.service(endpoint.path).hooks({ before: { all: beforecalls.map(hook => async (context) => { log.trace.beforeall({ enter: hook, args: { hook, context } }); const callback = endpoint.solos[hook]; if (callback && typeof callback === 'function') { context.log = logs[hook]; const method = hook.match(end); if (!method || method[1] === context.method) { log.debug.beforeall({ calling: hook }); return callback(context); } } return context; }), }, after: { all: aftercalls.map(hook => async (context) => { log.trace.afterall({ enter: hook, args: { hook, context } }); const callback = endpoint.solos[hook]; if (callback && typeof callback === 'function') { context.log = logs[hook]; const method = hook.match(end); if (!method || method[1] === context.method) { log.debug.afterall({ calling: hook }); return callback(context); } } return context; }), }, }); }); }, };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _root = require('./root'); var _root2 = _interopRequireDefault(_root); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @desc Determines whether is an Array */ var ObjectValidator = function (_RootValidator) { _inherits(ObjectValidator, _RootValidator); function ObjectValidator(i) { var _ret; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, ObjectValidator); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ObjectValidator).call(this, i, options)); return _ret = _this.validate(), _possibleConstructorReturn(_this, _ret); } /** * Whether or not the object contains a property * @param {String} k - The property, or key, to check */ _createClass(ObjectValidator, [{ key: 'contains', value: function contains(k) { if (this.i.hasOwnProperty(k)) return this; return { err: { code: 'NO_CONTAINS', desc: 'The item checked is does not have property ' + k + '.', valueChecked: this.i } }; } /** * Test whether it is a an array * @see http://stackoverflow.com/a/22482737/586131 */ }, { key: 'is', value: function is() { if (this.i instanceof Object && this.i !== null) return this; return { err: { code: 'NOT_OBJECT', desc: 'The item checked is not an object.', valueChecked: this.i } }; } }]); return ObjectValidator; }(_root2.default); exports.default = ObjectValidator; //# sourceMappingURL=object.js.map
var gulp = require('gulp'); var sass = require('gulp-sass'); var del = require('del'); var minifycss = require('gulp-uglifycss'); var autoprefixer = require('gulp-autoprefixer'); var mmq = require('gulp-merge-media-queries'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var imagemin = require('gulp-imagemin'); var rename = require('gulp-rename'); var lineec = require('gulp-line-ending-corrector'); var sourcemaps = require('gulp-sourcemaps'); var notify = require('gulp-notify'); var streamqueue = require('streamqueue'); var filter = require('gulp-filter'); var browserSync = require('browser-sync').create(); var rimraf = require('gulp-rimraf'); var ngAnnotate = require('gulp-ng-annotate'); var templateCache = require('gulp-angular-templatecache'); var reload = browserSync.reload; var paths = { assets: { scriptsSrc: './assets/js/*.js', scriptsDist: './build/js', stylesSrc: './assets/scss/style.scss', stylesDist: './build/css', imagesSrc: './assets/img/**/*.{png,jpg,gif,svg}', imagesDist: './build/img', }, // Sass will check these folders for files when you use @import. sass: [ 'bower_components/bootstrap/scss', 'bower_components/font-awesome/scss' ] } const AUTOPREFIXER_BROWSERS = [ 'last 2 version', '> 1%', 'ie >= 9', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4', 'bb >= 10' ]; gulp.task('browser-sync', function () { browserSync.init({ server: "./build", open: true, injectChanges: true }); }); gulp.task('empty-build', function () { return gulp.src('./build', { read: false }) .pipe(rimraf()); }); gulp.task('build-template-cache', ['empty-build'], function () { gulp.src('./partials/**/*.html') .pipe(templateCache({ root: 'partials/', standalone: true, module: 'DS.templates' })) .pipe(gulp.dest("./build/js")); }); gulp.task('styles', ['empty-build'], function () { gulp.src(paths.assets.stylesSrc) .pipe(sourcemaps.init()) .pipe(sass({ includePaths: paths.sass, errLogToConsole: true, outputStyle: 'compact', precision: 10 })) .on('error', console.error.bind(console)) .pipe(sourcemaps.write({ includeContent: false })) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(autoprefixer(AUTOPREFIXER_BROWSERS)) .pipe(sourcemaps.write('./')) .pipe(lineec()) .pipe(gulp.dest(paths.assets.stylesDist)) .pipe(filter('**/*.css')) .pipe(mmq({ log: true })) .pipe(browserSync.stream()) .pipe(rename({ suffix: '.min' })) .pipe(minifycss({ maxLineLen: 10 })) .pipe(lineec()) .pipe(gulp.dest(paths.assets.stylesDist)) .pipe(filter('**/*.css')) .pipe(browserSync.stream()) .pipe(notify({ message: 'TASK: "styles" Completed! 💯', onLast: true })) }); gulp.task('AppJs', ['empty-build'], function () { return streamqueue({ objectMode: true }, gulp.src('./assets/js/app.js'), gulp.src('./assets/js/services.js'), gulp.src('./assets/js/controllers.js'), gulp.src('./assets/js/directive.js') ) .pipe(concat('app' + '.js')) .pipe(lineec()) .pipe(gulp.dest(paths.assets.scriptsDist)) .pipe(rename({ basename: 'app', suffix: '.min' })) .pipe(ngAnnotate()) .pipe(uglify()) //.pipe(lineec()) .pipe(gulp.dest(paths.assets.scriptsDist)) .pipe(notify({ message: 'TASK: "AppJs" Completed! 💯', onLast: true })); }); gulp.task('icons', ['empty-build'], function() { return gulp.src('bower_components/font-awesome/fonts/**.*') .pipe(gulp.dest('./build/fonts')); }); gulp.task('VendorJs', ['empty-build'], function () { return streamqueue({ objectMode: true }, gulp.src('bower_components/jquery/dist/jquery.min.js'), gulp.src('bower_components/angular/angular.min.js'), gulp.src('bower_components/angular-route/angular-route.min.js'), gulp.src('bower_components/tether/dist/js/tether.min.js'), gulp.src('bower_components/bootstrap/dist/js/bootstrap.min.js') ) .pipe(concat('bundle' + '.js')) .pipe(lineec()) .pipe(gulp.dest(paths.assets.scriptsDist)) .pipe(rename({ basename: 'bundle', suffix: '.min' })) .pipe(ngAnnotate()) .pipe(uglify()) //.pipe(lineec()) .pipe(gulp.dest(paths.assets.scriptsDist)) .pipe(notify({ message: 'TASK: "VendorJs" Completed! 💯', onLast: true })); }); gulp.task('images', ['empty-build'], function () { gulp.src(paths.assets.imagesSrc) .pipe(imagemin({ progressive: true, optimizationLevel: 3, // 0-7 low-high interlaced: true, svgoPlugins: [{ removeViewBox: false }] })) .pipe(gulp.dest(paths.assets.imagesDist)) .pipe(notify({ message: 'TASK: "images" Completed! 💯', onLast: true })); }); gulp.task('views', ['empty-build'], function () { // Get our index.html gulp.src('./index.html') // And put it in the dist folder .pipe(gulp.dest('./build')) .pipe(notify({ message: 'TASK: "Views" Completed! 💯', onLast: true })); }); gulp.task('build', ['empty-build', 'build-template-cache', 'views', 'styles', 'VendorJs', 'AppJs', 'icons']); gulp.task('watch', function () { return gulp.watch(['./index.html', './partials/*.html', './assets/scss/**/*.scss', './assets/js/*.js'], ['build', reload]); }); gulp.task('default', ['watch', 'build', 'browser-sync']);
module.exports = { Not: { Found: { messages: { 'en-US': 'Order Not Found!', 'zh-CN': '订单未找到!' } }, Updated: { messages: { 'en-US': 'Order Not Updated!', 'zh-CN': '订单未更新!' } } }, State: { Transfer: { Not: { Allowed: { messages: { 'en-US': 'Order State Transfter Not Allowed!', 'zh-CN': '订单状态转换不被允许!' } } } } } };
// All symbols in the `Pf` category as per Unicode v6.1.0: [ '\xBB', '\u2019', '\u201D', '\u203A', '\u2E03', '\u2E05', '\u2E0A', '\u2E0D', '\u2E1D', '\u2E21' ];
import { getUrlParam,renderData,getMenuList } from './common'; $(function(){ getMenuList();//根据角色获取左侧栏手风琴列表 });
'use strict'; const Bluebird = require('bluebird'); const request = Bluebird.promisifyAll(require('request')); const PAGE_TOKEN = process.env['PAGE_TOKEN']; function sendMessage(sender, text) { let messageData = { text }; return request.postAsync({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: PAGE_TOKEN }, json: { recipient: { id: sender }, message: messageData, } }).then(function (response) { if (response.body.error) { console.log('Error: ', response.body.error); } }).catch(function (err) { console.error(err); }); } function getUserDetails (userId) { return request.getAsync(`https://graph.facebook.com/v2.6/` + `${userId}?fields=first_name,last_name,gender&access_token=${PAGE_TOKEN}`) .then((res) => { if (res.statusCode !== 200) { console.log(res.body); throw new Error('Non-200 response from facebook'); } return JSON.parse(res.body); }); } module.exports = { sendMessage, getUserDetails, };
module.exports = { "key": "metapod", "moves": [ { "learn_type": "tutor", "name": "electroweb" }, { "learn_type": "tutor", "name": "bug-bite" }, { "learn_type": "tutor", "name": "string-shot" }, { "learn_type": "tutor", "name": "iron-defense" }, { "learn_type": "level up", "level": 1, "name": "harden" } ] };
module.exports = function(request,response){ response.success({ state:0, data:2333 }); };
var slug = require('slug'); var View = require('ampersand-view'); var dom = require('ampersand-dom'); var templates = require('../../templates'); module.exports = View.extend({ template: templates.views.set.songs, initialize: function(params) { var self = this; this.model = params.model; this.model.on('change:songs', function() { self.render(); }); }, render: function() { var songs = (this.model && this.model.songs) ? this.model.songs : null; this.renderWithTemplate({ songs: songs, setName: this.model.name, slugger: slug }); this.setLoading(!songs); }, setLoading: function(isLoading) { var el = this.queryByHook('songs-view-container'); var className = 'default-loading'; if (isLoading) { dom.addClass(el, className); } else { dom.removeClass(el, className); } } });
'use strict'; var foo = require('foo'); console.log(foo); console.log(foo.blah); console.log(foo.bar);
var express = require("express"); var logger = require("morgan"); var http = require("http"); var app = express(); app.use(logger("short")); app.use(function(request,response){ response.writeHead(200,{'Content-Type':'text/plain'}); response.end('Hello Xinconan'); }); http.createServer(app).listen(3000);
version https://git-lfs.github.com/spec/v1 oid sha256:0aeda5db53fe2a5eed08c4174c6ad179cff8e6723ccc58d4055668ed38df3cf3 size 252430
var Type = require("@kaoscript/runtime").Type; module.exports = function() { function foobar(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } } function quzbaz(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0) { x = null; } if(!Type.isValue(x)) { } else { foobar(x); } } };
import webpack from 'webpack'; import cssnano from 'cssnano'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import config from '../config'; import _debug from 'debug'; const debug = _debug('app:webpack:config'); const paths = config.utils_paths; const { __DEV__, __PROD__, __TEST__ } = config.globals; debug('Create configuration.'); const webpackConfig = { name: 'client', target: 'web', devtool: config.compiler_devtool, resolve: { root: paths.client(), extensions: ['', '.js', '.jsx', '.json'] }, module: {} }; // ------------------------------------ // Entry Points // ------------------------------------ const APP_ENTRY_PATHS = [paths.client('main.js')]; webpackConfig.entry = { app: __DEV__ ? APP_ENTRY_PATHS.concat( `webpack-hot-middleware/client?path=${ config.compiler_public_path }__webpack_hmr` ) : APP_ENTRY_PATHS, vendor: config.compiler_vendor }; // ------------------------------------ // Bundle Output // ------------------------------------ webpackConfig.output = { filename: `[name].[${config.compiler_hash_type}].js`, path: paths.dist(), publicPath: config.compiler_public_path }; // ------------------------------------ // Plugins // ------------------------------------ webpackConfig.plugins = [ new webpack.DefinePlugin(config.globals), new HtmlWebpackPlugin({ template: paths.client('index.html'), hash: false, favicon: paths.client('static/hackduke-favicon.png'), filename: 'index.html', inject: 'body', minify: { collapseWhitespace: true } }) ]; if (__DEV__) { debug('Enable plugins for live development (HMR, NoErrors).'); webpackConfig.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ); } else if (__PROD__) { debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).'); webpackConfig.plugins.push( new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true, warnings: false } }) ); } // Don't split bundles during testing, since we only want import one bundle if (!__TEST__) { webpackConfig.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor'] }) ); } // ------------------------------------ // Pre-Loaders // ------------------------------------ /* [ NOTE ] We no longer use eslint-loader due to it severely impacting build times for larger projects. `npm run lint` still exists to aid in deploy processes (such as with CI), and it's recommended that you use a linting plugin for your IDE in place of this loader. If you do wish to continue using the loader, you can uncomment the code below and run `npm i --save-dev eslint-loader`. This code will be removed in a future release. webpackConfig.module.preLoaders = [{ test: /\.(js|jsx)$/, loader: 'eslint', exclude: /node_modules/ }] webpackConfig.eslint = { configFile: paths.base('.eslintrc'), emitWarning: __DEV__ } */ // ------------------------------------ // Loaders // ------------------------------------ // JavaScript / JSON webpackConfig.module.loaders = [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel', query: { cacheDirectory: true, plugins: ['transform-runtime'], presets: ['es2015', 'react', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ]; // ------------------------------------ // Style Loaders // ------------------------------------ // We use cssnano with the postcss loader, so we tell // css-loader not to duplicate minimization. const BASE_CSS_LOADER = 'css?sourceMap&-minimize'; // Add any packge names here whose styles need to be treated as CSS modules. // These paths will be combined into a single regex. const PATHS_TO_TREAT_AS_CSS_MODULES = [ // 'react-toolbox', (example) ]; // If config has CSS modules enabled, treat this project's styles as CSS modules. if (config.compiler_css_modules) { PATHS_TO_TREAT_AS_CSS_MODULES.push( paths .client() .replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&') // eslint-disable-line ); } const isUsingCSSModules = !!PATHS_TO_TREAT_AS_CSS_MODULES.length; const cssModulesRegex = new RegExp( `(${PATHS_TO_TREAT_AS_CSS_MODULES.join('|')})` ); // Loaders for styles that need to be treated as CSS modules. if (isUsingCSSModules) { const cssModulesLoader = [ BASE_CSS_LOADER, 'modules', 'importLoaders=1', 'localIdentName=[name]__[local]___[hash:base64:5]' ].join('&'); webpackConfig.module.loaders.push({ test: /\.scss$/, include: cssModulesRegex, loaders: ['style', cssModulesLoader, 'postcss', 'sass?sourceMap'] }); webpackConfig.module.loaders.push({ test: /\.css$/, include: cssModulesRegex, loaders: ['style', cssModulesLoader, 'postcss'] }); } // Loaders for files that should not be treated as CSS modules. const excludeCSSModules = isUsingCSSModules ? cssModulesRegex : false; webpackConfig.module.loaders.push({ test: /\.scss$/, exclude: excludeCSSModules, loaders: ['style', BASE_CSS_LOADER, 'postcss', 'sass?sourceMap'] }); webpackConfig.module.loaders.push({ test: /\.css$/, exclude: excludeCSSModules, loaders: ['style', BASE_CSS_LOADER, 'postcss'] }); // ------------------------------------ // Style Configuration // ------------------------------------ webpackConfig.sassLoader = { includePaths: paths.client('styles') }; webpackConfig.postcss = [ cssnano({ autoprefixer: { add: true, remove: true, browsers: ['last 2 versions'] }, discardComments: { removeAll: true }, discardUnused: false, mergeIdents: false, reduceIdents: false, safe: true, sourcemap: true }) ]; // File loaders /* eslint-disable */ webpackConfig.module.loaders.push( { test: /\.woff(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' }, { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' }, { test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' }, { test: /\.ttf(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]' }, { test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' }, { test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192' } ); /* eslint-enable */ // ------------------------------------ // Finalize Configuration // ------------------------------------ // when we don't know the public path (we know it only when HMR is enabled [in development]) we // need to use the extractTextPlugin to fix this issue: // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809 if (!__DEV__) { debug('Apply ExtractTextPlugin to CSS loaders.'); webpackConfig.module.loaders .filter( loader => loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0])) ) .forEach(loader => { const [first, ...rest] = loader.loaders; loader.loader = ExtractTextPlugin.extract(first, rest.join('!')); Reflect.deleteProperty(loader, 'loaders'); }); webpackConfig.plugins.push( new ExtractTextPlugin('[name].[contenthash].css', { allChunks: true }) ); } export default webpackConfig;
var x = { foo: bar, baz: qwz };
/* Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ module.exports = function (grunt) { 'use strict'; var path = require('path'), child_process = require('child_process'), async = require('async'); grunt.extendConfig = function(update) { function extend(target, update) { return Object.getOwnPropertyNames(update).reduce(function (result, key) { if (key in result) { result[key] = extend(result[key], update[key]); } else { result[key] = update[key]; } return result; }, target); } grunt.initConfig(extend(grunt.config(), update)); }; grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'lib/**/*.js', 'bin/esmangle.js', '*.js', 'test/regression/*.js' ], options: { jshintrc: '.jshintrc', force: false } }, mochaTest: { options: { reporter: 'spec' }, test: { src: ['test/*.js'] } }, shell: { browserify: { command: 'node_modules/.bin/browserify tools/entry.js -o build/esmangle.js', stdout: true, stderr: true }, esmangle: { command: 'bin/esmangle.js build/esmangle.js -o build/esmangle.min.js', stdout: true, stderr: true } } }); // load regression tests config grunt.loadTasks(path.join('test', 'regression')); grunt.registerMultiTask('git_reset_hard', function () { var done = this.async(), cwd = this.data.cwd; if (!grunt.file.exists(cwd)) { done(); return; } grunt.verbose.writeln('Resetting ' + cwd + ' ...'); grunt.util.spawn({ cmd: 'git', args: ['reset', '--hard'], opts: { cwd: cwd } }, function (error) { if (error) { grunt.verbose.error(error); done(error); return; } done(); }); }); grunt.registerMultiTask('npm_install', function () { var name = '$npm_install$/' + this.target, cwd = this.data.cwd, cfg = {}; grunt.verbose.writeln('shell:' + name); cfg[name] = { command: 'npm install --silent', options: { stdout: true, stderr: true, failOnError: true, execOptions: { cwd: cwd } } }; grunt.extendConfig({ shell: cfg }); grunt.task.run('shell:' + name); }); grunt.registerMultiTask('esmangle_apply', function () { var done = this.async(), log; log = grunt.log.write('minifying ' + this.filesSrc.length + ' files...'); async.eachLimit(this.filesSrc, 10, function (item, callback) { var escaped = JSON.stringify(item); child_process.exec('node bin/esmangle.js ' + escaped + ' -o ' + escaped, function (err) { callback(err); }); }, function (err) { if (err) { log.error(); done(false); } else { log.ok(); done(true); } }); }); grunt.registerTask('directory:build', 'create build directory', function () { grunt.file.mkdir('build'); }); grunt.registerTask('browserify', ['directory:build', 'shell:browserify']); // load tasks grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-update-submodules'); grunt.loadNpmTasks('grunt-shell'); // alias grunt.registerTask('test:regression', [ 'test:regression:esmangle', 'test:regression:q', 'test:regression:coffee-script-redux' ]); grunt.registerTask('test', 'mochaTest'); grunt.registerTask('lint', 'jshint'); grunt.registerTask('build', ['browserify', 'shell:esmangle']); grunt.registerTask('travis', ['lint', 'test', 'test:regression']); grunt.registerTask('default','travis'); }; /* vim: set sw=4 ts=4 et tw=80 : */
(function() { 'use strict'; angular.module('myApp.mtagMouseDown', []) .directive('mtagMouseDown', mouseDownDirective); function mouseDownDirective() { return { restrict: 'A', link: function(scope, elm, attrs) { var outerFn = scope.$eval(attrs.mtagMouseDown); elm.bind('mousedown', function(evt){ console.log("mousedown"); scope.$apply(function() { if(outerFn){ outerFn.call(scope, evt.which); } }); }); } } } })();
+function(){ $(window).on("scroll",function(){ $(window).scrollTop()>80? navf():navd(); }); function navf(){ $(".nav").addClass("float"); $(".cont").css("margin-top","74px"); } function navd(){ $(".nav").removeClass("float"); $(".cont").css("margin-top","20px"); } }();
var fs = require('fs'); function SaveImage(base64Image, filePath, cb){ var matches = base64Image.match(/^(data:image\/([A-Za-z\/]+);base64,)(.+)/); if(matches.length != 4){ return cb('invalid file format', null); } var imageRawData = matches[3]; var fileExtension = matches[2]; var imageBase64Prefix = matches[1]; fs.writeFile(filePath, imageRawData, { encoding: 'base64' }, function(err){ if(err){ return cb(err, null); } return cb(null, 'file saved - ' + filePath); }) } function DecodeImage(filePath, cb){ fs.readFile(filePath, 'base64', function(err, data){ if(err){ return cb(err, null); } data = 'data:image/jpeg;base64,' + data; return cb(null, data); }); } module.exports = { SaveImage: SaveImage, DecodeImage: DecodeImage }
"use strict"; /*eslint no-unused-vars: 0*/ var React = require("react"); var RawHtml = require("./RawHtml"); var classNames = require("classnames"); var pluckTdProps = require("../util/pluckTdProps"); var defineTdProps = require("../util/defineTdProps"); var entities = require("../util/entities"); var mixin = require("../util/mixin"); var ListItem = React.createClass({displayName: "ListItem", // Component API propTypes: { bullet: React.PropTypes.string.isRequired, className: React.PropTypes.string, itemWrapper: React.PropTypes.shape(defineTdProps()), bulletWrapper: React.PropTypes.shape(defineTdProps()) }, getDefaultProps: function () { return { bullet: entities.BULL, itemWrapper: { align: "left", valing: "top" }, bulletWrapper: { align: "left", valing: "top" } }; }, render: function () { var itemProps = this.getItemProps(); var bulletProps = this.getBulletProps(); var bullet = this.props.bullet; return ( React.createElement("tr", {className: classNames("list__item", this.props.className)}, React.createElement(RawHtml, React.__spread({wrapper: "td"}, bulletProps), bullet), React.createElement(RawHtml, React.__spread({wrapper: "td"}, itemProps), this.props.children) ) ); }, // Private API getItemProps: function () { var itemProps = pluckTdProps(mixin({}, ListItem.defaultProps.itemWrapper, this.props.itemWrapper || {})); itemProps.className = classNames("list__item-wrapper", itemProps.className); return itemProps; }, getBulletProps: function () { var itemProps = pluckTdProps(mixin({}, ListItem.defaultProps.bulletWrapper, this.props.bulletWrapper || {})); itemProps.className = classNames("list__bullet-wrapper", itemProps.className); return itemProps; } // Public API }); module.exports = ListItem;
import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; // ApplicationController#html = "some <b>html</b> <i>here</i>" moduleForAcceptance('Acceptance | Sanitizing HTML'); // {{sanitize-html html}} test("sanitizes HTML with default sanitizer if no config given", function(assert) { visit("/"); andThen(function() { var html = find("#sanitized-default").html(); assert.ok(html.indexOf("some html here") !== -1, "contains sanitized HTML ("+html+")"); }); }); // {{sanitize-html html "strict"}} test("looks up config on the container", function(assert) { visit("/"); andThen(function() { var html = find("#sanitized-with-config").html(); assert.ok(html.indexOf("some html <i>here</i>") !== -1, "contains sanitized HTML ("+html+")"); }); });
/** * Created by zhangran on 16/5/18. */ import Vue from 'vue' import Alert from '../../../components/Alert/Alert.vue' import _ from 'lodash' describe('Alert', function () { it('should computed alertClasses correctly', () => { var _Alert = _.assign(Alert); _Alert.type = 'success'; _Alert.description = '这事描述啊'; _Alert.showIcon = true; var alertClasses = _Alert.computed.alertClasses.call(_Alert) expect(alertClasses['ant-alert']).toBe(1); expect(alertClasses['ant-alert-success']).toBe('success'); expect(alertClasses['ant-alert-with-description']).toBe('这事描述啊'); expect(alertClasses['ant-alert-no-icon']).toBeFalsy(); }) it('should computed iconClasses correctly', () => { var _Alert = _.assign(Alert); _Alert.type = 'success'; _Alert.description = '这事描述啊'; _Alert.showIcon = true; var iconClasses = _Alert.computed.iconClasses.call(_Alert) expect(iconClasses['anticon']).toBe(1); expect(iconClasses['ant-alert-icon']).toBe(1); expect(iconClasses['anticon-check-circle-o']).toBeTruthy(1); }) })
// Compiled by ClojureScript 0.0-2322 goog.provide('clojure.browser.event'); goog.require('cljs.core'); goog.require('goog.events.EventType'); goog.require('goog.events.EventTarget'); goog.require('goog.events'); goog.require('goog.events'); clojure.browser.event.IEventType = (function (){var obj10729 = {};return obj10729; })(); clojure.browser.event.event_types = (function event_types(this$){if((function (){var and__5762__auto__ = this$;if(and__5762__auto__) {return this$.clojure$browser$event$IEventType$event_types$arity$1; } else {return and__5762__auto__; } })()) {return this$.clojure$browser$event$IEventType$event_types$arity$1(this$); } else {var x__6706__auto__ = (((this$ == null))?null:this$);return (function (){var or__5779__auto__ = (clojure.browser.event.event_types[goog.typeOf(x__6706__auto__)]);if(or__5779__auto__) {return or__5779__auto__; } else {var or__5779__auto____$1 = (clojure.browser.event.event_types["_"]);if(or__5779__auto____$1) {return or__5779__auto____$1; } else {throw cljs.core.missing_protocol.call(null,"IEventType.event-types",this$); } } })().call(null,this$); } }); goog.events.EventTarget.prototype.clojure$browser$event$IEventType$ = true; goog.events.EventTarget.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){var this$__$1 = this;return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){ return (function (p__10730){var vec__10731 = p__10730;var k = cljs.core.nth.call(null,vec__10731,(0),null);var v = cljs.core.nth.call(null,vec__10731,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null); });})(this$__$1)) ,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.events.EventType)))); }); if(typeof Element !== 'undefined') {Element.prototype.clojure$browser$event$IEventType$ = true; Element.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){var this$__$1 = this;return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){ return (function (p__10732){var vec__10733 = p__10732;var k = cljs.core.nth.call(null,vec__10733,(0),null);var v = cljs.core.nth.call(null,vec__10733,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null); });})(this$__$1)) ,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.events.EventType)))); }); } else {} clojure.browser.event.listen = (function() { var listen = null; var listen__3 = (function (src,type,fn){return listen.call(null,src,type,fn,false); }); var listen__4 = (function (src,type,fn,capture_QMARK_){return goog.events.listen(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_); }); listen = function(src,type,fn,capture_QMARK_){ switch(arguments.length){ case 3: return listen__3.call(this,src,type,fn); case 4: return listen__4.call(this,src,type,fn,capture_QMARK_); } throw(new Error('Invalid arity: ' + arguments.length)); }; listen.cljs$core$IFn$_invoke$arity$3 = listen__3; listen.cljs$core$IFn$_invoke$arity$4 = listen__4; return listen; })() ; clojure.browser.event.listen_once = (function() { var listen_once = null; var listen_once__3 = (function (src,type,fn){return listen_once.call(null,src,type,fn,false); }); var listen_once__4 = (function (src,type,fn,capture_QMARK_){return goog.events.listenOnce(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_); }); listen_once = function(src,type,fn,capture_QMARK_){ switch(arguments.length){ case 3: return listen_once__3.call(this,src,type,fn); case 4: return listen_once__4.call(this,src,type,fn,capture_QMARK_); } throw(new Error('Invalid arity: ' + arguments.length)); }; listen_once.cljs$core$IFn$_invoke$arity$3 = listen_once__3; listen_once.cljs$core$IFn$_invoke$arity$4 = listen_once__4; return listen_once; })() ; clojure.browser.event.unlisten = (function() { var unlisten = null; var unlisten__3 = (function (src,type,fn){return unlisten.call(null,src,type,fn,false); }); var unlisten__4 = (function (src,type,fn,capture_QMARK_){return goog.events.unlisten(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_); }); unlisten = function(src,type,fn,capture_QMARK_){ switch(arguments.length){ case 3: return unlisten__3.call(this,src,type,fn); case 4: return unlisten__4.call(this,src,type,fn,capture_QMARK_); } throw(new Error('Invalid arity: ' + arguments.length)); }; unlisten.cljs$core$IFn$_invoke$arity$3 = unlisten__3; unlisten.cljs$core$IFn$_invoke$arity$4 = unlisten__4; return unlisten; })() ; clojure.browser.event.unlisten_by_key = (function unlisten_by_key(key){return goog.events.unlistenByKey(key); }); clojure.browser.event.dispatch_event = (function dispatch_event(src,event){return goog.events.dispatchEvent(src,event); }); clojure.browser.event.expose = (function expose(e){return goog.events.expose(e); }); clojure.browser.event.fire_listeners = (function fire_listeners(obj,type,capture,event){return null; }); clojure.browser.event.total_listener_count = (function total_listener_count(){return goog.events.getTotalListenerCount(); }); clojure.browser.event.get_listener = (function get_listener(src,type,listener,opt_capt,opt_handler){return null; }); clojure.browser.event.all_listeners = (function all_listeners(obj,type,capture){return null; }); clojure.browser.event.unique_event_id = (function unique_event_id(event_type){return null; }); clojure.browser.event.has_listener = (function has_listener(obj,opt_type,opt_capture){return null; }); clojure.browser.event.remove_all = (function remove_all(opt_obj,opt_type,opt_capt){return null; });
export default class KeyManager { constructor() { this.downMap = {}; this.pressed = new Set(); } pressKey(key) { if (!this.isDown(key)) { this.pressed.add(key); } this.downMap[key] = true; } releaseKey(key) { this.downMap[key] = false; } clearState() { this.downMap = {}; this.pressed.clear(); } newFrame() { this.pressed.clear(); } isDown(key) { return !!this.downMap[key]; } isPressed(key) { return this.pressed.has(key); } }
const path = require('path'); const sources = path.resolve('./src'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); exports.tslint = { test: /\.tsx?$/, use: 'tslint', include: [ sources, ], }; exports.tsx = { test: /\.tsx?$/, loaders: ['awesome-typescript-loader'], include: [ sources, ], }; exports.html = { test: /\.html$/, use: 'raw-loader', include: [ sources, ], }; exports.css = { test: /\.css$/, include: [ sources, path.resolve(__dirname, "../node_modules/antd") ], use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [{ loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production' } }] }) /*[{ loader: 'style-loader', }, { loader: 'css-loader', options: { importLoaders: 1, } }, { loader: 'postcss-loader' } ]*/ }; function makeUrlLoader(pattern) { return { test: pattern, use: 'url-loader', include: [ sources, ], }; } exports.image = makeUrlLoader(/\.(png|jpg)$/i); exports.svg = makeUrlLoader(/\.svg$/); exports.eot = makeUrlLoader(/\.eot$/); exports.woff = makeUrlLoader(/\.woff$/); exports.woff2 = makeUrlLoader(/\.woff2$/); exports.ttf = makeUrlLoader(/\.ttf$/);
// Generated by CoffeeScript 1.7.1 (function() { var StormAgent, StormData, StormKeeper, StormRegistry, StormRule, StormRulesRegistry, StormToken, StormTokenRegistry, agent, config, storm, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; StormAgent = require('stormagent'); StormData = StormAgent.StormData; StormToken = (function(_super) { var schema; __extends(StormToken, _super); schema = { name: "tokens", type: "object", additionalProperties: false, properties: { name: { type: "string", required: false }, domainId: { type: "string", required: true }, identityId: { type: "string", required: true }, ruleId: { type: "string", required: true }, validity: { type: "number", required: true }, lastModified: { type: "string", required: false }, userData: { type: "array", items: { type: "object", required: false, additionalProperties: true, properties: { accountId: { type: "string", required: false }, userEmail: { type: "string", required: false } } } } } }; function StormToken(id, data) { StormToken.__super__.constructor.call(this, id, data, schema); } return StormToken; })(StormData); StormRule = (function(_super) { var schema; __extends(StormRule, _super); schema = { name: "rules", type: "object", additionalProperties: false, properties: { id: { type: "string", required: false }, name: { type: "string", required: false }, rules: { type: "array", required: true }, role: { type: "string", required: true } } }; function StormRule(id, data) { StormRule.__super__.constructor.call(this, id, data, schema); } return StormRule; })(StormData); StormRegistry = StormAgent.StormRegistry; StormTokenRegistry = (function(_super) { __extends(StormTokenRegistry, _super); function StormTokenRegistry(filename) { this.on('load', function(key, val) { var entry; entry = new StormToken(key, val); if (entry != null) { entry.saved = true; return this.add(key, entry); } }); this.on('removed', function(token) { if (token.destroy != null) { return token.destroy(); } }); StormTokenRegistry.__super__.constructor.call(this, filename); } StormTokenRegistry.prototype.get = function(key) { var entry; entry = StormTokenRegistry.__super__.get.call(this, key); if (entry == null) { return; } entry.data.id = entry.id; entry.data.validity = entry.validity; return entry.data; }; return StormTokenRegistry; })(StormRegistry); StormRulesRegistry = (function(_super) { __extends(StormRulesRegistry, _super); function StormRulesRegistry(filename) { this.on('load', function(key, val) { var entry; entry = new StormRule(key, val); if (entry != null) { entry.saved = true; return this.add(key, entry); } }); this.on('removed', function(rule) { if (rule.destroy != null) { return rule.destroy(); } }); StormRulesRegistry.__super__.constructor.call(this, filename); } StormRulesRegistry.prototype.get = function(key) { var entry; entry = StormRulesRegistry.__super__.get.call(this, key); if (entry == null) { return; } entry.data.id = entry.id; return entry.data; }; return StormRulesRegistry; })(StormRegistry); StormKeeper = (function(_super) { var fs; __extends(StormKeeper, _super); fs = require('fs'); function StormKeeper(config) { StormKeeper.__super__.constructor.apply(this, arguments); this["import"](module); this.log('stormkeeper constructor called', this.config.datadir); fs.mkdir("" + this.config.datadir, function(result) {}); this.tokens = new StormTokenRegistry("" + this.config.datadir + "/tokens.db"); this.rules = new StormRulesRegistry("" + this.config.datadir + "/rules.db"); } StormKeeper.prototype.status = function() { var state; state = StormKeeper.__super__.status.apply(this, arguments); state.tokens = this.tokens.list(); state.rules = this.rules.list(); return state; }; StormKeeper.prototype.run = function(config) { /* if config? @log 'run called with:', config res = validate config, schema @log 'run - validation of runtime config:', res @config = extend(@config, config) if res.valid */ StormKeeper.__super__.run.call(this, config); return this.tokens.expires(this.config.repeatdelay); }; StormKeeper.prototype.authorize = function(object, update) { var match, res; this.log("authorize: ", object); if (object instanceof Error) { throw object; } if (object instanceof StormToken) { match = this.rules.get(object.data.ruleId); if (match == null) { throw new Error('invalid reference to ruleId!'); } res = this.tokens.add(object.id, object); } if (object instanceof StormRule) { res = this.rules.add(object.id, object); } res.data.id = res.id; return res.data; }; StormKeeper.prototype.revoke = function(object) { if (object != null) { if (object instanceof StormToken) { this.tokens.remove(object.id); } if (object instanceof StormRule) { return this.rules.remove(object.id); } } }; return StormKeeper; })(StormAgent); module.exports = StormKeeper; module.exports.StormToken = StormToken; module.exports.StormRule = StormRule; if (require.main === module) { /* argv = require('optimist') .usage('Start stormkeeper with a configuration file.\nUsage: $0') .demand('c') .default('c','/etc/stormstack/stormkeeper.json') .alias('c', 'config') .describe('c', 'location of stormkeeper configuration file') .argv util=require('util') util.log "stormkeeper coming up as new storm token collector..." */ config = null; storm = null; agent = new StormKeeper(config); agent.run(storm); } }).call(this);
'use strict' var api = require('../api/speed') var def = require('../definition/speed/foot-per-second') var unit = 'foot-per-second' api.augment(unit, def) module.exports = api.get(unit)
/* * Miuview Gallery * admin.js * * Creator: Mihkel Oviir * 08.2011 * */ (function($) { $.fn.MiuView = function(o){ // Defaults if( !o ) var o = {}; if( o.url == undefined ) o.url = 'http://sookoll.ee/dev/miuview-api/html'; if( o.request == undefined ) o.request = 'getalbum'; if( o.album == undefined ) o.album = '*'; if( o.item == undefined ) o.item = '*'; if( o.key == undefined ) o.key = ''; if( o.thsize == undefined ) o.thsize = 150; if( o.size == undefined ) o.size = 1000; $(this).each(function(){ var mv = new MiuViewG(this); $.history.init(mv.historyCall,{unescape:'&'}); Shadowbox.init({ skipSetup:true, continuous:true, onOpen:function(i){ mv.initHistory = false; }, onFinish:function(i){ var item = Shadowbox.current; item = mv.getCurrentId(item); var hash = window.location.hash; var parts = hash.split('&'); window.location.hash = parts[0]+'&'+item; }, onClose:function(i){ var hash = window.location.hash; var parts = hash.split('&'); window.location.hash = parts[0]; mv.initHistory = true; } }); $('.miuview_gallery li a').live('click',function(e){ e.preventDefault(); var hash = $(this).attr('url'); hash = hash.replace(/^.*#/,''); $.history.load(hash); }); }); function MiuViewG(div){ var THIS = this; this.initHistory = true; this.div=div; this.mvAlbums={}; this.mvItems={}; this.historyCall=function(hash) { if(hash==''){ // gallery page $(THIS.div).html(''); var req = o.request; switch(req){ case 'getalbum': var data = {request:req,album:o.album,thsize:o.thsize}; break; case 'getitem': var data = {request:req,album:o.album,item:o.item,thsize:o.thsize,size:o.size}; break; } THIS.doGalleryView(data,req); }else if(THIS.initHistory == true){ $(THIS.div).html(''); Shadowbox.clearCache(); var parts = hash.split('&'); // album page THIS.mvItems={}; var req = 'getitem'; var data = {request:req,album:parts[0],item:o.item,thsize:o.thsize,size:o.size}; THIS.doGalleryView(data,req); Shadowbox.setup(); // item page if(parts[1]){ Shadowbox.open({ gallery:parts[0], content:THIS.mvItems[parts[1]].img_url, player:'img', title:THIS.mvItems[parts[1]].description }); } } } this.getCurrentId = function(num){ var j = 0; for(var i in THIS.mvItems){ if(j == num){ return i; } j++; } } this.doGalleryView=function(data,type){ THIS.doRequest(data,type); var content = THIS.galleryContent(type); $(THIS.div).html('<ul class="miuview_gallery">'+content+'</ul>'); } this.doRequest=function(d,t){ $.ajax({ url: o.url+'/?callback=?', dataType: 'json', data: d, async: false, success: function(r){ THIS.doData(r,t); } }); } this.doData=function(data,type){ switch(type){ case 'getalbum': for(var i in data.albums){ THIS.mvAlbums[data.albums[i].id] = data.albums[i]; } break; case 'getitem': for(var i in data.items){ THIS.mvItems[data.items[i].id] = data.items[i]; } break; } } this.galleryContent=function(type){ var list=''; switch(type){ case 'getalbum': for(var i in THIS.mvAlbums){ var descr = THIS.mvAlbums[i].description==null?i:THIS.mvAlbums[i].description; var image = THIS.mvAlbums[i].thumb==null || THIS.mvAlbums[i].thumb==''?'no_image.gif':THIS.mvAlbums[i].thumb_url; list+='<li id="'+i+'" class="left"><a href="'+i+'" url="'+i+'" class="openAlbum" title="Vaata albumit">'; list+='<img src="'+image+'" class="left" width="'+o.thsize+'" height="'+o.thsize+'"><br>'; list+='<span class="caption">'+descr+' pilte '+THIS.mvAlbums[i].items_count+'</span>'; list+='</a></li>'; } break; case 'getitem': for(var i in THIS.mvItems){ var descr = (THIS.mvItems[i].description==null || THIS.mvItems[i].description=='')?i:THIS.mvItems[i].description; list+='<li id="'+i+'" class="left"><a href="'+THIS.mvItems[i].img_url+'" url="'+THIS.mvItems[i].album+'&'+i+'" rel="shadowbox['+THIS.mvItems[i].album+'];player=img" title="'+descr+'">'; list+='<img src="'+THIS.mvItems[i].thumb_url+'" class="left" width="'+o.thsize+'" height="'+o.thsize+'"><br>'; list+='<span class="caption">'+descr+'</span>'; list+='</a></li>'; } break; } return list; } } }; })(jQuery);
"use strict"; var extend = require('lodash/extend'); var isString = require('lodash/isString'); var oo = require('../util/oo'); var Registry = require('../util/Registry'); var Fragmenter = require('./Fragmenter'); var encodeXMLEntities = require('../util/encodeXMLEntities'); function DOMExporter(config) { if (!config.converters) { throw new Error('config.converters is mandatory'); } if (!config.converters._isRegistry) { this.converters = new Registry(); config.converters.forEach(function(converter) { if (!converter.type) { console.error('Converter must provide the type of the associated node.', converter); return; } this.converters.add(converter.type, converter); }.bind(this)); } else { this.converters = config.converters; } this.state = { doc: null }; this.config = extend({idAttribute: 'id'}, config); // NOTE: Subclasses (HTMLExporter and XMLExporter) must initialize this // with a proper DOMElement instance which is used to create new elements. this._el = null; this.$$ = this.createElement.bind(this); } DOMExporter.Prototype = function() { this.exportDocument = function(doc) { // TODO: this is no left without much functionality // still, it would be good to have a consistent top-level API // i.e. converter.importDocument(el) and converter.exportDocument(doc) // On the other side, the 'internal' API methods are named this.convert*. return this.convertDocument(doc); }; /** @param {Document} @returns {DOMElement|DOMElement[]} The exported document as DOM or an array of elements if exported as partial, which depends on the actual implementation of `this.convertDocument()`. @abstract @example this.convertDocument = function(doc) { var elements = this.convertContainer(doc, this.state.containerId); var out = elements.map(function(el) { return el.outerHTML; }); return out.join(''); }; */ this.convertDocument = function(doc) { // eslint-disable-line throw new Error('This method is abstract'); }; this.convertContainer = function(container) { if (!container) { throw new Error('Illegal arguments: container is mandatory.'); } var doc = container.getDocument(); this.state.doc = doc; var elements = []; container.nodes.forEach(function(id) { var node = doc.get(id); var nodeEl = this.convertNode(node); elements.push(nodeEl); }.bind(this)); return elements; }; this.convertNode = function(node) { if (isString(node)) { // Assuming this.state.doc has been set by convertDocument node = this.state.doc.get(node); } else { this.state.doc = node.getDocument(); } var converter = this.getNodeConverter(node); if (!converter) { converter = this.getDefaultBlockConverter(); } var el; if (converter.tagName) { el = this.$$(converter.tagName); } else { el = this.$$('div'); } el.attr(this.config.idAttribute, node.id); if (converter.export) { el = converter.export(node, el, this) || el; } else { el = this.getDefaultBlockConverter().export(node, el, this) || el; } return el; }; this.convertProperty = function(doc, path, options) { this.initialize(doc, options); var wrapper = this.$$('div') .append(this.annotatedText(path)); return wrapper.innerHTML; }; this.annotatedText = function(path) { var self = this; var doc = this.state.doc; var annotations = doc.getIndex('annotations').get(path); var text = doc.get(path); var annotator = new Fragmenter(); annotator.onText = function(context, text) { context.children.push(encodeXMLEntities(text)); }; annotator.onEnter = function(fragment) { var anno = fragment.node; return { annotation: anno, children: [] }; }; annotator.onExit = function(fragment, context, parentContext) { var anno = context.annotation; var converter = self.getNodeConverter(anno); if (!converter) { converter = self.getDefaultPropertyAnnotationConverter(); } var el; if (converter.tagName) { el = this.$$(converter.tagName); } else { el = this.$$('span'); } el.attr(this.config.idAttribute, anno.id); el.append(context.children); if (converter.export) { converter.export(anno, el, self); } parentContext.children.push(el); }.bind(this); var wrapper = { children: [] }; annotator.start(wrapper, text, annotations); return wrapper.children; }; this.getNodeConverter = function(node) { return this.converters.get(node.type); }; this.getDefaultBlockConverter = function() { throw new Error('This method is abstract.'); }; this.getDefaultPropertyAnnotationConverter = function() { throw new Error('This method is abstract.'); }; this.getDocument = function() { return this.state.doc; }; this.createElement = function(str) { return this._el.createElement(str); }; }; oo.initClass(DOMExporter); module.exports = DOMExporter;
/*eslint-disable no-unused-lets*/ /*global window, $,d3, parameters, Set */ 'use strict'; import { dataset, networkData, swarmData } from '../explore.js'; import { networkColorScale, networkAuto, setNetworLimit, networkLimit, // showNetworkHierarchy, // networkID, // networkBackground, // networkBackgroundLimit } from '../network.js'; import { lineChart, updateLineChart } from '../line_chart'; import { percentiles, makeResizable, defaultConfig } from '../helpers.js'; import { setTimeSlider, initTooltip, tooltipFunction, initSliders, tooltip } from './interaction.js'; import { metadataColor } from '../metadata.js'; import { initColorPicker, returnColorScale } from './color_picker.js'; import { initListeners, playBoolean } from '../listener.js'; import { addSpatialViewGroup } from './legend.js'; import { initDendrogram, drawDendrogram, // networkHierarchyIds, // sethierarchyGroupStdev, resethierarchyGroupStdev } from '../hierarchy.js'; import { trackingBoolean, addTrackedData } from '../visual_parameter.js'; export let indexTime = 0; // actual time moment in the animation export let tankWidth; export let tankHeight; export let activeScale = 'black'; // can be speed, acceleration, .. and black (meaning no active scale) export let medoidAnimal = -1; // which animal is the medoid (-1 is no animal) export let activeAnimals = []; // active selected animals export let arrayAnimals; // array of animals for the specific time frame let svgContainer; // svg container for the spatial view let tank; // svg group for the spatial view tank // let networkBakData = {}; /** * Initialize the spatial view with all the important factors */ export function spatialViewInit() { let minPoint = parameters['min']['geometry']['coordinates']; let maxPoint = parameters['max']['geometry']['coordinates']; // let coordinateOrigin = parameters['coordinate_origin']['geometry']['coordinates']; // width = width *1.02 --> so there is a margin in the spatial view where no animal is ever tankWidth = (maxPoint[0] - minPoint[0]) * 1.02; tankHeight = (maxPoint[1] - minPoint[1]) * 1.02; //X and Y axis let x = d3.scaleLinear() .domain([minPoint[0], maxPoint[0]]) .range([minPoint[0], maxPoint[0]]); let xAxis = d3.axisBottom(x) .ticks(10) .tickSize(10) .tickPadding(5); let y = d3.scaleLinear() .domain([minPoint[1], maxPoint[1]]) .range([minPoint[1], maxPoint[1]]); let yAxis = d3.axisRight(y) .ticks(7) .tickSize(10) .tickPadding(5); // ZOOMING AND PANNING STUFF let zoomGroup; let zoom = d3.zoom() .scaleExtent([1, 6]) .on('zoom', function() { //constrained zooming // modify the translate so that it never exits the tank d3.event.transform.x = Math.min(0, tankWidth * (d3.event.transform.k - 1), Math.max(tankWidth * (1 - d3.event.transform.k), d3.event.transform.x)); d3.event.transform.y = Math.min(0, tankHeight * (d3.event.transform.k - 1), Math.max(tankHeight * (1 - d3.event.transform.k), d3.event.transform.y)); // translate and scale zoomGroup.attr('transform', d3.event.transform); // rescale the axis gXaxis.call(xAxis.scale(d3.event.transform.rescaleX(x))); gYaxis.call(yAxis.scale(d3.event.transform.rescaleY(y))); }); //the svg container svgContainer = d3.select('#main-vis') .classed('svg-container', true) // to make it responsive with css .append('svg') .attr('preserveAspectRatio', 'xMinYMin meet') .attr('viewBox', '0 0 ' + tankWidth + ' ' + tankHeight) // add the class svg-content .classed('svg-content', true) .attr('id', 'main-vis-svg') .call(zoom); /* depends on svg ratio, for e.g 1240/1900 = 0.65 so padding-bottom = 65% */ let percentage = Math.ceil((tankHeight / tankWidth) * 100); $('#main-vis').append($('<style>#main-vis::after {padding-top: ' + percentage + '%;display: block;content: "";}</style> ')); zoomGroup = svgContainer.append('svg:g'); // Visualize the background image if it is uploaded if (parameters.background_image) { zoomGroup .append('image') .attr('xlink:href', '/' + parameters.background_image) .attr('class', 'background-image') .attr('height', tankHeight) .attr('width', tankWidth) .attr('x', '0') .attr('y', '0'); } //append the tank group with a transformation which rotates the y axis tank = zoomGroup.append('svg:g') .attr('class', 'tank') .attr('transform', function() { let x = parameters.inverted_x ? -1 : 1; let y = parameters.inverted_y ? -1 : 1; return 'scale(' + x + ',' + y + ')'; }); //add the centroid tank.append('g') .attr('id', 'g-centroid') .append('circle') .attr('class', 'centroid') .attr('r', 6) .attr('cx', 0) .attr('cy', 0); // arrow for the centroid direction tank.select('#g-centroid') .append('svg:defs') .append('svg:marker') .attr('id', 'centroid-arrow') .attr('refX', 2) .attr('refY', 6) .attr('markerWidth', 13) .attr('markerHeight', 13) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M2,2 L2,11 L10,6 L2,2'); // Append the line for the direction arrow tank.select('#g-centroid') .append('line') .attr('id', 'centroid-line') .attr('marker-end', 'url(#centroid-arrow)'); //append network group tank.append('g') .attr('id', 'network-group'); //append delaunay-triangulation group tank.append('g') .attr('id', 'delaunay-triangulation-group'); //append voronoi group tank.append('g') .attr('id', 'vornoi-group'); //append the frame time text svgContainer.append('text') .attr('class', 'frame-text') .attr('x', 30) .attr('y', 30) .text('-- : -- : -- '); // add the axis let gXaxis = svgContainer.append('g') .attr('class', 'x axis') .call(xAxis); let gYaxis = svgContainer.append('g') .attr('class', 'y axis') .call(yAxis); // init stuff from other modules initTooltip(); initSliders(); addSpatialViewGroup(); initColorPicker(); lineChart(); initListeners(); initDendrogram(); makeResizable(tankHeight, tankWidth); defaultConfig(); // start the animation draw(); } /** * Drawing function - is called for each timestep * indexTime saves the current time */ export function draw() { //measure execution time of function draw // let t0 = performance.now(); //update time to wait aka speed of replay let timeToWait = $('input[type="radio"].group-playback-rate:checked') .val(); //scale the size by this number let animalScale = $('input[type="radio"].group-size:checked') .val(); //get the next animals arrayAnimals = dataset.filter(function(d) { return d['t'] === indexTime; }); //the timeout is set after one update 30 ms setTimeout(function() { // draw hierarchy drawDendrogram(); //change the time frame text svgContainer.select('.frame-text') .text(Math.floor(indexTime / 1500) % 60 + ':' + Math.floor(indexTime / parameters['fps']) % 60 + '::' + indexTime % parameters['fps']); // if a second has changed move the slider if (indexTime % parameters['fps'] === 0) { setTimeSlider(indexTime); } let svgAnimals = tank.selectAll('g.animal') .data(arrayAnimals); // Network vis let networkVis; // let networkVisBak; if (indexTime in networkData) { let network = networkData[indexTime]; // reset the group standard deviation for the hierarhcy // needed for coloring of the dendrogram nodes (variacne) resethierarchyGroupStdev(); // display the whole network network = network.map(function(item) { let animal1 = arrayAnimals.filter(function(obj) { return obj['a'] === item['s']; })[0]; let animal2 = arrayAnimals.filter(function(obj) { return obj['a'] === item['e']; })[0]; return { 'node1': animal1['a'], 'node2': animal2['a'], 'start': animal1['p'], 'end': animal2['p'], 'val': item['v'] }; }); network.forEach(function(d) { $(('#mc-' + d['node1'] + '-' + d['node2'])).css('fill', networkColorScale(d['val'])); $(('#mc-' + d['node2'] + '-' + d['node1'])).css('fill', networkColorScale(d['val'])); }); if (networkAuto) { let tmpArray = []; for (let i = 0; i < network.length; i++) { tmpArray.push(network[i]['val']); } setNetworLimit(percentiles(tmpArray)); } network = network.filter(function(d) { return d['val'] <= (1 - networkLimit); }); // DATA JOIN networkVis = tank.select('#network-group') .selectAll('line.network-edges') .data(network); // UPDATE networkVis .attr('x1', function(d) { return d['start'][0]; }) .attr('y1', function(d) { return -d['start'][1]; }) .attr('x2', function(d) { return d['end'][0]; }) .attr('y2', function(d) { return -d['end'][1]; }) .attr('stroke', function(d) { return networkColorScale((1 - d['val'])); }) .attr('stroke-opacity', function(d) { return 1 - d['val']; }); //ENTER networkVis .enter() .append('line') .attr('class', 'network-edges') .attr('x1', function(d) { return d['start'][0]; }) .attr('y1', function(d) { return -d['start'][1]; }) .attr('x2', function(d) { return d['end'][0]; }) .attr('y2', function(d) { return -d['end'][1]; }) .attr('stroke', function(d) { return networkColorScale(d['val']); }) .attr('stroke-opacity', function(d) { return d['val']; }); } else { networkVis = tank.selectAll('line.network-edges') .data([]); } // EXIT - network networkVis.exit() .remove(); // delaunay triangulation // DATA JOIN - triangulation var triangulation; if ($('#draw-triangulation') .is(':checked')) { triangulation = tank.select('#delaunay-triangulation-group') .selectAll('path.delaunay-triangulation') .data([swarmData[indexTime]['triangulation']]); // UPDATE - triangulation triangulation .attr('d', function(d) { return d; }); //ENTER - triangulation triangulation.enter() .append('path') .attr('class', 'delaunay-triangulation') .attr('d', function(d) { return d; }); } else { triangulation = tank.selectAll('path.delaunay-triangulation') .data([]); } // EXIT - triangulation triangulation.exit() .remove(); // Voronoi // DATA JOIN - voronoi var voronoi; if ($('#draw-voronoi') .is(':checked')) { //append the group for the voronoi paths voronoi = tank .select('#vornoi-group') .selectAll('path.voronoi') .data(swarmData[indexTime]['voronoi'].split(';')); // UPDATE - voronoi voronoi .attr('d', function(d) { return d; }); //ENTER - voronoi voronoi.enter() .append('path') .attr('class', 'voronoi') .attr('d', function(d) { return d; }); } else { voronoi = tank.select('#vornoi-group') .selectAll('path.voronoi') .data([]); } // EXIT - voronoi voronoi.exit() .remove(); //ENTER - append the animal groups let animalGroupings = svgAnimals .enter() .append('g') .attr('class', 'animal') .attr('id', function(d) { return 'animal-' + d['a']; }); // Append the circles for each animal to the animalgroup animalGroupings.append('circle') .attr('r', 1.5 * animalScale) .attr('cx', function(d) { return d['p'][0]; }) .attr('cy', function(d) { return -d['p'][1]; }) .on('mouseover', function(d) { tooltipFunction(d); }) .on('mouseout', function() { tooltip .transition() .duration(500) .style('opacity', 0); }) // add on click for the active fishs .on('click', function(d) { if (activeAnimals.includes(d['a'])) { activeAnimals = activeAnimals.filter(item => item !== d['a']); } else { activeAnimals.push(d['a']); } if (!$('#play-button') .hasClass('active')) { //go back one second and draw the next frame //this applys the changes indexTime--; draw(); } }); // UPDATE - animals circles svgAnimals.select('circle') .attr('cx', function(d) { return d['p'][0]; }) .attr('cy', function(d) { return -d['p'][1]; }) .attr('r', animalScale); // Append for each group the arrow, needed for coloring animalGroupings.append('svg:defs') .append('svg:marker') .attr('id', function(d) { return 'arrow-marker-' + d['a']; }) .attr('refX', 2) .attr('refY', 6) .attr('markerWidth', 13) .attr('markerHeight', 13) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M2,2 L2,11 L10,6 L2,2'); // Append the line for the direction arrow animalGroupings .append('line') .attr('class', 'arrow') .attr('marker-end', function(d) { return 'url(#arrow-marker-' + d['a'] + ')'; }); //execute only when draw direction button is checked if ($('#draw-direction') .is(':checked')) { // UPDATE animal direction arrow svgAnimals.select('line') .attr('x1', function(d) { return d['p'][0]; }) .attr('y1', function(d) { return -d['p'][1]; }) .attr('x2', function(d) { return (d['p'][0] + 2 * animalScale); }) .attr('y2', function(d) { return (-d['p'][1]); }) .attr('transform', function(d) { return 'rotate(' + -d['direction'] + ' ' + d['p'][0] + ' ' + -d['p'][1] + ')'; }); } else { // hide the arrows $('.arrow').hide(); } // EXIT - the groups svgAnimals.exit() .remove(); //Convex hull if ($('#draw-convex-hull') .is(':checked')) { // DATA JOIN - paths var hullPath = tank.selectAll('path.hull-path') .data([swarmData[indexTime]['convex_hull']]); // UPDATE - hull path hullPath .attr('d', function(d) { return d; }); // ENTER - hull paths hullPath.enter() .append('path') .attr('class', 'hull-path') .attr('d', function(d) { return d; }); } else { // draw no hull hullPath = tank.select('path.hull-path') .data([]); } // EXIT - hull paths hullPath.exit() .remove(); //change the colors of the fish if (activeScale !== 'black') { // once the fill for the heads and the stroke for the path var tmpScale = returnColorScale(); svgAnimals .transition() .duration(10) .style('fill', function(d) { return tmpScale(d[activeScale]); }) .attr('stroke', function(d) { return tmpScale(d[activeScale]); }); } else { //color every fish black svgAnimals .style('fill', '#000') .attr('stroke', '#000'); if (!$.isEmptyObject(metadataColor)) { Object.keys(metadataColor).forEach(function(key) { d3 .select('#animal-' + key) .style('fill', metadataColor[key]) .attr('stroke', metadataColor[key]); }); } } //change opactiy if the fish is selected if (activeAnimals.length) { svgAnimals .style('opacity', function(d) { if (activeAnimals.includes(d['a'])) { return 1; } else { return 0.25; } }); if ($('#remove-active-selected-button') .is(':disabled')) { $('#remove-active-selected-button') .prop('disabled', false); $('#visual-parameter-button') .prop('disabled', false); } // if tracking is on if (trackingBoolean) { addTrackedData(arrayAnimals[0]['t'], activeAnimals); } } else { if (!$('#remove-active-selected-button') .is(':disabled')) { $('#remove-active-selected-button') .prop('disabled', true); $('#visual-parameter-button') .prop('disabled', true); } // normal opacity svgAnimals .style('opacity', 1); } //draw centroid d3.select('.centroid') .attr('cx', function() { if ('centroid' in swarmData[0]) { return swarmData[indexTime]['centroid'][0]; } else { return 0; } }) .attr('cy', function() { if ('centroid' in swarmData[0]) { return -swarmData[indexTime]['centroid'][1]; } else { return 0; } }); if ($('#draw-direction').is(':checked') && swarmData[indexTime].centroid && $('#draw-centroid').is(':checked')) { d3.select('#centroid-line') .classed('hidden', false); // UPDATE animal direction arrow d3.select('#centroid-line') .attr('x1', function() { return swarmData[indexTime]['centroid'][0]; }) .attr('y1', function() { return -swarmData[indexTime]['centroid'][1]; }) .attr('x2', function() { return (swarmData[indexTime]['centroid'][0] + 2 * animalScale); }) .attr('y2', function() { return -swarmData[indexTime]['centroid'][1]; }) .attr('transform', function() { return 'rotate(' + -swarmData[indexTime]['direction'] + ' ' + swarmData[indexTime]['centroid'][0] + ' ' + -swarmData[indexTime]['centroid'][1] + ')'; }); } else { // hide the arrows d3.select('#centroid-line') .attr('class', 'hidden'); } // medoid if (medoidAnimal !== -1) { d3.selectAll('#animal-' + medoidAnimal) .classed('medoid', false); medoidAnimal = swarmData[indexTime]['medoid']; d3.selectAll('#animal-' + medoidAnimal) .classed('medoid', true); } //next frame indexTime++; updateLineChart(); //check if play button is active and if the animation is not finished if (indexTime >= swarmData.length) { //start again from the start indexTime = 0; draw(); } else if (playBoolean) { //measure execution time // let t1 = performance.now(); // console.log(t1 - t0); // in milliseconds draw(); } }, timeToWait); } /************************************************ Setter *************************************************/ /** * Set the index time to a new value * @param {Number} value - new time step */ export function setIndexTime(value) { if (typeof value === 'number' && (indexTime <= swarmData.length)) { indexTime = value; } else { indexTime = 0; } } /** * Decrease time by 1 */ export function decIndexTime() { indexTime = indexTime - 1; } /** * Set the the new active scale - e.g. speed, acceleration, black etc. * @param {String} value - active scale for the individual animals */ export function setActiveScale(value) { activeScale = value; } /** * Set the new medoid animal * @param {Number} value - Unique id of the animal */ export function setMedoidAnimal(value) { medoidAnimal = value; } /** * Set the selected and highlighted animals * @param {array} value - array of unqiue id of the animals */ export function setActiveAnimals(value) { activeAnimals = value; }
#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('easy-dashboard-clinet:server'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); }
function drawStepBarVisualization(d) { var data = d // Create and populate the data table. var dataTable = new google.visualization.DataTable(); dataTable.addColumn('string', 'Build Date'); dataTable.addColumn('number', 'Duration (nanoseconds)'); dataTable.addColumn('string', 'Status'); dataTable.addColumn('string', 'Feature'); dataTable.addColumn('string', 'Scenario'); dataTable.addColumn('string', 'Step'); dataTable.addColumn({type:'string', role:'tooltip'}); dataTable.addColumn('string', 'Browser'); dataTable.addColumn('string', 'Mobilizer Version'); for(var i=0; i < data.length; i++) { dataTable.addRow([data[i].build_date+"_"+data[i].build_time, data[i].duration, data[i].status, data[i].feature_name, data[i].scenario_name, data[i].name, data[i].duration_converted + "\n hr:min:sec:ms \n" + data[i].mobilizer_build_tag, data[i].browser, data[i].mobilizer]); } var statusBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'control1', 'options': { 'filterColumnLabel': 'Status', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var browserBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'browser1', 'options': { 'filterColumnLabel': 'Browser', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var versionBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'version1', 'options': { 'filterColumnLabel': 'Mobilizer Version', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var featureBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'featureBarFilter', 'options': { 'filterColumnLabel': 'Feature', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false }, }, }); var scenarioBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'scenarioBarFilter', 'options': { 'filterColumnLabel': 'Scenario', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false }, }, }); var stepBarPicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'stepBarFilter', 'options': { 'filterColumnLabel': 'Step', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false, 'sortValues': false }, }, }); // Define a slider control for the 'Build Date' column var slider = new google.visualization.ControlWrapper({ 'controlType': 'StringFilter', 'containerId': 'control2', 'options': { 'filterColumnLabel': 'Build Date', 'ui': {'labelStacking': 'vertical'} } }); var barChart = new google.visualization.ChartWrapper({ 'chartType': 'BarChart', 'containerId': 'chart1', 'options': { 'width': 900, 'height': 700, 'tooltip': {'column':6}, 'hAxis': { 'slantedText': true, 'title': "Duration (nanoseconds)" }, 'vAxis': { 'title': "Run Date" }, 'chartArea': {top: 10, right: 0, bottom: 0} }, // Configure the barchart to use columns 0 (Build Date/Time Stamp) and 1 (Duration) 'view': {'columns': [0, 1, 6]} }); // Create the dashboard. new google.visualization.Dashboard(document.getElementById('dashboard')). bind(statusBarPicker, barChart). bind(featureBarPicker, [barChart, scenarioBarPicker, stepBarPicker, statusBarPicker]). bind(scenarioBarPicker, [barChart, stepBarPicker, statusBarPicker]). bind(stepBarPicker, [barChart, slider, statusBarPicker]). bind(slider, barChart). bind(browserBarPicker, barChart). bind(versionBarPicker, barChart). // Draw the dashboard draw(dataTable); } function drawStepLineVisualization(d2) { data3 = d2 // Create and populate the data table. var dataTable3 = new google.visualization.DataTable(); dataTable3.addColumn('date', 'Build Date'); dataTable3.addColumn('number', 'Duration (nanoseconds)'); dataTable3.addColumn('string', 'Status'); dataTable3.addColumn('string', 'Feature'); dataTable3.addColumn('string', 'Scenario'); dataTable3.addColumn('string', 'Step'); dataTable3.addColumn({type:'string', role:'tooltip'}); dataTable3.addColumn('string', 'Browser'); dataTable3.addColumn('string', 'Mobilizer Version'); for(var i=0; i < data3.length; i++) { dataTable3.addRow([new Date(data3[i].runstamp), data3[i].duration, data3[i].status, data3[i].feature_name, data3[i].scenario_name, data3[i].name, data3[i].duration_converted + "\n hr:min:sec:ms \n" + data3[i].mobilizer_build_tag, data3[i].browser, data3[i].mobilizer]); } var datePicker = new google.visualization.ControlWrapper({ 'controlType': 'ChartRangeFilter', 'containerId': 'suiteRangeFilter', 'options': { // Filter by the date axis. 'filterColumnIndex': 0, 'ui': { 'chartType': 'LineChart', 'chartOptions': { 'chartArea': {'width': '90%', 'height':'70'}, 'hAxis': {'textPosition': 'out', 'slantedText': true} }, // Display a single series that shows the closing value of the stock. // Thus, this view has two columns: the date (axis) and the stock value (line series). 'chartView': { 'columns': [0, 1] } }}, }); var featureLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'featureLineFilter', 'options': { 'filterColumnLabel': 'Feature', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false } }, }); var scenarioLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'scenarioLineFilter', 'options': { 'filterColumnLabel': 'Scenario', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false } }, }) var stepLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'stepLineFilter', 'options': { 'filterColumnLabel': 'Step', 'ui': { 'labelStacking': 'vertical', 'allowNone': false, 'allowTyping': false, 'allowMultiple': false, 'sortValues': false } }, }) var statusLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'statusLineFilter', 'options': { 'filterColumnLabel': 'Status', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var browserLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'browser2', 'options': { 'filterColumnLabel': 'Browser', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var versionLinePicker = new google.visualization.ControlWrapper({ 'controlType': 'CategoryFilter', 'containerId': 'version2', 'options': { 'filterColumnLabel': 'Mobilizer Version', 'ui': { 'labelStacking': 'vertical', 'allowTyping': false, 'allowMultiple': false } } }); var lineChart = new google.visualization.ChartWrapper({ 'chartType': 'LineChart', 'containerId': 'linechart', 'options': { 'width': 1010, 'height': 700, 'pointSize': 6, 'tooltip': {'column':6}, 'hAxis': { 'slantedText': true, 'title': "Run Date" }, 'vAxis':{ 'title': "Duration (nanoseconds)" }, 'chartArea': {top: 10, right: 0, bottom: 0} }, // Configure the barchart to use columns 0 (Build Date/Time Stamp) and 1 (Duration) 'view': {'columns': [0, 1, 6]} }); // Create the dashboard. new google.visualization.Dashboard(document.getElementById('dashboard3')). bind(statusLinePicker, [lineChart, datePicker]). bind(stepLinePicker, [lineChart, datePicker, statusLinePicker]). bind(scenarioLinePicker, [lineChart, datePicker, stepLinePicker, statusLinePicker]). bind(featureLinePicker, [lineChart, datePicker, scenarioLinePicker, stepLinePicker, statusLinePicker]). bind(datePicker, lineChart). bind(browserLinePicker, lineChart). bind(versionLinePicker, lineChart). // Draw the dashboard draw(dataTable3); } function showStepFailedImage(){ $('#imageButton').toggle(); }
$(document).ready(function() { var converter = new Showdown.converter(); $.ajax({ method: "GET", url: "https://kriek.co.uk/cantrip/README.md" }).done(function(response) { // Render data var id = getMyId(); // $('.main').append(converter.makeHtml(decodeURIComponent(escape(atob(response.content.replace(/\s/g, '')))))); $('.main').append(converter.makeHtml(response.replace(/randomID/g,id))); // Formatting $('pre').addClass('prettyprint'); $('#cantrip').remove(); prettyPrint(); // set correct license url $('a[href="LICENSE"]').attr("href","https://raw.githubusercontent.com/kriekapps/cantrip/master/LICENSE").attr("target","_blank"); $('a[href="https://kriek.co.uk/cantrip"]').remove(); var firstCurl = true; //Add try buttons $(".prettyprint").each(function(index) { var innerText = $(this).text(); if (innerText.indexOf("$ curl") > -1) { var footer = $("<div class='codeFooter'></div>"); var button = $("<button class='tryit'>Try it out</button>"); footer.append(button); $(this).after(footer); button.click(function() { displayDialog(parseCURL(innerText)); }); if (firstCurl) { firstCurl = false; $(footer).after("<div class='footNote'>Note: a personal cantrip instance has been generated for you with the ID " + getMyId() + ". Feel free to play with it!</div>"); } } }); }).fail(function(xhr, err) { console.log(xhr, err); }); $(".dialog .baseUrl").text("https://cantrip.kriek.io/" + getMyId() + "/"); $(".dialog .close, .cover").click(function() { $(".dialog, .cover").hide(); }); $(".dialog .submit").click(function() { $(".dialog .data").css({ "color": "black" }); //Check if we're sending valid JSON if ($(".dialog button.active").data("method") !== "GET" && $(".dialog button.active").data("method") !== "DELETE") { try { JSON.parse($(".dialog .data").val()); } catch(err) { $(".dialog .data").css({ "color": "#c00029" }); return; } } $(".dialog .response code").html("").parent().removeClass("prettyprinted"); $.ajax({ method: $(".dialog button.active").data("method"), dataType: "JSON", url: "https://cantrip.kriek.io/" + getMyId() + "/" + $(".dialog .url").val(), data: $(".dialog .data").val(), contentType: "application/json" }).done(function(response) { $(".dialog .response code").html(JSON.stringify(response, null, "\t")); prettyPrint(); }).fail(function(response) { $(".dialog .response code").html(JSON.stringify(JSON.parse(response.responseText), null, "\t")); prettyPrint(); }); }); $(".dialog .methodButtons button").click(function() { $(".dialog .methodButtons button").removeClass("active"); $(this).addClass("active"); }); }); function getMyId(){ var id = ""; if (Modernizr.localstorage) { id = localStorage.getItem("cantripId") || Math.random().toString(36).substring(7); localStorage.setItem("cantripId", id); } else { id = Math.random().toString(36).substring(7); } return id; } function parseCURL(text) { var data = { method: "GET", url: "https://cantrip.kriek.io/" + getMyId(), data: "" } var fragments = text.split("\\\n"); for (var i = 0; i < fragments.length; i++) { var fragment = fragments[i].trim(); if (fragment.indexOf("-X") > -1) { data.method = fragment.split(" ")[1]; } else if (fragment.indexOf("-d") > -1) { data.data = fragment.replace("-d ", "").replace(/\'/g, ""); } else { data.url = fragment.replace("$ curl ", "").replace(/\"/g, ""); } } return data; } function displayDialog(data) { $(".dialog .url").val(data.url.replace("https://cantrip.kriek.io/" + getMyId() + "/", "")); $(".dialog .data").val(data.data); $(".dialog .methodButtons button").removeClass("active"); $(".dialog .methodButtons button[data-method=" + data.method + "]").addClass("active"); $(".dialog .response code").html(""); $(".dialog, .cover").show(); $(".dialog").css({ top: (window.scrollY || window.pageYOffset) + 100 }); }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), errorHandler = require('../errors.server.controller'), mongoose = require('mongoose'), passport = require('passport'), ccap = require('ccap'), fs = require('fs'), User = mongoose.model('User'); var i = 0; exports.captcha_x = function(req,res){ var captcha = ccap(240); var ary = captcha.get(); fs.rename('/Downloads/meanjs/public/cap_img/captcha_.bmp', '/Downloads/meanjs/public/cap_img/'+ ary[0] + '.bmp', function (err) { if (err) throw err; console.log('renamed complete'); }); res.json(ary); console.log(ary[0]); }; /** * Signup */ exports.signup = function(req, res) { // For security measurement we remove the roles from the req.body object delete req.body.roles; // Init Variables var user = new User(req.body); var message = null; // Add missing user fields user.provider = 'local'; user.displayName = user.firstName + ' ' + user.lastName; // Then save the user user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { // Remove sensitive data before login user.password = undefined; user.salt = undefined; req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } }); }; /** * Signin after passport authentication */ exports.signin = function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err || !user) { res.status(400).send(info); } else { // Remove sensitive data before login user.password = undefined; user.salt = undefined; req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } })(req, res, next); }; /** * Signout */ exports.signout = function(req, res) { req.logout(); res.redirect('/'); }; /** * OAuth callback */ exports.oauthCallback = function(strategy) { return function(req, res, next) { passport.authenticate(strategy, function(err, user, redirectURL) { if (err || !user) { return res.redirect('/#!/signin'); } req.login(user, function(err) { if (err) { return res.redirect('/#!/signin'); } return res.redirect(redirectURL || '/'); }); })(req, res, next); }; }; /** * Helper function to save or update a OAuth user profile */ exports.saveOAuthUserProfile = function(req, providerUserProfile, done) { if (!req.user) { // Define a search query fields var searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField; var searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField; // Define main provider search query var mainProviderSearchQuery = {}; mainProviderSearchQuery.provider = providerUserProfile.provider; mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]; // Define additional provider search query var additionalProviderSearchQuery = {}; additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]; // Define a search query to find existing user with current provider profile var searchQuery = { $or: [mainProviderSearchQuery, additionalProviderSearchQuery] }; User.findOne(searchQuery, function(err, user) { if (err) { return done(err); } else { if (!user) { var possibleUsername = providerUserProfile.username || ((providerUserProfile.email) ? providerUserProfile.email.split('@')[0] : ''); User.findUniqueUsername(possibleUsername, null, function(availableUsername) { user = new User({ firstName: providerUserProfile.firstName, lastName: providerUserProfile.lastName, username: availableUsername, displayName: providerUserProfile.displayName, email: providerUserProfile.email, provider: providerUserProfile.provider, providerData: providerUserProfile.providerData }); // And save the user user.save(function(err) { return done(err, user); }); }); } else { return done(err, user); } } }); } else { // User is already logged in, join the provider data to the existing user var user = req.user; // Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured if (user.provider !== providerUserProfile.provider && (!user.additionalProvidersData || !user.additionalProvidersData[providerUserProfile.provider])) { // Add the provider data to the additional provider data field if (!user.additionalProvidersData) user.additionalProvidersData = {}; user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData; // Then tell mongoose that we've updated the additionalProvidersData field user.markModified('additionalProvidersData'); // And save the user user.save(function(err) { return done(err, user, '/#!/settings/accounts'); }); } else { return done(new Error('User is already connected using this provider'), user); } } }; /** * Remove OAuth provider */ exports.removeOAuthProvider = function(req, res, next) { var user = req.user; var provider = req.param('provider'); if (user && provider) { // Delete the additional provider if (user.additionalProvidersData[provider]) { delete user.additionalProvidersData[provider]; // Then tell mongoose that we've updated the additionalProvidersData field user.markModified('additionalProvidersData'); } user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } }); } };
var insertTo = "icerik"; function insertAtCaret(areaId,text) { var caretPos = document.getElementById(areaId).selectionStart; var textarea = $("#" + areaId); var textAreaTxt = textarea.val(); textarea.val(textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos) ); } function bb(code, isArgumented, alerttext) { if (isArgumented) { var argument = prompt(alerttext,""); if (argument !== null) insertAtCaret(insertTo, "[" + code + "="+ argument +"]" + "[/" + code + "]"); } if (!isArgumented) insertAtCaret(insertTo, "[" + code + "]" + "[/" + code + "]"); }
(function() { var multiplex = Reveal.getConfig().multiplex, socketId = multiplex.id, socket = io.connect(multiplex.url); socket.on(multiplex.id, function(data) { // ignore data from sockets that aren't ours if(data.socketId !== socketId) { return; } Reveal.slide(data.indexh, data.indexv, data.indexf, 'remote'); }); }());
/* * The compiler used to require O(2^N) passes to copmile inner functions * (where N is function nesting level). Deeply nested functions would * hit the compiler "token limit" and cause a RangeError to prevent the * compiler from taking an inordinate amount of time. * * This has now been fixed (Duktape 0.10.0) so test that deep nesting * works properly. */ /*--- { "custom": true, "slow": true } ---*/ /*=== returned ===*/ function deepInnerFunctionTest() { var txt = ''; var i; for (i = 0; i < 1000; i++) { txt = 'function func' + i + '() { ' + txt + ' }'; } //print(txt); eval(txt); } try { deepInnerFunctionTest(); print('returned'); } catch (e) { print(e.name); }
// Hprose for JavaScript v2.0.33 // Copyright (c) 2008-2016 http://hprose.com // Hprose is freely distributable under the MIT license. // For all details and documentation: // https://github.com/hprose/hprose-js /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Init.js * * * * hprose init for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ var hprose = {}; /* global global, window, self */ hprose.global = ( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * DeviceOne.js * * * * setTimeout patch for DeviceOne. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (global) { 'use strict'; if (typeof global.setTimeout !== "undefined") { return; } if (typeof global.require !== "function") { return; } var deviceone; try { deviceone = global.require("deviceone"); } catch (e) { return; } if (!deviceone) { return; } global.setTimeout = function(func, delay) { if (delay <= 0) { delay = 1; } var timer = deviceone.mm("do_Timer"); timer.delay = delay; timer.interval = delay; timer.on('tick', function() { timer.stop(); func(); }); timer.start(); return timer; }; global.clearTimeout = function(timer) { if (timer.isStart()) { timer.stop(); } }; })(hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Base64.js * * * * Base64 for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (global) { 'use strict'; if (typeof(global.btoa) === "undefined") { global.btoa = (function() { var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); return function(str) { var buf, i, j, len, r, l, c; i = j = 0; len = str.length; r = len % 3; len = len - r; l = (len / 3) << 2; if (r > 0) { l += 4; } buf = new Array(l); while (i < len) { c = str.charCodeAt(i++) << 16 | str.charCodeAt(i++) << 8 | str.charCodeAt(i++); buf[j++] = base64EncodeChars[c >> 18] + base64EncodeChars[c >> 12 & 0x3f] + base64EncodeChars[c >> 6 & 0x3f] + base64EncodeChars[c & 0x3f] ; } if (r === 1) { c = str.charCodeAt(i++); buf[j++] = base64EncodeChars[c >> 2] + base64EncodeChars[(c & 0x03) << 4] + "=="; } else if (r === 2) { c = str.charCodeAt(i++) << 8 | str.charCodeAt(i++); buf[j++] = base64EncodeChars[c >> 10] + base64EncodeChars[c >> 4 & 0x3f] + base64EncodeChars[(c & 0x0f) << 2] + "="; } return buf.join(''); }; })(); } if (typeof(global.atob) === "undefined") { global.atob = (function() { var base64DecodeChars = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; return function(str) { var c1, c2, c3, c4; var i, j, len, r, l, out; len = str.length; if (len % 4 !== 0) { return ''; } if (/[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\+\/\=]/.test(str)) { return ''; } if (str.charAt(len - 2) === '=') { r = 1; } else if (str.charAt(len - 1) === '=') { r = 2; } else { r = 0; } l = len; if (r > 0) { l -= 4; } l = (l >> 2) * 3 + r; out = new Array(l); i = j = 0; while (i < len) { // c1 c1 = base64DecodeChars[str.charCodeAt(i++)]; if (c1 === -1) { break; } // c2 c2 = base64DecodeChars[str.charCodeAt(i++)]; if (c2 === -1) { break; } out[j++] = String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4)); // c3 c3 = base64DecodeChars[str.charCodeAt(i++)]; if (c3 === -1) { break; } out[j++] = String.fromCharCode(((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2)); // c4 c4 = base64DecodeChars[str.charCodeAt(i++)]; if (c4 === -1) { break; } out[j++] = String.fromCharCode(((c3 & 0x03) << 6) | c4); } return out.join(''); }; })(); } })(hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Helper.js * * * * hprose helper for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, undefined) { 'use strict'; var propertyToMethod = function(prop) { if ('get' in prop && 'set' in prop) { return function() { if (arguments.length === 0) { return prop.get(); } prop.set(arguments[0]); }; } if ('get' in prop) { return prop.get; } if ('set' in prop) { return prop.set; } } var defineProperties = (typeof Object.defineProperties !== 'function' ? function(obj, properties) { var buildinMethod = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; buildinMethod.forEach(function(name) { var prop = properties[name]; if ('value' in prop) { obj[name] = prop.value; } }); for (var name in properties) { var prop = properties[name]; obj[name] = undefined; if ('value' in prop) { obj[name] = prop.value; } else if ('get' in prop || 'set' in prop) { obj[name] = propertyToMethod(prop); } } } : function(obj, properties) { for (var name in properties) { var prop = properties[name]; if ('get' in prop || 'set' in prop) { properties[name] = { value: propertyToMethod(prop) }; } } Object.defineProperties(obj, properties); } ); var Temp = function() {}; var createObject = (typeof Object.create !== 'function' ? function(prototype, properties) { if (typeof prototype != 'object' && typeof prototype != 'function') { throw new TypeError('prototype must be an object or function'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; if (properties) { defineProperties(result, properties); } return result; } : function(prototype, properties) { if (properties) { for (var name in properties) { var prop = properties[name]; if ('get' in prop || 'set' in prop) { properties[name] = { value: propertyToMethod(prop) }; } } return Object.create(prototype, properties); } return Object.create(prototype); } ); var generic = function(method) { if (typeof method !== "function") { throw new TypeError(method + " is not a function"); } return function(context) { return method.apply(context, Array.prototype.slice.call(arguments, 1)); }; }; var toArray = function(arrayLikeObject) { var n = arrayLikeObject.length; var a = new Array(n); for (var i = 0; i < n; ++i) { a[i] = arrayLikeObject[i]; } return a; }; var toBinaryString = function(bytes) { if (bytes instanceof ArrayBuffer) { bytes = new Uint8Array(bytes); } var n = bytes.length; if (n < 0xFFFF) { return String.fromCharCode.apply(String, toArray(bytes)); } var remain = n & 0x7FFF; var count = n >> 15; var a = new Array(remain ? count + 1 : count); for (var i = 0; i < count; ++i) { a[i] = String.fromCharCode.apply(String, toArray(bytes.subarray(i << 15, (i + 1) << 15))); } if (remain) { a[count] = String.fromCharCode.apply(String, toArray(bytes.subarray(count << 15, n))); } return a.join(''); }; var toUint8Array = function(bs) { var n = bs.length; var data = new Uint8Array(n); for (var i = 0; i < n; i++) { data[i] = bs.charCodeAt(i) & 0xFF; } return data; }; var parseuri = function(url) { var pattern = new RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"); var matches = url.match(pattern); var host = matches[4].split(':', 2); return { protocol: matches[1], host: matches[4], hostname: host[0], port: parseInt(host[1], 10) || 0, path: matches[5], query: matches[7], fragment: matches[9] }; }; var isObjectEmpty = function (obj) { if (obj) { var prop; for (prop in obj) { return false; } } return true; }; hprose.defineProperties = defineProperties; hprose.createObject = createObject; hprose.generic = generic; hprose.toBinaryString = toBinaryString; hprose.toUint8Array = toUint8Array; hprose.toArray = toArray; hprose.parseuri = parseuri; hprose.isObjectEmpty = isObjectEmpty; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Polyfill.js * * * * Polyfill for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (generic, undefined) { 'use strict'; /* Function */ if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), toBind = this, NOP = function() {}, bound = function() { return toBind.apply(this instanceof NOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { NOP.prototype = this.prototype; } bound.prototype = new NOP(); return bound; }; } /* Array */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement /*, fromIndex */) { if (this === null || this === undefined) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); var len = o.length >>> 0; if (len === 0) { return -1; } var n = +Number(arguments[1]) || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in o && o[k] === searchElement) { return k; } k++; } return -1; }; } if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(searchElement /*, fromIndex */) { if (this === null || this === undefined) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); var len = o.length >>> 0; if (len === 0) { return -1; } var n = +Number(arguments[1]) || 0; if (Math.abs(n) === Infinity) { n = 0; } for (var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { if (k in o && o[k] === searchElement) { return k; } } return -1; }; } if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(fun + " is not a function"); } var res = []; var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // in case fun mutates this if (fun.call(thisp, val, i, t)) { res.push(val); } } } return res; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(fun + " is not a function"); } var thisp = arguments[1]; for (var i = 0; i <len; i++) { if (i in t) { fun.call(thisp, t[i], i, t); } } }; } if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(fun + " is not a function"); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t && !fun.call(thisp, t[i], i, t)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(fun + " is not a function"); } var thisp = arguments[1]; var res = new Array(len); for (var i = 0; i <len; i++) { if (i in t) { res[i] = fun.call(thisp, t[i], i, t); } } return res; }; } if (!Array.prototype.some) { Array.prototype.some = function(fun /*, thisp */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(fun + " is not a function"); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisp, t[i], i, t)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function(callbackfn /*, initialValue */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof callbackfn !== "function") { throw new TypeError("First argument is not callable"); } if (len === 0 && arguments.length === 1) { // == on purpose to test 0 and false. throw new TypeError("Array length is 0 and no second argument"); } var i = 0, accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { accumulator = t[0]; // Increase i to start searching the secondly defined element in the array i = 1; // start accumulating at the second element } for (; i < len; ++i) { if (i in t) { accumulator = callbackfn.call(undefined, accumulator, t[i], i, t); } } return accumulator; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function(callbackfn /*, initialValue */) { if (this === null || this === undefined) { throw new TypeError("this is null or not defined"); } var t = Object(this); var len = t.length >>> 0; if (typeof callbackfn !== "function") { throw new TypeError("First argument is not callable"); } // no value to return if no initial value, empty array if (len === 0 && arguments.length === 1) { throw new TypeError("Array length is 0 and no second argument"); } var k = len - 1; var accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { do { if (k in t) { accumulator = t[k--]; break; } // if array contains no values, no initial value to return if (--k < 0) { throw new TypeError("Array contains no values"); } } while (true); } while (k >= 0) { if (k in t) { accumulator = callbackfn.call(undefined, accumulator, t[k], k, t); } k--; } return accumulator; }; } if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/ ) { var O = Object(this); var len = parseInt(O.length, 10) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1], 10) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN return true; } k++; } return false; }; } if (!Array.prototype.find) { Array.prototype.find = function(predicate) { if (this === null || this === undefined) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } if (!Array.prototype.findIndex) { Array.prototype.findIndex = function(predicate) { if (this === null || this === undefined) { throw new TypeError('Array.prototype.findIndex called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; }; } if (!Array.prototype.fill) { Array.prototype.fill = function(value) { if (this === null || this === undefined) { throw new TypeError('this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; var start = arguments[1]; var relativeStart = start >> 0; var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); var end = arguments[2]; var relativeEnd = end === undefined ? len : end >> 0; var f = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); while (k < f) { O[k] = value; k++; } return O; }; } if (!Array.prototype.copyWithin) { Array.prototype.copyWithin = function(target, start/*, end*/) { if (this === null || this === undefined) { throw new TypeError('this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; var relativeTarget = target >> 0; var to = relativeTarget < 0 ? Math.max(len + relativeTarget, 0) : Math.min(relativeTarget, len); var relativeStart = start >> 0; var from = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); var end = arguments[2]; var relativeEnd = end === undefined ? len : end >> 0; var f = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); var count = Math.min(f - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (from in O) { O[to] = O[from]; } else { delete O[to]; } from += direction; to += direction; count--; } return O; }; } if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } if (!Array.from) { Array.from = (function() { var toStr = Object.prototype.toString; var isCallable = function(fn) { return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; }; var toInteger = function(value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var maxSafeInteger = Math.pow(2, 53) - 1; var toLength = function(value) { var len = toInteger(value); return Math.min(Math.max(len, 0), maxSafeInteger); }; return function(arrayLike/*, mapFn, thisArg */) { var C = this; var items = Object(arrayLike); if (arrayLike === null || arrayLike === undefined) { throw new TypeError("Array.from requires an array-like object - not null or undefined"); } var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } if (arguments.length > 2) { T = arguments[2]; } } var len = toLength(items.length); var A = isCallable(C) ? Object(new C(len)) : new Array(len); var k = 0; var kValue; while (k < len) { kValue = items[k]; if (mapFn) { A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); } else { A[k] = kValue; } k += 1; } A.length = len; return A; }; }()); } if (!Array.of) { Array.of = function() { return Array.prototype.slice.call(arguments); }; } /* String */ if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position){ position = position || 0; return this.substr(position, searchString.length) === searchString; }; } if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; } if (!String.prototype.includes) { String.prototype.includes = function() { if (typeof arguments[1] === "number") { if (this.length < arguments[0].length + arguments[1].length) { return false; } else { return this.substr(arguments[1], arguments[0].length) === arguments[0]; } } else { return String.prototype.indexOf.apply(this, arguments) !== -1; } }; } if (!String.prototype.repeat) { String.prototype.repeat = function(count) { var str = this.toString(); count = +count; if (count !== count) { count = 0; } if (count < 0) { throw new RangeError('repeat count must be non-negative'); } if (count === Infinity) { throw new RangeError('repeat count must be less than infinity'); } count = Math.floor(count); if (str.length === 0 || count === 0) { return ''; } // Ensuring count is a 31-bit integer allows us to heavily optimize the // main part. But anyway, most current (August 2014) browsers can't handle // strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) { throw new RangeError('repeat count must not overflow maximum string size'); } var rpt = ''; for (;;) { if ((count & 1) === 1) { rpt += str; } count >>>= 1; if (count === 0) { break; } str += str; } // Could we try: // return Array(count + 1).join(this); return rpt; }; } if (!String.prototype.trim) { String.prototype.trim = function() { return this.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); }; } if (!String.prototype.trimLeft) { String.prototype.trimLeft = function() { return this.toString().replace(/^[\s\xa0]+/, ''); }; } if (!String.prototype.trimRight) { String.prototype.trimRight = function() { return this.toString().replace(/[\s\xa0]+$/, ''); }; } /* Object */ if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { throw new TypeError('Object.keys called on non-object'); } var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); } /* Date */ if (!Date.now) { Date.now = function () { return +(new Date()); }; } if (!Date.prototype.toISOString) { var f = function(n) { return n < 10 ? '0' + n : n; }; Date.prototype.toISOString = function () { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; } function genericMethods(obj, properties) { var proto = obj.prototype; for (var i = 0, len = properties.length; i < len; i++) { var property = properties[i]; var method = proto[property]; if (typeof method === 'function' && typeof obj[property] === 'undefined') { obj[property] = generic(method); } } } genericMethods(Array, [ "pop", "push", "reverse", "shift", "sort", "splice", "unshift", "concat", "join", "slice", "indexOf", "lastIndexOf", "filter", "forEach", "every", "map", "some", "reduce", "reduceRight", "includes", "find", "findIndex", "fill", "copyWithin" ]); genericMethods(String, [ 'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt', 'charCodeAt', 'indexOf', 'lastIndexOf', 'include', 'startsWith', 'endsWith', 'repeat', 'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase', 'toLocaleUpperCase', 'match', 'search', 'replace', 'split', 'substr', 'concat', 'slice' ]); })(hprose.generic); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HarmonyMaps.js * * * * Harmony Maps for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (global) { 'use strict'; var hasWeakMap = 'WeakMap' in global; var hasMap = 'Map' in global; var hasForEach = true; if (hasMap) { hasForEach = 'forEach' in new global.Map(); } if (hasWeakMap && hasMap && hasForEach) { return; } var hasObject_create = 'create' in Object; var createNPO = function () { return hasObject_create ? Object.create(null) : {}; }; var namespaces = createNPO(); var count = 0; var reDefineValueOf = function (obj) { var privates = createNPO(); var baseValueOf = obj.valueOf; var valueOf = function (namespace, n) { if ((this === obj) && (n in namespaces) && (namespaces[n] === namespace)) { if (!(n in privates)) { privates[n] = createNPO(); } return privates[n]; } else { return baseValueOf.apply(this, arguments); } }; if (hasObject_create && 'defineProperty' in Object) { Object.defineProperty(obj, 'valueOf', { value: valueOf, writable: true, configurable: true, enumerable: false }); } else { obj.valueOf = valueOf; } }; if (!hasWeakMap) { global.WeakMap = function WeakMap() { var namespace = createNPO(); var n = count++; namespaces[n] = namespace; var map = function (key) { if (key !== Object(key)) { throw new Error('value is not a non-null object'); } var privates = key.valueOf(namespace, n); if (privates !== key.valueOf()) { return privates; } reDefineValueOf(key); return key.valueOf(namespace, n); }; var m = this; if (hasObject_create) { m = Object.create(WeakMap.prototype, { get: { value: function (key) { return map(key).value; }, writable: false, configurable: false, enumerable: false }, set: { value: function (key, value) { map(key).value = value; }, writable: false, configurable: false, enumerable: false }, has: { value: function (key) { return 'value' in map(key); }, writable: false, configurable: false, enumerable: false }, 'delete': { value: function (key) { return delete map(key).value; }, writable: false, configurable: false, enumerable: false }, clear: { value: function () { delete namespaces[n]; n = count++; namespaces[n] = namespace; }, writable: false, configurable: false, enumerable: false } }); } else { m.get = function (key) { return map(key).value; }; m.set = function (key, value) { map(key).value = value; }; m.has = function (key) { return 'value' in map(key); }; m['delete'] = function (key) { return delete map(key).value; }; m.clear = function () { delete namespaces[n]; n = count++; namespaces[n] = namespace; }; } if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); } } return m; }; } if (!hasMap) { var objectMap = function () { var namespace = createNPO(); var n = count++; var nullMap = createNPO(); namespaces[n] = namespace; var map = function (key) { if (key === null) { return nullMap; } var privates = key.valueOf(namespace, n); if (privates !== key.valueOf()) { return privates; } reDefineValueOf(key); return key.valueOf(namespace, n); }; return { get: function (key) { return map(key).value; }, set: function (key, value) { map(key).value = value; }, has: function (key) { return 'value' in map(key); }, 'delete': function (key) { return delete map(key).value; }, clear: function () { delete namespaces[n]; n = count++; namespaces[n] = namespace; } }; }; var noKeyMap = function () { var map = createNPO(); return { get: function () { return map.value; }, set: function (_, value) { map.value = value; }, has: function () { return 'value' in map; }, 'delete': function () { return delete map.value; }, clear: function () { map = createNPO(); } }; }; var scalarMap = function () { var map = createNPO(); return { get: function (key) { return map[key]; }, set: function (key, value) { map[key] = value; }, has: function (key) { return key in map; }, 'delete': function (key) { return delete map[key]; }, clear: function () { map = createNPO(); } }; }; if (!hasObject_create) { var stringMap = function () { var map = {}; return { get: function (key) { return map['!' + key]; }, set: function (key, value) { map['!' + key] = value; }, has: function (key) { return ('!' + key) in map; }, 'delete': function (key) { return delete map['!' + key]; }, clear: function () { map = {}; } }; }; } global.Map = function Map() { var map = { 'number': scalarMap(), 'string': hasObject_create ? scalarMap() : stringMap(), 'boolean': scalarMap(), 'object': objectMap(), 'function': objectMap(), 'unknown': objectMap(), 'undefined': noKeyMap(), 'null': noKeyMap() }; var size = 0; var keys = []; var m = this; if (hasObject_create) { m = Object.create(Map.prototype, { size: { get : function () { return size; }, configurable: false, enumerable: false }, get: { value: function (key) { return map[typeof(key)].get(key); }, writable: false, configurable: false, enumerable: false }, set: { value: function (key, value) { if (!this.has(key)) { keys.push(key); size++; } map[typeof(key)].set(key, value); }, writable: false, configurable: false, enumerable: false }, has: { value: function (key) { return map[typeof(key)].has(key); }, writable: false, configurable: false, enumerable: false }, 'delete': { value: function (key) { if (this.has(key)) { size--; keys.splice(keys.indexOf(key), 1); return map[typeof(key)]['delete'](key); } return false; }, writable: false, configurable: false, enumerable: false }, clear: { value: function () { keys.length = 0; for (var key in map) { map[key].clear(); } size = 0; }, writable: false, configurable: false, enumerable: false }, forEach: { value: function (callback, thisArg) { for (var i = 0, n = keys.length; i < n; i++) { callback.call(thisArg, this.get(keys[i]), keys[i], this); } }, writable: false, configurable: false, enumerable: false } }); } else { m.size = size; m.get = function (key) { return map[typeof(key)].get(key); }; m.set = function (key, value) { if (!this.has(key)) { keys.push(key); this.size = ++size; } map[typeof(key)].set(key, value); }; m.has = function (key) { return map[typeof(key)].has(key); }; m['delete'] = function (key) { if (this.has(key)) { this.size = --size; keys.splice(keys.indexOf(key), 1); return map[typeof(key)]['delete'](key); } return false; }; m.clear = function () { keys.length = 0; for (var key in map) { map[key].clear(); } this.size = size = 0; }; m.forEach = function (callback, thisArg) { for (var i = 0, n = keys.length; i < n; i++) { callback.call(thisArg, this.get(keys[i]), keys[i], this); } }; } if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); } } return m; }; } if (!hasForEach) { var OldMap = global.Map; global.Map = function Map() { var map = new OldMap(); var size = 0; var keys = []; var m = Object.create(Map.prototype, { size: { get : function () { return size; }, configurable: false, enumerable: false }, get: { value: function (key) { return map.get(key); }, writable: false, configurable: false, enumerable: false }, set: { value: function (key, value) { if (!map.has(key)) { keys.push(key); size++; } map.set(key, value); }, writable: false, configurable: false, enumerable: false }, has: { value: function (key) { return map.has(key); }, writable: false, configurable: false, enumerable: false }, 'delete': { value: function (key) { if (map.has(key)) { size--; keys.splice(keys.indexOf(key), 1); return map['delete'](key); } return false; }, writable: false, configurable: false, enumerable: false }, clear: { value: function () { if ('clear' in map) { map.clear(); } else { for (var i = 0, n = keys.length; i < n; i++) { map['delete'](keys[i]); } } keys.length = 0; size = 0; }, writable: false, configurable: false, enumerable: false }, forEach: { value: function (callback, thisArg) { for (var i = 0, n = keys.length; i < n; i++) { callback.call(thisArg, this.get(keys[i]), keys[i], this); } }, writable: false, configurable: false, enumerable: false } }); if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); } } return m; }; } })(hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * TimeoutError.js * * * * TimeoutError for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function(hprose, global) { function TimeoutError(message) { Error.call(this); this.message = message; this.name = TimeoutError.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, TimeoutError); } } TimeoutError.prototype = hprose.createObject(Error.prototype); TimeoutError.prototype.constructor = TimeoutError; global.TimeoutError = TimeoutError; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * setImmediate.js * * * * setImmediate for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function(global, undefined) { 'use strict'; if (global.setImmediate) { return; } var doc = global.document; var MutationObserver = global.MutationObserver || global.WebKitMutationObserver || global.MozMutationOvserver; var polifill = {}; var nextId = 1; var tasks = {}; function wrap(handler) { var args = Array.prototype.slice.call(arguments, 1); return function() { handler.apply(undefined, args); }; } function clear(handleId) { delete tasks[handleId]; } function run(handleId) { var task = tasks[handleId]; if (task) { try { task(); } finally { clear(handleId); } } } function create(args) { tasks[nextId] = wrap.apply(undefined, args); return nextId++; } polifill.mutationObserver = function() { var queue = [], node = doc.createTextNode(''), observer = new MutationObserver(function() { while (queue.length > 0) { run(queue.shift()); } }); observer.observe(node, {"characterData": true}); return function() { var handleId = create(arguments); queue.push(handleId); node.data = handleId & 1; return handleId; }; }; polifill.messageChannel = function() { var channel = new global.MessageChannel(); channel.port1.onmessage = function(event) { run(Number(event.data)); }; return function() { var handleId = create(arguments); channel.port2.postMessage(handleId); return handleId; }; }; polifill.nextTick = function() { return function() { var handleId = create(arguments); global.process.nextTick( wrap( run, handleId ) ); return handleId; }; }; polifill.postMessage = function() { var iframe = doc.createElement('iframe'); iframe.style.display = 'none'; doc.documentElement.appendChild(iframe); var iwin = iframe.contentWindow; iwin.document.write('<script>window.onmessage=function(){parent.postMessage(1, "*");};</script>'); iwin.document.close(); var queue = []; window.addEventListener('message', function() { while (queue.length > 0) { run(queue.shift()); } }); return function() { var handleId = create(arguments); queue.push(handleId); iwin.postMessage(1, "*"); return handleId; }; }; polifill.readyStateChange = function() { var html = doc.documentElement; return function() { var handleId = create(arguments); var script = doc.createElement('script'); script.onreadystatechange = function() { run(handleId); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); return handleId; }; }; // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = (attachTo && attachTo.setTimeout ? attachTo : global); polifill.setTimeout = function() { return function() { var handleId = create(arguments); attachTo.setTimeout( wrap( run, handleId ), 0 ); return handleId; }; }; // Don't get fooled by e.g. browserify environments. // For Node.js before 0.9 if (typeof(global.process) !== 'undefined' && Object.prototype.toString.call(global.process) === '[object process]' && !global.process.browser) { attachTo.setImmediate = polifill.nextTick(); } // For IE 6–9 else if (doc && ('onreadystatechange' in doc.createElement('script'))) { attachTo.setImmediate = polifill.readyStateChange(); } // For MutationObserver, where supported else if (doc && MutationObserver) { attachTo.setImmediate = polifill.mutationObserver(); } // For web workers, where supported else if (global.MessageChannel) { attachTo.setImmediate = polifill.messageChannel(); } // For non-IE modern browsers else if (doc && 'postMessage' in global && 'addEventListener' in global) { attachTo.setImmediate = polifill.postMessage(); } // For older browsers else { attachTo.setImmediate = polifill.setTimeout(); } attachTo.clearImmediate = clear; })(hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Future.js * * * * hprose Future for JavaScript. * * * * LastModified: Dec 5, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var PENDING = 0; var FULFILLED = 1; var REJECTED = 2; var defineProperties = hprose.defineProperties; var createObject = hprose.createObject; var hasPromise = 'Promise' in global; var setImmediate = global.setImmediate; var setTimeout = global.setTimeout; var clearTimeout = global.clearTimeout; var TimeoutError = global.TimeoutError; var foreach = Array.prototype.forEach; var slice = Array.prototype.slice; function Future(computation) { var self = this; defineProperties(this, { _subscribers: { value: [] }, resolve: { value: this.resolve.bind(this) }, reject: { value: this.reject.bind(this) } }); if (typeof computation === 'function') { setImmediate(function() { try { self.resolve(computation()); } catch(e) { self.reject(e); } }); } } function isFuture(obj) { return obj instanceof Future; } function toFuture(obj) { return isFuture(obj) ? obj : value(obj); } function isPromise(obj) { return 'function' === typeof obj.then; } function delayed(duration, value) { var computation = (typeof value === 'function') ? value : function() { return value; }; var future = new Future(); setTimeout(function() { try { future.resolve(computation()); } catch(e) { future.reject(e); } }, duration); return future; } function error(e) { var future = new Future(); future.reject(e); return future; } function value(v) { var future = new Future(); future.resolve(v); return future; } function sync(computation) { try { var result = computation(); return value(result); } catch(e) { return error(e); } } function promise(executor) { var future = new Future(); executor(future.resolve, future.reject); return future; } function arraysize(array) { var size = 0; foreach.call(array, function() { ++size; }); return size; } function all(array) { return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); var result = new Array(n); if (count === 0) { return result; } var future = new Future(); foreach.call(array, function(element, index) { toFuture(element).then(function(value) { result[index] = value; if (--count === 0) { future.resolve(result); } }, future.reject); }); return future; }); } function join() { return all(arguments); } function race(array) { return toFuture(array).then(function(array) { var future = new Future(); foreach.call(array, function(element) { toFuture(element).fill(future); }); return future; }); } function any(array) { return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); if (count === 0) { throw new RangeError('any(): array must not be empty'); } var reasons = new Array(n); var future = new Future(); foreach.call(array, function(element, index) { toFuture(element).then(future.resolve, function(e) { reasons[index] = e; if (--count === 0) { future.reject(reasons); } }); }); return future; }); } function settle(array) { return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); var result = new Array(n); if (count === 0) { return result; } var future = new Future(); foreach.call(array, function(element, index) { var f = toFuture(element); f.complete(function() { result[index] = f.inspect(); if (--count === 0) { future.resolve(result); } }); }); return future; }); } function attempt(handler/*, arg1, arg2, ... */) { var thisArg = (function() { return this; })(); var args = slice.call(arguments, 1); return all(args).then(function(args) { return handler.apply(thisArg, args); }); } function run(handler, thisArg/*, arg1, arg2, ... */) { var args = slice.call(arguments, 2); return all(args).then(function(args) { return handler.apply(thisArg, args); }); } function isGenerator(obj) { if (!obj) { return false; } return 'function' == typeof obj.next && 'function' == typeof obj['throw']; } function isGeneratorFunction(obj) { if (!obj) { return false; } var constructor = obj.constructor; if (!constructor) { return false; } if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) { return true; } return isGenerator(constructor.prototype); } function getThunkCallback(future) { return function(err, res) { if (err instanceof Error) { return future.reject(err); } if (arguments.length < 2) { return future.resolve(err); } if (err === null || err === undefined) { res = slice.call(arguments, 1); } else { res = slice.call(arguments, 0); } if (res.length == 1) { future.resolve(res[0]); } else { future.resolve(res); } }; } function thunkToPromise(fn) { if (isGeneratorFunction(fn) || isGenerator(fn)) { return co(fn); } var thisArg = (function() { return this; })(); var future = new Future(); fn.call(thisArg, getThunkCallback(future)); return future; } function thunkify(fn) { return function() { var args = slice.call(arguments, 0); var thisArg = this; var results = new Future(); args.push(function() { thisArg = this; results.resolve(arguments); }); try { fn.apply(this, args); } catch (err) { results.resolve([err]); } return function(done) { results.then(function(results) { done.apply(thisArg, results); }); }; }; } function promisify(fn) { return function() { var args = slice.call(arguments, 0); var future = new Future(); args.push(getThunkCallback(future)); try { fn.apply(this, args); } catch (err) { future.reject(err); } return future; }; } function toPromise(obj) { if (isGeneratorFunction(obj) || isGenerator(obj)) { return co(obj); } return toFuture(obj); } function co(gen) { var thisArg = (function() { return this; })(); if (typeof gen === 'function') { var args = slice.call(arguments, 1); gen = gen.apply(thisArg, args); } if (!gen || typeof gen.next !== 'function') { return toFuture(gen); } var future = new Future(); function onFulfilled(res) { try { next(gen.next(res)); } catch (e) { future.reject(e); } } function onRejected(err) { try { next(gen['throw'](err)); } catch (e) { future.reject(e); } } function next(ret) { if (ret.done) { future.resolve(ret.value); } else { (('function' == typeof ret.value) ? thunkToPromise(ret.value) : toPromise(ret.value)).then(onFulfilled, onRejected); } } onFulfilled(); return future; } function wrap(handler, thisArg) { return function() { thisArg = thisArg || this; return all(arguments).then(function(args) { var result = handler.apply(thisArg, args); if (isGeneratorFunction(result) || isGenerator(result)) { return co.call(thisArg, result); } return result; }); }; } co.wrap = wrap; function forEach(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.forEach(callback, thisArg); }); } function every(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.every(callback, thisArg); }); } function some(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.some(callback, thisArg); }); } function filter(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.filter(callback, thisArg); }); } function map(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.map(callback, thisArg); }); } function reduce(array, callback, initialValue) { if (arguments.length > 2) { return all(array).then(function(array) { return toFuture(initialValue).then(function(value) { return array.reduce(callback, value); }); }); } return all(array).then(function(array) { return array.reduce(callback); }); } function reduceRight(array, callback, initialValue) { if (arguments.length > 2) { return all(array).then(function(array) { return toFuture(initialValue).then(function(value) { return array.reduceRight(callback, value); }); }); } return all(array).then(function(array) { return array.reduceRight(callback); }); } function indexOf(array, searchElement, fromIndex) { return all(array).then(function(array) { return toFuture(searchElement).then(function(searchElement) { return array.indexOf(searchElement, fromIndex); }); }); } function lastIndexOf(array, searchElement, fromIndex) { return all(array).then(function(array) { return toFuture(searchElement).then(function(searchElement) { if (fromIndex === undefined) { fromIndex = array.length - 1; } return array.lastIndexOf(searchElement, fromIndex); }); }); } function includes(array, searchElement, fromIndex) { return all(array).then(function(array) { return toFuture(searchElement).then(function(searchElement) { return array.includes(searchElement, fromIndex); }); }); } function find(array, predicate, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.find(predicate, thisArg); }); } function findIndex(array, predicate, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.findIndex(predicate, thisArg); }); } defineProperties(Future, { // port from Dart delayed: { value: delayed }, error: { value: error }, sync: { value: sync }, value: { value: value }, // Promise compatible all: { value: all }, race: { value: race }, resolve: { value: value }, reject: { value: error }, // extended methods promise: { value: promise }, isFuture: { value: isFuture }, toFuture: { value: toFuture }, isPromise: { value: isPromise }, toPromise: { value: toPromise }, join: { value: join }, any: { value: any }, settle: { value: settle }, attempt: { value: attempt }, run: { value: run }, thunkify: { value: thunkify }, promisify: { value: promisify }, co: { value: co }, wrap: { value: wrap }, // for array forEach: { value: forEach }, every: { value: every }, some: { value: some }, filter: { value: filter }, map: { value: map }, reduce: { value: reduce }, reduceRight: { value: reduceRight }, indexOf: { value: indexOf }, lastIndexOf: { value: lastIndexOf }, includes: { value: includes }, find: { value: find }, findIndex: { value: findIndex } }); function _call(callback, next, x) { setImmediate(function() { try { var r = callback(x); next.resolve(r); } catch(e) { next.reject(e); } }); } function _resolve(onfulfill, next, x) { if (onfulfill) { _call(onfulfill, next, x); } else { next.resolve(x); } } function _reject(onreject, next, e) { if (onreject) { _call(onreject, next, e); } else { next.reject(e); } } defineProperties(Future.prototype, { _value: { writable: true }, _reason: { writable: true }, _state: { value: PENDING, writable: true }, resolve: { value: function(value) { if (value === this) { this.reject(new TypeError('Self resolution')); return; } if (isFuture(value)) { value.fill(this); return; } if ((value !== null) && (typeof value === 'object') || (typeof value === 'function')) { var then; try { then = value.then; } catch (e) { this.reject(e); return; } if (typeof then === 'function') { var notrun = true; try { var self = this; then.call(value, function(y) { if (notrun) { notrun = false; self.resolve(y); } }, function(r) { if (notrun) { notrun = false; self.reject(r); } }); return; } catch (e) { if (notrun) { notrun = false; this.reject(e); } } return; } } if (this._state === PENDING) { this._state = FULFILLED; this._value = value; var subscribers = this._subscribers; while (subscribers.length > 0) { var subscriber = subscribers.shift(); _resolve(subscriber.onfulfill, subscriber.next, value); } } } }, reject: { value: function(reason) { if (this._state === PENDING) { this._state = REJECTED; this._reason = reason; var subscribers = this._subscribers; while (subscribers.length > 0) { var subscriber = subscribers.shift(); _reject(subscriber.onreject, subscriber.next, reason); } } } }, then: { value: function(onfulfill, onreject) { if (typeof onfulfill !== 'function') { onfulfill = null; } if (typeof onreject !== 'function') { onreject = null; } var next = new Future(); if (this._state === FULFILLED) { _resolve(onfulfill, next, this._value); } else if (this._state === REJECTED) { _reject(onreject, next, this._reason); } else { this._subscribers.push({ onfulfill: onfulfill, onreject: onreject, next: next }); } return next; } }, done: { value: function(onfulfill, onreject) { this.then(onfulfill, onreject).then(null, function(error) { setImmediate(function() { throw error; }); }); } }, inspect: { value: function() { switch (this._state) { case PENDING: return { state: 'pending' }; case FULFILLED: return { state: 'fulfilled', value: this._value }; case REJECTED: return { state: 'rejected', reason: this._reason }; } } }, catchError: { value: function(onreject, test) { if (typeof test === 'function') { var self = this; return this['catch'](function(e) { if (test(e)) { return self['catch'](onreject); } else { throw e; } }); } return this['catch'](onreject); } }, 'catch': { value: function(onreject) { return this.then(null, onreject); } }, fail: { value: function(onreject) { this.done(null, onreject); } }, whenComplete: { value: function(action) { return this.then( function(v) { action(); return v; }, function(e) { action(); throw e; } ); } }, complete: { value: function(oncomplete) { oncomplete = oncomplete || function(v) { return v; }; return this.then(oncomplete, oncomplete); } }, always: { value: function(oncomplete) { this.done(oncomplete, oncomplete); } }, fill: { value: function(future) { this.then(future.resolve, future.reject); } }, timeout: { value: function(duration, reason) { var future = new Future(); var timeoutId = setTimeout(function() { future.reject(reason || new TimeoutError('timeout')); }, duration); this.whenComplete(function() { clearTimeout(timeoutId); }) .fill(future); return future; } }, delay: { value: function(duration) { var future = new Future(); this.then(function(result) { setTimeout(function() { future.resolve(result); }, duration); }, future.reject); return future; } }, tap: { value: function(onfulfilledSideEffect, thisArg) { return this.then(function(result) { onfulfilledSideEffect.call(thisArg, result); return result; }); } }, spread: { value: function(onfulfilledArray, thisArg) { return this.then(function(array) { return onfulfilledArray.apply(thisArg, array); }); } }, get: { value: function(key) { return this.then(function(result) { return result[key]; }); } }, set: { value: function(key, value) { return this.then(function(result) { result[key] = value; return result; }); } }, apply: { value: function(method, args) { args = args || []; return this.then(function(result) { return all(args).then(function(args) { return result[method].apply(result, args); }); }); } }, call: { value: function(method) { var args = slice.call(arguments, 1); return this.then(function(result) { return all(args).then(function(args) { return result[method].apply(result, args); }); }); } }, bind: { value: function(method) { var bindargs = slice.call(arguments); if (Array.isArray(method)) { for (var i = 0, n = method.length; i < n; ++i) { bindargs[0] = method[i]; this.bind.apply(this, bindargs); } return; } bindargs.shift(); var self = this; defineProperties(this, { method: { value: function() { var args = slice.call(arguments); return self.then(function(result) { return all(bindargs.concat(args)).then(function(args) { return result[method].apply(result, args); }); }); } } }); return this; } }, forEach: { value: function(callback, thisArg) { return forEach(this, callback, thisArg); } }, every: { value: function(callback, thisArg) { return every(this, callback, thisArg); } }, some: { value: function(callback, thisArg) { return some(this, callback, thisArg); } }, filter: { value: function(callback, thisArg) { return filter(this, callback, thisArg); } }, map: { value: function(callback, thisArg) { return map(this, callback, thisArg); } }, reduce: { value: function(callback, initialValue) { if (arguments.length > 1) { return reduce(this, callback, initialValue); } return reduce(this, callback); } }, reduceRight: { value: function(callback, initialValue) { if (arguments.length > 1) { return reduceRight(this, callback, initialValue); } return reduceRight(this, callback); } }, indexOf: { value: function(searchElement, fromIndex) { return indexOf(this, searchElement, fromIndex); } }, lastIndexOf: { value: function(searchElement, fromIndex) { return lastIndexOf(this, searchElement, fromIndex); } }, includes: { value: function(searchElement, fromIndex) { return includes(this, searchElement, fromIndex); } }, find: { value: function(predicate, thisArg) { return find(this, predicate, thisArg); } }, findIndex: { value: function(predicate, thisArg) { return findIndex(this, predicate, thisArg); } } }); hprose.Future = Future; hprose.thunkify = thunkify; hprose.promisify = promisify; hprose.co = co; hprose.co.wrap = hprose.wrap = wrap; function Completer() { var future = new Future(); defineProperties(this, { future: { value: future }, complete: { value: future.resolve }, completeError: { value: future.reject }, isCompleted: { get: function() { return ( future._state !== PENDING ); } } }); } hprose.Completer = Completer; hprose.resolved = value; hprose.rejected = error; hprose.deferred = function() { var self = new Future(); return createObject(null, { promise: { value: self }, resolve: { value: self.resolve }, reject: { value: self.reject } }); }; if (hasPromise) { return; } function MyPromise(executor) { Future.call(this); executor(this.resolve, this.reject); } MyPromise.prototype = createObject(Future.prototype); MyPromise.prototype.constructor = Future; defineProperties(MyPromise, { all: { value: all }, race: { value: race }, resolve: { value: value }, reject: { value: error } }); global.Promise = MyPromise; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * BinaryString.js * * * * hprose BinaryString for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose) { 'use strict'; var defineProperties = hprose.defineProperties; var createObject = hprose.createObject; function BinaryString(bs, needtest) { if (!needtest || /^[\x00-\xff]*$/.test(bs)) { defineProperties(this, { length: { value: bs.length }, toString: { value: function() { return bs; } }, valueOf: { value: function() { return bs; }, writable: true, configurable: true, enumerable: false } }); } else { throw new Error("argument is not a binary string."); } } var methods = {}; ['quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt', 'charCodeAt', 'indexOf', 'lastIndexOf', 'include', 'startsWith', 'endsWith', 'repeat', 'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase', 'toLocaleUpperCase', 'match', 'search', 'replace', 'split', 'substr', 'concat', 'slice'].forEach(function(name) { methods[name] = { value: String.prototype[name] }; }); BinaryString.prototype = createObject(null, methods); BinaryString.prototype.constructor = BinaryString; hprose.BinaryString = BinaryString; hprose.binary = function(bs) { return new BinaryString(bs, true); }; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * StringIO.js * * * * hprose StringIO for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, undefined) { 'use strict'; var defineProperties = hprose.defineProperties; // i is a int32 number function int32BE(i) { return String.fromCharCode( i >>> 24 & 0xFF, i >>> 16 & 0xFF, i >>> 8 & 0xFF, i & 0xFF ); } // i is a int32 number function int32LE(i) { return String.fromCharCode( i & 0xFF, i >>> 8 & 0xFF, i >>> 16 & 0xFF, i >>> 24 & 0xFF ); } // s is an UTF16 encode string function utf8Encode(s) { var buf = []; var n = s.length; for (var i = 0, j = 0; i < n; ++i, ++j) { var codeUnit = s.charCodeAt(i); if (codeUnit < 0x80) { buf[j] = s.charAt(i); } else if (codeUnit < 0x800) { buf[j] = String.fromCharCode(0xC0 | (codeUnit >> 6), 0x80 | (codeUnit & 0x3F)); } else if (codeUnit < 0xD800 || codeUnit > 0xDFFF) { buf[j] = String.fromCharCode(0xE0 | (codeUnit >> 12), 0x80 | ((codeUnit >> 6) & 0x3F), 0x80 | (codeUnit & 0x3F)); } else { if (i + 1 < n) { var nextCodeUnit = s.charCodeAt(i + 1); if (codeUnit < 0xDC00 && 0xDC00 <= nextCodeUnit && nextCodeUnit <= 0xDFFF) { var rune = (((codeUnit & 0x03FF) << 10) | (nextCodeUnit & 0x03FF)) + 0x010000; buf[j] = String.fromCharCode( 0xF0 | ((rune >> 18) &0x3F), 0x80 | ((rune >> 12) & 0x3F), 0x80 | ((rune >> 6) & 0x3F), 0x80 | (rune & 0x3F)); ++i; continue; } } throw new Error('Malformed string'); } } return buf.join(''); } function readShortString(bs, n) { var charCodes = new Array(n); var i = 0, off = 0; for (var len = bs.length; i < n && off < len; i++) { var unit = bs.charCodeAt(off++); switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: charCodes[i] = unit; break; case 12: case 13: if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bs.charCodeAt(off++) & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bs.charCodeAt(off++) & 0x3F) << 6) | (bs.charCodeAt(off++) & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bs.charCodeAt(off++) & 0x3F) << 12) | ((bs.charCodeAt(off++) & 0x3F) << 6) | (bs.charCodeAt(off++) & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } } if (i < n) { charCodes.length = i; } return [String.fromCharCode.apply(String, charCodes), off]; } function readLongString(bs, n) { var buf = []; var charCodes = new Array(0x8000); var i = 0, off = 0; for (var len = bs.length; i < n && off < len; i++) { var unit = bs.charCodeAt(off++); switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: charCodes[i] = unit; break; case 12: case 13: if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bs.charCodeAt(off++) & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bs.charCodeAt(off++) & 0x3F) << 6) | (bs.charCodeAt(off++) & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bs.charCodeAt(off++) & 0x3F) << 12) | ((bs.charCodeAt(off++) & 0x3F) << 6) | (bs.charCodeAt(off++) & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } if (i >= 0x7FFF - 1) { var size = i + 1; charCodes.length = size; buf[buf.length] = String.fromCharCode.apply(String, charCodes); n -= size; i = -1; } } if (i > 0) { charCodes.length = i; buf[buf.length] = String.fromCharCode.apply(String, charCodes); } return [buf.join(''), off]; } // bs is an UTF8 encode binary string // n is UTF16 length function readString(bs, n) { if (n === undefined || n === null || (n < 0)) { n = bs.length; } if (n === 0) { return ['', 0]; } return ((n < 0xFFFF) ? readShortString(bs, n) : readLongString(bs, n)); } // bs is an UTF8 encode binary string // n is UTF16 length function readUTF8(bs, n) { if (n === undefined || n === null || (n < 0)) { n = bs.length; } if (n === 0) { return ''; } var i = 0, off = 0; for (var len = bs.length; i < n && off < len; i++) { var unit = bs.charCodeAt(off++); switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: break; case 12: case 13: if (off < len) { ++off; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { off += 2; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bs.charCodeAt(off++) & 0x3F) << 12) | ((bs.charCodeAt(off++) & 0x3F) << 6) | (bs.charCodeAt(off++) & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } } return bs.substr(0, off); } // bs is an UTF8 encode binary string function utf8Decode(bs) { return readString(bs)[0]; } // s is an UTF16 encode string function utf8Length(s) { var n = s.length; var length = 0; for (var i = 0; i < n; ++i) { var codeUnit = s.charCodeAt(i); if (codeUnit < 0x80) { ++length; } else if (codeUnit < 0x800) { length += 2; } else if (codeUnit < 0xD800 || codeUnit > 0xDFFF) { length += 3; } else { if (i + 1 < n) { var nextCodeUnit = s.charCodeAt(i + 1); if (codeUnit < 0xDC00 && 0xDC00 <= nextCodeUnit && nextCodeUnit <= 0xDFFF) { ++i; length += 4; continue; } } throw new Error('Malformed string'); } } return length; } // bs is an UTF8 encode binary string function utf16Length(bs) { var n = bs.length; var length = 0; for (var i = 0; i < n; ++i, ++length) { var unit = bs.charCodeAt(i); switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: break; case 12: case 13: if (i < n) { ++i; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (i + 1 < n) { i += 2; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (i + 2 < n) { var rune = (((unit & 0x07) << 18) | ((bs.charCodeAt(i++) & 0x3F) << 12) | ((bs.charCodeAt(i++) & 0x3F) << 6) | (bs.charCodeAt(i++) & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { ++length; break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } } return length; } function isUTF8(bs) { for (var i = 0, n = bs.length; i < n; ++i) { var unit = bs.charCodeAt(i); switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: break; case 12: case 13: if (i < n) { ++i; break; } return false; case 14: if (i + 1 < n) { i += 2; break; } return false; case 15: if (i + 2 < n) { var rune = (((unit & 0x07) << 18) | ((bs.charCodeAt(i++) & 0x3F) << 12) | ((bs.charCodeAt(i++) & 0x3F) << 6) | (bs.charCodeAt(i++) & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { break; } } return false; default: return false; } } return true; } function StringIO() { var a = arguments; switch (a.length) { case 1: this._buffer = [a[0].toString()]; break; case 2: this._buffer = [a[0].toString().substr(a[1])]; break; case 3: this._buffer = [a[0].toString().substr(a[1], a[2])]; break; default: this._buffer = ['']; break; } this.mark(); } defineProperties(StringIO.prototype, { _buffer: { writable: true }, _off: { value: 0, writable: true }, _wmark: { writable: true }, _rmark: { writable: true }, toString: { value: function() { if (this._buffer.length > 1) { this._buffer = [this._buffer.join('')]; } return this._buffer[0]; } }, length: { get: function() { return this.toString().length; } }, position: { get: function() { return this._off; } }, mark: { value: function() { this._wmark = this.length(); this._rmark = this._off; } }, reset: { value: function() { this._buffer = [this.toString().substr(0, this._wmark)]; this._off = this._rmark; } }, clear: { value: function() { this._buffer = ['']; this._wmark = 0; this._off = 0; this._rmark = 0; } }, writeByte: { value: function(b) { this._buffer.push(String.fromCharCode(b & 0xFF)); } }, writeInt32BE: { value: function(i) { if ((i === (i | 0)) && (i <= 2147483647)) { this._buffer.push(int32BE(i)); return; } throw new TypeError('value is out of bounds'); } }, writeUInt32BE: { value: function(i) { if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._buffer.push(int32BE(i | 0)); return; } throw new TypeError('value is out of bounds'); } }, writeInt32LE: { value: function(i) { if ((i === (i | 0)) && (i <= 2147483647)) { this._buffer.push(int32LE(i)); return; } throw new TypeError('value is out of bounds'); } }, writeUInt32LE: { value: function(i) { if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._buffer.push(int32LE(i | 0)); return; } throw new TypeError('value is out of bounds'); } }, writeUTF16AsUTF8: { value: function(str) { this._buffer.push(utf8Encode(str)); } }, writeUTF8AsUTF16: { value: function(str) { this._buffer.push(utf8Decode(str)); } }, write: { value: function(data) { this._buffer.push(data); } }, readByte: { value: function() { if (this._off < this.length()) { return this._buffer[0].charCodeAt(this._off++); } return -1; } }, readChar: { value: function() { if (this._off < this.length()) { return this._buffer[0].charAt(this._off++); } return ''; } }, readInt32BE: { value: function() { var len = this.length(); var buf = this._buffer[0]; var off = this._off; if (off + 3 < len) { var result = buf.charCodeAt(off++) << 24 | buf.charCodeAt(off++) << 16 | buf.charCodeAt(off++) << 8 | buf.charCodeAt(off++); this._off = off; return result; } throw new Error('EOF'); } }, readUInt32BE: { value: function() { var value = this.readInt32BE(); if (value < 0) { return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, readInt32LE: { value: function() { var len = this.length(); var buf = this._buffer[0]; var off = this._off; if (off + 3 < len) { var result = buf.charCodeAt(off++) | buf.charCodeAt(off++) << 8 | buf.charCodeAt(off++) << 16 | buf.charCodeAt(off++) << 24; this._off = off; return result; } throw new Error('EOF'); } }, readUInt32LE: { value: function() { var value = this.readInt32LE(); if (value < 0) { return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, read: { value: function(n) { var off = this._off; var len = this.length(); if (off + n > len) { n = len - off; } if (n === 0) { return ''; } this._off = off + n; return this._buffer[0].substring(off, this._off); } }, skip: { value: function(n) { var len = this.length(); if (this._off + n > len) { n = len - this._off; this._off = len; } else { this._off += n; } return n; } }, // the result is an String, and includes tag. readString: { value: function(tag) { var len = this.length(); var off = this._off; var buf = this._buffer[0]; var pos = buf.indexOf(tag, off); if (pos === -1) { buf = buf.substr(off); this._off = len; } else { buf = buf.substring(off, pos + 1); this._off = pos + 1; } return buf; } }, // the result is a String, and doesn't include tag. // but the position is the same as readString readUntil: { value: function(tag) { var len = this.length(); var off = this._off; var buf = this._buffer[0]; var pos = buf.indexOf(tag, off); if (pos === this._off) { buf = ''; this._off++; } else if (pos === -1) { buf = buf.substr(off); this._off = len; } else { buf = buf.substring(off, pos); this._off = pos + 1; } return buf; } }, // n is the UTF16 length readUTF8: { value: function(n) { var len = this.length(); var r = readUTF8(this._buffer[0].substring(this._off, Math.min(this._off + n * 3, len)), n); this._off += r.length; return r; } }, // n is the UTF16 length readUTF8AsUTF16: { value: function(n) { var len = this.length(); var r = readString(this._buffer[0].substring(this._off, Math.min(this._off + n * 3, len)), n); this._off += r[1]; return r[0]; } }, // n is also the UTF16 length readUTF16AsUTF8: { value: function(n) { return utf8Encode(this.read(n)); } }, // returns a view of the the internal buffer and clears `this`. take: { value: function() { var buffer = this.toString(); this.clear(); return buffer; } }, clone: { value: function() { return new StringIO(this.toString()); } }, trunc: { value: function() { var buf = this.toString().substring(this._off, this._length); this._buffer[0] = buf; this._off = 0; this._wmark = 0; this._rmark = 0; } } }); defineProperties(StringIO, { utf8Encode: { value: utf8Encode }, utf8Decode: { value: utf8Decode }, utf8Length: { value: utf8Length }, utf16Length: { value: utf16Length }, isUTF8: { value: isUTF8 } }); hprose.StringIO = StringIO; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Tags.js * * * * hprose tags enum for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global) { 'use strict'; global.HproseTags = hprose.Tags = { /* Serialize Tags */ TagInteger : 'i', TagLong : 'l', TagDouble : 'd', TagNull : 'n', TagEmpty : 'e', TagTrue : 't', TagFalse : 'f', TagNaN : 'N', TagInfinity : 'I', TagDate : 'D', TagTime : 'T', TagUTC : 'Z', TagBytes : 'b', // Only support bytes in binary mode. TagUTF8Char : 'u', TagString : 's', TagGuid : 'g', TagList : 'a', TagMap : 'm', TagClass : 'c', TagObject : 'o', TagRef : 'r', /* Serialize Marks */ TagPos : '+', TagNeg : '-', TagSemicolon : ';', TagOpenbrace : '{', TagClosebrace : '}', TagQuote : '"', TagPoint : '.', /* Protocol Tags */ TagFunctions : 'F', TagCall : 'C', TagResult : 'R', TagArgument : 'A', TagError : 'E', TagEnd : 'z' }; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * ClassManager.js * * * * hprose ClassManager for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global) { 'use strict'; var WeakMap = global.WeakMap; var createObject = hprose.createObject; var classCache = createObject(null); var aliasCache = new WeakMap(); function register(cls, alias) { aliasCache.set(cls, alias); classCache[alias] = cls; } function getClassAlias(cls) { return aliasCache.get(cls); } function getClass(alias) { return classCache[alias]; } global.HproseClassManager = hprose.ClassManager = createObject(null, { register: { value: register }, getClassAlias: { value: getClassAlias }, getClass: { value: getClass } }); hprose.register = register; register(Object, 'Object'); })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Writer.js * * * * hprose Writer for JavaScript. * * * * LastModified: Feb 13, 2017 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var Map = global.Map; var StringIO = hprose.StringIO; var BinaryString = hprose.BinaryString; var Tags = hprose.Tags; var ClassManager = hprose.ClassManager; var defineProperties = hprose.defineProperties; var createObject = hprose.createObject; var utf8Encode = StringIO.utf8Encode; function getClassName(obj) { var cls = obj.constructor; if (!cls) { return 'Object'; } var classname = ClassManager.getClassAlias(cls); if (classname) { return classname; } if (cls.name) { classname = cls.name; } else { var ctor = cls.toString(); classname = ctor.substr(0, ctor.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, ''); if (classname === '' || classname === 'Object') { return (typeof(obj.getClassName) === 'function') ? obj.getClassName() : 'Object'; } } if (classname !== 'Object') { ClassManager.register(cls, classname); } return classname; } var fakeWriterRefer = createObject(null, { set: { value: function () {} }, write: { value: function () { return false; } }, reset: { value: function () {} } }); function RealWriterRefer(stream) { defineProperties(this, { _stream: { value: stream }, _ref: { value: new Map(), writable: true } }); } defineProperties(RealWriterRefer.prototype, { _refcount: { value: 0, writable: true }, set: { value: function (val) { this._ref.set(val, this._refcount++); } }, write: { value: function (val) { var index = this._ref.get(val); if (index !== undefined) { this._stream.write(Tags.TagRef); this._stream.write(index); this._stream.write(Tags.TagSemicolon); return true; } return false; } }, reset: { value: function () { this._ref = new Map(); this._refcount = 0; } } }); function realWriterRefer(stream) { return new RealWriterRefer(stream); } function Writer(stream, simple, binary) { this.binary = !!binary; defineProperties(this, { stream: { value: stream }, _classref: { value: createObject(null), writable: true }, _fieldsref: { value: [], writable: true }, _refer: { value: simple ? fakeWriterRefer : realWriterRefer(stream) } }); } function serialize(writer, value) { var stream = writer.stream; if (value === undefined || value === null || value.constructor === Function) { stream.write(Tags.TagNull); return; } if (value === '') { stream.write(Tags.TagEmpty); return; } switch (value.constructor) { case Number: writeNumber(writer, value); break; case Boolean: writeBoolean(writer, value); break; case String: if (value.length === 1) { stream.write(Tags.TagUTF8Char); stream.write(writer.binary ? utf8Encode(value) : value); } else { writer.writeStringWithRef(value); } break; case BinaryString: if (writer.binary) { writer.writeBinaryWithRef(value); } else { throw new Error('The binary string does not support serialization in text mode.'); } break; case Date: writer.writeDateWithRef(value); break; case Map: writer.writeMapWithRef(value); break; default: if (Array.isArray(value)) { writer.writeListWithRef(value); } else { var classname = getClassName(value); if (classname === 'Object') { writer.writeMapWithRef(value); } else { writer.writeObjectWithRef(value); } } break; } } function writeNumber(writer, n) { var stream = writer.stream; n = n.valueOf(); if (n === (n | 0)) { if (0 <= n && n <= 9) { stream.write(n); } else { stream.write(Tags.TagInteger); stream.write(n); stream.write(Tags.TagSemicolon); } } else { writeDouble(writer, n); } } function writeInteger(writer, n) { var stream = writer.stream; if (0 <= n && n <= 9) { stream.write(n); } else { if (n < -2147483648 || n > 2147483647) { stream.write(Tags.TagLong); } else { stream.write(Tags.TagInteger); } stream.write(n); stream.write(Tags.TagSemicolon); } } function writeDouble(writer, n) { var stream = writer.stream; if (n !== n) { stream.write(Tags.TagNaN); } else if (n !== Infinity && n !== -Infinity) { stream.write(Tags.TagDouble); stream.write(n); stream.write(Tags.TagSemicolon); } else { stream.write(Tags.TagInfinity); stream.write((n > 0) ? Tags.TagPos : Tags.TagNeg); } } function writeBoolean(writer, b) { writer.stream.write(b.valueOf() ? Tags.TagTrue : Tags.TagFalse); } function writeUTCDate(writer, date) { writer._refer.set(date); var stream = writer.stream; stream.write(Tags.TagDate); stream.write(('0000' + date.getUTCFullYear()).slice(-4)); stream.write(('00' + (date.getUTCMonth() + 1)).slice(-2)); stream.write(('00' + date.getUTCDate()).slice(-2)); stream.write(Tags.TagTime); stream.write(('00' + date.getUTCHours()).slice(-2)); stream.write(('00' + date.getUTCMinutes()).slice(-2)); stream.write(('00' + date.getUTCSeconds()).slice(-2)); var millisecond = date.getUTCMilliseconds(); if (millisecond !== 0) { stream.write(Tags.TagPoint); stream.write(('000' + millisecond).slice(-3)); } stream.write(Tags.TagUTC); } function writeDate(writer, date) { writer._refer.set(date); var stream = writer.stream; var year = ('0000' + date.getFullYear()).slice(-4); var month = ('00' + (date.getMonth() + 1)).slice(-2); var day = ('00' + date.getDate()).slice(-2); var hour = ('00' + date.getHours()).slice(-2); var minute = ('00' + date.getMinutes()).slice(-2); var second = ('00' + date.getSeconds()).slice(-2); var millisecond = ('000' + date.getMilliseconds()).slice(-3); if ((hour === '00') && (minute === '00') && (second === '00') && (millisecond === '000')) { stream.write(Tags.TagDate); stream.write(year); stream.write(month); stream.write(day); } else if ((year === '1970') && (month === '01') && (day === '01')) { stream.write(Tags.TagTime); stream.write(hour); stream.write(minute); stream.write(second); if (millisecond !== '000') { stream.write(Tags.TagPoint); stream.write(millisecond); } } else { stream.write(Tags.TagDate); stream.write(year); stream.write(month); stream.write(day); stream.write(Tags.TagTime); stream.write(hour); stream.write(minute); stream.write(second); if (millisecond !== '000') { stream.write(Tags.TagPoint); stream.write(millisecond); } } stream.write(Tags.TagSemicolon); } function writeTime(writer, time) { writer._refer.set(time); var stream = writer.stream; var hour = ('00' + time.getHours()).slice(-2); var minute = ('00' + time.getMinutes()).slice(-2); var second = ('00' + time.getSeconds()).slice(-2); var millisecond = ('000' + time.getMilliseconds()).slice(-3); stream.write(Tags.TagTime); stream.write(hour); stream.write(minute); stream.write(second); if (millisecond !== '000') { stream.write(Tags.TagPoint); stream.write(millisecond); } stream.write(Tags.TagSemicolon); } function writeBinary(writer, bs) { writer._refer.set(bs); var stream = writer.stream; stream.write(Tags.TagBytes); var n = bs.length; if (n > 0) { stream.write(n); stream.write(Tags.TagQuote); stream.write(bs); } else { stream.write(Tags.TagQuote); } stream.write(Tags.TagQuote); } function writeString(writer, str) { writer._refer.set(str); var stream = writer.stream; var n = str.length; stream.write(Tags.TagString); if (n > 0) { stream.write(n); stream.write(Tags.TagQuote); stream.write(writer.binary ? utf8Encode(str) : str); } else { stream.write(Tags.TagQuote); } stream.write(Tags.TagQuote); } function writeList(writer, array) { writer._refer.set(array); var stream = writer.stream; var n = array.length; stream.write(Tags.TagList); if (n > 0) { stream.write(n); stream.write(Tags.TagOpenbrace); for (var i = 0; i < n; i++) { serialize(writer, array[i]); } } else { stream.write(Tags.TagOpenbrace); } stream.write(Tags.TagClosebrace); } function writeMap(writer, map) { writer._refer.set(map); var stream = writer.stream; var fields = []; for (var key in map) { if (map.hasOwnProperty(key) && typeof(map[key]) !== 'function') { fields[fields.length] = key; } } var n = fields.length; stream.write(Tags.TagMap); if (n > 0) { stream.write(n); stream.write(Tags.TagOpenbrace); for (var i = 0; i < n; i++) { serialize(writer, fields[i]); serialize(writer, map[fields[i]]); } } else { stream.write(Tags.TagOpenbrace); } stream.write(Tags.TagClosebrace); } function writeHarmonyMap(writer, map) { writer._refer.set(map); var stream = writer.stream; var n = map.size; stream.write(Tags.TagMap); if (n > 0) { stream.write(n); stream.write(Tags.TagOpenbrace); map.forEach(function(value, key) { serialize(writer, key); serialize(writer, value); }); } else { stream.write(Tags.TagOpenbrace); } stream.write(Tags.TagClosebrace); } function writeObject(writer, obj) { var stream = writer.stream; var classname = getClassName(obj); var fields, index; if (classname in writer._classref) { index = writer._classref[classname]; fields = writer._fieldsref[index]; } else { fields = []; for (var key in obj) { if (obj.hasOwnProperty(key) && typeof(obj[key]) !== 'function') { fields[fields.length] = key.toString(); } } index = writeClass(writer, classname, fields); } stream.write(Tags.TagObject); stream.write(index); stream.write(Tags.TagOpenbrace); writer._refer.set(obj); var n = fields.length; for (var i = 0; i < n; i++) { serialize(writer, obj[fields[i]]); } stream.write(Tags.TagClosebrace); } function writeClass(writer, classname, fields) { var stream = writer.stream; var n = fields.length; stream.write(Tags.TagClass); stream.write(classname.length); stream.write(Tags.TagQuote); stream.write(writer.binary ? utf8Encode(classname) : classname); stream.write(Tags.TagQuote); if (n > 0) { stream.write(n); stream.write(Tags.TagOpenbrace); for (var i = 0; i < n; i++) { writeString(writer, fields[i]); } } else { stream.write(Tags.TagOpenbrace); } stream.write(Tags.TagClosebrace); var index = writer._fieldsref.length; writer._classref[classname] = index; writer._fieldsref[index] = fields; return index; } defineProperties(Writer.prototype, { binary: { value: false, writable: true }, serialize: { value: function(value) { serialize(this, value); } }, writeInteger: { value: function(value) { writeInteger(this, value); } }, writeDouble: { value: function(value) { writeDouble(this, value); } }, writeBoolean: { value: function(value) { writeBoolean(this, value); } }, writeUTCDate: { value: function(value) { writeUTCDate(this, value); } }, writeUTCDateWithRef: { value: function(value) { if (!this._refer.write(value)) { writeUTCDate(this, value); } } }, writeDate: { value: function(value) { writeDate(this, value); } }, writeDateWithRef: { value: function(value) { if (!this._refer.write(value)) { writeDate(this, value); } } }, writeTime: { value: function(value) { writeTime(this, value); } }, writeTimeWithRef: { value: function(value) { if (!this._refer.write(value)) { writeTime(this, value); } } }, writeBinary: { value: function(value) { writeBinary(this, value); } }, writeBinaryWithRef: { value: function(value) { if (!this._refer.write(value)) { writeBinary(this, value); } } }, writeString: { value: function(value) { writeString(this, value); } }, writeStringWithRef: { value: function(value) { if (!this._refer.write(value)) { writeString(this, value); } } }, writeList: { value: function(value) { writeList(this, value); } }, writeListWithRef: { value: function(value) { if (!this._refer.write(value)) { writeList(this, value); } } }, writeMap: { value: function(value) { if (value instanceof Map) { writeHarmonyMap(this, value); } else { writeMap(this, value); } } }, writeMapWithRef: { value: function(value) { if (!this._refer.write(value)) { this.writeMap(value); } } }, writeObject: { value: function(value) { writeObject(this, value); } }, writeObjectWithRef: { value: function(value) { if (!this._refer.write(value)) { writeObject(this, value); } } }, reset: { value: function() { this._classref = createObject(null); this._fieldsref.length = 0; this._refer.reset(); } } }); global.HproseWriter = hprose.Writer = Writer; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Reader.js * * * * hprose Reader for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var Map = global.Map; var StringIO = hprose.StringIO; var BinaryString = hprose.BinaryString; var Tags = hprose.Tags; var ClassManager = hprose.ClassManager; var defineProperties = hprose.defineProperties; var createObject = hprose.createObject; function unexpectedTag(tag, expectTags) { if (tag && expectTags) { throw new Error('Tag "' + expectTags + '" expected, but "' + tag + '" found in stream'); } if (tag) { throw new Error('Unexpected serialize tag "' + tag + '" in stream'); } throw new Error('No byte found in stream'); } function readRaw(stream, binary) { var ostream = new StringIO(); _readRaw(stream, ostream, binary); return ostream.take(); } function _readRaw(stream, ostream, binary) { __readRaw(stream, ostream, stream.readChar(), binary); } function __readRaw(stream, ostream, tag, binary) { ostream.write(tag); switch (tag) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case Tags.TagNull: case Tags.TagEmpty: case Tags.TagTrue: case Tags.TagFalse: case Tags.TagNaN: break; case Tags.TagInfinity: ostream.write(stream.read()); break; case Tags.TagInteger: case Tags.TagLong: case Tags.TagDouble: case Tags.TagRef: readNumberRaw(stream, ostream); break; case Tags.TagDate: case Tags.TagTime: readDateTimeRaw(stream, ostream); break; case Tags.TagUTF8Char: readUTF8CharRaw(stream, ostream, binary); break; case Tags.TagBytes: readBinaryRaw(stream, ostream, binary); break; case Tags.TagString: readStringRaw(stream, ostream, binary); break; case Tags.TagGuid: readGuidRaw(stream, ostream); break; case Tags.TagList: case Tags.TagMap: case Tags.TagObject: readComplexRaw(stream, ostream, binary); break; case Tags.TagClass: readComplexRaw(stream, ostream, binary); _readRaw(stream, ostream, binary); break; case Tags.TagError: _readRaw(stream, ostream, binary); break; default: unexpectedTag(tag); } } function readNumberRaw(stream, ostream) { var tag; do { tag = stream.read(); ostream.write(tag); } while (tag !== Tags.TagSemicolon); } function readDateTimeRaw(stream, ostream) { var tag; do { tag = stream.read(); ostream.write(tag); } while (tag !== Tags.TagSemicolon && tag !== Tags.TagUTC); } function readUTF8CharRaw(stream, ostream, binary) { if (binary) { ostream.write(stream.readUTF8(1)); } else { ostream.write(stream.readChar()); } } function readBinaryRaw(stream, ostream, binary) { if (!binary) { throw new Error('The binary string does not support to unserialize in text mode.'); } var s = stream.readUntil(Tags.TagQuote); ostream.write(s); ostream.write(Tags.TagQuote); var count = 0; if (s.length > 0) { count = parseInt(s, 10); } ostream.write(stream.read(count + 1)); } function readStringRaw(stream, ostream, binary) { var s = stream.readUntil(Tags.TagQuote); ostream.write(s); ostream.write(Tags.TagQuote); var count = 0; if (s.length > 0) { count = parseInt(s, 10); } if (binary) { ostream.write(stream.readUTF8(count + 1)); } else { ostream.write(stream.read(count + 1)); } } function readGuidRaw(stream, ostream) { ostream.write(stream.read(38)); } function readComplexRaw(stream, ostream, binary) { var tag; do { tag = stream.readChar(); ostream.write(tag); } while (tag !== Tags.TagOpenbrace); while ((tag = stream.readChar()) !== Tags.TagClosebrace) { __readRaw(stream, ostream, tag, binary); } ostream.write(tag); } function RawReader(stream, binary) { defineProperties(this, { stream: { value : stream }, binary: { value : !!binary, writable: true }, readRaw: { value: function() { return readRaw(stream, this.binary); } } }); } hprose.RawReader = RawReader; var fakeReaderRefer = createObject(null, { set: { value: function() {} }, read: { value: function() { unexpectedTag(Tags.TagRef); } }, reset: { value: function() {} } }); function RealReaderRefer() { defineProperties(this, { ref: { value: [] } }); } defineProperties(RealReaderRefer.prototype, { set: { value: function(val) { this.ref.push(val); } }, read: { value: function(index) { return this.ref[index]; } }, reset: { value: function() { this.ref.length = 0; } } }); function realReaderRefer() { return new RealReaderRefer(); } function getter(str) { var obj = global; var names = str.split('.'); var i; for (i = 0; i < names.length; i++) { obj = obj[names[i]]; if (obj === undefined) { return null; } } return obj; } function findClass(cn, poslist, i, c) { if (i < poslist.length) { var pos = poslist[i]; cn[pos] = c; var cls = findClass(cn, poslist, i + 1, '.'); if (i + 1 < poslist.length) { if (cls === null) { cls = findClass(cn, poslist, i + 1, '_'); } } return cls; } var classname = cn.join(''); try { var cl = getter(classname); return ((typeof(cl) === 'function') ? cl : null); } catch (e) { return null; } } function getClass(classname) { var cls = ClassManager.getClass(classname); if (cls) { return cls; } cls = getter(classname); if (typeof(cls) === 'function') { ClassManager.register(cls, classname); return cls; } var poslist = []; var pos = classname.indexOf('_'); while (pos >= 0) { poslist[poslist.length] = pos; pos = classname.indexOf('_', pos + 1); } if (poslist.length > 0) { var cn = classname.split(''); cls = findClass(cn, poslist, 0, '.'); if (cls === null) { cls = findClass(cn, poslist, 0, '_'); } if (typeof(cls) === 'function') { ClassManager.register(cls, classname); return cls; } } cls = function () {}; defineProperties(cls.prototype, { 'getClassName': { value: function () { return classname; } } }); ClassManager.register(cls, classname); return cls; } function readInt(stream, tag) { var s = stream.readUntil(tag); if (s.length === 0) { return 0; } return parseInt(s, 10); } function unserialize(reader) { var stream = reader.stream; var tag = stream.readChar(); switch (tag) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case Tags.TagInteger: return readIntegerWithoutTag(stream); case Tags.TagLong: return readLongWithoutTag(stream); case Tags.TagDouble: return readDoubleWithoutTag(stream); case Tags.TagNull: return null; case Tags.TagEmpty: return ''; case Tags.TagTrue: return true; case Tags.TagFalse: return false; case Tags.TagNaN: return NaN; case Tags.TagInfinity: return readInfinityWithoutTag(stream); case Tags.TagDate: return readDateWithoutTag(reader); case Tags.TagTime: return readTimeWithoutTag(reader); case Tags.TagBytes: return readBinaryWithoutTag(reader); case Tags.TagUTF8Char: return readUTF8CharWithoutTag(reader); case Tags.TagString: return readStringWithoutTag(reader); case Tags.TagGuid: return readGuidWithoutTag(reader); case Tags.TagList: return readListWithoutTag(reader); case Tags.TagMap: return reader.useHarmonyMap ? readHarmonyMapWithoutTag(reader) : readMapWithoutTag(reader); case Tags.TagClass: readClass(reader); return readObject(reader); case Tags.TagObject: return readObjectWithoutTag(reader); case Tags.TagRef: return readRef(reader); case Tags.TagError: throw new Error(readString(reader)); default: unexpectedTag(tag); } } function readIntegerWithoutTag(stream) { return readInt(stream, Tags.TagSemicolon); } function readInteger(stream) { var tag = stream.readChar(); switch (tag) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case Tags.TagInteger: return readIntegerWithoutTag(stream); default: unexpectedTag(tag); } } function readLongWithoutTag(stream) { var s = stream.readUntil(Tags.TagSemicolon); var l = parseInt(s, 10); if (l.toString() === s) { return l; } return s; } function readLong(stream) { var tag = stream.readChar(); switch (tag) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case Tags.TagInteger: case Tags.TagLong: return readLongWithoutTag(stream); default: unexpectedTag(tag); } } function readDoubleWithoutTag(stream) { return parseFloat(stream.readUntil(Tags.TagSemicolon)); } function readDouble(stream) { var tag = stream.readChar(); switch (tag) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case Tags.TagInteger: case Tags.TagLong: case Tags.TagDouble: return readDoubleWithoutTag(stream); case Tags.TagNaN: return NaN; case Tags.TagInfinity: return readInfinityWithoutTag(stream); default: unexpectedTag(tag); } } function readInfinityWithoutTag(stream) { return ((stream.readChar() === Tags.TagNeg) ? -Infinity : Infinity); } function readBoolean(stream) { var tag = stream.readChar(); switch (tag) { case Tags.TagTrue: return true; case Tags.TagFalse: return false; default: unexpectedTag(tag); } } function readDateWithoutTag(reader) { var stream = reader.stream; var year = parseInt(stream.read(4), 10); var month = parseInt(stream.read(2), 10) - 1; var day = parseInt(stream.read(2), 10); var date; var tag = stream.readChar(); if (tag === Tags.TagTime) { var hour = parseInt(stream.read(2), 10); var minute = parseInt(stream.read(2), 10); var second = parseInt(stream.read(2), 10); var millisecond = 0; tag = stream.readChar(); if (tag === Tags.TagPoint) { millisecond = parseInt(stream.read(3), 10); tag = stream.readChar(); if ((tag >= '0') && (tag <= '9')) { stream.skip(2); tag = stream.readChar(); if ((tag >= '0') && (tag <= '9')) { stream.skip(2); tag = stream.readChar(); } } } if (tag === Tags.TagUTC) { date = new Date(Date.UTC(year, month, day, hour, minute, second, millisecond)); } else { date = new Date(year, month, day, hour, minute, second, millisecond); } } else if (tag === Tags.TagUTC) { date = new Date(Date.UTC(year, month, day)); } else { date = new Date(year, month, day); } reader.refer.set(date); return date; } function readDate(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagDate: return readDateWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readTimeWithoutTag(reader) { var stream = reader.stream; var time; var hour = parseInt(stream.read(2), 10); var minute = parseInt(stream.read(2), 10); var second = parseInt(stream.read(2), 10); var millisecond = 0; var tag = stream.readChar(); if (tag === Tags.TagPoint) { millisecond = parseInt(stream.read(3), 10); tag = stream.readChar(); if ((tag >= '0') && (tag <= '9')) { stream.skip(2); tag = stream.readChar(); if ((tag >= '0') && (tag <= '9')) { stream.skip(2); tag = stream.readChar(); } } } if (tag === Tags.TagUTC) { time = new Date(Date.UTC(1970, 0, 1, hour, minute, second, millisecond)); } else { time = new Date(1970, 0, 1, hour, minute, second, millisecond); } reader.refer.set(time); return time; } function readTime(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagTime: return readTimeWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readBinaryWithoutTag(reader) { if (!reader.binary) { throw new Error('The binary string does not support to unserialize in text mode.'); } var stream = reader.stream; var count = readInt(stream, Tags.TagQuote); var bs = new BinaryString(stream.read(count)); stream.skip(1); reader.refer.set(bs); return bs; } function readBinary(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagEmpty: return new BinaryString(''); case Tags.TagBytes: return readBinaryWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readUTF8CharWithoutTag(reader) { if (reader.binary) { return reader.stream.readUTF8AsUTF16(1); } return reader.stream.read(1); } function _readString(reader) { var stream = reader.stream; var count = readInt(stream, Tags.TagQuote); var s; if (reader.binary) { s = stream.readUTF8AsUTF16(count); } else { s = stream.read(count); } stream.skip(1); return s; } function readStringWithoutTag(reader) { var s = _readString(reader); reader.refer.set(s); return s; } function readString(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagEmpty: return ''; case Tags.TagUTF8Char: return readUTF8CharWithoutTag(reader); case Tags.TagString: return readStringWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readGuidWithoutTag(reader) { var stream = reader.stream; stream.skip(1); var s = stream.read(36); stream.skip(1); reader.refer.set(s); return s; } function readGuid(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagGuid: return readGuidWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readListWithoutTag(reader) { var stream = reader.stream; var list = []; reader.refer.set(list); var count = readInt(stream, Tags.TagOpenbrace); for (var i = 0; i < count; i++) { list[i] = unserialize(reader); } stream.skip(1); return list; } function readList(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagList: return readListWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readMapWithoutTag(reader) { var stream = reader.stream; var map = {}; reader.refer.set(map); var count = readInt(stream, Tags.TagOpenbrace); for (var i = 0; i < count; i++) { var key = unserialize(reader); var value = unserialize(reader); map[key] = value; } stream.skip(1); return map; } function readMap(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagMap: return readMapWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readHarmonyMapWithoutTag(reader) { var stream = reader.stream; var map = new Map(); reader.refer.set(map); var count = readInt(stream, Tags.TagOpenbrace); for (var i = 0; i < count; i++) { var key = unserialize(reader); var value = unserialize(reader); map.set(key, value); } stream.skip(1); return map; } function readHarmonyMap(reader) { var tag = reader.stream.readChar(); switch (tag) { case Tags.TagNull: return null; case Tags.TagMap: return readHarmonyMapWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readObjectWithoutTag(reader) { var stream = reader.stream; var cls = reader.classref[readInt(stream, Tags.TagOpenbrace)]; var obj = new cls.classname(); reader.refer.set(obj); for (var i = 0; i < cls.count; i++) { obj[cls.fields[i]] = unserialize(reader); } stream.skip(1); return obj; } function readObject(reader) { var tag = reader.stream.readChar(); switch(tag) { case Tags.TagNull: return null; case Tags.TagClass: readClass(reader); return readObject(reader); case Tags.TagObject: return readObjectWithoutTag(reader); case Tags.TagRef: return readRef(reader); default: unexpectedTag(tag); } } function readClass(reader) { var stream = reader.stream; var classname = _readString(reader); var count = readInt(stream, Tags.TagOpenbrace); var fields = []; for (var i = 0; i < count; i++) { fields[i] = readString(reader); } stream.skip(1); classname = getClass(classname); reader.classref.push({ classname: classname, count: count, fields: fields }); } function readRef(reader) { return reader.refer.read(readInt(reader.stream, Tags.TagSemicolon)); } function Reader(stream, simple, useHarmonyMap, binary) { RawReader.call(this, stream, binary); this.useHarmonyMap = !!useHarmonyMap; defineProperties(this, { classref: { value: [] }, refer: { value: simple ? fakeReaderRefer : realReaderRefer() } }); } Reader.prototype = createObject(RawReader.prototype); Reader.prototype.constructor = Reader; defineProperties(Reader.prototype, { useHarmonyMap: { value: false, writable: true }, checkTag: { value: function(expectTag, tag) { if (tag === undefined) { tag = this.stream.readChar(); } if (tag !== expectTag) { unexpectedTag(tag, expectTag); } } }, checkTags: { value: function(expectTags, tag) { if (tag === undefined) { tag = this.stream.readChar(); } if (expectTags.indexOf(tag) >= 0) { return tag; } unexpectedTag(tag, expectTags); } }, unserialize: { value: function() { return unserialize(this); } }, readInteger: { value: function() { return readInteger(this.stream); } }, readLong: { value: function() { return readLong(this.stream); } }, readDouble: { value: function() { return readDouble(this.stream); } }, readBoolean: { value: function() { return readBoolean(this.stream); } }, readDateWithoutTag: { value: function() { return readDateWithoutTag(this); } }, readDate: { value: function() { return readDate(this); } }, readTimeWithoutTag: { value: function() { return readTimeWithoutTag(this); } }, readTime: { value: function() { return readTime(this); } }, readBinaryWithoutTag: { value: function() { return readBinaryWithoutTag(this); } }, readBinary: { value: function() { return readBinary(this); } }, readStringWithoutTag: { value: function() { return readStringWithoutTag(this); } }, readString: { value: function() { return readString(this); } }, readGuidWithoutTag: { value: function() { return readGuidWithoutTag(this); } }, readGuid: { value: function() { return readGuid(this); } }, readListWithoutTag: { value: function() { return readListWithoutTag(this); } }, readList: { value: function() { return readList(this); } }, readMapWithoutTag: { value: function() { return this.useHarmonyMap ? readHarmonyMapWithoutTag(this) : readMapWithoutTag(this); } }, readMap: { value: function() { return this.useHarmonyMap ? readHarmonyMap(this) : readMap(this); } }, readObjectWithoutTag: { value: function() { return readObjectWithoutTag(this); } }, readObject: { value: function() { return readObject(this); } }, reset: { value: function() { this.classref.length = 0; this.refer.reset(); } } }); global.HproseReader = hprose.Reader = Reader; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Formatter.js * * * * hprose Formatter for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose) { 'use strict'; var StringIO = hprose.StringIO; var Writer = hprose.Writer; var Reader = hprose.Reader; var createObject = hprose.createObject; function serialize(value, simple, binary) { var stream = new StringIO(); var writer = new Writer(stream, simple, binary); writer.serialize(value); return stream.take(); } function unserialize(stream, simple, useHarmonyMap, binary) { if (!(stream instanceof StringIO)) { stream = new StringIO(stream); } return new Reader(stream, simple, useHarmonyMap, binary).unserialize(); } hprose.Formatter = createObject(null, { serialize: { value: serialize }, unserialize: { value: unserialize } }); hprose.serialize = serialize; hprose.unserialize = unserialize; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * ResultMode.js * * * * hprose ResultMode for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global) { 'use strict'; global.HproseResultMode = hprose.ResultMode = { Normal: 0, Serialized: 1, Raw: 2, RawWithEndTag: 3 }; hprose.Normal = hprose.ResultMode.Normal; hprose.Serialized = hprose.ResultMode.Serialized; hprose.Raw = hprose.ResultMode.Raw; hprose.RawWithEndTag = hprose.ResultMode.RawWithEndTag; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Client.js * * * * hprose client for JavaScript. * * * * LastModified: Jan 31, 2018 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var setImmediate = global.setImmediate; var Tags = hprose.Tags; var ResultMode = hprose.ResultMode; var StringIO = hprose.StringIO; var Writer = hprose.Writer; var Reader = hprose.Reader; var Future = hprose.Future; var defineProperties = hprose.defineProperties; var createObject = hprose.createObject; var parseuri = hprose.parseuri; var isObjectEmpty = hprose.isObjectEmpty; var GETFUNCTIONS = Tags.TagEnd; function noop(){} var s_boolean = 'boolean'; var s_string = 'string'; var s_number = 'number'; var s_function = 'function'; var s_object = 'object'; function Client(uri, functions, settings) { // private members var _uri, _uriList = [], _index = -1, _binary = false, _byref = false, _simple = false, _timeout = 30000, _retry = 10, _idempotent = false, _failswitch = false, _failround = 0, _lock = false, _tasks = [], _useHarmonyMap = false, _filters = [], _batch = false, _batches = [], _ready = new Future(), _topics = createObject(null), _id = null, _keepAlive = true, _invokeHandler = invokeHandler, _batchInvokeHandler = batchInvokeHandler, _beforeFilterHandler = beforeFilterHandler, _afterFilterHandler = afterFilterHandler, _invokeHandlers = [], _batchInvokeHandlers = [], _beforeFilterHandlers = [], _afterFilterHandlers = [], self = this; function outputFilter(request, context) { for (var i = 0, n = _filters.length; i < n; i++) { request = _filters[i].outputFilter(request, context); } return request; } function inputFilter(response, context) { for (var i = _filters.length - 1; i >= 0; i--) { response = _filters[i].inputFilter(response, context); } return response; } function beforeFilterHandler(request, context) { request = outputFilter(request, context); return _afterFilterHandler(request, context) .then(function(response) { if (context.oneway) { return; } return inputFilter(response, context); }); } function afterFilterHandler(request, context) { return self.sendAndReceive(request, context).catchError(function(e) { var response = retry(request, context); if (response !== null) { return response; } throw e; }); } function sendAndReceive(request, context, onsuccess, onerror) { _beforeFilterHandler(request, context).then(onsuccess, onerror); } function failswitch() { var n = _uriList.length; if (n > 1) { var i = _index + 1; if (i >= n) { i = 0; _failround++; } _index = i; _uri = _uriList[_index]; } else { _failround++; } if (typeof self.onfailswitch === s_function) { self.onfailswitch(self); } } function retry(data, context) { if (context.failswitch) { failswitch(); } if (context.idempotent && (context.retried < context.retry)) { var interval = ++context.retried * 500; if (context.failswitch) { interval -= (_uriList.length - 1) * 500; } if (interval > 5000) { interval = 5000; } if (interval > 0) { return Future.delayed(interval, function() { return afterFilterHandler(data, context); }); } else { return afterFilterHandler(data, context); } } return null; } function normalizeFunctions(functions) { var root = [createObject(null)]; for (var i in functions) { var func = functions[i].split('_'); var n = func.length - 1; if (n > 0) { var node = root; for (var j = 0; j < n; j++) { var f = func[j]; if (node[0][f] === undefined) { node[0][f] = [createObject(null)]; } node = node[0][f]; } node.push(func[n]); } root.push(functions[i]); } return root; } function initService(stub) { var context = { retry: _retry, retried: 0, idempotent: true, failswitch: true, timeout: _timeout, client: self, userdata: {} }; var onsuccess = function(data) { var error = null; try { var stream = new StringIO(data); var reader = new Reader(stream, true); var tag = stream.readChar(); switch (tag) { case Tags.TagError: error = new Error(reader.readString()); break; case Tags.TagFunctions: var functions = normalizeFunctions(reader.readList()); reader.checkTag(Tags.TagEnd); setFunctions(stub, functions); break; default: error = new Error('Wrong Response:\r\n' + data); break; } } catch (e) { error = e; } if (error !== null) { _ready.reject(error); } else { _ready.resolve(stub); } }; sendAndReceive(GETFUNCTIONS, context, onsuccess, _ready.reject); } function setFunction(stub, name) { return function() { if (_batch) { return _invoke(stub, name, Array.slice(arguments), true); } else { return Future.all(arguments).then(function(args) { return _invoke(stub, name, args, false); }); } }; } function setMethods(stub, obj, namespace, name, methods) { if (obj[name] !== undefined) { return; } obj[name] = {}; if (typeof(methods) === s_string || methods.constructor === Object) { methods = [methods]; } if (Array.isArray(methods)) { for (var i = 0; i < methods.length; i++) { var m = methods[i]; if (typeof(m) === s_string) { obj[name][m] = setFunction(stub, namespace + name + '_' + m); } else { for (var n in m) { setMethods(stub, obj[name], namespace + name + '_', n, m[n]); } } } } } function setFunctions(stub, functions) { for (var i = 0; i < functions.length; i++) { var f = functions[i]; if (typeof(f) === s_string) { if (stub[f] === undefined) { stub[f] = setFunction(stub, f); } } else { for (var name in f) { setMethods(stub, stub, '', name, f[name]); } } } } function copyargs(src, dest) { var n = Math.min(src.length, dest.length); for (var i = 0; i < n; ++i) { dest[i] = src[i]; } } function initContext(batch) { if (batch) { return { mode: ResultMode.Normal, binary: _binary, byref: _byref, simple: _simple, onsuccess: undefined, onerror: undefined, useHarmonyMap: _useHarmonyMap, client: self, userdata: {} }; } return { mode: ResultMode.Normal, binary: _binary, byref: _byref, simple: _simple, timeout: _timeout, retry: _retry, retried: 0, idempotent: _idempotent, failswitch: _failswitch, oneway: false, sync: false, onsuccess: undefined, onerror: undefined, useHarmonyMap: _useHarmonyMap, client: self, userdata: {} }; } function getContext(stub, name, args, batch) { var context = initContext(batch); if (name in stub) { var method = stub[name]; for (var key in method) { if (key in context) { context[key] = method[key]; } } } var i = 0, n = args.length; for (; i < n; ++i) { if (typeof args[i] === s_function) { break; } } if (i === n) { return context; } var extra = args.splice(i, n - i); context.onsuccess = extra[0]; n = extra.length; for (i = 1; i < n; ++i) { var arg = extra[i]; switch (typeof arg) { case s_function: context.onerror = arg; break; case s_boolean: context.byref = arg; break; case s_number: context.mode = arg; break; case s_object: for (var k in arg) { if (k in context) { context[k] = arg[k]; } } break; } } return context; } function encode(name, args, context) { var stream = new StringIO(); stream.write(Tags.TagCall); var writer = new Writer(stream, context.simple, context.binary); writer.writeString(name); if (args.length > 0 || context.byref) { writer.reset(); writer.writeList(args); if (context.byref) { writer.writeBoolean(true); } } return stream; } function __invoke(name, args, context, batch) { if (_lock) { return Future.promise(function(resolve, reject) { _tasks.push({ batch: batch, name: name, args: args, context: context, resolve: resolve, reject: reject }); }); } if (batch) { return multicall(name, args, context); } return call(name, args, context); } function _invoke(stub, name, args, batch) { return __invoke(name, args, getContext(stub, name, args, batch), batch); } function errorHandling(name, error, context, reject) { try { if (context.onerror) { context.onerror(name, error); } else if (self.onerror) { self.onerror(name, error); } reject(error); } catch (e) { reject(e); } } function invokeHandler(name, args, context) { var request = encode(name, args, context); request.write(Tags.TagEnd); return Future.promise(function(resolve, reject) { sendAndReceive(request.toString(), context, function(response) { if (context.oneway) { resolve(); return; } var result = null; var error = null; try { if (context.mode === ResultMode.RawWithEndTag) { result = response; } else if (context.mode === ResultMode.Raw) { result = response.substring(0, response.length - 1); } else { var stream = new StringIO(response); var reader = new Reader(stream, false, context.useHarmonyMap, context.binary); var tag = stream.readChar(); if (tag === Tags.TagResult) { if (context.mode === ResultMode.Serialized) { result = reader.readRaw(); } else { result = reader.unserialize(); } tag = stream.readChar(); if (tag === Tags.TagArgument) { reader.reset(); var _args = reader.readList(); copyargs(_args, args); tag = stream.readChar(); } } else if (tag === Tags.TagError) { error = new Error(reader.readString()); tag = stream.readChar(); } if (tag !== Tags.TagEnd) { error = new Error('Wrong Response:\r\n' + response); } } } catch (e) { error = e; } if (error) { reject(error); } else { resolve(result); } }, reject); }); } function unlock(sync) { return function() { if (sync) { _lock = false; setImmediate(function(tasks) { tasks.forEach(function(task) { if ('settings' in task) { endBatch(task.settings) .then(task.resolve, task.reject); } else { __invoke(task.name, task.args, task.context, task.batch).then(task.resolve, task.reject); } }); }, _tasks); _tasks = []; } }; } function call(name, args, context) { if (context.sync) { _lock = true; } var promise = Future.promise(function(resolve, reject) { _invokeHandler(name, args, context).then(function(result) { try { if (context.onsuccess) { try { context.onsuccess(result, args); } catch (e) { if (context.onerror) { context.onerror(name, e); } reject(e); } } resolve(result); } catch (e) { reject(e); } }, function(error) { errorHandling(name, error, context, reject); }); }); promise.whenComplete(unlock(context.sync)); return promise; } function multicall(name, args, context) { return Future.promise(function(resolve, reject) { _batches.push({ args: args, name: name, context: context, resolve: resolve, reject: reject }); }); } function getBatchContext(settings) { var context = { timeout: _timeout, binary: _binary, retry: _retry, retried: 0, idempotent: _idempotent, failswitch: _failswitch, oneway: false, sync: false, client: self, userdata: {} }; for (var k in settings) { if (k in context) { context[k] = settings[k]; } } return context; } function batchInvokeHandler(batches, context) { var request = batches.reduce(function(stream, item) { item.context.binary = context.binary; stream.write(encode(item.name, item.args, item.context)); return stream; }, new StringIO()); request.write(Tags.TagEnd); return Future.promise(function(resolve, reject) { sendAndReceive(request.toString(), context, function(response) { if (context.oneway) { resolve(batches); return; } var i = -1; var stream = new StringIO(response); var reader = new Reader(stream, false, false, context.binary); var tag = stream.readChar(); try { while (tag !== Tags.TagEnd) { var result = null; var error = null; var mode = batches[++i].context.mode; if (mode >= ResultMode.Raw) { result = new StringIO(); } if (tag === Tags.TagResult) { if (mode === ResultMode.Serialized) { result = reader.readRaw(); } else if (mode >= ResultMode.Raw) { result.write(Tags.TagResult); result.write(reader.readRaw()); } else { reader.useHarmonyMap = batches[i].context.useHarmonyMap; reader.reset(); result = reader.unserialize(); } tag = stream.readChar(); if (tag === Tags.TagArgument) { if (mode >= ResultMode.Raw) { result.write(Tags.TagArgument); result.write(reader.readRaw()); } else { reader.reset(); var _args = reader.readList(); copyargs(_args, batches[i].args); } tag = stream.readChar(); } } else if (tag === Tags.TagError) { if (mode >= ResultMode.Raw) { result.write(Tags.TagError); result.write(reader.readRaw()); } else { reader.reset(); error = new Error(reader.readString()); } tag = stream.readChar(); } if ([Tags.TagEnd, Tags.TagResult, Tags.TagError].indexOf(tag) < 0) { reject(new Error('Wrong Response:\r\n' + response)); return; } if (mode >= ResultMode.Raw) { if (mode === ResultMode.RawWithEndTag) { result.write(Tags.TagEnd); } batches[i].result = result.toString(); } else { batches[i].result = result; } batches[i].error = error; } } catch (e) { reject(e); return; } resolve(batches); }, reject); }); } function beginBatch() { _batch = true; } function endBatch(settings) { settings = settings || {}; _batch = false; if (_lock) { return Future.promise(function(resolve, reject) { _tasks.push({ batch: true, settings: settings, resolve: resolve, reject: reject }); }); } var batchSize = _batches.length; if (batchSize === 0) { return Future.value([]); } var context = getBatchContext(settings); if (context.sync) { _lock = true; } var batches = _batches; _batches = []; var promise = Future.promise(function(resolve, reject) { _batchInvokeHandler(batches, context).then(function(batches) { batches.forEach(function(i) { if (i.error) { errorHandling(i.name, i.error, i.context, i.reject); } else { try { if (i.context.onsuccess) { try { i.context.onsuccess(i.result, i.args); } catch (e) { if (i.context.onerror) { i.context.onerror(i.name, e); } i.reject(e); } } i.resolve(i.result); } catch (e) { i.reject(e); } } delete i.context; delete i.resolve; delete i.reject; }); resolve(batches); }, function(error) { batches.forEach(function(i) { if ('reject' in i) { errorHandling(i.name, error, i.context, i.reject); } }); reject(error); }); }); promise.whenComplete(unlock(context.sync)); return promise; } function getUri() { return _uri; } function getUriList() { return _uriList; } function setUriList(uriList) { if (typeof(uriList) === s_string) { _uriList = [uriList]; } else if (Array.isArray(uriList)) { _uriList = uriList.slice(0); _uriList.sort(function() { return Math.random() - 0.5; }); } else { return; } _index = 0; _uri = _uriList[_index]; } function getBinary() { return _binary; } function setBinary(value) { _binary = !!value; } function getFailswitch() { return _failswitch; } function setFailswitch(value) { _failswitch = !!value; } function getFailround() { return _failround; } function getTimeout() { return _timeout; } function setTimeout(value) { if (typeof(value) === 'number') { _timeout = value | 0; } else { _timeout = 0; } } function getRetry() { return _retry; } function setRetry(value) { if (typeof(value) === 'number') { _retry = value | 0; } else { _retry = 0; } } function getIdempotent() { return _idempotent; } function setIdempotent(value) { _idempotent = !!value; } function setKeepAlive(value) { _keepAlive = !!value; } function getKeepAlive() { return _keepAlive; } function getByRef() { return _byref; } function setByRef(value) { _byref = !!value; } function getSimpleMode() { return _simple; } function setSimpleMode(value) { _simple = !!value; } function getUseHarmonyMap() { return _useHarmonyMap; } function setUseHarmonyMap(value) { _useHarmonyMap = !!value; } function getFilter() { if (_filters.length === 0) { return null; } if (_filters.length === 1) { return _filters[0]; } return _filters.slice(); } function setFilter(filter) { _filters.length = 0; if (Array.isArray(filter)) { filter.forEach(function(filter) { addFilter(filter); }); } else { addFilter(filter); } } function addFilter(filter) { if (filter && typeof filter.inputFilter === 'function' && typeof filter.outputFilter === 'function') { _filters.push(filter); } } function removeFilter(filter) { var i = _filters.indexOf(filter); if (i === -1) { return false; } _filters.splice(i, 1); return true; } function filters() { return _filters; } function useService(uri, functions, create) { if (create === undefined) { if (typeof(functions) === s_boolean) { create = functions; functions = false; } if (!functions) { if (typeof(uri) === s_boolean) { create = uri; uri = false; } else if (uri && uri.constructor === Object || Array.isArray(uri)) { functions = uri; uri = false; } } } var stub = self; if (create) { stub = {}; } if (!uri && !_uri) { return new Error('You should set server uri first!'); } if (uri) { _uri = uri; } if (typeof(functions) === s_string || (functions && functions.constructor === Object)) { functions = [functions]; } if (!Array.isArray(functions)) { setImmediate(initService, stub); return _ready; } setFunctions(stub, functions); _ready.resolve(stub); return stub; } function invoke(name, args, onsuccess/*, onerror, settings*/) { var argc = arguments.length; if ((argc < 1) || (typeof name !== s_string)) { throw new Error('name must be a string'); } if (argc === 1) { args = []; } if (argc === 2) { if (!Array.isArray(args)) { var _args = []; if (typeof args !== s_function) { _args.push(noop); } _args.push(args); args = _args; } } if (argc > 2) { if (typeof onsuccess !== s_function) { args.push(noop); } for (var i = 2; i < argc; i++) { args.push(arguments[i]); } } return _invoke(self, name, args, _batch); } function ready(onComplete, onError) { return _ready.then(onComplete, onError); } function getTopic(name, id) { if (_topics[name]) { var topics = _topics[name]; if (topics[id]) { return topics[id]; } } return null; } // subscribe(name, callback, timeout, failswitch) // subscribe(name, id, callback, timeout, failswitch) function subscribe(name, id, callback, timeout, failswitch) { if (typeof name !== s_string) { throw new TypeError('topic name must be a string.'); } if (id === undefined || id === null) { if (typeof callback === s_function) { id = callback; } else { throw new TypeError('callback must be a function.'); } } if (!_topics[name]) { _topics[name] = createObject(null); } if (typeof id === s_function) { timeout = callback; callback = id; autoId().then(function(id) { subscribe(name, id, callback, timeout, failswitch); }); return; } if (typeof callback !== s_function) { throw new TypeError('callback must be a function.'); } if (Future.isPromise(id)) { id.then(function(id) { subscribe(name, id, callback, timeout, failswitch); }); return; } // Default subscribe timeout is 5 minutes. if (timeout === undefined) { timeout = 300000; } var topic = getTopic(name, id); if (topic === null) { var cb = function() { _invoke(self, name, [id, topic.handler, cb, { idempotent: true, failswitch: failswitch, timeout: timeout }], false); }; topic = { handler: function(result) { var topic = getTopic(name, id); if (topic) { if (result !== null) { var callbacks = topic.callbacks; for (var i = 0, n = callbacks.length; i < n; ++i) { try { callbacks[i](result); } catch (e) {} } } if (getTopic(name, id) !== null) { cb(); } } }, callbacks: [callback] }; _topics[name][id] = topic; cb(); } else if (topic.callbacks.indexOf(callback) < 0) { topic.callbacks.push(callback); } } function delTopic(topics, id, callback) { if (topics) { if (typeof callback === s_function) { var topic = topics[id]; if (topic) { var callbacks = topic.callbacks; var p = callbacks.indexOf(callback); if (p >= 0) { callbacks[p] = callbacks[callbacks.length - 1]; callbacks.length--; } if (callbacks.length === 0) { delete topics[id]; } } } else { delete topics[id]; } } } // unsubscribe(name) // unsubscribe(name, callback) // unsubscribe(name, id) // unsubscribe(name, id, callback) function unsubscribe(name, id, callback) { if (typeof name !== s_string) { throw new TypeError('topic name must be a string.'); } if (id === undefined || id === null) { if (typeof callback === s_function) { id = callback; } else { delete _topics[name]; return; } } if (typeof id === s_function) { callback = id; id = null; } if (id === null) { if (_id === null) { if (_topics[name]) { var topics = _topics[name]; for (id in topics) { delTopic(topics, id, callback); } } } else { _id.then(function(id) { unsubscribe(name, id, callback); }); } } else if (Future.isPromise(id)) { id.then(function(id) { unsubscribe(name, id, callback); }); } else { delTopic(_topics[name], id, callback); } if (isObjectEmpty(_topics[name])) { delete _topics[name]; } } function isSubscribed(name) { return !!_topics[name]; } function subscribedList() { var list = []; for (var name in _topics) { list.push(name); } return list; } function getId() { return _id; } function autoId() { if (_id === null) { _id = _invoke(self, '#', [], false); } return _id; } autoId.sync = true; autoId.idempotent = true; autoId.failswitch = true; function addInvokeHandler(handler) { _invokeHandlers.push(handler); _invokeHandler = _invokeHandlers.reduceRight( function(next, handler) { return function(name, args, context) { return Future.toPromise(handler(name, args, context, next)); }; }, invokeHandler); } function addBatchInvokeHandler(handler) { _batchInvokeHandlers.push(handler); _batchInvokeHandler = _batchInvokeHandlers.reduceRight( function(next, handler) { return function(batches, context) { return Future.toPromise(handler(batches, context, next)); }; }, batchInvokeHandler); } function addBeforeFilterHandler(handler) { _beforeFilterHandlers.push(handler); _beforeFilterHandler = _beforeFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { return Future.toPromise(handler(request, context, next)); }; }, beforeFilterHandler); } function addAfterFilterHandler(handler) { _afterFilterHandlers.push(handler); _afterFilterHandler = _afterFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { return Future.toPromise(handler(request, context, next)); }; }, afterFilterHandler); } function use(handler) { addInvokeHandler(handler); return self; } var batch = createObject(null, { begin: { value: beginBatch }, end: { value: endBatch }, use: { value: function(handler) { addBatchInvokeHandler(handler); return batch; } } }); var beforeFilter = createObject(null, { use: { value: function(handler) { addBeforeFilterHandler(handler); return beforeFilter; } } }); var afterFilter = createObject(null, { use: { value: function(handler) { addAfterFilterHandler(handler); return afterFilter; } } }); defineProperties(this, { '#': { value: autoId }, onerror: { value: null, writable: true }, onfailswitch: { value: null, writable: true }, uri: { get: getUri }, uriList: { get: getUriList, set: setUriList }, id: { get: getId }, binary: { get: getBinary, set: setBinary }, failswitch: { get: getFailswitch, set: setFailswitch }, failround: { get: getFailround }, timeout: { get: getTimeout, set: setTimeout }, retry: { get: getRetry, set: setRetry }, idempotent: { get: getIdempotent, set: setIdempotent }, keepAlive: { get: getKeepAlive, set: setKeepAlive }, byref: { get: getByRef, set: setByRef }, simple: { get: getSimpleMode, set: setSimpleMode }, useHarmonyMap: { get: getUseHarmonyMap, set: setUseHarmonyMap }, filter: { get: getFilter, set: setFilter }, addFilter: { value: addFilter }, removeFilter: { value: removeFilter }, filters: { get: filters }, useService: { value: useService }, invoke: { value: invoke }, ready: { value: ready }, subscribe: { value: subscribe }, unsubscribe: { value: unsubscribe }, isSubscribed: { value : isSubscribed }, subscribedList: { value : subscribedList }, use: { value: use }, batch: { value: batch }, beforeFilter: { value: beforeFilter }, afterFilter: { value: afterFilter } }); /* function constructor */ { if ((settings) && (typeof settings === s_object)) { ['failswitch', 'timeout', 'retry', 'idempotent', 'keepAlive', 'byref', 'simple','useHarmonyMap', 'filter', 'binary'].forEach(function(key) { if (key in settings) { self[key](settings[key]); } }); } if (uri) { setUriList(uri); useService(functions); } } } function checkuri(uri) { var parser = parseuri(uri); var protocol = parser.protocol; if (protocol === 'http:' || protocol === 'https:' || protocol === 'tcp:' || protocol === 'tcp4:'|| protocol === 'tcp6:' || protocol === 'tcps:' || protocol === 'tcp4s:' || protocol === 'tcp6s:' || protocol === 'tls:' || protocol === 'ws:' || protocol === 'wss:') { return; } throw new Error('The ' + protocol + ' client isn\'t implemented.'); } function create(uri, functions, settings) { try { return hprose.HttpClient.create(uri, functions, settings); } catch(e) {} try { return hprose.TcpClient.create(uri, functions, settings); } catch(e) {} try { return hprose.WebSocketClient.create(uri, functions, settings); } catch(e) {} if (typeof uri === 'string') { checkuri(uri); } else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); throw new Error('Not support multiple protocol.'); } throw new Error('You should set server uri first!'); } defineProperties(Client, { create: { value: create } }); global.HproseClient = hprose.Client = Client; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * FlashHttpRequest.js * * * * POST data to HTTP Server (using Flash). * * * * LastModified: Dec 2, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ /* * Interfaces: * FlashHttpRequest.post(url, header, data, callback, timeout, binary); */ /* public class FlashHttpRequest * static encapsulation environment for FlashHttpRequest */ /*jshint unused:false */ (function (global) { 'use strict'; if (typeof global.document === "undefined") { global.FlashHttpRequest = { flashSupport: function() { return false; } }; return; } // get flash path var document = global.document; var scripts = document.getElementsByTagName('script'); var flashpath = ((scripts.length > 0) && scripts[scripts.length - 1].getAttribute('flashpath')) || global.hproseFlashPath || ''; scripts = null; // static private members var localfile = (global.location !== undefined && global.location.protocol === 'file:'); var XMLHttpRequest = global.XMLHttpRequest; var nativeXHR = (typeof(XMLHttpRequest) !== 'undefined'); var corsSupport = (!localfile && nativeXHR && 'withCredentials' in new XMLHttpRequest()); var flashID = 'flashhttprequest_as3'; var flashSupport = false; /* * to save Flash Request */ var request = null; /* * to save all request callback functions */ var callbackList = []; /* * to save FlashHttpRequest tasks. */ var jsTaskQueue = []; var swfTaskQueue = []; /* * to save js & swf status. */ var jsReady = false; var swfReady = false; function checkFlash() { if (!navigator) { return 0; } var flash = 'Shockwave Flash'; var flashmime = 'application/x-shockwave-flash'; var flashax = 'ShockwaveFlash.ShockwaveFlash'; var plugins = navigator.plugins; var mimetypes = navigator.mimeTypes; var version = 0; var ie = false; if (plugins && plugins[flash]) { version = plugins[flash].description; if (version && !(mimetypes && mimetypes[flashmime] && !mimetypes[flashmime].enabledPlugin)) { version = version.replace(/^.*\s+(\S+\s+\S+$)/, '$1'); version = parseInt(version.replace(/^(.*)\..*$/, '$1'), 10); } } else if (global.ActiveXObject) { try { ie = true; var ax = new global.ActiveXObject(flashax); if (ax) { version = ax.GetVariable('$version'); if (version) { version = version.split(' ')[1].split(','); version = parseInt(version[0], 10); } } } catch(e) {} } if (version < 10) { return 0; } else if (ie) { return 1; } else { return 2; } } function setFlash() { var flashStatus = checkFlash(); flashSupport = flashStatus > 0; if (flashSupport) { var div = document.createElement('div'); div.style.width = 0; div.style.height = 0; if (flashStatus === 1) { div.innerHTML = ['<object ', 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ', 'type="application/x-shockwave-flash" ', 'width="0" height="0" id="', flashID, '" name="', flashID, '">', '<param name="movie" value="', flashpath , 'FlashHttpRequest.swf?', +(new Date()), '" />', '<param name="allowScriptAccess" value="always" />', '<param name="quality" value="high" />', '<param name="wmode" value="opaque" />', '</object>'].join(''); } else { div.innerHTML = '<embed id="' + flashID + '" ' + 'src="' + flashpath + 'FlashHttpRequest.swf?' + (+(new Date())) + '" ' + 'type="application/x-shockwave-flash" ' + 'width="0" height="0" name="' + flashID + '" ' + 'allowScriptAccess="always" />'; } document.documentElement.appendChild(div); } } function setJsReady() { if (jsReady) { return; } if (!localfile && !corsSupport) { setFlash(); } jsReady = true; while (jsTaskQueue.length > 0) { var task = jsTaskQueue.shift(); if (typeof(task) === 'function') { task(); } } } function post(url, header, data, callbackid, timeout, binary) { data = encodeURIComponent(data); if (swfReady) { request.post(url, header, data, callbackid, timeout, binary); } else { swfTaskQueue.push(function() { request.post(url, header, data, callbackid, timeout, binary); }); } } var FlashHttpRequest = {}; FlashHttpRequest.flashSupport = function() { return flashSupport; }; FlashHttpRequest.post = function(url, header, data, callback, timeout, binary) { var callbackid = -1; if (callback) { callbackid = callbackList.length; callbackList[callbackid] = callback; } if (jsReady) { post(url, header, data, callbackid, timeout, binary); } else { jsTaskQueue.push(function() { post(url, header, data, callbackid, timeout, binary); }); } }; FlashHttpRequest.__callback = function (callbackid, data, error) { data = (data !== null) ? decodeURIComponent(data) : null; error = (error !== null) ? decodeURIComponent(error) : null; if (typeof(callbackList[callbackid]) === 'function') { callbackList[callbackid](data, error); } delete callbackList[callbackid]; }; FlashHttpRequest.__jsReady = function () { return jsReady; }; FlashHttpRequest.__setSwfReady = function () { request = (navigator.appName.indexOf('Microsoft') !== -1) ? global[flashID] : document[flashID]; swfReady = true; global.__flash__removeCallback = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; while (swfTaskQueue.length > 0) { var task = swfTaskQueue.shift(); if (typeof(task) === 'function') { task(); } } }; global.FlashHttpRequest = FlashHttpRequest; setJsReady(); })(hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * CookieManager.js * * * * hprose CookieManager for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose) { 'use strict'; var parseuri = hprose.parseuri; var s_cookieManager = {}; function setCookie(headers, uri) { var parser = parseuri(uri); var host = parser.host; var name, values; function _setCookie(value) { var cookies, cookie, i; cookies = value.replace(/(^\s*)|(\s*$)/g, '').split(';'); cookie = {}; value = cookies[0].replace(/(^\s*)|(\s*$)/g, '').split('=', 2); if (value[1] === undefined) { value[1] = null; } cookie.name = value[0]; cookie.value = value[1]; for (i = 1; i < cookies.length; i++) { value = cookies[i].replace(/(^\s*)|(\s*$)/g, '').split('=', 2); if (value[1] === undefined) { value[1] = null; } cookie[value[0].toUpperCase()] = value[1]; } // Tomcat can return SetCookie2 with path wrapped in " if (cookie.PATH) { if (cookie.PATH.charAt(0) === '"') { cookie.PATH = cookie.PATH.substr(1); } if (cookie.PATH.charAt(cookie.PATH.length - 1) === '"') { cookie.PATH = cookie.PATH.substr(0, cookie.PATH.length - 1); } } else { cookie.PATH = '/'; } if (cookie.EXPIRES) { cookie.EXPIRES = Date.parse(cookie.EXPIRES); } if (cookie.DOMAIN) { cookie.DOMAIN = cookie.DOMAIN.toLowerCase(); } else { cookie.DOMAIN = host; } cookie.SECURE = (cookie.SECURE !== undefined); if (s_cookieManager[cookie.DOMAIN] === undefined) { s_cookieManager[cookie.DOMAIN] = {}; } s_cookieManager[cookie.DOMAIN][cookie.name] = cookie; } for (name in headers) { values = headers[name]; name = name.toLowerCase(); if ((name === 'set-cookie') || (name === 'set-cookie2')) { if (typeof(values) === 'string') { values = [values]; } values.forEach(_setCookie); } } } function getCookie(uri) { var parser = parseuri(uri); var host = parser.host; var path = parser.path; var secure = (parser.protocol === 'https:'); var cookies = []; for (var domain in s_cookieManager) { if (host.indexOf(domain) > -1) { var names = []; for (var name in s_cookieManager[domain]) { var cookie = s_cookieManager[domain][name]; if (cookie.EXPIRES && ((new Date()).getTime() > cookie.EXPIRES)) { names.push(name); } else if (path.indexOf(cookie.PATH) === 0) { if (((secure && cookie.SECURE) || !cookie.SECURE) && (cookie.value !== null)) { cookies.push(cookie.name + '=' + cookie.value); } } } for (var i in names) { delete s_cookieManager[domain][names[i]]; } } } if (cookies.length > 0) { return cookies.join('; '); } return ''; } hprose.cookieManager = { setCookie: setCookie, getCookie: getCookie }; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HttpClient.js * * * * hprose http client for JavaScript. * * * * LastModified: Dec 2, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var Client = hprose.Client; var Future = hprose.Future; var createObject = hprose.createObject; var defineProperties = hprose.defineProperties; var toBinaryString = hprose.toBinaryString; var toUint8Array = hprose.toUint8Array; var parseuri = hprose.parseuri; var cookieManager = hprose.cookieManager; var TimeoutError = global.TimeoutError; var FlashHttpRequest = global.FlashHttpRequest; var XMLHttpRequest = global.XMLHttpRequest; if (global.plus && global.plus.net && global.plus.net.XMLHttpRequest) { XMLHttpRequest = global.plus.net.XMLHttpRequest; } else if (global.document && global.document.addEventListener) { global.document.addEventListener("plusready", function() { XMLHttpRequest = global.plus.net.XMLHttpRequest; }, false); } var deviceone; try { deviceone = global.require("deviceone"); } catch (e) {} var localfile = (global.location !== undefined && global.location.protocol === 'file:'); var nativeXHR = (typeof(XMLHttpRequest) !== 'undefined'); var corsSupport = (!localfile && nativeXHR && 'withCredentials' in new XMLHttpRequest()); var ActiveXObject = global.ActiveXObject; var XMLHttpNameCache = null; function createMSXMLHttp() { if (XMLHttpNameCache !== null) { // Use the cache name first. return new ActiveXObject(XMLHttpNameCache); } var MSXML = ['MSXML2.XMLHTTP', 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MsXML2.XMLHTTP.2.6', 'Microsoft.XMLHTTP', 'Microsoft.XMLHTTP.1.0', 'Microsoft.XMLHTTP.1']; var n = MSXML.length; for(var i = 0; i < n; i++) { try { var xhr = new ActiveXObject(MSXML[i]); // Cache the XMLHttp ActiveX object name. XMLHttpNameCache = MSXML[i]; return xhr; } catch(e) {} } throw new Error('Could not find an installed XML parser'); } function createXHR() { if (nativeXHR) { return new XMLHttpRequest(); } else if (ActiveXObject) { return createMSXMLHttp(); } else { throw new Error("XMLHttpRequest is not supported by this browser."); } } function noop(){} if (nativeXHR && typeof(Uint8Array) !== 'undefined' && !XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function(bs) { var data = toUint8Array(bs); this.send(ArrayBuffer.isView ? data : data.buffer); }; } function getResponseHeader(headers) { var header = createObject(null); if (headers) { headers = headers.split("\r\n"); for (var i = 0, n = headers.length; i < n; i++) { if (headers[i] !== "") { var kv = headers[i].split(": ", 2); var k = kv[0].trim(); var v = kv[1].trim(); if (k in header) { if (Array.isArray(header[k])) { header[k].push(v); } else { header[k] = [header[k], v]; } } else { header[k] = v; } } } } return header; } function HttpClient(uri, functions, settings) { if (this.constructor !== HttpClient) { return new HttpClient(uri, functions, settings); } Client.call(this, uri, functions, settings); var _header = createObject(null); var self = this; function getRequestHeader(headers) { var header = createObject(null); var name, value; for (name in _header) { header[name] = _header[name]; } if (headers) { for (name in headers) { value = headers[name]; if (Array.isArray(value)) { header[name] = value.join(', '); } else { header[name] = value; } } } return header; } function xhrPost(request, context) { var future = new Future(); var xhr = createXHR(); xhr.open('POST', self.uri(), true); if (corsSupport) { xhr.withCredentials = 'true'; } var header = getRequestHeader(context.httpHeader); for (var name in header) { xhr.setRequestHeader(name, header[name]); } if (!context.binary) { xhr.setRequestHeader("Content-Type", "text/plain; charset=UTF-8"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { xhr.onreadystatechange = noop; if (xhr.status) { var headers = xhr.getAllResponseHeaders(); context.httpHeader = getResponseHeader(headers); if (xhr.status === 200) { if (context.binary) { future.resolve(toBinaryString(xhr.response)); } else { future.resolve(xhr.responseText); } } else { future.reject(new Error(xhr.status + ':' + xhr.statusText)); } } } }; xhr.onerror = function() { future.reject(new Error('error')); }; if (context.timeout > 0) { future = future.timeout(context.timeout).catchError(function(e) { xhr.onreadystatechange = noop; xhr.onerror = noop; xhr.abort(); throw e; }, function(e) { return e instanceof TimeoutError; }); } if (context.binary) { xhr.responseType = "arraybuffer"; xhr.sendAsBinary(request); } else { xhr.send(request); } return future; } function fhrPost(request, context) { var future = new Future(); var callback = function(data, error) { context.httpHeader = createObject(null); if (error === null) { future.resolve(data); } else { future.reject(new Error(error)); } }; var header = getRequestHeader(context.httpHeader); FlashHttpRequest.post(self.uri(), header, request, callback, context.timeout, context.binary); return future; } function apiPost(request, context) { var future = new Future(); var header = getRequestHeader(context.httpHeader); var cookie = cookieManager.getCookie(self.uri()); if (cookie !== '') { header['Cookie'] = cookie; } global.api.ajax({ url: self.uri(), method: 'post', data: { body: request }, timeout: context.timeout, dataType: 'text', headers: header, returnAll: true, certificate: self.certificate }, function(ret, err) { if (ret) { context.httpHeader = ret.headers; if (ret.statusCode === 200) { cookieManager.setCookie(ret.headers, self.uri()); future.resolve(ret.body); } else { future.reject(new Error(ret.statusCode+':'+ret.body)); } } else { future.reject(new Error(err.msg)); } }); return future; } function deviceOnePost(request, context) { var future = new Future(); var http = deviceone.mm('do_Http'); http.method = "POST"; http.timeout = context.timeout; http.contentType = "text/plain; charset=UTF-8"; http.url = self.uri(); http.body = request; var header = getRequestHeader(context.httpHeader); for (var name in header) { http.setRequestHeader(name, header[name]); } var cookie = cookieManager.getCookie(self.uri()); if (cookie !== '') { http.setRequestHeader('Cookie', cookie); } http.on("success", function(data) { var cookie = http.getResponseHeader('set-cookie'); if (cookie) { cookieManager.setCookie({'set-cookie': cookie}, self.uri()); } future.resolve(data); }); http.on("fail", function(result) { future.reject(new Error(result.status + ":" + result.data)); }); http.request(); context.httpHeader = createObject(null); return future; } function isCrossDomain() { if (global.location === undefined) { return true; } var parser = parseuri(self.uri()); if (parser.protocol !== global.location.protocol) { return true; } if (parser.host !== global.location.host) { return true; } return false; } function sendAndReceive(request, context) { var fhr = (FlashHttpRequest.flashSupport() && !localfile && !corsSupport && (context.binary || isCrossDomain())); var apicloud = (typeof(global.api) !== "undefined" && typeof(global.api.ajax) !== "undefined"); var future = fhr ? fhrPost(request, context) : apicloud ? apiPost(request, context) : deviceone ? deviceOnePost(request, context) : xhrPost(request, context); if (context.oneway) { future.resolve(); } return future; } function setHeader(name, value) { if (name.toLowerCase() !== 'content-type') { if (value) { _header[name] = value; } else { delete _header[name]; } } } defineProperties(this, { certificate: { value: null, writable: true }, setHeader: { value: setHeader }, sendAndReceive: { value: sendAndReceive } }); } function checkuri(uri) { var parser = parseuri(uri); if (parser.protocol === 'http:' || parser.protocol === 'https:') { return; } throw new Error('This client desn\'t support ' + parser.protocol + ' scheme.'); } function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { throw new Error('You should set server uri first!'); } return new HttpClient(uri, functions, settings); } defineProperties(HttpClient, { create: { value: create } }); global.HproseHttpClient = hprose.HttpClient = HttpClient; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * WebSocketClient.js * * * * hprose websocket client for JavaScript. * * * * LastModified: Aug 20, 2017 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var StringIO = hprose.StringIO; var Client = hprose.Client; var Future = hprose.Future; var TimeoutError = global.TimeoutError; var defineProperties = hprose.defineProperties; var toBinaryString = hprose.toBinaryString; var toUint8Array = hprose.toUint8Array; var parseuri = hprose.parseuri; var WebSocket = global.WebSocket || global.MozWebSocket; function noop(){} function WebSocketClient(uri, functions, settings) { if (typeof(WebSocket) === "undefined") { throw new Error('WebSocket is not supported by this browser.'); } if (this.constructor !== WebSocketClient) { return new WebSocketClient(uri, functions, settings); } Client.call(this, uri, functions, settings); var _id = 0; var _count = 0; var _futures = []; var _contexts = []; var _requests = []; var _ready = null; var ws = null; var self = this; function getNextId() { return (_id < 0x7fffffff) ? ++_id : _id = 0; } function send(id, request) { var stream = new StringIO(); stream.writeInt32BE(id); if (_contexts[id].binary) { stream.write(request); } else { stream.writeUTF16AsUTF8(request); } var message = toUint8Array(stream.take()); if (ArrayBuffer.isView) { ws.send(message); } else { ws.send(message.buffer); } } function onopen(e) { _ready.resolve(e); } function onmessage(e) { var stream; if (typeof e.data === "string") { stream = new StringIO(StringIO.utf8Encode(e.data)); } else { stream = new StringIO(toBinaryString(e.data)); } var id = stream.readInt32BE(); var future = _futures[id]; var context = _contexts[id]; delete _futures[id]; delete _contexts[id]; if (future !== undefined) { --_count; var data = stream.read(stream.length() - 4); if (!context.binary) { data = StringIO.utf8Decode(data); } future.resolve(data); } if ((_count < 100) && (_requests.length > 0)) { ++_count; var request = _requests.pop(); _ready.then(function() { send(request[0], request[1]); }); } if (_count === 0 && !self.keepAlive()) { close(); } } function onclose(e) { _futures.forEach(function(future, id) { future.reject(new Error(e.code + ':' + e.reason)); delete _futures[id]; }); _count = 0; ws = null; } function connect() { _ready = new Future(); ws = new WebSocket(self.uri()); ws.binaryType = 'arraybuffer'; ws.onopen = onopen; ws.onmessage = onmessage; ws.onerror = noop; ws.onclose = onclose; } function sendAndReceive(request, context) { var id = getNextId(); var future = new Future(); _futures[id] = future; _contexts[id] = context; if (context.timeout > 0) { future = future.timeout(context.timeout).catchError(function(e) { delete _futures[id]; --_count; close(); throw e; }, function(e) { return e instanceof TimeoutError; }); } if (ws === null || ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) { connect(); } if (_count < 100) { ++_count; _ready.then(function() { send(id, request); }); } else { _requests.push([id, request]); } if (context.oneway) { future.resolve(); } return future; } function close() { if (ws !== null) { ws.onopen = noop; ws.onmessage = noop; ws.onclose = noop; ws.close(); } } defineProperties(this, { sendAndReceive: { value: sendAndReceive }, close: { value: close } }); } function checkuri(uri) { var parser = parseuri(uri); if (parser.protocol === 'ws:' || parser.protocol === 'wss:') { return; } throw new Error('This client desn\'t support ' + parser.protocol + ' scheme.'); } function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { throw new Error('You should set server uri first!'); } return new WebSocketClient(uri, functions, settings); } defineProperties(WebSocketClient, { create: { value: create } }); global.HproseWebSocketClient = hprose.WebSocketClient = WebSocketClient; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * ChromeTcpSocket.js * * * * chrome tcp socket for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var Future = hprose.Future; var defineProperties = hprose.defineProperties; var toUint8Array = hprose.toUint8Array; var toBinaryString = hprose.toBinaryString; function noop(){} var socketPool = {}; var socketManager = null; function receiveListener(info) { var socket = socketPool[info.socketId]; socket.onreceive(toBinaryString(info.data)); } function receiveErrorListener(info) { var socket = socketPool[info.socketId]; socket.onerror(info.resultCode); socket.destroy(); } function ChromeTcpSocket() { if (socketManager === null) { socketManager = global.chrome.sockets.tcp; socketManager.onReceive.addListener(receiveListener); socketManager.onReceiveError.addListener(receiveErrorListener); } this.socketId = new Future(); this.connected = false; this.timeid = undefined; this.onclose = noop; this.onconnect = noop; this.onreceive = noop; this.onerror = noop; } defineProperties(ChromeTcpSocket.prototype, { connect: { value: function(address, port, options) { var self = this; socketManager.create({ persistent: options && options.persistent }, function(createInfo) { if (options) { if ('noDelay' in options) { socketManager.setNoDelay(createInfo.socketId, options.noDelay, function(result) { if (result < 0) { self.socketId.reject(result); socketManager.disconnect(createInfo.socketId); socketManager.close(createInfo.socketId); self.onclose(); } }); } if ('keepAlive' in options) { socketManager.setKeepAlive(createInfo.socketId, options.keepAlive, function(result) { if (result < 0) { self.socketId.reject(result); socketManager.disconnect(createInfo.socketId); socketManager.close(createInfo.socketId); self.onclose(); } }); } } if (options && options.tls) { socketManager.setPaused(createInfo.socketId, true, function() { socketManager.connect(createInfo.socketId, address, port, function(result) { if (result < 0) { self.socketId.reject(result); socketManager.disconnect(createInfo.socketId); socketManager.close(createInfo.socketId); self.onclose(); } else { socketManager.secure(createInfo.socketId, function(secureResult) { if (secureResult !== 0) { self.socketId.reject(result); socketManager.disconnect(createInfo.socketId); socketManager.close(createInfo.socketId); self.onclose(); } else { socketManager.setPaused(createInfo.socketId, false, function() { self.socketId.resolve(createInfo.socketId); }); } }); } }); }); } else { socketManager.connect(createInfo.socketId, address, port, function(result) { if (result < 0) { self.socketId.reject(result); socketManager.disconnect(createInfo.socketId); socketManager.close(createInfo.socketId); self.onclose(); } else { self.socketId.resolve(createInfo.socketId); } }); } }); this.socketId.then(function(socketId) { socketPool[socketId] = self; self.connected = true; self.onconnect(socketId); }, function(reason) { self.onerror(reason); }); } }, send: { value: function(data) { data = toUint8Array(data).buffer; var self = this; var promise = new Future(); this.socketId.then(function(socketId) { socketManager.send(socketId, data, function(sendInfo) { if (sendInfo.resultCode < 0) { self.onerror(sendInfo.resultCode); promise.reject(sendInfo.resultCode); self.destroy(); } else { promise.resolve(sendInfo.bytesSent); } }); }); return promise; } }, destroy: { value: function() { var self = this; this.connected = false; this.socketId.then(function(socketId) { socketManager.disconnect(socketId); socketManager.close(socketId); delete socketPool[socketId]; self.onclose(); }); } }, ref: { value: function() { this.socketId.then(function(socketId) { socketManager.setPaused(socketId, false); }); } }, unref: { value: function() { this.socketId.then(function(socketId) { socketManager.setPaused(socketId, true); }); } }, clearTimeout: { value: function() { if (this.timeid !== undefined) { global.clearTimeout(this.timeid); } } }, setTimeout: { value: function(timeout, fn) { this.clearTimeout(); this.timeid = global.setTimeout(fn, timeout); } } }); hprose.ChromeTcpSocket = ChromeTcpSocket; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * APICloudTcpSocket.js * * * * APICloud tcp socket for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var Future = hprose.Future; var defineProperties = hprose.defineProperties; var atob = global.atob; var btoa = global.btoa; function noop(){} var socketPool = {}; var socketManager = null; function APICloudTcpSocket() { if (socketManager === null) { socketManager = global.api.require('socketManager'); } this.socketId = new Future(); this.connected = false; this.timeid = undefined; this.onclose = noop; this.onconnect = noop; this.onreceive = noop; this.onerror = noop; } defineProperties(APICloudTcpSocket.prototype, { connect: { value: function(address, port, options) { var self = this; socketManager.createSocket({ type: 'tcp', host: address, port: port, timeout: options.timeout, returnBase64: true }, function(ret/*, err*/) { if (ret) { switch(ret.state) { case 101: break; case 102: self.socketId.resolve(ret.sid); break; case 103: self.onreceive(atob(ret.data.replace(/\s+/g, ''))); break; case 201: self.socketId.reject(new Error('Create TCP socket failed')); break; case 202: self.socketId.reject(new Error('TCP connection failed')); break; case 203: self.onclose(); self.onerror(new Error('Abnormal disconnect connection')); break; case 204: self.onclose(); break; case 205: self.onclose(); self.onerror(new Error('Unknown error')); break; } } }); this.socketId.then(function(socketId) { socketPool[socketId] = self; self.connected = true; self.onconnect(socketId); }, function(reason) { self.onerror(reason); }); } }, send: { value: function(data) { var self = this; var promise = new Future(); this.socketId.then(function(socketId) { socketManager.write({ sid: socketId, data: btoa(data), base64: true }, function(ret, err) { if (ret.status) { promise.resolve(); } else { self.onerror(new Error(err.msg)); promise.reject(err.msg); self.destroy(); } }); }); return promise; } }, destroy: { value: function() { var self = this; this.connected = false; this.socketId.then(function(socketId) { socketManager.closeSocket({ sid: socketId }, function(ret, err) { if (!ret.status) { self.onerror(new Error(err.msg)); } }); delete socketPool[socketId]; //self.onclose(); }); } }, ref: { value: noop }, unref: { value: noop }, clearTimeout: { value: function() { if (this.timeid !== undefined) { global.clearTimeout(this.timeid); } } }, setTimeout: { value: function(timeout, fn) { this.clearTimeout(); this.timeid = global.setTimeout(fn, timeout); } } }); hprose.APICloudTcpSocket = APICloudTcpSocket; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * TcpClient.js * * * * hprose tcp client for JavaScript. * * * * LastModified: Dec 2, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global, undefined) { 'use strict'; var TimeoutError = global.TimeoutError; var ChromeTcpSocket = hprose.ChromeTcpSocket; var APICloudTcpSocket = hprose.APICloudTcpSocket; var Client = hprose.Client; var StringIO = hprose.StringIO; var Future = hprose.Future; var createObject = hprose.createObject; var defineProperties = hprose.defineProperties; var parseuri = hprose.parseuri; function noop(){} function setReceiveHandler(socket, onreceive) { socket.onreceive = function(data) { if (!('receiveEntry' in socket)) { socket.receiveEntry = { stream: new StringIO(), headerLength: 4, dataLength: -1, id: null }; } var entry = socket.receiveEntry; var stream = entry.stream; var headerLength = entry.headerLength; var dataLength = entry.dataLength; var id = entry.id; stream.write(data); while (true) { if ((dataLength < 0) && (stream.length() >= headerLength)) { dataLength = stream.readInt32BE(); if ((dataLength & 0x80000000) !== 0) { dataLength &= 0x7fffffff; headerLength = 8; } } if ((headerLength === 8) && (id === null) && (stream.length() >= headerLength)) { id = stream.readInt32BE(); } if ((dataLength >= 0) && ((stream.length() - headerLength) >= dataLength)) { onreceive(stream.read(dataLength), id); headerLength = 4; id = null; stream.trunc(); dataLength = -1; } else { break; } } entry.stream = stream; entry.headerLength = headerLength; entry.dataLength = dataLength; entry.id = id; }; } function TcpTransporter(client) { if (client) { this.client = client; this.uri = this.client.uri(); this.size = 0; this.pool = []; this.requests = []; } } defineProperties(TcpTransporter.prototype, { create: { value: function() { var parser = parseuri(this.uri); var protocol = parser.protocol; var address = parser.hostname; var port = parseInt(parser.port, 10); var tls; if (protocol === 'tcp:' || protocol === 'tcp4:' || protocol === 'tcp6:') { tls = false; } else if (protocol === 'tcps:' || protocol === 'tcp4s:' || protocol === 'tcp6s:' || protocol === 'tls:') { tls = true; } else { throw new Error('Unsupported ' + protocol + ' protocol!'); } var conn; if (global.chrome && global.chrome.sockets && global.chrome.sockets.tcp) { conn = new ChromeTcpSocket(); } else if (global.api && global.api.require) { conn = new APICloudTcpSocket(); } else { throw new Error('TCP Socket is not supported by this browser or platform.'); } var self = this; conn.connect(address, port, { persistent: true, tls: tls, timeout: this.client.timeout(), noDelay: this.client.noDelay(), keepAlive: this.client.keepAlive() }); conn.onclose = function() { --self.size; }; ++this.size; return conn; } } }); function FullDuplexTcpTransporter(client) { TcpTransporter.call(this, client); } FullDuplexTcpTransporter.prototype = createObject( TcpTransporter.prototype, { fetch: { value: function() { var pool = this.pool; while (pool.length > 0) { var conn = pool.pop(); if (conn.connected) { if (conn.count === 0) { conn.clearTimeout(); conn.ref(); } return conn; } } return null; } }, init: { value: function(conn) { var self = this; conn.count = 0; conn.futures = {}; conn.contexts = {}; conn.timeoutIds = {}; setReceiveHandler(conn, function(data, id) { var future = conn.futures[id]; var context = conn.contexts[id]; if (future) { self.clean(conn, id); if (conn.count === 0) { self.recycle(conn); } if (!context.binary) { data = StringIO.utf8Decode(data); } future.resolve(data); } }); conn.onerror = function (e) { var futures = conn.futures; for (var id in futures) { var future = futures[id]; self.clean(conn, id); future.reject(e); } }; } }, recycle: { value: function(conn) { conn.unref(); conn.setTimeout(this.client.poolTimeout(), function() { conn.destroy(); }); } }, clean: { value: function(conn, id) { if (conn.timeoutIds[id] !== undefined) { global.clearTimeout(conn.timeoutIds[id]); delete conn.timeoutIds[id]; } delete conn.futures[id]; delete conn.contexts[id]; --conn.count; this.sendNext(conn); } }, sendNext: { value: function(conn) { if (conn.count < 10) { if (this.requests.length > 0) { var request = this.requests.pop(); request.push(conn); this.send.apply(this, request); } else { if (this.pool.lastIndexOf(conn) < 0) { this.pool.push(conn); } } } } }, send: { value: function(request, future, id, context, conn) { var self = this; var timeout = context.timeout; if (timeout > 0) { conn.timeoutIds[id] = global.setTimeout(function() { self.clean(conn, id); if (conn.count === 0) { self.recycle(conn); } future.reject(new TimeoutError('timeout')); }, timeout); } conn.count++; conn.futures[id] = future; conn.contexts[id] = context; var len = request.length; var buf = new StringIO(); buf.writeInt32BE(len | 0x80000000); buf.writeInt32BE(id); if (context.binary) { buf.write(request); } else { buf.writeUTF16AsUTF8(request); } conn.send(buf.take()).then(function() { self.sendNext(conn); }); } }, getNextId: { value: function() { return (this.nextid < 0x7fffffff) ? ++this.nextid : this.nextid = 0; } }, sendAndReceive: { value: function(request, future, context) { var conn = this.fetch(); var id = this.getNextId(); if (conn) { this.send(request, future, id, context, conn); } else if (this.size < this.client.maxPoolSize()) { conn = this.create(); conn.onerror = function(e) { future.reject(e); }; var self = this; conn.onconnect = function() { self.init(conn); self.send(request, future, id, context, conn); }; } else { this.requests.push([request, future, id, context]); } } } }); FullDuplexTcpTransporter.prototype.constructor = TcpTransporter; function HalfDuplexTcpTransporter(client) { TcpTransporter.call(this, client); } HalfDuplexTcpTransporter.prototype = createObject( TcpTransporter.prototype, { fetch: { value: function() { var pool = this.pool; while (pool.length > 0) { var conn = pool.pop(); if (conn.connected) { conn.clearTimeout(); conn.ref(); return conn; } } return null; } }, recycle: { value: function(conn) { if (this.pool.lastIndexOf(conn) < 0) { conn.unref(); conn.setTimeout(this.client.poolTimeout(), function() { conn.destroy(); }); this.pool.push(conn); } } }, clean: { value: function(conn) { conn.onreceive = noop; conn.onerror = noop; if (conn.timeoutId !== undefined) { global.clearTimeout(conn.timeoutId); delete conn.timeoutId; } } }, sendNext: { value: function(conn) { if (this.requests.length > 0) { var request = this.requests.pop(); request.push(conn); this.send.apply(this, request); } else { this.recycle(conn); } } }, send: { value: function(request, future, context, conn) { var self = this; var timeout = context.timeout; if (timeout > 0) { conn.timeoutId = global.setTimeout(function() { self.clean(conn); conn.destroy(); future.reject(new TimeoutError('timeout')); }, timeout); } setReceiveHandler(conn, function(data) { self.clean(conn); self.sendNext(conn); if (!context.binary) { data = StringIO.utf8Decode(data); } future.resolve(data); }); conn.onerror = function(e) { self.clean(conn); future.reject(e); }; var len = request.length; var buf = new StringIO(); buf.writeInt32BE(len); if (context.binary) { buf.write(request); } else { buf.writeUTF16AsUTF8(request); } conn.send(buf.take()); } }, sendAndReceive: { value: function(request, future, context) { var conn = this.fetch(); if (conn) { this.send(request, future, context, conn); } else if (this.size < this.client.maxPoolSize()) { conn = this.create(); var self = this; conn.onerror = function(e) { future.reject(e); }; conn.onconnect = function() { self.send(request, future, context, conn); }; } else { this.requests.push([request, future, context]); } } } }); HalfDuplexTcpTransporter.prototype.constructor = TcpTransporter; function TcpClient(uri, functions, settings) { if (this.constructor !== TcpClient) { return new TcpClient(uri, functions, settings); } Client.call(this, uri, functions, settings); var self = this; var _noDelay = true; var _fullDuplex = false; var _maxPoolSize = 10; var _poolTimeout = 30000; var fdtrans = null; var hdtrans = null; function getNoDelay() { return _noDelay; } function setNoDelay(value) { _noDelay = !!value; } function getFullDuplex() { return _fullDuplex; } function setFullDuplex(value) { _fullDuplex = !!value; } function getMaxPoolSize() { return _maxPoolSize; } function setMaxPoolSize(value) { if (typeof(value) === 'number') { _maxPoolSize = value | 0; if (_maxPoolSize < 1) { _maxPoolSize = 10; } } else { _maxPoolSize = 10; } } function getPoolTimeout() { return _poolTimeout; } function setPoolTimeout(value) { if (typeof(value) === 'number') { _poolTimeout = value | 0; } else { _poolTimeout = 0; } } function sendAndReceive(request, context) { var future = new Future(); if (_fullDuplex) { if ((fdtrans === null) || (fdtrans.uri !== self.uri)) { fdtrans = new FullDuplexTcpTransporter(self); } fdtrans.sendAndReceive(request, future, context); } else { if ((hdtrans === null) || (hdtrans.uri !== self.uri)) { hdtrans = new HalfDuplexTcpTransporter(self); } hdtrans.sendAndReceive(request, future, context); } if (context.oneway) { future.resolve(); } return future; } defineProperties(this, { noDelay: { get: getNoDelay, set: setNoDelay }, fullDuplex: { get: getFullDuplex, set: setFullDuplex }, maxPoolSize: { get: getMaxPoolSize, set: setMaxPoolSize }, poolTimeout: { get: getPoolTimeout, set: setPoolTimeout }, sendAndReceive: { value: sendAndReceive } }); } function checkuri(uri) { var parser = parseuri(uri); var protocol = parser.protocol; if (protocol === 'tcp:' || protocol === 'tcp4:'|| protocol === 'tcp6:' || protocol === 'tcps:' || protocol === 'tcp4s:' || protocol === 'tcp6s:' || protocol === 'tls:') { return; } throw new Error('This client desn\'t support ' + protocol + ' scheme.'); } function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { throw new Error('You should set server uri first!'); } return new TcpClient(uri, functions, settings); } defineProperties(TcpClient, { create: { value: create } }); global.HproseTcpClient = hprose.TcpClient = TcpClient; })(hprose, hprose.global); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * JSONRPCClientFilter.js * * * * jsonrpc client filter for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ /* global JSON */ (function (hprose) { 'use strict'; var Tags = hprose.Tags; var StringIO = hprose.StringIO; var Writer = hprose.Writer; var Reader = hprose.Reader; var s_id = 1; function JSONRPCClientFilter(version) { this.version = version || '2.0'; } JSONRPCClientFilter.prototype.inputFilter = function inputFilter(data/*, context*/) { if (data.charAt(0) === '{') { data = '[' + data + ']'; } var responses = JSON.parse(data); var stream = new StringIO(); var writer = new Writer(stream, true); for (var i = 0, n = responses.length; i < n; ++i) { var response = responses[i]; if (response.error) { stream.write(Tags.TagError); writer.writeString(response.error.message); } else { stream.write(Tags.TagResult); writer.serialize(response.result); } } stream.write(Tags.TagEnd); return stream.take(); }; JSONRPCClientFilter.prototype.outputFilter = function outputFilter(data/*, context*/) { var requests = []; var stream = new StringIO(data); var reader = new Reader(stream, false, false); var tag = stream.readChar(); do { var request = {}; if (tag === Tags.TagCall) { request.method = reader.readString(); tag = stream.readChar(); if (tag === Tags.TagList) { request.params = reader.readListWithoutTag(); tag = stream.readChar(); } if (tag === Tags.TagTrue) { tag = stream.readChar(); } } if (this.version === '1.1') { request.version = '1.1'; } else if (this.version === '2.0') { request.jsonrpc = '2.0'; } request.id = s_id++; requests.push(request); } while (tag === Tags.TagCall); if (requests.length > 1) { return JSON.stringify(requests); } return JSON.stringify(requests[0]); }; hprose.JSONRPCClientFilter = JSONRPCClientFilter; })(hprose); /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Loader.js * * * * hprose CommonJS/AMD/CMD loader for JavaScript. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ /* global define, module */ (function (hprose) { 'use strict'; hprose.common = { Completer: hprose.Completer, Future: hprose.Future, ResultMode: hprose.ResultMode }; hprose.io = { StringIO: hprose.StringIO, ClassManager: hprose.ClassManager, Tags: hprose.Tags, RawReader: hprose.RawReader, Reader: hprose.Reader, Writer: hprose.Writer, Formatter: hprose.Formatter }; hprose.client = { Client: hprose.Client, HttpClient: hprose.HttpClient, TcpClient: hprose.TcpClient, WebSocketClient: hprose.WebSocketClient }; hprose.filter = { JSONRPCClientFilter: hprose.JSONRPCClientFilter }; if (typeof define === 'function') { if (define.cmd) { define('hprose', [], hprose); } else if (define.amd) { define('hprose', [], function() { return hprose; }); } } if (typeof module === 'object') { module.exports = hprose; } })(hprose);
'use strict'; var MenuItem = require('../dist/Drawer/MenuItem') var Drawer = require('../dist/Drawer/Drawer') var Divider = require('../dist/Drawer/Divider') var DrawerDomain = require('../dist/Drawer/DrawerDomain') module.exports = { MenuItem: MenuItem.default, Drawer: Drawer.default, Divider: Divider.default, DrawerDomain: DrawerDomain.DrawerDomain, }
function Vlan() { this.priority = null; this.canonical_format = null; this.id = null; } // http://en.wikipedia.org/wiki/IEEE_802.1Q Vlan.prototype.decode = function (raw_packet, offset) { this.priority = (raw_packet[offset] & 0xE0) >> 5; this.canonical_format = (raw_packet[offset] & 0x10) >> 4; this.id = ((raw_packet[offset] & 0x0F) << 8) | raw_packet[offset + 1]; return this; }; Vlan.prototype.decoderName = "vlan"; Vlan.prototype.eventsOnDecode = false; Vlan.prototype.toString = function () { return this.priority + " " + this.canonical_format + " " + this.id; }; module.exports = Vlan;
import React from 'react' import { Link } from 'gatsby' import svgRightArrow from '../images/right-arrow.svg' export default class EternalArchives extends React.Component { state = { isOpen: false, } toggleOpen = () => { this.setState(prevState => ({ isOpen: !prevState.isOpen, })) } render() { return ( <div> <div style={{ display: 'flex', justifyContent: 'space-between', cursor: 'pointer', }} onClick={this.toggleOpen} > <h5> Eternal Archives <br /> <span>/1999-2003/</span> </h5> <img src={svgRightArrow} style={{ height: '30px', transition: '475ms', transform: `rotate(${this.state.isOpen ? 90 : 0}deg)`, }} alt="right arrow" /> </div> {this.state.isOpen && ( <ul className="sidenav"> <li> <em>Fan Fiction</em> </li> <li> <Link to="/eternal-archives/fiction/leaders-of-the-great-dark-beyond/"> Leaders of the Great Dark Beyond <span className="sidenav-info">/a Warcraft story/</span> </Link> </li> <li> <Link to="/eternal-archives/fiction/sargeras-tomb/"> Sargeras' tomb <span className="sidenav-info">/a Warcraft story/</span> </Link> </li> <li> <Link to="/eternal-archives/fiction/triumph-of-the-orcish-hordes/"> Triumph of the orcish hordes <span className="sidenav-info">/a Warcraft story/</span> </Link> </li> <li> <Link to="/eternal-archives/fiction/the-small-village-tavern/"> The small village tavern <span className="sidenav-info">/a Warcraft story/</span> </Link> </li> <li> <Link to="/eternal-archives/fiction/athene-d2-character-story/"> Athine Palade: <span className="sidenav-info">/Diablo 2 character story/</span> </Link> </li> <li> <Link to="/eternal-archives/fiction/log-of-gelus-life/"> Log of Gelu's life <span className="sidenav-info"> /a Heroes of Might and Magic story/ </span> </Link> </li> <li> <em>Media</em> </li> <li> <Link to="/eternal-archives/music/">Music</Link> </li> <li> <Link to="/eternal-archives/music-videos-and-mixtapes/"> Videos and Mixtapes </Link> </li> <li> <Link to="/eternal-archives/game-dev-videos/"> Game Dev Videos </Link> </li> <li> <em>Random</em> </li> <li> <Link to="/eternal-archives/starcraft-encyclopedia/"> StarCraft Encyclopedia </Link> </li> <li> <Link to="/eternal-archives/starcraft-screenshots/"> StarCraft Screenshots </Link> </li> <li> <Link to="/eternal-archives/diablo-unique-mobs/"> Diablo Unique Mobs </Link> </li> <li> <Link to="/eternal-archives/warcraft-units/">WarCraft Units</Link> </li> <li> <Link to="/eternal-archives/funny-win98-bugs/"> Funny Windows 98 bugs </Link> </li> <li> <Link to="/eternal-archives/batch-files/">Batch files</Link> </li> <li> <Link to="/eternal-archives/my-first-site-and-programs/"> My first site and programs </Link> </li> </ul> )} </div> ) } }
'use strict'; var chai = require( 'chai' ); var expect = chai.expect; chai.use( require( 'sinon-chai' ) ); var sinon = require( 'sinon' ); var sandbox = require( 'sandboxed-module' ); var WPRequest = require( '../../../lib/shared/wp-request' ); describe( 'WPRequest', function() { var request; beforeEach(function() { request = new WPRequest(); }); describe( 'constructor', function() { it( 'should create a WPRequest instance', function() { expect( request instanceof WPRequest ).to.be.true; }); it( 'should set any passed-in options', function() { request = new WPRequest({ booleanProp: true, strProp: 'Some string' }); expect( request._options.booleanProp ).to.be.true; expect( request._options.strProp ).to.equal( 'Some string' ); }); it( 'should define a _supportedMethods array', function() { var _supportedMethods = request._supportedMethods.sort().join( '|' ); expect( _supportedMethods ).to.equal( 'delete|get|head|post|put' ); expect( request._path ).to.deep.equal( {} ); expect( request._template ).to.equal( '' ); }); }); describe( '_checkMethodSupport', function() { it( 'should return true when called with a supported method', function() { expect( request._checkMethodSupport( 'get' ) ).to.equal( true ); }); it( 'should throw an error when called with an unsupported method', function() { request._supportedMethods = [ 'get' ]; expect(function() { return request._checkMethodSupport( 'post' ); }).to.throw(); }); }); // constructor describe( 'namespace', function() { it( 'is defined', function() { expect( request ).to.have.property( 'namespace' ); expect( request.namespace ).to.be.a( 'function' ); }); it( 'sets a value that is prepended to the path', function() { request.namespace( 'ns' ); expect( request._renderPath() ).to.equal( 'ns' ); }); it( 'prefixes any provided template', function() { request._template = 'template'; request.namespace( 'ns' ); expect( request._renderPath() ).to.equal( 'ns/template' ); }); it( 'can be removed (to use the legacy api v1) with an empty string', function() { request._template = 'template'; request.namespace( 'wp' ).namespace( '' ); expect( request._renderPath() ).to.equal( 'template' ); }); it( 'can be removed (to use the legacy api v1) by omitting arguments', function() { request._template = 'template'; request.namespace( 'wp' ).namespace(); expect( request._renderPath() ).to.equal( 'template' ); }); }); describe( 'version', function() { it( 'is defined', function() { expect( request ).to.have.property( 'version' ); expect( request.version ).to.be.a( 'function' ); }); it( 'sets a value that is prepended to the path', function() { request.version( 'v8' ); expect( request._renderPath() ).to.equal( 'v8' ); }); it( 'prefixes the provided template', function() { request._template = 'template'; request.version( 'v8' ); expect( request._renderPath() ).to.equal( 'v8/template' ); }); it( 'prefixes any provided namespace', function() { request._template = 'template'; request.namespace( 'ns' ); request.version( 'v8' ); expect( request._renderPath() ).to.equal( 'ns/v8/template' ); }); it( 'can be removed (to use the legacy api v1) with an empty string', function() { request._template = 'template'; request.version( 'v2' ).version( '' ); expect( request._renderPath() ).to.equal( 'template' ); }); it( 'can be removed (to use the legacy api v1) by omitting arguments', function() { request._template = 'template'; request.version( 'v2' ).version(); expect( request._renderPath() ).to.equal( 'template' ); }); }); describe( 'auth', function() { it( 'is defined', function() { expect( request ).to.have.property( 'auth' ); expect( request.auth ).to.be.a( 'function' ); }); it( 'sets the "auth" option to "true"', function() { expect( request._options ).not.to.have.property( 'auth' ); request.auth(); expect( request._options ).to.have.property( 'auth' ); expect( request._options.auth ).to.be.true; }); it( 'sets the username and password options, if provided', function() { expect( request._options ).not.to.have.property( 'username' ); expect( request._options ).not.to.have.property( 'password' ); request.auth( 'user', 'pass' ); expect( request._options ).to.have.property( 'username' ); expect( request._options ).to.have.property( 'password' ); expect( request._options.username ).to.equal( 'user' ); expect( request._options.password ).to.equal( 'pass' ); }); }); // auth describe( '._auth', function() { var mockAgent; beforeEach(function() { mockAgent = { auth: sinon.stub(), set: sinon.stub() }; }); it( 'should set a header on the request if a nonce is provided', function() { request._options = { nonce: 'testnonce' }; request._auth( mockAgent ); expect( mockAgent.set ).to.have.been.calledWith( 'X-WP-Nonce', 'testnonce' ); }); it( 'should set basic auth on the provided request if auth is forced', function() { request._options = { username: 'usr', password: 'pwd' }; request._auth( mockAgent, true ); expect( mockAgent.auth ).to.have.been.calledWith( 'usr', 'pwd' ); }); it( 'should set auth on the provided request if the "auth" option is true', function() { request._options = { username: 'usr', password: 'pwd', auth: true }; request._auth( mockAgent ); expect( mockAgent.auth ).to.have.been.calledWith( 'usr', 'pwd' ); }); it( 'should not set auth if username is not available', function() { request._options = { password: 'pwd' }; request._auth( mockAgent, true ); expect( mockAgent.auth ).not.to.have.been.called; }); it( 'should not set auth if password is not available', function() { request._options = { username: 'usr' }; request._auth( mockAgent, true ); expect( mockAgent.auth ).not.to.have.been.called; }); it( 'should not set auth if auth is not true, and not forced', function() { request._options = { username: 'usr', password: 'pwd' }; request._auth( mockAgent ); expect( mockAgent.auth ).not.to.have.been.called; }); }); // ._auth describe( 'request methods', function() { var MockAgent = require( '../../mocks/mock-superagent' ); var mockAgent; var SandboxedRequest; var wpRequest; beforeEach(function() { mockAgent = new MockAgent(); SandboxedRequest = sandbox.require( '../../../lib/shared/wp-request', { requires: { 'superagent': mockAgent } }); wpRequest = new SandboxedRequest({ endpoint: 'url/' }); }); describe( '.get()', function() { it( 'should trigger an HTTP GET request', function() { sinon.spy( mockAgent, 'get' ); sinon.stub( mockAgent, 'end' ); wpRequest.get(); expect( mockAgent.get ).to.have.been.calledOnce; expect( mockAgent.get ).to.have.been.calledWith( 'url/' ); expect( mockAgent.end ).to.have.been.calledOnce; }); it( 'should invoke a callback, if provided', function() { var spy = sinon.spy(); mockAgent._response = { body: 'data', headers: {} }; return wpRequest.get( spy ).then( function() { expect( spy ).to.have.been.calledOnce; expect( spy ).to.have.been.calledWith( null, 'data' ); }); }); it( 'should return a Promise to the request data', function() { mockAgent._response = { body: 'data', headers: {} }; var promise = wpRequest.get(); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function( data ) { expect( data ).to.equal( 'data' ); }); }); }); // .get() describe( '.then()', function() { it( 'should invoke GET and pass the results to the provided callback', function() { mockAgent._response = { body: 'data', headers: {} }; var get = sinon.spy( wpRequest, 'get' ); var success = sinon.stub(); var failure = sinon.stub(); var promise = wpRequest.then( success, failure ); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function() { expect( get ).to.have.been.calledWith(); expect( success ).to.have.been.calledWith( 'data' ); expect( failure ).not.to.have.been.called; }); }); it( 'should call the failure callback if GET fails', function() { mockAgent._err = 'Something went wrong'; var success = sinon.stub(); var failure = sinon.stub(); var promise = wpRequest.then( success, failure ); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function() { expect( failure ).to.have.been.calledWith( 'Something went wrong' ); expect( success ).not.to.have.been.called; }); }); }); // .then() describe( '.post()', function() { it( 'should trigger an HTTP POST request', function() { sinon.spy( mockAgent, 'post' ); sinon.spy( mockAgent, 'auth' ); sinon.spy( mockAgent, 'send' ); sinon.stub( mockAgent, 'end' ); wpRequest._options.username = 'user'; wpRequest._options.password = 'pass'; var data = { some: 'data' }; wpRequest.post( data ); expect( mockAgent.post ).to.have.been.calledOnce; expect( mockAgent.post ).to.have.been.calledWith( 'url/' ); expect( mockAgent.auth ).to.have.been.calledOnce; expect( mockAgent.auth ).to.have.been.calledWith( 'user', 'pass' ); expect( mockAgent.send ).to.have.been.calledOnce; expect( mockAgent.send ).to.have.been.calledWith( data ); }); it( 'should invoke a callback, if provided', function() { var spy = sinon.spy(); var data = { some: 'data' }; mockAgent._response = { body: 'some data', headers: {} }; return wpRequest.post( data, spy ).then( function() { expect( spy ).to.have.been.calledOnce; expect( spy ).to.have.been.calledWith( null, 'some data' ); }); }); it( 'should return a Promise to the request response', function() { mockAgent._response = { body: 'resp', headers: {} }; var data = { some: 'data' }; var promise = wpRequest.post( data ); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function( resp ) { expect( resp ).to.equal( 'resp' ); }); }); }); // .post() describe( '.put()', function() { it( 'should trigger an HTTP PUT request', function() { sinon.spy( mockAgent, 'put' ); sinon.spy( mockAgent, 'auth' ); sinon.spy( mockAgent, 'send' ); sinon.stub( mockAgent, 'end' ); wpRequest._options.username = 'user'; wpRequest._options.password = 'pass'; var data = { some: 'data' }; wpRequest.put( data ); expect( mockAgent.put ).to.have.been.calledOnce; expect( mockAgent.put ).to.have.been.calledWith( 'url/' ); expect( mockAgent.auth ).to.have.been.calledOnce; expect( mockAgent.auth ).to.have.been.calledWith( 'user', 'pass' ); expect( mockAgent.send ).to.have.been.calledOnce; expect( mockAgent.send ).to.have.been.calledWith( data ); }); it( 'should invoke a callback, if provided', function() { var spy = sinon.spy(); var data = { some: 'data' }; mockAgent._response = { body: 'some data', headers: {} }; return wpRequest.put( data, spy ).then( function() { expect( spy ).to.have.been.calledOnce; expect( spy ).to.have.been.calledWith( null, 'some data' ); }); }); it( 'should return a Promise to the request data', function() { mockAgent._response = { body: 'resp', headers: {} }; var data = { some: 'data' }; var promise = wpRequest.put( data ); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function( resp ) { expect( resp ).to.equal( 'resp' ); }); }); }); // .put() describe( '.delete()', function() { it( 'should trigger an HTTP DELETE request', function() { sinon.spy( mockAgent, 'del' ); sinon.spy( mockAgent, 'auth' ); sinon.stub( mockAgent, 'end' ); wpRequest._options.username = 'user'; wpRequest._options.password = 'pass'; wpRequest.delete(); expect( mockAgent.del ).to.have.been.calledOnce; expect( mockAgent.del ).to.have.been.calledWith( 'url/' ); expect( mockAgent.auth ).to.have.been.calledOnce; expect( mockAgent.auth ).to.have.been.calledWith( 'user', 'pass' ); }); it( 'should invoke a callback, if provided', function() { var spy = sinon.spy(); mockAgent._response = { body: 'some data', headers: {} }; return wpRequest.delete( spy ).then( function() { expect( spy ).to.have.been.calledOnce; expect( spy ).to.have.been.calledWith( null, 'some data' ); }); }); it( 'should return a Promise to the body of the request data', function() { mockAgent._response = { body: 'resp', headers: {} }; var promise = wpRequest.delete(); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function( resp ) { expect( resp ).to.equal( 'resp' ); }); }); }); // .delete() describe( '.head()', function() { it( 'should trigger an HTTP HEAD request', function() { sinon.spy( mockAgent, 'head' ); sinon.stub( mockAgent, 'end' ); wpRequest.head(); expect( mockAgent.head ).to.have.been.calledOnce; expect( mockAgent.head ).to.have.been.calledWith( 'url/' ); expect( mockAgent.end ).to.have.been.calledOnce; }); it( 'should invoke a callback, if provided', function() { var spy = sinon.spy(); mockAgent._response = { headers: 'some headers' }; return wpRequest.head( spy ).then(function() { expect( spy ).to.have.been.calledOnce; expect( spy ).to.have.been.calledWith( null, 'some headers' ); }); }); it( 'should return a Promise to the headers from the response', function() { mockAgent._response = { headers: 'resp' }; var promise = wpRequest.head(); expect( promise ).to.have.property( 'then' ); expect( promise.then ).to.be.a( 'function' ); return promise.then(function( resp ) { expect( resp ).to.equal( 'resp' ); }); }); }); // .head() describe( 'pagination', function() { beforeEach(function() { wpRequest = new SandboxedRequest({ endpoint: 'http://site.com/wp-json' }); }); it( 'passes data through unchanged if no headers are present', function() { mockAgent._response = { body: 'some object' }; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.equal( 'some object' ); expect( parsedResult ).not.to.have.property( '_paging' ); }); }); it( 'passes data through unchanged if header has no link property', function() { mockAgent._response = { headers: { 'x-wp-totalpages': '0', 'x-wp-total': '0' }, body: 'some object' }; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.equal( 'some object' ); expect( parsedResult ).not.to.have.property( '_paging' ); }); }); it( 'passes data through unchanged if pagination header is unset or empty', function() { mockAgent._response = { headers: { link: '' }, body: 'some object' }; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.equal( 'some object' ); expect( parsedResult ).not.to.have.property( '_paging' ); }); }); it( 'parses link headers', function() { mockAgent._response = { headers: { 'x-wp-totalpages': 4, 'x-wp-total': 7, link: [ '</wp-json/wp/v2/posts?page=1>; rel="prev",', '</wp-json/wp/v2/posts?page=2>; rel="next",', '<http://site.com/wp-json/wp/v2/posts/1024>; rel="item";', 'title="Article Title",', '<http://site.com/wp-json/wp/v2/posts/994>; rel="item";', 'title="Another Article"' ].join( ' ' ) }, body: {} }; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.have.property( '_paging' ); expect( parsedResult._paging ).to.have.property( 'links' ); expect( parsedResult._paging.links ).to.have.property( 'prev' ); var expectedPrevLink = '/wp-json/wp/v2/posts?page=1'; expect( parsedResult._paging.links.prev ).to.equal( expectedPrevLink ); expect( parsedResult._paging.links ).to.have.property( 'next' ); var expectedNextLink = '/wp-json/wp/v2/posts?page=2'; expect( parsedResult._paging.links.next ).to.equal( expectedNextLink ); }); }); describe( '.next object', function() { beforeEach(function() { mockAgent._response = { headers: { 'x-wp-totalpages': 4, 'x-wp-total': 7, link: '</wp-json/wp/v2/posts?page=3>; rel="next"' }, body: {} }; }); it( 'is generated if a "next" header is present', function() { return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.have.property( '_paging' ); expect( parsedResult._paging ).to.have.property( 'next' ); expect( parsedResult._paging.next ).to.be.an.instanceof( SandboxedRequest ); expect( parsedResult._paging.next._options.endpoint ).to.equal( 'http://site.com/wp-json/wp/v2/posts?page=3' ); }); }); it( 'is generated correctly for requests to explicit endpoints', function() { // Testing full URLs as endpoints validates that _paging.next.then works wpRequest._options.endpoint = 'http://site.com/wp-json/wp/v2/posts?page=3'; mockAgent._response.headers.link = '</wp-json/wp/v2/posts?page=4>; rel="next"'; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.have.property( '_paging' ); expect( parsedResult._paging ).to.have.property( 'next' ); expect( parsedResult._paging.next ).to.be.an.instanceof( SandboxedRequest ); expect( parsedResult._paging.next._options.endpoint ).to.equal( 'http://site.com/wp-json/wp/v2/posts?page=4' ); }); }); }); describe( '.prev object', function() { beforeEach(function() { mockAgent._response = { headers: { 'x-wp-totalpages': 4, 'x-wp-total': 7, link: '</wp-json/wp/v2/posts?page=2>; rel="prev"' }, body: {} }; }); it( 'is generated if a "prev" header is present', function() { return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.have.property( '_paging' ); expect( parsedResult._paging ).to.have.property( 'prev' ); expect( parsedResult._paging.prev ).to.be.an.instanceof( SandboxedRequest ); expect( parsedResult._paging.prev._options.endpoint ).to.equal( 'http://site.com/wp-json/wp/v2/posts?page=2' ); }); }); it( 'is generated correctly for requests to explicit endpoints', function() { // Testing full URLs as endpoints validates that _paging.prev.then works wpRequest._options.endpoint = 'http://site.com/wp-json/wp/v2/posts?page=2'; mockAgent._response.headers.link = '</wp-json/wp/v2/posts?page=1>; rel="prev"'; return wpRequest.then(function( parsedResult ) { expect( parsedResult ).to.have.property( '_paging' ); expect( parsedResult._paging ).to.have.property( 'prev' ); expect( parsedResult._paging.prev ).to.be.an.instanceof( SandboxedRequest ); expect( parsedResult._paging.prev._options.endpoint ).to.equal( 'http://site.com/wp-json/wp/v2/posts?page=1' ); }); }); }); }); // Pagination }); // Request methods });
export class Welcome{ constructor () { this.user = { name : 'test user' }; } }
var items = { "I002" : { "icon" : "<img class='icon' src='https://i.imgur.com/IDqn2R0.png' alt='I002' />", "name" : "빨간포션", "type" : "소모품", "effects" : ["HP를 75만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["파란달팽이", "빨간달팽이", "『Boss』마노", "슬라임"], "karta" : "Victoria", "chance" : ["6%", "7%", "30%", "5%"] }, "I00C" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZGcNJzK.png' alt='I00C' />", "name" : "하얀 반팔 면티", "type" : "장비", "stats" : { "reqlvl" : "5", "def" : "7" }, "mob" : ["파란달팽이", "빨간달팽이", "『Boss』마노"], "karta" : "Victoria", "chance" : ["4%", "4%", "30%"] }, "I003" : { "icon" : "<img class='icon' src='https://i.imgur.com/798CzVi.png' alt='I003' />", "name" : "파란포션", "type" : "소모품", "effects" : ["MP를 50만큼 회복시켜줍니다."], "mob" : ["파란달팽이", "빨간달팽이", "『Boss』마노", "슬라임"], "karta" : "Victoria", "chance" : ["4%", "5%", "30%", "5%"] }, "I0I8" : { "icon" : "<img class='icon' src='https://i.imgur.com/4Iijf5Z.png' alt='I0I8' />", "name" : "[불꽃늑대에게 이동]", "type" : "소모품", "effects" : ["불꽃늑대 격파시 모든플레이어 메이플+2000 흭득! [영웅이 클릭시 이동됩니다.]", "불꽃늑대에게 강제이동을 당한 플레이어에게 메이플+200 보너스를 받습니다."], "mob" : ["파란달팽이", "빨간달팽이", "슬라임", "주황버섯", "리본 돼지", "스티지", "[정예]드레이크", "화이트 팽", "주니어 예티", "페페", "[정예]예티와페페", "[정예]타우로마시스", "[정예]웨어울프", "파이렛", "『정예』타나토스", "『정예』게이트 키퍼", "[정예]바이킹", "본 피쉬", "[정예]샤크", "『정예』불독", "켄타우로스", "블러드 하프", "『정예』다크 코니언", "『정예』레드 와이번"], "karta" : "Victoria", "chance" : ["1.3%", "1.3%", "1.3%", "1.3%", "1.3%", "1.3%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "3%", "3%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%", "1.5%"] }, "I00D" : { "icon" : "<img class='icon' src='https://i.imgur.com/P5Z1U7f.png' alt='I00D' />", "name" : "흰색 고무신", "type" : "장비", "stats" : { "reqlvl" : "5", "def" : "2", "mvspd" : "30" }, "mob" : "빨간달팽이", "karta" : "Victoria", "chance" : "4%" }, "I00E" : { "icon" : "<img class='icon' src='https://i.imgur.com/SDWgDk4.png' alt='I00E' />", "name" : "노가다 목장갑", "type" : "장비", "stats" : { "reqlvl" : "5", "def" : "2", "atkspd" : "4" }, "mob" : "빨간달팽이", "karta" : "Victoria", "chance" : "4%" }, "I0EQ" : { "icon" : "<img class='icon' src='https://i.imgur.com/Iy9hlwN.png' alt='I0EQ' />", "name" : "[치장]산소통", "type" : "치장", "effects" : ["[강화 불가 아이템]"], "stats" : { "misc" : "치장 인벤토리에 장착해주세요.", "hp" : "40000", "mvspd" : "50" }, "mob" : ["『Boss』마노", "『Boss』아이언 호그", "[정예]드레이크", "본 피쉬", "[엘리트]줄라이", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.2%", "1.5%", "1.1%", "1.2%", "2%", "1.5%", "2%"] }, "I00F" : { "icon" : "<img class='icon' src='https://i.imgur.com/c5nqsIs.png' alt='I00F' />", "name" : "추 귀걸이", "type" : "장신구", "stats" : { "reqlvl" : "5", "str" : "4", "dex" : "1", "int" : "2", "hp" : "40", "mp" : "40" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I008" : { "icon" : "<img class='icon' src='https://i.imgur.com/X5jyw4I.png' alt='I008' />", "name" : "가니어", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "12", "dex" : "6", "mp" : "30" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I00A" : { "icon" : "<img class='icon' src='https://i.imgur.com/YaSQtK1.png' alt='I00A' />", "name" : "고목 스태프", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "7", "int" : "6", "mp" : "90" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I007" : { "icon" : "<img class='icon' src='https://i.imgur.com/DEkyMFZ.png' alt='I007' />", "name" : "목검", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "4", "str" : "5", "hp" : "200" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I0BL" : { "icon" : "<img class='icon' src='https://i.imgur.com/nVuTDoc.png' alt='I0BL' />", "name" : "후루츠 대거", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "10", "atkspd" : "2", "dex" : "2", "hp" : "80" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I00B" : { "icon" : "<img class='icon' src='https://i.imgur.com/Xm98QKc.png' alt='I00B' />", "name" : "우드 완드", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "2", "int" : "3", "mp" : "200" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I004" : { "icon" : "<img class='icon' src='https://i.imgur.com/STeHZH8.png' alt='I004' />", "name" : "장창", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "10", "str" : "3", "hp" : "80" }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I00Y" : { "icon" : "<img class='icon' src='https://i.imgur.com/cCRIgPO.png' alt='I00Y' />", "name" : "호신부적", "type" : "기타", "effects" : "이 아이템을 지닌 영웅이 전사하면 자동으로 부활합니다.", "mob" : ["『Boss』마노", "『Boss』머쉬맘", "『Boss』아이언 호그", "『RAID』킹슬라임", "『Boss』좀비머쉬맘"], "karta" : "Victoria", "chance" : ["15%", "15%", "15%", "10%", "10%"] }, "I0G6" : { "icon" : "<img class='icon' src='https://i.imgur.com/nEQ8eOE.png' alt='I0G6' />", "name" : "워 보우", "type" : "무기", "stats" : { "reqlvl" : "1", "atk" : "20", "hp" : "25", "dex" : "3", "crit" : "5%*3", }, "mob" : "『Boss』마노", "karta" : "Victoria", "chance" : "15%" }, "I03U" : { "icon" : "<img class='icon' src='https://i.imgur.com/sTXdpsy.png' alt='I03U' />", "name" : "엘릭서", "type" : "소모품", "effects" : ["HP/MP를 5000만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『Boss』마노", "『Boss』머쉬맘", "『Boss』아이언 호그", "『RAID』킹슬라임", "『Boss』좀비머쉬맘", "[정예]드레이크", "『Boss』얼음마녀", "[정예]예티와페페", "『Boss』스노우맨", "[정예]타우로마시스", "『Boss』주니어 발록", "[정예]웨어울프"], "karta" : "Victoria", "chance" : ["30%", "40%", "50%", "3x 100%", "100%", "100%", "3x 100%", "100%", "3x 100%", "2x 100%", "5x 100%", "50%"] }, "I009" : { "icon" : "<img class='icon' src='https://i.imgur.com/vK1ig3O.png' alt='I009' />", "name" : "수비 표창", "type" : "무기", "stats" : { "reqlvl" : "5", "atkspd" : "10", "dex" : "2" }, "mob" : "슬라임", "karta" : "Victoria", "chance" : "3%" }, "I00G" : { "icon" : "<img class='icon' src='https://i.imgur.com/BvJH2m4.png' alt='I00G' />", "name" : "냄비뚜껑", "type" : "장비", "stats" : { "reqlvl" : "20", "def" : "10", "hp" : "500", "mp" : "300", "mpreg" : "10%" }, "mob" : "초록버섯", "karta" : "Victoria", "chance" : "2%" }, "I00M" : { "icon" : "<img class='icon' src='https://i.imgur.com/PT3RiJ6.png' alt='I00M' />", "name" : "주홍포션", "type" : "소모품", "effects" : ["HP를 200만큼 회복시켜줍니다.","[창고로 사용가능]"], "mob" : ["초록버섯", "주황버섯", "리본 돼지"], "karta" : "Victoria", "chance" : ["5%", "5%", "5%"] }, "I00N" : { "icon" : "<img class='icon' src='https://i.imgur.com/hU3nc9E.png' alt='I00N' />", "name" : "마나 엘릭서", "type" : "소모품", "effects" : ["MP를 300만큼 회복시켜줍니다.","[창고로 사용가능]"], "mob" : ["초록버섯", "주황버섯", "리본 돼지"], "karta" : "Victoria", "chance" : ["5%", "5%", "5%"] }, "I00H" : { "icon" : "<img class='icon' src='https://i.imgur.com/CIStMkV.png' alt='I00H' />", "name" : "메바", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "30", "mp" : "200", "dex" : "17" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I0BM" : { "icon" : "<img class='icon' src='https://i.imgur.com/g2ohc3E.png' alt='I0BM' />", "name" : "필드 대거", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "50", "hp" : "200", "dex" : "6", "atkspd" : "3" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00J" : { "icon" : "<img class='icon' src='https://i.imgur.com/dKKXeP1.png' alt='I00J' />", "name" : "미스릴 완드", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "10", "mp" : "700", "int" : "10" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00K" : { "icon" : "<img class='icon' src='https://i.imgur.com/2carhGb.png' alt='I00K' />", "name" : "양손검", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "15", "hp" : "1000", "str" : "12" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I0G7" : { "icon" : "<img class='icon' src='https://i.imgur.com/Tdfn06r.png' alt='I0G7' />", "name" : "배틀 보우", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "50", "hp" : "100", "dex" : "6", "crit" : "5%*3.5" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00I" : { "icon" : "<img class='icon' src='https://i.imgur.com/Z62nJNy.png' alt='I00I' />", "name" : "위저드 스태프", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "25", "mp" : "250", "int" : "15" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00L" : { "icon" : "<img class='icon' src='https://i.imgur.com/BULPksW.png' alt='I00L' />", "name" : "포크창", "type" : "무기", "stats" : { "reqlvl" : "25", "atk" : "50", "hp" : "200", "str" : "5" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00O" : { "icon" : "<img class='icon' src='https://i.imgur.com/l2G8ip1.png' alt='I00O' />", "name" : "월비 표창", "type" : "무기", "stats" : { "reqlvl" : "25", "atkspd" : "15", "dex" : "10" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I00P" : { "icon" : "<img class='icon' src='https://i.imgur.com/auxW71Y.png' alt='I00P' />", "name" : "번개 귀걸이", "type" : "장신구", "stats" : { "reqlvl" : "20", "str" : "8", "dex" : "6", "int" : "6", "hp" : "300", "mp" : "300" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "15%" }, "I0ER" : { "icon" : "<img class='icon' src='https://i.imgur.com/vboLO31.png' alt='I0ER' />", "name" : "[치장]그녀의망토", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "mp" : "40000", "mvspd" : "50" }, "mob" : ["『Boss』머쉬맘", "[정예]드레이크", "[정예]바이킹", "[엘리트]줄라이", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.3%", "1.1%", "1.3%", "2%", "1.5%", "2%"] }, "I015" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I015' />", "name" : "[메달]머쉬맘 슬레이어", "type" : "메달", "effects" : ["[보조 인벤토리에 장착해주세요.]"], "stats" : { "str" : "10", "dex" : "10", "int" : "10" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "4%" }, "I01S" : { "icon" : "<img class='icon' src='https://i.imgur.com/wZHZCZe.png' alt='I01S' />", "name" : "머쉬킹의 레더 글로브", "type" : "장비", "effects" : ["[보조 인벤토리에 장착해주세요.]"], "stats" : { "reqlvl" : "30", "def" : "5", "atkspd" : "8", "crit" : "10%*2" }, "mob" : "『Boss』머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I00Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/c6BMIUc.png' alt='I00Q' />", "name" : "우드 버클러", "type" : "장비", "stats" : { "reqlvl" : "25", "def" : "15", "hp" : "800", "hpreg" : "[초당]3" }, "mob" : "주황버섯", "karta" : "Victoria", "chance" : "2%" }, "I00R" : { "icon" : "<img class='icon' src='https://i.imgur.com/HGuHSgV.png' alt='I00R' />", "name" : "흰색 검도복", "type" : "장비", "stats" : { "reqlvl" : "25", "def" : "18" }, "mob" : "주황버섯", "karta" : "Victoria", "chance" : "2%" }, "I01C" : { "icon" : "<img class='icon' src='https://i.imgur.com/Z4kyAkL.png' alt='I01C' />", "name" : "파란색 캔버스화", "type" : "장비", "stats" : { "reqlvl" : "38", "def" : "7", "mvspd" : "50" }, "mob" : "리본 돼지", "karta" : "Victoria", "chance" : "2%" }, "I01D" : { "icon" : "<img class='icon' src='https://i.imgur.com/B1gTADK.png' alt='I01D' />", "name" : "흑룡포", "type" : "장비", "stats" : { "reqlvl" : "40", "def" : "23" }, "mob" : "리본 돼지", "karta" : "Victoria", "chance" : "2%" }, "I016" : { "icon" : "<img class='icon' src='https://i.imgur.com/EDTPAOm.png' alt='I016' />", "name" : "다크 가디언", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "60", "mp" : "500", "dex" : "30" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I0BN" : { "icon" : "<img class='icon' src='https://i.imgur.com/nefuDuy.png' alt='I0BN' />", "name" : "삼각 자마다르", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "80", "hp" : "500", "dex" : "10", "atkspd" : "4" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I01Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/Jq8bmot.png' alt='I01Q' />", "name" : "돼지머리띠", "type" : "장비", "stats" : { "reqlvl" : "40", "def" : "10", "hp" : "1300" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I019" : { "icon" : "<img class='icon' src='https://i.imgur.com/RI5rDTo.png' alt='I019' />", "name" : "삼지창", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "80", "hp" : "500", "str" : "9" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I0G8" : { "icon" : "<img class='icon' src='https://i.imgur.com/CO2XrDu.png' alt='I0G8' />", "name" : "라이덴", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "80", "hp" : "200", "dex" : "10", "crit" : "5%*4" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I018" : { "icon" : "<img class='icon' src='https://i.imgur.com/PD3WKT2.png' alt='I018' />", "name" : "왕푸", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "28", "hp" : "1700", "str" : "16", "hpreg" : "5" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I017" : { "icon" : "<img class='icon' src='https://i.imgur.com/TpCjZFz.png' alt='I017' />", "name" : "위저드 완드", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "24", "mp" : "1200", "int" : "18" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I01A" : { "icon" : "<img class='icon' src='https://i.imgur.com/NrBIFgN.png' alt='I01A' />", "name" : "페탈 스태프", "type" : "무기", "stats" : { "reqlvl" : "40", "atk" : "38", "mp" : "400", "int" : "30" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I01B" : { "icon" : "<img class='icon' src='https://i.imgur.com/XgpllQe.png' alt='I01B' />", "name" : "블루 문", "type" : "장신구", "stats" : { "reqlvl" : "45", "str" : "14", "dex" : "14", "int" : "16", "hp" : "700", "mp" : "700" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "15%" }, "I01W" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZCL96yz.png' alt='I01W' />", "name" : "하얀포션", "type" : "소모품", "effects" : ["HP를 500만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『Boss』아이언 호그", "스티지", "좀비버섯", "콜드아이"], "karta" : "Victoria", "chance" : ["100%", "4%", "10%", "10%"] }, "I01X" : { "icon" : "<img class='icon' src='https://i.imgur.com/qhnJtUS.png' alt='I01X' />", "name" : "맑은물", "type" : "소모품", "effects" : ["MP를 800만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『Boss』아이언 호그", "스티지", "콜드아이", "좀비버섯"], "karta" : "Victoria", "chance" : ["100%", "4%", "10%", "10%"] }, "I02G" : { "icon" : "<img class='icon' src='https://i.imgur.com/FGMhpyC.png' alt='I02G' />", "name" : "Lv + 5", "type" : "소모품", "effects" : ["사용시 영웅 LV+5가 됩니다.", "[창고로 사용해도 영웅 LV.5가 증가됩니다.]", "경고:LV.6000이 되는 분들은 사용하지 말아주세요."], "mob" : ["『Boss』아이언 호그", "『RAID』킹슬라임", "『Boss』좀비머쉬맘", "『Boss』얼음마녀", "『Boss』스노우맨", "『Boss』주니어 발록", "『Boss』라이칸스로프"], "karta" : "Victoria", "chance" : ["4%", "10%", "4%", "5% & 5%", "5% & 5%", "5%", "5%"] }, "I01E" : { "icon" : "<img class='icon' src='https://i.imgur.com/SkMmGr4.png' alt='I01E' />", "name" : "[메달]히든 스트리트 정복자", "type" : "메달", "effects" : ["[보조 인벤토리에 장착해주세요.]"], "stats" : { "str" : "12", "dex" : "12", "int" : "12" }, "mob" : "『Boss』아이언 호그", "karta" : "Victoria", "chance" : "4%" }, "I00Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/mzjLTKB.png' alt='I00Z' />", "name" : "『킹슬라임 방울』", "type" : "기타", "effects" : ["퀘스트 아이템[세이브 불가 아이템]-헬로토에게 가십시오."], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "3x 100%" }, "I00U" : { "icon" : "<img class='icon' src='https://i.imgur.com/mzjLTKB.png' alt='I00U' />", "name" : "『슬라임 방울』", "type" : "기타", "mob" : ["『RAID』킹슬라임", "[파퀘]슬라임"], "karta" : "Victoria", "chance" : ["5x 100%", "100%"] }, "I01F" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I01F' />", "name" : "- 1차승급 - 전직서[스피어맨]", "type" : "기타", "effects" : ["전직서:스피어맨 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I0BK" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I0BK' />", "name" : "- 1차승급 - 전직서[시프]", "type" : "기타", "effects" : ["전직서:시프 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I001" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I001' />", "name" : "- 1차승급 - 전직서[어쌔신]", "type" : "기타", "effects" : ["전직서:어쌔신 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I01G" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I01G' />", "name" : "- 1차승급 - 전직서[위자드]", "type" : "기타", "effects" : ["전직서:위자드 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I01I" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I01I' />", "name" : "- 1차승급 - 전직서[클레릭]", "type" : "기타", "effects" : ["전직서:클레릭 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I01H" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I01H' />", "name" : "- 1차승급 - 전직서[페이지]", "type" : "기타", "effects" : ["전직서:페이지 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I0G3" : { "icon" : "<img class='icon' src='https://i.imgur.com/atgwC8V.png' alt='I0G3' />", "name" : "- 1차승급 - 전직서[헌터]", "type" : "기타", "effects" : ["전직서:헌터 전직의성소 나무에게 가세요. -세이브 불가아이템-"], "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "100%" }, "I01Y" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I01Y' />", "name" : "[메달]킹슬라임 슬레이어", "type" : "메달", "effects" : ["[보조 인벤토리에 장착해주세요.]"], "stats" : { "str" : "17", "dex" : "17", "int" : "17", "atk" : "50" }, "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "3%" }, "I00S" : { "icon" : "<img class='icon' src='https://i.imgur.com/q0YaG3T.png' alt='I00S' />", "name" : "파란색 가운", "type" : "장비", "stats" : { "reqlvl" : "30", "def" : "25", "str" : "13", "dex" : "13", "int" : "13" }, "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "15%" }, "I00W" : { "icon" : "<img class='icon' src='https://i.imgur.com/l2AQ1IP.png' alt='I00W' />", "name" : "허름한 망토", "type" : "장비", "stats" : { "reqlvl" : "25", "eva" : "10%", "hpreg" : "[초당]8", "mpreg" : "[초당]15%" }, "mob" : "『RAID』킹슬라임", "karta" : "Victoria", "chance" : "15%" }, "I00X" : { "icon" : "<img class='icon' src='https://i.imgur.com/Ckcjaa8.png' alt='I00X' />", "name" : "[치장]요정의날개", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "자신 이동속도 +50"], "mob" : ["『RAID』킹슬라임", "『Boss』"], "karta" : "Victoria", "chance" : ["1.5%", "2%"] }, "I03V" : { "icon" : "<img class='icon' src='https://i.imgur.com/93A9Rqz.png' alt='I03V' />", "name" : "파워엘릭서", "type" : "소모품", "effects" : ["HP/MP를 10000만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『RAID』킹슬라임", "『Boss』좀비머쉬맘", "[정예]드레이크", "『Boss』얼음마녀", "[정예]예티와페페", "『Boss』스노우맨", "[정예]타우로마시스", "『Boss』주니어 발록", "[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』크림슨 발록", "[정예]바이킹", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["100%", "50%", "30%", "2x 100%", "100%", "3x 100%", "100%", "5x 100%", "100%", "3x 100%", "5x 100%", "100% & 50%", "5x 100%"] }, "I010" : { "icon" : "<img class='icon' src='https://i.imgur.com/pqxcxwk.png' alt='I010' />", "name" : "『통행증』", "type" : "기타", "effects" : ["다음지역으로 이동하세요.[한분만 있으시면 됩니다.]"], "mob" : "[파퀘]네키", "karta" : "Victoria", "chance" : "15%" }, "I01O" : { "icon" : "<img class='icon' src='https://i.imgur.com/0nbOWbC.png' alt='I01O' />", "name" : "목비 표창", "type" : "무기", "stats" : { "reqlvl" : "50", "atkspd" : "20", "dex" : "25" }, "mob" : ["[파퀘]스티지", "스티지"], "karta" : "Victoria", "chance" : ["10%", "1.5%"] }, "I01U" : { "icon" : "<img class='icon' src='https://i.imgur.com/UGvFIq9.png' alt='I01U' />", "name" : "화이트 크로스 체인메일", "type" : "장비", "stats" : { "reqlvl" : "70", "def" : "35", "hpreg" : "5" }, "mob" : "스티지", "karta" : "Victoria", "chance" : "1.5%" }, "I01R" : { "icon" : "<img class='icon' src='https://i.imgur.com/VbFDbwR.png' alt='I01R' />", "name" : "흰색 모험가의 망토", "type" : "장비", "stats" : { "reqlvl" : "60", "eva" : "15%", "hpreg" : "[초당]20", "mpreg" : "[초당]20%" }, "mob" : "좀비버섯", "karta" : "Victoria", "chance" : "1.5%" }, "I027" : { "icon" : "<img class='icon' src='https://i.imgur.com/9tTMYjz.png' alt='I027' />", "name" : "토비 표창", "type" : "무기", "stats" : { "atkspd" : "30", "dex" : "15%", "dex" : "90", "atk" : "110", "mp" : "1100" }, "mob" : ["콜드아이", "[정예]드레이크"], "karta" : "Victoria", "chance" : ["0.9%", "1.5%"] }, "I02R" : { "icon" : "<img class='icon' src='https://i.imgur.com/S9JVFEU.png' alt='I02R' />", "name" : "본 헬름", "type" : "장비", "stats" : { "atkspd" : "105", "def" : "28", "hp" : "3800", "mp" : "3800", "mvspd" : "40" }, "mob" : ["콜드아이", "화이트 팽"], "karta" : "Victoria", "chance" : ["1.1%", "1.5%"] }, "I0EP" : { "icon" : "<img class='icon' src='https://i.imgur.com/yNB3Vwu.png' alt='I0EP' />", "name" : "[치장]월묘꼬리", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "str" : "150", "dex" : "150", "int" : "150", "mvspd" : "70" }, "mob" : ["콜드아이", "『Boss』좀비머쉬맘", "[정예]예티와페페", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["0.8%", "1.4%", "1.2%", "1.5%", "2%"] }, "I01P" : { "icon" : "<img class='icon' src='https://i.imgur.com/oxLvCwO.png' alt='I01P' />", "name" : "금비 표창", "type" : "장신구?", "stats" : { "atkspd" : "25", "dex" : "50" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "5%" }, "I01K" : { "icon" : "<img class='icon' src='https://i.imgur.com/kdaylUu.png' alt='I01K' />", "name" : "나카마키", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "220", "hp" : "2500", "str" : "20", "crit" : "20%*2+2000" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I01J" : { "icon" : "<img class='icon' src='https://i.imgur.com/OpsWj26.png' alt='I01J' />", "name" : "다크 보닌", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "120", "mp" : "1500", "hp" : "500", "dex" : "70" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I01N" : { "icon" : "<img class='icon' src='https://i.imgur.com/nPKlgjk.png' alt='I01N' />", "name" : "아크 스태프", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "90", "mp" : "1000", "hp" : "300", "int" : "95" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I0BO" : { "icon" : "<img class='icon' src='https://i.imgur.com/9zh4D7Y.png' alt='I0BO' />", "name" : "차", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "220", "hp" : "2500", "dex" : "17", "atkspd" : "5" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I0G9" : { "icon" : "<img class='icon' src='https://i.imgur.com/koPZlD3.png' alt='I0G9' />", "name" : "메이플 헌터스", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "220", "hp" : "500", "dex" : "30", "crit" : "5%*5" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I01M" : { "icon" : "<img class='icon' src='https://i.imgur.com/hA1ICCz.png' alt='I01M' />", "name" : "쟈드", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "80", "hp" : "2500", "str" : "60", "hpreg" : "15" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I01L" : { "icon" : "<img class='icon' src='https://i.imgur.com/NOFV2MW.png' alt='I01L' />", "name" : "크리스탈 완드", "type" : "무기", "stats" : { "reqlvl" : "90", "atk" : "50", "mp" : "4000", "int" : "30", "mpreg" : "10%" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "10%" }, "I01Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I01Z' />", "name" : "[메달]좀비머쉬맘 슬레이어", "type" : "메달", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "str" : "20", "dex" : "20", "int" : "20" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "2%" }, "I01V" : { "icon" : "<img class='icon' src='https://i.imgur.com/GnrY7yT.png' alt='I01V' />", "name" : "[치장]엔젤릭 블레스", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "자신[순수]공격력비례 공격력:+15%"], "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "1.5%" }, "I01T" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZdBgo5E.png' alt='I01T' />", "name" : "메탈 하트 귀걸이", "type" : "장신구", "stats" : { "reqlvl" : "80", "str" : "20", "dex" : "20", "int" : "20", "hp" : "1400", "mp" : "1400" }, "mob" : "『Boss』좀비머쉬맘", "karta" : "Victoria", "chance" : "5%" }, "I025" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I025' />", "name" : "메소 더미", "type" : "기타", "effects" : "메소 + 4000", "mob" : ["[정예]드레이크", "『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["30%", "5x 100%"] }, "I026" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I026' />", "name" : "메이플", "type" : "기타", "effects" : "메이플 + 1", "mob" : ["[정예]드레이크", "『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["15% & 15%", "x3 100%"] }, "I027" : { "icon" : "<img class='icon' src='https://i.imgur.com/rf5FyZV.png' alt='I027' />", "name" : "토비 표창", "type" : "무기", "stats" : { "reqlvl" : "200", "atkspd" : "30", "dex" : "90", "atk" : "110", "mp" : "1100" }, "mob" : ["[정예]드레이크"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I02D" : { "icon" : "<img class='icon' src='https://i.imgur.com/pP4cOo2.png' alt='I02D' />", "name" : "미스틱 실드", "type" : "장신구", "stats" : { "reqlvl" : "200", "mdef" : "17%", "hp" : "3000", "mp" : "3000", "mpreg" : "25%" }, "mob" : ["[정예]드레이크"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I02F" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZoIZjyr.png' alt='I02F' />", "name" : "다크아나카룬", "type" : "장비", "stats" : { "reqlvl" : "140", "def" : "30", "int" : "50", "mp" : "4800" }, "mob" : ["[정예]드레이크"], "karta" : "Victoria", "chance" : ["2%"] }, "I02E" : { "icon" : "<img class='icon' src='https://i.imgur.com/OgLL7rF.png' alt='I02E' />", "name" : "오리엔타이칸", "type" : "장비", "stats" : { "reqlvl" : "140", "def" : "54", "str" : "38", "hpreg" : "15", "hp" : "4500" }, "mob" : ["[정예]드레이크"], "karta" : "Victoria", "chance" : ["2%"] }, "I02B" : { "icon" : "<img class='icon' src='https://i.imgur.com/1R4n4K9.png' alt='I02B' />", "name" : "『드레이크 머리뼈』", "type" : "장비", "effects" : "조합아이템", "mob" : ["[정예]드레이크"], "karta" : "Victoria", "chance" : ["15%"] }, "I02K" : { "icon" : "<img class='icon' src='https://i.imgur.com/o7rjVu0.png' alt='I02K' />", "name" : "[치장]함박눈", "type" : "치장", "effects" : "[치장 인벤토리에 장착해주세요.]", "stats" : { "def" : "100" }, "mob" : ["『Boss』얼음마녀", "『Boss』스노우맨", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["1.5%", "1.5%", "2%"] }, "I02P" : { "icon" : "<img class='icon' src='https://i.imgur.com/6KolGaW.png' alt='I02P' />", "name" : "다크 슬레인", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "340", "mp" : "3000", "hp" : "1500", "dex" : "110" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I0BP" : { "icon" : "<img class='icon' src='https://i.imgur.com/kx15w4t.png' alt='I0BP' />", "name" : "태극부채", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "540", "hp" : "8000", "dex" : "50", "atkspd" : "6" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I02L" : { "icon" : "<img class='icon' src='https://i.imgur.com/N6BHh16.png' alt='I02L' />", "name" : "쏜즈 스태프", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "150", "mp" : "4000", "hp" : "1000", "int" : "120" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I0GA" : { "icon" : "<img class='icon' src='https://i.imgur.com/5aiGlHK.png' alt='I0GA' />", "name" : "발터2000", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "340", "crit" : "5%*6", "hp" : "1700", "dex" : "110" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I02O" : { "icon" : "<img class='icon' src='https://i.imgur.com/1U1raDe.png' alt='I02O' />", "name" : "아쿠아 스노우보드", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "540", "crit" : "20%확률로 3배 추뎀+3000", "hp" : "8000", "str" : "55" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I02N" : { "icon" : "<img class='icon' src='https://i.imgur.com/kk9OhaJ.png' alt='I02N' />", "name" : "크로미", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "80", "mp" : "8000", "int" : "60", "mpreg" : "20%" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I02M" : { "icon" : "<img class='icon' src='https://i.imgur.com/hVGOe57.png' alt='I02M' />", "name" : "호검", "type" : "무기", "stats" : { "reqlvl" : "150", "atk" : "170", "mp" : "6000", "str" : "120", "hpreg" : "30" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["10%"] }, "I02T" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I02T' />", "name" : "[메달]얼음마녀 슬레이어", "type" : "메달", "stats" : { "str" : "35", "dex" : "35", "int" : "35" }, "mob" : ["『Boss』얼음마녀"], "karta" : "Victoria", "chance" : ["4%"] }, "I0EO" : { "icon" : "<img class='icon' src='https://i.imgur.com/yTzJtl7.png' alt='I0EO' />", "name" : "[치장]가죽핸드백", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "int" : "400", "hp" : "30000" }, "mob" : ["『Boss』얼음마녀", "[엘리트]모카딘", "[엘리트]싸움꾼 플레트", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["1.3%", "2%", "1.5%", "3%"] }, "I02Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/puDjoAB.png' alt='I02Q' />", "name" : "장미꽃 귀걸이", "type" : "장신구", "stats" : { "reqlvl" : "130", "str" : "40", "dex" : "40", "int" : "40", "hp" : "3000", "mp" : "2000" }, "mob" : ["『Boss』얼음마녀", "『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["3%", "5%"] }, "I02S" : { "icon" : "<img class='icon' src='https://i.imgur.com/tcclUmg.png' alt='I02S' />", "name" : "흰색 가이야의 망토", "type" : "장비", "stats" : { "reqlvl" : "110", "eva" : "18%", "hpreg" : "[초당]50", "mpreg" : "[초당]23%" }, "mob" : ["주니어 예티"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I037" : { "icon" : "<img class='icon' src='https://i.imgur.com/SckJ0qs.png' alt='I037' />", "name" : "이카루스 망토", "type" : "장비", "stats" : { "reqlvl" : "240", "eva" : "20%", "hpreg" : "[초당]60", "mpreg" : "[초당]25%" }, "mob" : ["페페"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I02U" : { "icon" : "<img class='icon' src='https://i.imgur.com/3MEtKyA.png' alt='I02U' />", "name" : "다크 레퀴엠", "type" : "장비", "stats" : { "reqlvl" : "220", "def" : "65", "int" : "130", "mp" : "2500", "hp" : "5000" }, "mob" : ["[정예]예티와페페"], "karta" : "Victoria", "chance" : ["2%"] }, "I02W" : { "icon" : "<img class='icon' src='https://i.imgur.com/OPOstqe.png' alt='I02W' />", "name" : "다크 스콜피오", "type" : "장비", "stats" : { "reqlvl" : "220", "def" : "68", "dex" : "120", "mp" : "2000", "hp" : "7000" }, "mob" : ["[정예]예티와페페"], "karta" : "Victoria", "chance" : ["2%"] }, "I02V" : { "icon" : "<img class='icon' src='https://i.imgur.com/8GAPxyH.png' alt='I02V' />", "name" : "오리할콘 플라틴", "type" : "장비", "stats" : { "reqlvl" : "220", "def" : "80", "dex" : "100", "hpreg" : "30", "hp" : "10000" }, "mob" : ["[정예]예티와페페"], "karta" : "Victoria", "chance" : ["2%"] }, "I02Y" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I02Y' />", "name" : "메이플[2]", "type" : "기타", "effects" : "메이플 + 2", "mob" : ["[정예]예티와페페", "『Boss』스노우맨", "[정예]웨어울프", "[파퀘]렛츠", "[파퀘]블록골렘"], "karta" : "Victoria", "chance" : ["15%", "x3 100%", "15%", "15%", "5x 100%"] }, "I02X" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I02X' />", "name" : "메소 더미[2]", "type" : "기타", "effects" : "메소 + 8000", "mob" : ["[정예]예티와페페", "『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["30%", "5x 100%"] }, "I030" : { "icon" : "<img class='icon' src='https://i.imgur.com/CINHkks.png' alt='I030' />", "name" : "뇌전수리검", "type" : "장신구", "stats" : { "reqlvl" : "270", "atkspd" : "30", "dex" : "100", "atk" : "400", "mdef" : "20%" }, "mob" : ["[정예]예티와페페", "[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.5%", "2%"] }, "I02Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/b6lcTFh.png' alt='I02Z' />", "name" : "에스터 실드", "type" : "장신구", "stats" : { "reqlvl" : "350", "mdef" : "23%", "hp" : "6200", "mp" : "6200", "mpreg" : "27%" }, "mob" : ["[정예]예티와페페", "[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.5%", "2%"] }, "I031" : { "icon" : "<img class='icon' src='https://i.imgur.com/ekzUmnS.png' alt='I031' />", "name" : "해골방패", "type" : "장비", "stats" : { "reqlvl" : "250", "str" : "96", "def" : "75", "hp" : "9000", "mdef" : "25%" }, "mob" : ["[정예]예티와페페"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0B7" : { "icon" : "<img class='icon' src='https://i.imgur.com/Zs4Np43.png' alt='I0B7' />", "name" : "골든 와이어스", "type" : "장비", "stats" : { "reqlvl" : "500", "def" : "60", "atkspd" : "15", "crit" : "30% * 6" }, "mob" : ["[정예]예티와페페", "[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.2%", "1.2%"] }, "I032" : { "icon" : "<img class='icon' src='https://i.imgur.com/by8mFII.png' alt='I032' />", "name" : "다크 기간틱", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "670", "mp" : "5500", "hp" : "2500", "dex" : "200" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I034" : { "icon" : "<img class='icon' src='https://i.imgur.com/ytQFkta.png' alt='I034' />", "name" : "보라색 서핑보드", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "1057", "str" : "80", "hp" : "15000", "crit" : "20%확률로 4배 추뎀+4000" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I036" : { "icon" : "<img class='icon' src='https://i.imgur.com/3qm4p6v.png' alt='I036' />", "name" : "그리스", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "400", "hp" : "9500", "str" : "200", "hpreg" : "70" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I035" : { "icon" : "<img class='icon' src='https://i.imgur.com/dbL7M7O.png' alt='I035' />", "name" : "엔젤윙즈", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "200", "mp" : "20000", "int" : "90", "mpreg" : "30%" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I033" : { "icon" : "<img class='icon' src='https://i.imgur.com/QVjEXaC.png' alt='I033' />", "name" : "이블윙즈", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "250", "mp" : "10000", "hp" : "3000", "int" : "210" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I0GB" : { "icon" : "<img class='icon' src='https://i.imgur.com/yhDOLz2.png' alt='I0GB' />", "name" : "메이플 간디바", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "999", "hp" : "6000", "dex" : "250", "crit" : "5% * 7.5" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I0BQ" : { "icon" : "<img class='icon' src='https://i.imgur.com/auUff8U.png' alt='I0BQ' />", "name" : "신기타", "type" : "무기", "stats" : { "reqlvl" : "300", "atk" : "1057", "hp" : "15000", "dex" : "70", "atkspd" : "7" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I03P" : { "icon" : "<img class='icon' src='https://i.imgur.com/bzsqS8j.png' alt='I03P' />", "name" : "퍼플 시니어 슈즈", "type" : "장비", "stats" : { "reqlvl" : "200", "def" : "77", "mvspd" : "60", "hpreg" : "45" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["10%"] }, "I0C3" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I0C3' />", "name" : "[메달]스노우맨 슬레이어", "type" : "메달", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "str" : "70", "dex" : "70", "int" : "70" }, "mob" : ["『Boss』스노우맨"], "karta" : "Victoria", "chance" : ["4%"] }, "I038" : { "icon" : "<img class='icon' src='https://i.imgur.com/daPUDO7.png' alt='I038' />", "name" : "다크 발퀴레", "type" : "장비", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "reqlvl" : "350", "def" : "100", "str" : "180", "hpreg" : "50", "hp" : "20000" }, "mob" : ["[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I039" : { "icon" : "<img class='icon' src='https://i.imgur.com/aiBwfX1.png' alt='I039' />", "name" : "다크 크리시아", "type" : "장비", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "reqlvl" : "350", "def" : "70", "int" : "180", "mp" : "8000", "hp" : "6000" }, "mob" : ["[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I03A" : { "icon" : "<img class='icon' src='https://i.imgur.com/aiBwfX1.png' alt='I03A' />", "name" : "다크 피라티드", "type" : "장비", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "reqlvl" : "350", "def" : "80", "dex" : "180", "mp" : "4000", "hp" : "10000" }, "mob" : ["[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I03M" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I03M' />", "name" : "메소 더미[3]", "type" : "기타", "effects" : "메소 + 15000", "mob" : ["[정예]타우로마시스", "『Boss』주니어 발록", "[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』크림슨 발록", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["30%", "5x 100%", "30%", "4x 100%", "5x 100%", "5x 100%"] }, "I03N" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I03N' />", "name" : "메이플[3]", "type" : "기타", "effects" : "메이플 + 3", "mob" : ["[정예]타우로마시스", "『Boss』주니어 발록", "『Boss』라이칸스로프", "『Boss』크림슨 발록", "[엘리트]줄라이", "『RAID』마왕 발록", "[파퀘]롬바드"], "karta" : "Victoria", "chance" : ["15%", "3x 100%", "4x 100%", "5x 100%", "6x 100%", "5x 100%", "3x 100%"] }, "I03D" : { "icon" : "<img class='icon' src='https://i.imgur.com/S49iT3g.png' alt='I03D' />", "name" : "『타우로마시스의뿔』", "type" : "기타", "mob" : "[정예]타우로마시스", "karta" : "Victoria", "chance" : "15%" }, "I03B" : { "icon" : "<img class='icon' src='https://i.imgur.com/8Y9aPrn.png' alt='I03B' />", "name" : "골든 에이션트 실드", "type" : "장비", "stats" : { "reqlvl" : "400", "str" : "140", "def" : "80", "hp" : "15000", "mdef" : "28%" }, "mob" : ["[정예]타우로마시스", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["1.5%", "10%"] }, "I03C" : { "icon" : "<img class='icon' src='https://i.imgur.com/Tx7SAmm.png' alt='I03C' />", "name" : "소드 이어링", "type" : "장신구", "stats" : { "reqlvl" : "300", "str" : "60", "dex" : "60", "int" : "60", "hp" : "7000", "mp" : "4000" }, "mob" : ["[정예]타우로마시스", "『Boss』주니어 발록", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["1.5%", "5%", "20%"] }, "I03G" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5PbCux.png' alt='I03G' />", "name" : "그륜힐", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "750", "hp" : "18400", "str" : "350", "hpreg" : "120" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "10%"] }, "I03K" : { "icon" : "<img class='icon' src='https://i.imgur.com/jqxufkX.png' alt='I03K' />", "name" : "레이븐 스태프", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "680", "mp" : "13000", "hp" : "5000", "int" : "350" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "10%"] }, "I03J" : { "icon" : "<img class='icon' src='https://i.imgur.com/2e6YT7g.png' alt='I03J' />", "name" : "피닉스 완드", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "400", "mp" : "35000", "int" : "150", "mpreg" : "35%" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "[파퀘]알리샤르"] }, "I03I" : { "icon" : "<img class='icon' src='https://i.imgur.com/MBcbyZu.png' alt='I03I' />", "name" : "황룡도", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "1950", "hp" : "30000", "str" : "150", "crit" : "20%확률로 5배+추뎀5000" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "10%"] }, "I03H" : { "icon" : "<img class='icon' src='https://i.imgur.com/clSl3iR.png' alt='I03H' />", "name" : "흑갑충", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "980", "mp" : "9000", "hp" : "7000", "dex" : "350" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "10%"] }, "I0GC" : { "icon" : "<img class='icon' src='https://i.imgur.com/CAzKZCa.png' alt='I0GC' />", "name" : "블루 힌켈", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "1500", "hp" : "15000", "dex" : "400", "crit" : "5%*10" }, "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["10%"] }, "I0BR" : { "icon" : "<img class='icon' src='https://i.imgur.com/c9yiovm.png' alt='I0BR' />", "name" : "게타", "type" : "무기", "stats" : { "reqlvl" : "500", "atk" : "1950", "hp" : "30000", "dex" : "120", "atkspd" : "8" }, "mob" : ["『Boss』주니어 발록", "『RAID』마왕 발록", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%", "20%", "10%"] }, "I03Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/2RH4AQb.png' alt='I03Q' />", "name" : "다크 카젠부츠", "type" : "장비", "stats" : { "reqlvl" : "450", "def" : "80", "mvspd" : "80", "str" : "100" }, "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["15%"] }, "I04D" : { "icon" : "<img class='icon' src='https://i.imgur.com/8IeHew4.png' alt='I04D' />", "name" : "[치장]주니어발록 날개", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "자신 이동속도 +50"], "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I03R" : { "icon" : "<img class='icon' src='https://i.imgur.com/C2SdOLP.png' alt='I03R' />", "name" : "다크 크리시아슈즈", "type" : "장비", "stats" : { "reqlvl" : "450", "def" : "80", "mvspd" : "80", "int" : "100" }, "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["15%"] }, "I03S" : { "icon" : "<img class='icon' src='https://i.imgur.com/z53TbrB.png' alt='I03S' />", "name" : "레드 루티드슈즈", "type" : "장비", "stats" : { "reqlvl" : "450", "def" : "80", "mvspd" : "80", "dex" : "100" }, "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["15%"] }, "I03L" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I03L' />", "name" : "[메달]주니어발록 슬레이어", "type" : "메달", "effects" : "[보조 인벤토리에 장착해주세요.]", "stats" : { "str" : "100", "dex" : "100", "int" : "100" }, "mob" : ["『Boss』주니어 발록"], "karta" : "Victoria", "chance" : ["4%"] }, "I0EN" : { "icon" : "<img class='icon' src='https://i.imgur.com/dfugzGD.png' alt='I0EN' />", "name" : "[치장]물고기작살", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "str" : "100", "dex" : "100", "int" : "100", "atkspd" : "35", }, "mob" : ["『Boss』주니어 발록", "[정예]웨어울프", "[정예]샤크", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.15%", "1.3%", "1.5%", "2%"] }, "I04T" : { "icon" : "<img class='icon' src='https://i.imgur.com/4m5VsjI.png' alt='I04T' />", "name" : "『석양의 발록주문서』", "type" : "기타", "effects" : "대장장이에게 강화시도!(세이브)불가 아이템", "mob" : ["『Boss』주니어 발록", "『Boss』크림슨 발록", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["10%", "30%", "100%"] }, "I04V" : { "icon" : "<img class='icon' src='https://i.imgur.com/q091piy.png' alt='I04V' />", "name" : "『웨어울프의 발톱』", "type" : "기타", "mob" : ["[정예]웨어울프"], "karta" : "Victoria", "chance" : ["30%"] }, "I04X" : { "icon" : "<img class='icon' src='https://i.imgur.com/kuJ4uRE.png' alt='I04X' />", "name" : "일비표창", "type" : "장비", "effects" : ["[고정]추가데미지:27777"], "stats" : { "reqlvl" : "700", "atkspd" : "40", "dex" : "300", "atk" : "1200", "crit" : "30% * 4", "mdef" : "25%" }, "mob" : ["[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』파우스트"], "karta" : "Victoria", "chance" : ["1.5%", "3%", "3%"] }, "I04Y" : { "icon" : "<img class='icon' src='https://i.imgur.com/tPA5GbB.png' alt='I04Y' />", "name" : "온화의망토", "type" : "장비", "stats" : { "reqlvl" : "669", "eva" : "25%", "hpreg" : "[초당]150", "mpreg" : "[초당]40%", "str" : "77", "dex" : "77", "int" : "77" }, "mob" : ["[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』파우스트"], "karta" : "Victoria", "chance" : ["1.5%", "3%", "3%"] }, "I04Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/szxsjMF.png' alt='I04Z' />", "name" : "골드 아퀼라 실드", "type" : "장비", "stats" : { "reqlvl" : "700", "str" : "250", "def" : "100", "hp" : "35000", "mdef" : "30%" }, "mob" : ["[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』파우스트"], "karta" : "Victoria", "chance" : ["1.5%", "3%", "3%"] }, "I04Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/szxsjMF.png' alt='I04Z' />", "name" : "골드 아퀼라 실드", "type" : "장비", "stats" : { "reqlvl" : "700", "str" : "250", "def" : "100", "hp" : "35000", "mdef" : "30%" }, "mob" : ["[정예]웨어울프", "『Boss』라이칸스로프", "『Boss』파우스트"], "karta" : "Victoria", "chance" : ["1.5%", "3%", "3%"] }, "I0B8" : { "icon" : "<img class='icon' src='https://i.imgur.com/a8P0yIf.png' alt='I0B8' />", "name" : "다크 엠페러", "type" : "무기", "stats" : { "reqlvl" : "900", "atkspd" : "20", "def" : "100", "crit" : "30% *10.0" }, "mob" : ["[정예]웨어울프", "『Boss』라이칸스로프"], "karta" : "Victoria", "chance" : ["1.2%", "3%"] }, "I054" : { "icon" : "<img class='icon' src='https://i.imgur.com/fhJahq5.png' alt='I054' />", "name" : "코브라스티어", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "1500", "hp" : "15000", "mp" : "15000", "dex" : "500" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I051" : { "icon" : "<img class='icon' src='https://i.imgur.com/37FZefT.png' alt='I051' />", "name" : "케이그", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "1400", "hp" : "10000", "mp" : "20000", "int" : "500" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I0BS" : { "icon" : "<img class='icon' src='https://i.imgur.com/GBKFlxl.png' alt='I0BS' />", "name" : "칸디네", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "3500", "hp" : "50000", "dex" : "250", "atkspd" : "9" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I050" : { "icon" : "<img class='icon' src='https://i.imgur.com/vkv8Sig.png' alt='I050' />", "name" : "마기코라스", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "750", "mp" : "50000", "int" : "400", "mpreg" : "40%" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I052" : { "icon" : "<img class='icon' src='https://i.imgur.com/63XVGPx.png' alt='I052' />", "name" : "그레이트 로헨", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "1050", "hp" : "25000", "str" : "500", "hpreg" : "200" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I0GD" : { "icon" : "<img class='icon' src='https://i.imgur.com/vE3q6M7.png' alt='I0GD' />", "name" : "메투스", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "2800", "hp" : "30000", "dex" : "550", "crit" : "5%*15" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I0GD" : { "icon" : "<img class='icon' src='https://i.imgur.com/1Q7lGZt.png' alt='I0GD' />", "name" : "호신공창", "type" : "무기", "stats" : { "reqlvl" : "800", "atk" : "3500", "hp" : "50000", "str" : "250", "crit" : "20%확률로 7배+추뎀15000" }, "mob" : ["『Boss』라이칸스로프", "『Boss』타이머"], "karta" : "Victoria", "chance" : ["7%", "3%"] }, "I055" : { "icon" : "<img class='icon' src='https://i.imgur.com/0Mlxjjp.png' alt='I055' />", "name" : "[유니크]알테어 이어링", "type" : "장신구", "effects" : ["60초마다.마법방어시전", "[설명]: 찬란하도다.."], "stats" : { "reqlvl" : "1000", "str" : "198", "dex" : "198", "int" : "198", "hp" : "25000", "mp" : "30000" }, "mob" : ["『Boss』라이칸스로프", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["1.5%", "2%"] }, "I0EM" : { "icon" : "<img class='icon' src='https://i.imgur.com/0Mlxjjp.png' alt='I0EM' />", "name" : "[치장]막대사탕", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "int" : "350", "mpreg" : "5%", }, "mob" : ["『Boss』라이칸스로프", "『정예』불독", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.3%", "2%", "1.5%", "2%"] }, "I0C4" : { "icon" : "<img class='icon' src='https://i.imgur.com/V5rgN4W.png' alt='I0C4' />", "name" : "[메달]라이칸스로프 슬레이어", "type" : "메달", "stats" : { "str" : "120", "dex" : "120", "int" : "120" }, "mob" : ["『Boss』라이칸스로프"], "karta" : "Victoria", "chance" : ["4%"] }, "I056" : { "icon" : "<img class='icon' src='https://i.imgur.com/NgK5yGK.png' alt='I056' />", "name" : "메이플 실드", "type" : "장비", "stats" : { "reqlvl" : "700", "mdef" : "120", "hp" : "50000", "mp" : "50000", "mpreg" : "40%" }, "mob" : ["『Boss』크림슨 발록"], "karta" : "Victoria", "chance" : ["5%"] }, "I05O" : { "icon" : "<img class='icon' src='https://i.imgur.com/cZQucy4.png' alt='I05O' />", "name" : "『크림슨 발록의털』", "type" : "기타", "mob" : ["『Boss』크림슨 발록"], "karta" : "Victoria", "chance" : ["30%"] }, "I058" : { "icon" : "<img class='icon' src='https://i.imgur.com/p7UV70x.png' alt='I058' />", "name" : "『치장』이노센트 주문서[날개]", "type" : "기타", "effects" : ["[대장장이에게 강화시도!(세이브)불가 아이템]", "성공률25%"], "stats" : { "str" : "200", "dex" : "200", "int" : "200", "misc" : "+증가" }, "mob" : ["『Boss』크림슨 발록", "『RAID』파풀라투스2", "『RAID』자쿰", "『Boss』그리프", "『Boss』마뇽", "[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["30%", "30%", "30%", "30%", "30%", "10%", "15%", "17%", "20%", "10% (1 항목 만)"] }, "I05K" : { "icon" : "<img class='icon' src='https://i.imgur.com/p7UV70x.png' alt='I05K' />", "name" : "『치장』이노센트 주문서[무기]", "type" : "기타", "effects" : ["[대장장이에게 강화시도!(세이브)불가 아이템]", "성공률25%"], "stats" : { "str" : "200", "dex" : "200", "int" : "200", "misc" : "+증가" }, "mob" : ["『Boss』크림슨 발록", "『RAID』파풀라투스2", "『RAID』자쿰", "『Boss』그리프", "『Boss』마뇽", "[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["30%", "30%", "30%", "30%", "30%", "10%", "15%", "17%", "20%", "10% (1 항목 만)"] }, "I05M" : { "icon" : "<img class='icon' src='https://i.imgur.com/RMzvDhy.png' alt='I05M' />", "name" : "적견랑포", "type" : "장비", "stats" : { "reqlvl" : "700", "def" : "140", "int" : "480", "hp" : "35000", "mp" : "35000" }, "mob" : ["『Boss』크림슨 발록"], "karta" : "Victoria", "chance" : ["7%"] }, "I05N" : { "icon" : "<img class='icon' src='https://i.imgur.com/fCuSo5T.png' alt='I05N' />", "name" : "퍼플 엘소르", "type" : "장비", "stats" : { "reqlvl" : "700", "def" : "200", "str" : "480", "hpreg" : "200", "hp" : "100000" }, "mob" : ["『Boss』크림슨 발록"], "karta" : "Victoria", "chance" : ["7%"] }, "I05L" : { "icon" : "<img class='icon' src='https://i.imgur.com/9pd5Ajs.png' alt='I05L' />", "name" : "다크 카티나스", "type" : "장비", "stats" : { "reqlvl" : "700", "def" : "200", "dex" : "480", "mp" : "35000", "hp" : "35000" }, "mob" : ["『Boss』크림슨 발록"], "karta" : "Victoria", "chance" : ["7%"] }, "I0EK" : { "icon" : "<img class='icon' src='https://i.imgur.com/33LxQIy.png' alt='I0EK' />", "name" : "[치장]신문지칼", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "dex" : "100", "atkspd" : "40" }, "mob" : ["『Boss』크림슨 발록", "『정예』게이트 키퍼", "『정예』타나토스", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.4%", "1.4%", "2%", "1.5%", "2%"] }, "I0EL" : { "icon" : "<img class='icon' src='https://i.imgur.com/aSrYFM0.png' alt='I0EL' />", "name" : "[치장]프라이팬", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "str" : "100", "atkspd" : "40" }, "mob" : ["『Boss』크림슨 발록", "『정예』게이트 키퍼", "『정예』타나토스", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.4%", "1.4%", "2%", "1.5%", "2%"] }, "I05S" : { "icon" : "<img class='icon' src='https://i.imgur.com/OihCfJU.png' alt='I05S' />", "name" : "다크 바르슈즈", "type" : "장비", "stats" : { "reqlvl" : "1000", "def" : "120", "mvspd" : "100", "int" : "400", "mp" : "50000" }, "mob" : ["파이렛"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I05R" : { "icon" : "<img class='icon' src='https://i.imgur.com/MBjuWhc.png' alt='I05R' />", "name" : "다크 카티나부츠", "type" : "장비", "stats" : { "reqlvl" : "1000", "def" : "120", "mvspd" : "100", "dex" : "400", "mp" : "50000" }, "mob" : ["파이렛"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I05Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/63vyRc6.png' alt='I05Q' />", "name" : "다크 크리센트 부츠", "type" : "장비", "stats" : { "reqlvl" : "1000", "def" : "120", "mvspd" : "100", "str" : "400", "hp" : "75000" }, "mob" : ["파이렛"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I05U" : { "icon" : "<img class='icon' src='https://i.imgur.com/kj8n6C1.png' alt='I05U' />", "name" : "『시간의여행자의모레』", "type" : "기타", "mob" : "파이렛", "karta" : "Victoria", "chance" : "30%" }, "I05W" : { "icon" : "<img class='icon' src='https://i.imgur.com/oYK9MuY.png' alt='I05W' />", "name" : "『차원의 균열 조각[A]』", "type" : "기타", "mob" : ["『정예』게이트 키퍼", "『정예』타나토스"], "karta" : "Victoria", "chance" : ["20%", "20%"] }, "I05X" : { "icon" : "<img class='icon' src='https://i.imgur.com/kR86abo.png' alt='I05X' />", "name" : "『차원의 균열 조각[B]』", "type" : "기타", "mob" : ["『정예』게이트 키퍼", "『정예』타나토스"], "karta" : "Victoria", "chance" : ["20%", "20%"] }, "I05V" : { "icon" : "<img class='icon' src='https://i.imgur.com/z2Ibxmu.png' alt='I05V' />", "name" : "『차원의 균열 조각[C]』", "type" : "기타", "mob" : ["『정예』게이트 키퍼", "『정예』타나토스"], "karta" : "Victoria", "chance" : ["20%", "20%"] }, "I069" : { "icon" : "<img class='icon' src='https://i.imgur.com/rD3ZVz8.png' alt='I069' />", "name" : "밸류 포션", "type" : "소모품", "effects" : ["HP/MP를 100000만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『정예』게이트 키퍼", "『정예』타나토스", "『RAID』파풀라투스2", "본 피쉬", "[정예]샤크", "『정예』불독", "『RAID』자쿰", "켄타우로스", "블러드 하프", "『Boss』그리프", "『Boss』마뇽", "『정예』다크 코니언", "『정예』레드 와이번"], "karta" : "Victoria", "chance" : ["50%", "50%", "5x 100%", "15%", "50%", "50%", "5x 100%", "3%", "3%", "5x 100%", "5x 100%", "50% & 50%", "50%"] }, "I05Z" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I05Z' />", "name" : "메소 더미[4]", "type" : "기타", "effects" : "메소 + 20000", "mob" : ["『정예』게이트 키퍼", "『정예』타나토스", "[정예]바이킹", "『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["50%", "50%", "30%", "5x 100%"] }, "I060" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I060' />", "name" : "메이플[4]", "type" : "기타", "effects" : "메이플 + 4", "mob" : ["『정예』게이트 키퍼", "『정예』타나토스", "[정예]바이킹", "『RAID』파풀라투스2", "[파퀘]스타픽시", "[파퀘]알리샤르", "[파퀘]네펜더스"], "karta" : "Victoria", "chance" : ["50%", "50%", "15%", "5x 100%", "15%", "5x 100%", "5X 100%"] }, "I0B9" : { "icon" : "<img class='icon' src='https://i.imgur.com/xSLs1tm.png' alt='I0B9' />", "name" : "블랙 가리나 글러브", "type" : "장비", "stats" : { "reqlvl" : "1500", "def" : "150", "atkspd" : "25", "crit" : "30% *15" }, "mob" : ["『정예』게이트 키퍼", "『정예』타나토스", "[정예]바이킹"], "karta" : "Victoria", "chance" : ["1.5%", "1.5%", "1.2%"] }, "I05T" : { "icon" : "<img class='icon' src='https://i.imgur.com/AjUSSDR.png' alt='I05T' />", "name" : "『바이킹의 돛』", "type" : "기타", "mob" : ["[정예]바이킹"], "karta" : "Victoria", "chance" : ["60%"] }, "I066" : { "icon" : "<img class='icon' src='https://i.imgur.com/cP6GRz7.png' alt='I066' />", "name" : "다이몬의 완드", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "1500", "mp" : "100000", "int" : "650", "mpreg" : "45%" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I068" : { "icon" : "<img class='icon' src='https://i.imgur.com/S39vb1G.png' alt='I068' />", "name" : "라 투헨더", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "2200", "hp" : "80000", "str" : "800", "hpreg" : "300" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I065" : { "icon" : "<img class='icon' src='https://i.imgur.com/H8uDcuL.png' alt='I065' />", "name" : "블루마린", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "2500", "mp" : "50000", "hp" : "25000", "int" : "800" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I064" : { "icon" : "<img class='icon' src='https://i.imgur.com/zLeNw5I.png' alt='I064' />", "name" : "캐스터스", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "3000", "mp" : "35000", "hp" : "35000", "dex" : "800" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I0BT" : { "icon" : "<img class='icon' src='https://i.imgur.com/7kOtLz9.png' alt='I0BT' />", "name" : "용천권", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "8000", "hp" : "100000", "dex" : "650", "atkspd" : "15" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I0GE" : { "icon" : "<img class='icon' src='https://i.imgur.com/SelEGyT.png' alt='I0GE' />", "name" : "다크 니스룩", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "5000", "hp" : "50000", "dex" : "700", "crit" : "5%*20" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I067" : { "icon" : "<img class='icon' src='https://i.imgur.com/gBHSNhC.png' alt='I067' />", "name" : "페어프로즌", "type" : "무기", "stats" : { "reqlvl" : "1500", "atk" : "8000", "hp" : "100000", "str" : "650", "crit" : "25%확률로 8배+추뎀20000" }, "mob" : ["『RAID』파풀라투스2", "『정예』불독", "『Boss』세르프"], "karta" : "Victoria", "chance" : ["10%", "1.5%", "3%"] }, "I06C" : { "icon" : "<img class='icon' src='https://i.imgur.com/kvksYJM.png' alt='I06C' />", "name" : "[치장]파풀라투스의시계", "type" : "치장", "effects" : "[치장 인벤토리에 장착해주세요.]", "stats" : { "mp" : "100000", "hp" : "100000" }, "mob" : ["『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I063" : { "icon" : "<img class='icon' src='https://i.imgur.com/WeEwFFR.png' alt='I063' />", "name" : "[유니크]루디브리엄의망토", "type" : "장비", "effects" : "[설명:파풀라투스 원정대 성공 증표]", "stats" : { "reqlvl" : "2000", "eva" : "30%", "mpreg" : "[초당]50%", "hpreg" : "[초당]500", "str" : "1000", "dex" : "1000", "int" : "1000" }, "mob" : ["『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["5%"] }, "I06H" : { "icon" : "<img class='icon' src='https://i.imgur.com/g62Wip5.png' alt='I06H' />", "name" : "[유니크]이온 슈트", "type" : "장비", "effects" : "아이템설명:[루디브리엄의 사수하라!!]", "stats" : { "reqlvl" : "1500", "def" : "300", "str" : "800", "dex" : "800", "int" : "800", "mp" : "200000", "hp" : "200000" }, "mob" : ["『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["5%"] }, "I0C9" : { "icon" : "<img class='icon' src='https://i.imgur.com/x56AaSc.png' alt='I0C9' />", "name" : "『소울조각:파풀라투스』", "type" : "장비", "effects" : "조합아이템", "mob" : ["『RAID』파풀라투스2", "『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["15%", "60%|50%|40%"] }, "I0HI" : { "icon" : "<img class='icon' src='https://i.imgur.com/jeI9Dkj.png' alt='I0HI' />", "name" : "[치장]파풀라투스의날개", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "[강화 불가 아이템]"], "stats" : { "str" : "250", "dex" : "250", "int" : "250", "mvspd" : "100" }, "mob" : ["『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I06X" : { "icon" : "<img class='icon' src='https://i.imgur.com/p7UV70x.png' alt='I06X' />", "name" : "『치장』이노센트 주문서[오라]", "type" : "기타", "effects" : ["대장장이에게 강화시도!(세이브)불가 아이템", "성공률25%"], "stats" : { "hp" : "50000", "mp" : "50000", "misc" : "+증가" }, "mob" : ["『RAID』파풀라투스2", "『RAID』자쿰", "『파퀘』파라오", "『Boss』그리프", "『Boss』마뇽", "[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["30%", "30%", "30%", "30%", "30%", "10%", "15%", "17%", "20%", "10% (1 항목 만)"] }, "I08S" : { "icon" : "<img class='icon' src='https://i.imgur.com/6iajumQ.png' alt='I08S' />", "name" : "『다크 타키온』", "type" : "기타", "effects" : ["3차전직 재료아이템"], "mob" : ["『RAID』파풀라투스2"], "karta" : "Victoria", "chance" : ["100%"] }, "I06I" : { "icon" : "<img class='icon' src='https://i.imgur.com/pqxcxwk.png' alt='I06I' />", "name" : "『루디통행증』", "type" : "기타", "effects" : ["다음지역으로 이동하세요.[한분만 있으시면 됩니다.]"], "mob" : ["[파퀘]렛츠"], "karta" : "Victoria", "chance" : ["40%"] }, "I06L" : { "icon" : "<img class='icon' src='https://i.imgur.com/pqxcxwk.png' alt='I06L' />", "name" : "『루디통행증』4", "type" : "기타", "effects" : ["다음지역으로 이동하세요.[한분만 있으시면 됩니다.]"], "mob" : ["[파퀘]롬바드"], "karta" : "Victoria", "chance" : ["100%"] }, "I06O" : { "icon" : "<img class='icon' src='https://i.imgur.com/5zzorhB.png' alt='I06O' />", "name" : "『마법의구름』", "type" : "기타", "effects" : ["다음지역으로 이동하세요.[한분만 있으시면 됩니다.]"], "mob" : ["[파퀘]스타픽시"], "karta" : "Victoria", "chance" : ["40%"] }, "I06Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/ne65Eiv.png' alt='I06Q' />", "name" : "『마법의씨앗』2", "type" : "기타", "effects" : ["다음지역으로 이동하세요.[한분만 있으시면 됩니다.]"], "mob" : ["[파퀘]외로운 스타픽시"], "karta" : "Victoria", "chance" : ["100%"] }, "I07M" : { "icon" : "<img class='icon' src='https://i.imgur.com/lnSs8u0.png' alt='I07M' />", "name" : "『석회가루병』", "type" : "기타", "effects" : ["조합아이템"], "mob" : ["본 피쉬"], "karta" : "Victoria", "chance" : ["20%"] }, "I07G" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I07G' />", "name" : "메소 더미[5]", "type" : "기타", "effects" : "메소 + 30000", "mob" : ["[정예]샤크", "『정예』불독", "『RAID』자쿰", "『Boss』파우스트", "켄타우로스", "블러드 하프"], "karta" : "Victoria", "chance" : ["30%", "30%", "5x 100%", "3x 100%", "20%", "20%"] }, "I07F" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I07F' />", "name" : "메이플[5]", "type" : "기타", "effects" : "메이플 + 5", "mob" : ["[정예]샤크", "『정예』불독", "『RAID』자쿰", "『Boss』파우스트", "켄타우로스", "블러드 하프"], "karta" : "Victoria", "chance" : ["15%", "15%", "5x 100%", "3x 100%", "10%", "10%"] }, "I07J" : { "icon" : "<img class='icon' src='https://i.imgur.com/Y0RoyUv.png' alt='I07J' />", "name" : "블랙 가리나", "type" : "장비", "stats" : { "reqlvl" : "1500", "def" : "200", "dex" : "700", "mp" : "80000", "hp" : "80000" }, "mob" : ["[정예]샤크"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I07K" : { "icon" : "<img class='icon' src='https://i.imgur.com/xk37jK6.png' alt='I07K' />", "name" : "블루 드래곤갑옷", "type" : "장비", "stats" : { "reqlvl" : "1500", "def" : "250", "str" : "700", "hpreg" : "300", "hp" : "150000" }, "mob" : ["[정예]샤크"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I07I" : { "icon" : "<img class='icon' src='https://i.imgur.com/cmhH3mM.png' alt='I07I' />", "name" : "블루 바즈라", "type" : "장비", "stats" : { "reqlvl" : "1500", "def" : "250", "int" : "700", "mp" : "80000", "hp" : "80000" }, "mob" : ["[정예]샤크"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I07L" : { "icon" : "<img class='icon' src='https://i.imgur.com/SUr5B6C.png' alt='I07L' />", "name" : "『냉동 샥스핀』", "type" : "기타", "effects" : ["조합아이템"], "mob" : ["[정예]샤크"], "karta" : "Victoria", "chance" : ["30%"] }, "I07Q" : { "icon" : "<img class='icon' src='https://i.imgur.com/CArbaCd.png' alt='I07Q' />", "name" : "참화도", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "5000", "str" : "1500", "hpreg" : "400", "hp" : "200000" }, "mob" : ["『RAID』피아누스(오른쪽)", "『Boss』포장마차"], "karta" : "Victoria", "chance" : ["10%", "3%"] }, "I08A" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZJkZJCv.png' alt='I08A' />", "name" : "메이플 표창", "type" : "장비", "stats" : { "reqlvl" : "1500", "atkspd" : "45", "atk" : "7000", "dex" : "800", "crit" : "크리티컬30%확률로 *8 [고정]추가데미지:120000", "mdef" : "34%" }, "mob" : ["『정예』불독", "『RAID』자쿰"], "karta" : "Victoria", "chance" : ["1.4%", "30%"] }, "I08B" : { "icon" : "<img class='icon' src='https://i.imgur.com/fRMfqoI.png' alt='I08B' />", "name" : "인내의 포스쉴드", "type" : "장비", "stats" : { "reqlvl" : "1500", "mp" : "100000", "mpreg" : "45%", "hp" : "100000", "mdef" : "35%" }, "mob" : ["『정예』불독", "『RAID』자쿰"], "karta" : "Victoria", "chance" : ["1.4%", "30%"] }, "I08C" : { "icon" : "<img class='icon' src='https://i.imgur.com/ZyPwrqY.png' alt='I08C' />", "name" : "『불독의 송곳니』", "type" : "기타", "effects" : ["조합아이템"], "mob" : ["『정예』불독"], "karta" : "Victoria", "chance" : ["30%"] }, "I08R" : { "icon" : "<img class='icon' src='https://i.imgur.com/EagjtxR.png' alt='I08R' />", "name" : "『어둠의크리스탈』", "type" : "기타", "effects" : ["3차전직 재료아이템"], "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["100%"] }, "I08W" : { "icon" : "<img class='icon' src='https://i.imgur.com/74OGQzI.png' alt='I08W' />", "name" : "[치장]자쿰의 손", "type" : "기타", "effects" : ["[치장 인벤토리에 장착해주세요.]", "자신 이동속도 +50"], "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["1.2%"] }, "I08V" : { "icon" : "<img class='icon' src='https://i.imgur.com/IDCTXTd.png' alt='I08V' />", "name" : "[유니크]자쿰의투구", "type" : "장비", "effects" : ["60초마다.마법방어시전", "[설명]: 자쿰 원정대를 성공한 증표이다."], "stats" : { "reqlvl" : "2500", "str" : "3000", "dex" : "3000", "int" : "3000", "hp" : "300000", "mp" : "300000" }, "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["20%"] }, "I0B6" : { "icon" : "<img class='icon' src='https://i.imgur.com/0QLrNnb.png' alt='I0B6' />", "name" : "『레전더리』자쿰의 망토", "type" : "장비", "effects" : ["설명:자쿰 원정대 성공 증표]"], "stats" : { "reqlvl" : "3000", "eva" : "35%", "str" : "2300", "dex" : "2300", "int" : "2300", "hpreg" : "[초당]1000", "mpreg" : "[초당]60%" }, "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0CB" : { "icon" : "<img class='icon' src='https://i.imgur.com/x56AaSc.png' alt='I0CB' />", "name" : "『소울조각:자쿰』", "type" : "기타", "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["20%"] }, "I0AL" : { "icon" : "<img class='icon' src='https://i.imgur.com/iz3Xain.png' alt='I0AL' />", "name" : "『자쿰의 돌 조각』", "type" : "기타", "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["100%"] }, "I0EJ" : { "icon" : "<img class='icon' src='https://i.imgur.com/NI9C09g.png' alt='I0EJ' />", "name" : "[치장]자쿰의나뭇가지", "type" : "기타", "effects" : ["[치장 인벤토리에 장착해주세요.]", "INT+1000", "MP리젠:25%", "[강화 불가 아이템]"], "mob" : ["『RAID』자쿰"], "karta" : "Victoria", "chance" : ["5%"] }, "I0H9" : { "icon" : "<img class='icon' src='https://i.imgur.com/w2a9vjB.png' alt='I0H9' />", "name" : "[레시피]샤키엘의날개", "type" : "기타", "effects" : ["연금술사에게 레시피합성 하기 누르시면됩니다.", "주니어발록 날개+Max,요정의날개+Max,자쿰의손+Max,[드랍]투명망토+Max,혼테일의날개+Max,마왕발록+Max, 중 하나와 레시피와 합성시 샤키엘의날개 로 변경됩니다.", "[주의:변경시 이전치장아이템으로 되돌아갈 수 없습니다.[투명망토는가능] 신중하게 해주세요.]"], "mob" : ["『RAID』자쿰", "[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.1%", "1.1%", "1.1%", "1.1%", "1.1%"] }, "I0MT" : { "icon" : "<img class='icon' src='https://i.imgur.com/yCPaZQO.png' alt='I0MT' />", "name" : "[에픽]갈색삿갓", "type" : "장비", "effects" : ["특수능력:30%확률로 섀도우계열&나이트로드계열 타겟성 스킬에 DEX*40 추가데미지를 줍니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "1000", "dex" : "5000", "atkspd" : "45", "hp" : "400000", "mp" : "400000" }, "mob" : ["『Boss』파우스트"], "karta" : "Victoria", "chance" : ["2%"] }, "I0MX" : { "icon" : "<img class='icon' src='https://i.imgur.com/mcMjnGF.png' alt='I0MX' />", "name" : "[에픽]슈퍼겔만의 목걸이", "type" : "장비", "effects" : ["특수능력:피격시 10%확률로 파풀라투스 콩 소환 콩데미지 자신HP500% 데미지를 줍니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "2000", "str" : "15000", "dex" : "15000", "int" : "15000", "atkspd" : "45", "hp" : "200만", "mp" : "200만" }, "mob" : ["『Boss』타이머"], "karta" : "Victoria", "chance" : ["2%"] }, "I0MZ" : { "icon" : "<img class='icon' src='https://i.imgur.com/gMw8TG9.png' alt='I0MZ' />", "name" : "[에픽]백의 서", "type" : "장비", "effects" : ["특수능력:아크메이지&비숍이 마법사용시 10%확률로 자신위치 400XP범위 적에게 썬더스톰을 시전합니다.", "INT*75 데미지를 줍니다..", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "2000", "int" : "20000", "mp" : "400만" }, "mob" : ["『Boss』타이머"], "karta" : "Victoria", "chance" : ["2%"] }, "I0DH" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I0DH' />", "name" : "메소 더미[7]", "type" : "기타", "effects" : "메소 + 50000", "mob" : ["『Boss』타이머", "『파퀘』파라오", "『정예』레드 와이번"], "karta" : "Victoria", "chance" : ["3x 100%", "5x 100%", "30%"] }, "I0A7" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I0A7' />", "name" : "메이플[6]", "type" : "기타", "effects" : "메이플 + 6", "mob" : ["『Boss』타이머", "『파퀘』스켈레곤", "『파퀘』파라오", "『Boss』그리프", "『Boss』마뇽", "『정예』다크 코니언", "[엘리트]카리아인"], "karta" : "Victoria", "chance" : ["3x 100%", "30%", "5x 100%", "5x 100%", "5x 100%", "15%", "6x 100%"] }, "I0N1" : { "icon" : "<img class='icon' src='https://i.imgur.com/dTH9xZU.png' alt='I0N1' />", "name" : "[에픽]템페스트 견장", "type" : "장비", "effects" : ["특수능력:나이트로드&보우마스터&섀도우가 공격시 5% 출혈 DEX*15씩 추가데미지를 줍니다.", "특수능력2:나이트로드&보우마스터&섀도우가 공격시 1%확률로 150XP 적에게 지뢰폭탄 DEX*67 데미지를 줍니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "3500", "dex" : "35000", "hp" : "500만" }, "mob" : ["『Boss』세르프"], "karta" : "Victoria", "chance" : ["2%"] }, "I0N2" : { "icon" : "<img class='icon' src='https://i.imgur.com/8TUea7f.png' alt='I0N2' />", "name" : "[에픽]템페스트 벨트", "type" : "장비", "effects" : ["특수능력:아크메이지&비숍이 타겟 마법사용시 30%확률로 썬더볼트 시전 300XP 적에게 INT*80 데미지를 줍니다..", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "3500", "int" : "35000", "hp" : "500만" }, "mob" : ["『Boss』세르프"], "karta" : "Victoria", "chance" : ["2%"] }, "I0N0" : { "icon" : "<img class='icon' src='https://i.imgur.com/RMoCrxF.png' alt='I0N0' />", "name" : "[에픽]템페스트 팬던트", "type" : "장비", "effects" : [" 특수능력:팔라딘&다크나이트가 피격시 6%확률로 고정HP100만이 회복되고 파동시전 200XP범위 적에게 STR*55 데미지를 줍니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "3500", "str" : "35000", "hp" : "500만" }, "mob" : ["『Boss』세르프"], "karta" : "Victoria", "chance" : ["2%"] }, "I0B0" : { "icon" : "<img class='icon' src='https://i.imgur.com/831R7cx.png' alt='I0B0' />", "name" : "[치장]냉동참치", "type" : "치장", "mob" : ["『Boss』세르프"], "karta" : "Victoria", "chance" : ["2%"] }, "I0EW" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I0EW' />", "name" : "메소 더미[8]", "type" : "기타", "effects" : "메소 + 75000", "mob" : ["『Boss』세르프"], "karta" : "Victoria", "chance" : ["3x 100%"] }, "I0CV" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I0CV' />", "name" : "메이플[8]", "type" : "기타", "effects" : "메이플 + 8", "mob" : ["『Boss』세르프", "[엘리트]싸움꾼 플레트"], "karta" : "Victoria", "chance" : ["3x 100%", "6x 100%"] }, "I0N3" : { "icon" : "<img class='icon' src='https://i.imgur.com/CUdS3tq.png' alt='I0N3' />", "name" : "[에픽]천룡추", "type" : "장비", "effects" : ["특수능력:다크나이트&팔라딘이 공격시 거대도끼 휘두르기!!이펙 1%확률로 STR*70 데미지를 주며 HP150만씩 고정 회복합니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "4500", "str" : "40000", "hp" : "600만" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["2%"] }, "I0N4" : { "icon" : "<img class='icon' src='https://i.imgur.com/tj05FCg.png' alt='I0N4' />", "name" : "[에픽]무한의 마법 화살", "type" : "장비", "effects" : ["특수능력:보우마스터가 공격시 3%확률로 DEX*89 데미지를 주고 하늘에서 화살이 떨어집니다.", "나이트로드인 경우 공격시 3%확률로 DEX*89 데미지를 주고 박쥐가 나옵니다.", "섀도우인 경우 공격시 3%확률로 DEX*89 데미지를주고 붉은손톱이 발동됩니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "4500", "dex" : "40000", "hp" : "600만" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["2%"] }, "I0N5" : { "icon" : "<img class='icon' src='https://i.imgur.com/0wIhsve.png' alt='I0N5' />", "name" : "[에픽]백금의 서", "type" : "장비", "effects" : ["특수능력:아크메이지가 마법 사용시 10%확률로 프로즌오브가 자동 소환됩니다..", "비숍인 경우 마법사용시 10%확률로 200XP범위 미니 제네시스가 발동됩니다.", "특수 보스몬스터에게 드랍되는 희귀성 아이템입니다."], "stats" : { "reqlvl" : "4500", "int" : "40000", "hp" : "600만" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["2%"] }, "I07S" : { "icon" : "<img class='icon' src='https://i.imgur.com/oxGf2j5.png' alt='I07S' />", "name" : "레드 크리븐", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "5000", "mp" : "80000", "hp" : "100000", "dex" : "1500" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I0BU" : { "icon" : "<img class='icon' src='https://i.imgur.com/gFQmqJP.png' alt='I0BU' />", "name" : "블러드 대거", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "12000", "atkspd" : "20", "hp" : "200000", "dex" : "1000" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I07R" : { "icon" : "<img class='icon' src='https://i.imgur.com/vVoHL1c.png' alt='I07R' />", "name" : "피나카", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "12000", "hp" : "200000", "str" : "1000", "crit" : "25%확률로 10배+추뎀50000" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I0GF" : { "icon" : "<img class='icon' src='https://i.imgur.com/VBcbvsy.png' alt='I0GF' />", "name" : "크로우 롱보우", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "8000", "hp" : "85000", "dex" : "1250", "crit" : "5%*25" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I07O" : { "icon" : "<img class='icon' src='https://i.imgur.com/YPRSe7s.png' alt='I07O' />", "name" : "드래곤 완드", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "3000", "mp" : "200000", "int" : "1000", "mpreg" : "50%" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I07P" : { "icon" : "<img class='icon' src='https://i.imgur.com/1w80seU.png' alt='I07P' />", "name" : "드래곤 스태프", "type" : "무기", "stats" : { "reqlvl" : "2000", "atk" : "4000", "mp" : "100000", "hp" : "80000", "int" : "1500" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3%"] }, "I0AT" : { "icon" : "<img class='icon' src='https://i.imgur.com/7ozujbV.png' alt='I0AT' />", "name" : "[유니크]메이플 이어링", "type" : "장신구", "stats" : { "reqlvl" : "2500", "def" : "200", "mvspd" : "130", "str" : "1250", "dex" : "1250", "int" : "1250", "hp" : "300000" }, "mob" : ["『Boss』포장마차", "『정예』레드 와이번"], "karta" : "Victoria", "chance" : ["3%", "1.2%"] }, "I04U" : { "icon" : "<img class='icon' src='https://i.imgur.com/ykLrKyi.png' alt='I04U' />", "name" : "[치장]화염의카타나", "type" : "치장", "effects" : "[치장 인벤토리에 장착해주세요.]", "stats" : { "atkspd" : "35" }, "mob" : ["『Boss』포장마차", "『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["2%", "1%"] }, "I0FP" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I0FP' />", "name" : "메소 더미[9]", "type" : "기타", "effects" : "메소 + 90000", "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["3x 100%"] }, "I0CW" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I0CW' />", "name" : "메이플[9]", "type" : "기타", "effects" : "메이플 + 9", "mob" : ["『Boss』포장마차", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["3x 100%", "6x 100%"] }, "I0HN" : { "icon" : "<img class='icon' src='https://i.imgur.com/flHQCVt.png' alt='I0HN' />", "name" : "『이지스의 룬』", "type" : "기타", "mob" : ["『파퀘』스켈레곤"], "karta" : "Victoria", "chance" : ["25%"] }, "I0D1" : { "icon" : "<img class='icon' src='https://i.imgur.com/6aPTzs3.png' alt='I0D1' />", "name" : "황금 별 포션", "type" : "소모품", "effects" : ["HP/MP를 250000만큼 회복시켜줍니다.", "[창고로 사용가능]"], "mob" : ["『파퀘』파라오", "『파퀘』레드 와이번", "[엘리트]모카딘", "『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["30%|30%|30%", "20%", "3x 100%", "5x 100%"] }, "I0A6" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I0A6' />", "name" : "메소 더미[6]", "type" : "기타", "effects" : "메소 + 40000", "mob" : ["『파퀘』스켈레곤", "『Boss』그리프", "『Boss』마뇽", "『정예』다크 코니언"], "karta" : "Victoria", "chance" : ["60%", "5x 100%", "5x 100%", "30%"] }, "I0HO" : { "icon" : "<img class='icon' src='https://i.imgur.com/nEDqcfF.png' alt='I0HO' />", "name" : "파라오의 신발[STR]", "type" : "장비", "stats" : { "reqlvl" : "2500", "def" : "150", "mvspd" : "120", "str" : "1000", "hp" : "400000" }, "mob" : ["『파퀘』파라오", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["5%", "3%"] }, "I0HP" : { "icon" : "<img class='icon' src='https://i.imgur.com/nEDqcfF.png' alt='I0HP' />", "name" : "파라오의 신발[DEX]", "type" : "장비", "stats" : { "reqlvl" : "2500", "def" : "150", "mvspd" : "120", "dex" : "1000", "hp" : "400000" }, "mob" : ["『파퀘』파라오", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["5%", "3%"] }, "I0HQ" : { "icon" : "<img class='icon' src='https://i.imgur.com/nEDqcfF.png' alt='I0HQ' />", "name" : "파라오의 신발[INT]", "type" : "장비", "stats" : { "reqlvl" : "2500", "def" : "150", "mvspd" : "120", "int" : "1000", "hp" : "400000" }, "mob" : ["『파퀘』파라오", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["5%", "3%"] }, "I0HR" : { "icon" : "<img class='icon' src='https://i.imgur.com/TAXd9yV.png' alt='I0HR' />", "name" : "[유니크]불멸의반지", "type" : "장비", "effects" : ["40초마다. 400XP범위적에게 자동 마법데미지 400만 모래폭풍 발동", "『설명:파라오의 반지』"], "stats" : { "reqlvl" : "2500", "atk" : "8000", "atkspd" : "40%", "crit" : "30% *20.0+20만 추가데미지" }, "mob" : ["『파퀘』파라오", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.5%"] }, "I0HS" : { "icon" : "<img class='icon' src='https://i.imgur.com/7O6mk1x.png' alt='I0HS' />", "name" : "[유니크]불멸의 벨트", "type" : "장비", "effects" : ["40초마다. 400XP범위적에게 자동 마법데미지 400만 모래폭풍 발동", "『설명:파라오의 반지』"], "stats" : { "reqlvl" : "2100", "mdef" : "40%", "atk" : "8888", "str" : "4000", "dex" : "4000", "int" : "4000", "hp" : "60만", "crit" : "크리티컬5%확률로 *12" }, "mob" : ["『파퀘』파라오", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.5%", "1.5%"] }, "I0HT" : { "icon" : "<img class='icon' src='https://i.imgur.com/kSI5rW1.png' alt='I0HT' />", "name" : "『네트 에메랄드』", "type" : "기타", "mob" : ["『파퀘』파라오"], "karta" : "Victoria", "chance" : ["100%|50%|20%"] }, "I0CJ" : { "icon" : "<img class='icon' src='https://i.imgur.com/unl2NgK.png' alt='I0CJ' />", "name" : "『소울인첸터』", "type" : "기타", "mob" : ["『파퀘』파라오", "[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘", "[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["15%", "5%", "10%", "12%", "15%", "5%"] }, "I0AA" : { "icon" : "<img class='icon' src='https://i.imgur.com/NOIVAy0.png' alt='I0AA' />", "name" : "님블리스트", "type" : "장비", "stats" : { "reqlvl" : "2000", "mdef" : "38%", "dex" : "2000", "hp" : "200000", "hpreg" : "300" }, "mob" : ["켄타우로스"], "karta" : "Victoria", "chance" : ["1.2%"] }, "I0A9" : { "icon" : "<img class='icon' src='https://i.imgur.com/uCdFQa7.png' alt='I0A9' />", "name" : "지혜의 포스실드", "type" : "장비", "stats" : { "reqlvl" : "2000", "mdef" : "38%", "int" : "2000", "hp" : "200000", "mpreg" : "50%" }, "mob" : ["블러드 하프"], "karta" : "Victoria", "chance" : ["1.2%"] }, "I09L" : { "icon" : "<img class='icon' src='https://i.imgur.com/2RtTGL0.png' alt='I09L' />", "name" : "『그리프의뿔』", "type" : "기타", "mob" : ["『Boss』그리프"], "karta" : "Victoria", "chance" : ["30%"] }, "I0A2" : { "icon" : "<img class='icon' src='https://i.imgur.com/tq8FQyk.png' alt='I0A2' />", "name" : "크로우 스태프", "type" : "무기", "stats" : { "reqlvl" : "2500", "mpreg" : "50%", "mp" : "200000", "hp" : "150000", "int" : "3000" }, "mob" : ["『Boss』그리프"], "karta" : "Victoria", "chance" : ["4%"] }, "I0A5" : { "icon" : "<img class='icon' src='https://i.imgur.com/NlRDgx8.png' alt='I0A5' />", "name" : "드래곤 슬레브", "type" : "무기", "stats" : { "reqlvl" : "2500", "atk" : "10000", "mp" : "150000", "hp" : "200000", "dex" : "3000" }, "mob" : ["『Boss』그리프"], "karta" : "Victoria", "chance" : ["4%"] }, "I0GG" : { "icon" : "<img class='icon' src='https://i.imgur.com/51417JI.png' alt='I0GG' />", "name" : "드래곤 샤인보우", "type" : "무기", "stats" : { "reqlvl" : "2500", "atk" : "14000", "hp" : "120000", "dex" : "1600", "crit" : "5%*30" }, "mob" : ["『Boss』그리프"], "karta" : "Victoria", "chance" : ["4%"] }, "I09J" : { "icon" : "<img class='icon' src='https://i.imgur.com/LBJmhhq.png' alt='I09J' />", "name" : "『질긴 용가죽』", "type" : "기타", "mob" : ["『Boss』그리프", "『Boss』마뇽", "『정예』다크 코니언"], "karta" : "Victoria", "chance" : ["50%|50%", "50%|50%", "40%"] }, "I09M" : { "icon" : "<img class='icon' src='https://i.imgur.com/Pjwke3Y.png' alt='I09M' />", "name" : "『마뇽의꼬리』", "type" : "기타", "mob" : ["『Boss』마뇽"], "karta" : "Victoria", "chance" : ["30%"] }, "I0A3" : { "icon" : "<img class='icon' src='https://i.imgur.com/ddpC3oZ.png' alt='I0A3' />", "name" : "드래곤 클레이모어", "type" : "무기", "stats" : { "reqlvl" : "2500", "atk" : "8000", "hp" : "300000", "str" : "3000", "hpreg" : "500" }, "mob" : ["『Boss』마뇽"], "karta" : "Victoria", "chance" : ["5%"] }, "I0A4" : { "icon" : "<img class='icon' src='https://i.imgur.com/0cmU1W6.png' alt='I0A4' />", "name" : "드래곤 팔티잔", "type" : "무기", "stats" : { "reqlvl" : "2500", "atk" : "20000", "hp" : "250000", "str" : "1500", "crit" : "25%확률로 15배+추뎀100000" }, "mob" : ["『Boss』마뇽"], "karta" : "Victoria", "chance" : ["5%"] }, "I0BV" : { "icon" : "<img class='icon' src='https://i.imgur.com/aUmZ9Db.png' alt='I0BV' />", "name" : "드래곤 칸자르", "type" : "무기", "stats" : { "reqlvl" : "2500", "atk" : "20000", "hp" : "250000", "dex" : "1500", "atkspd" : "25" }, "mob" : ["『Boss』마뇽"], "karta" : "Victoria", "chance" : ["5%"] }, "I0A8" : { "icon" : "<img class='icon' src='https://i.imgur.com/pjHoPMF.png' alt='I0A8' />", "name" : "드래곤 실드", "type" : "장비", "stats" : { "reqlvl" : "2000", "mdef" : "38%", "hp" : "200000", "str" : "2000", "hpreg" : "300" }, "mob" : ["『정예』다크 코니언"], "karta" : "Victoria", "chance" : ["1.2%"] }, "I0BE" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I0BE' />", "name" : "메이플[7]", "type" : "기타", "effects" : "메이플 + 7", "mob" : ["『정예』레드 와이번", "『파퀘』레드 와이번"], "karta" : "Victoria", "chance" : ["15%", "15%"] }, "I0AO" : { "icon" : "<img class='icon' src='https://i.imgur.com/nVoRtet.png' alt='I0AO' />", "name" : "『와이번의 날개』", "type" : "기타", "mob" : ["『Boss』마뇽"], "karta" : "Victoria", "chance" : ["40%"] }, "I0BA" : { "icon" : "<img class='icon' src='https://i.imgur.com/BMbBcKH.png' alt='I0BA' />", "name" : "『드래곤의정수』", "type" : "기타", "mob" : ["『파퀘』레드 와이번"], "karta" : "Victoria", "chance" : ["40%"] }, "I0CP" : { "icon" : "<img class='icon' src='https://i.imgur.com/BMbBcKH.png' alt='I0CP' />", "name" : "[엘리트보스]줄라이", "type" : "기타", "effects" : "1차승급자가 클릭시 엘리트보스[줄라이]등장!!", "mob" : ["[정예]드레이크", "[정예]예티와페페", "[정예]타우로마시스"], "karta" : "Victoria", "chance" : ["2.5%", "2.5%", "2.5%"] }, "I0HG" : { "icon" : "<img class='icon' src='https://i.imgur.com/w2a9vjB.png' alt='I0HG' />", "name" : "[레시피]썬더세이버", "type" : "기타", "effects" : ["연금술사에게 레시피합성 하기 누르시면됩니다.", "파괴자+Max,붉은대검+Max,얼음검+Max,[치장]투명무기+Max,[치장]광선창+Max,[제작]카이셀리움,[제작]움트라세이버,[제작]다크소울,[제작]용마제구검 중 하나와 레시피와 합성시 [제작]썬더세이버 로 변경됩니다."], "mob" : ["[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.1%", "1.1%", "1.1%", "1.1%"] }, "I0HF" : { "icon" : "<img class='icon' src='https://i.imgur.com/w2a9vjB.png' alt='I0HF' />", "name" : "[레시피]옴브라루체", "type" : "기타", "effects" : ["연금술사에게 레시피합성 하기 누르시면됩니다.", "파괴자+Max,붉은대검+Max,얼음검+Max,[치장]광선창+Max,[치장]투명무기+Max,[제작]카이셀리움,[제작]썬더세이버,[제작]다크소울,[제작]용마제구검 중 하나와 레시피와 합성시 [제작]움트라세이버 로 변경됩니다."], "mob" : ["[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["1.1%", "1.1%", "1.1%", "1.1%"] }, "I0KY" : { "icon" : "<img class='icon' src='https://i.imgur.com/C051nox.png' alt='I0KY' />", "name" : "[유니크]데빌의 혼", "type" : "장비", "effects" : ["60초마다.마법방어시전", "[설명]: 엘리트 보스몹에 장식물 이다."], "stats" : { "reqlvl" : "2000", "str" : "1500", "dex" : "1500", "int" : "1500", "hp" : "120000", "mp" : "120000" }, "mob" : ["[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘"], "karta" : "Victoria", "chance" : ["3%", "5%", "7.5%", "10%"] }, "I0CY" : { "icon" : "<img class='icon' src='https://i.imgur.com/O8rNTJL.png' alt='I0CY' />", "name" : "만병통치약", "type" : "장비", "effects" : ["60초마다.마법방어시전", "[설명]: 엘리트 보스몹에 장식물 이다."], "stats" : { "reqlvl" : "2000", "str" : "1500", "dex" : "1500", "int" : "1500", "hp" : "120000", "mp" : "120000" }, "mob" : ["[엘리트]줄라이", "[엘리트]카리아인", "[엘리트]싸움꾼 플레트", "[엘리트]모카딘", "『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["100%", "100%", "100%", "100%", "100%"] }, "I0CQ" : { "icon" : "<img class='icon' src='https://i.imgur.com/BMbBcKH.png' alt='I0CQ' />", "name" : "[엘리트보스]카리아인", "type" : "기타", "effects" : "2차승급자가 클릭시 엘리트보스[카리아인]등장!!", "mob" : ["[정예]바이킹", "[정예]샤크", "『정예』불독"], "karta" : "Victoria", "chance" : ["2.5%", "2.5%", "2.5%"] }, "I0DD" : { "icon" : "<img class='icon' src='https://i.imgur.com/BMbBcKH.png' alt='I0DD' />", "name" : "[엘리트보스]플레트", "type" : "기타", "effects" : "3차승급자가 클릭시 엘리트보스[플레트]등장!!", "mob" : ["켄타우로스", "블러드 하프"], "karta" : "Victoria", "chance" : ["2%", "2%"] }, "I0CR" : { "icon" : "<img class='icon' src='https://i.imgur.com/BMbBcKH.png' alt='I0CR' />", "name" : "[엘리트보스]모카딘", "type" : "기타", "effects" : "3차승급자가 클릭시 엘리트보스[모카딘]등장!!", "mob" : ["『정예』다크 코니언", "『정예』레드 와이번"], "karta" : "Victoria", "chance" : ["2.5%", "2.5%"] }, "I0JC" : { "icon" : "<img class='icon' src='https://i.imgur.com/CylQyNi.png' alt='I0JC' />", "name" : "메소 더미[10]", "type" : "기타", "effects" : "메소 + 150000", "mob" : ["『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["5x 100%"] }, "I0FO" : { "icon" : "<img class='icon' src='https://i.imgur.com/wt0o8KS.png' alt='I0FO' />", "name" : "메이플[30]", "type" : "기타", "effects" : "메이플 + 30", "mob" : ["『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["5x 100%"] }, "I0J7" : { "icon" : "<img class='icon' src='https://i.imgur.com/w2a9vjB.png' alt='I0J7' />", "name" : "[레시피]머리위에유령", "type" : "기타", "effects" : ["[모험맵에서만가능]", " 연금술사에게 레시피합성 하기 누르시면됩니다.", "메이플오라+Max,다크세라핌+Max 중 하나와 레시피와 합성시 파풀라투스의유령 으로 변경됩니다."], "mob" : ["『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["5%"] }, "I0IC" : { "icon" : "<img class='icon' src='https://i.imgur.com/6x3mOc3.png' alt='I0IC' />", "name" : "『재료』시간조각", "type" : "기타", "effects" : ["[아케인 심볼 조합아이템]"], "mob" : ["『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["60%"] }, "I0J6" : { "icon" : "<img class='icon' src='https://i.imgur.com/6x3mOc3.png' alt='I0J6' />", "name" : "『변질된 타키온』", "type" : "기타", "effects" : ["조합재료"], "mob" : ["『카오스』파풀라투스2"], "karta" : "Victoria", "chance" : ["30%|20%|10%"] }, "I092" : { "icon" : "<img class='icon' src='https://i.imgur.com/6jYNGGY.png' alt='I092' />", "name" : "[이벤트][STR]연금술사의반지", "type" : "장신구", "effects" : ["HP:10000 갯수마다. 1단위마다. 공격력2000/HP10000씩 증가합니다. 5단위 갯수마다. STR + 500이 됩니다.", "[이벤트인벤토리]에 장착해주세요."], "mob" : ["[파퀘]알리샤르", "[파퀘]파파픽시", "『파퀘』파라오", "『파퀘』드래곤 라이더"], "karta" : "Victoria", "chance" : ["10%", "15%", "20%", "25%"] }, "I093" : { "icon" : "<img class='icon' src='https://i.imgur.com/6jYNGGY.png' alt='I093' />", "name" : "[이벤트][DEX]연금술사의반지", "type" : "장신구", "effects" : ["HP:4500/MP4500 갯수마다. 1단위마다. 공격력2000/HP/MP4500씩 증가합니다. 5단위 갯수마다. DEX + 500이 됩니다.", "[이벤트인벤토리]에 장착해주세요."], "mob" : ["[파퀘]알리샤르", "[파퀘]파파픽시", "『파퀘』파라오", "『파퀘』드래곤 라이더"], "karta" : "Victoria", "chance" : ["10%", "15%", "20%", "25%"] }, "I094" : { "icon" : "<img class='icon' src='https://i.imgur.com/6jYNGGY.png' alt='I094' />", "name" : "[이벤트][INT]연금술사의반지", "type" : "장신구", "effects" : ["HP:4500/MP:4500 갯수마다. 1단위마다 .공격력:2000/HP/MP4500씩 증가합니다. 5단위 갯수마다. INT + 500이 됩니다.", "[이벤트인벤토리]에 장착해주세요."], "mob" : ["[파퀘]알리샤르", "[파퀘]파파픽시", "『파퀘』파라오", "『파퀘』드래곤 라이더"], "karta" : "Victoria", "chance" : ["10%", "15%", "20%", "25%"] }, "I0I3" : { "icon" : "<img class='icon' src='https://i.imgur.com/8tjAT6l.png' alt='I0I3' />", "name" : "[할로윈]메이플 블랙 두손검", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "팔라딘이 공격시 10% 확률로 STR*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I1" : { "icon" : "<img class='icon' src='https://i.imgur.com/JVZUmeT.png' alt='I0I1' />", "name" : "[할로윈]메이플 블랙 보우", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "보우마스터가 공격 마법사용시 10% 확률로 DEX*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I5" : { "icon" : "<img class='icon' src='https://i.imgur.com/JVZUmeT.png' alt='I0I5' />", "name" : "[할로윈]메이플 블랙 보우", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "보우마스터가 공격 마법사용시 10% 확률로 DEX*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I2" : { "icon" : "<img class='icon' src='https://i.imgur.com/cfRqqE1.png' alt='I0I2' />", "name" : "[할로윈]메이플 블랙 아대", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "나이트로드가 공격 마법사용시 10% 확률로 DEX*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I4" : { "icon" : "<img class='icon' src='https://i.imgur.com/B2epqRn.png' alt='I0I4' />", "name" : "[할로윈]메이플 블랙 완드", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "비숍이 공격 마법사용시 10% 확률로 INT*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I0" : { "icon" : "<img class='icon' src='https://i.imgur.com/cycqgd3.png' alt='I0I0' />", "name" : "[할로윈]메이플 블랙 커터", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "시프마스터가 공격 마법사용시 10%확률로 DEX*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I6" : { "icon" : "<img class='icon' src='https://i.imgur.com/mPq1jDr.png' alt='I0I6' />", "name" : "[할로윈]메이플 블랙 폴암", "type" : "무기", "effects" : ["[이벤트 인벤토리에 장착해주세요.]", "다크나이트가 착용시 공격시 10% 확률로 STR*7 데미지를 줍니다.", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "str" : "999", "dex" : "999", "int" : "999" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0MQ" : { "icon" : "<img class='icon' src='https://i.imgur.com/pmymBoE.png' alt='I0MQ' />", "name" : "[한정]도깨비 방망이", "type" : "무기", "effects" : ["특수능력:피격시 6%확률로 지진발동! 적에게 HP10% 만큼 데미지를 줍니다.", "특수능력:공격시 3%확률로 금나와라 뚝딱 발동!! 자신 메소만큼 * 10 데미지를 줍니다"], "stats" : { "reqlvl" : "1", "atk" : "50000", "hp" : "100만", "str" : "5000", "dex" : "5000", "int" : "5000" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0MP" : { "icon" : "<img class='icon' src='https://i.imgur.com/Sw3Chad.png' alt='I0MP' />", "name" : "[한정]도깨비 망토", "type" : "장비", "effects" : ["[특수효과: 피격시5%확률로 공격한 유닛에게 LV*1500 데미지를 줍니다.]"], "stats" : { "str" : "4000", "dex" : "4000", "int" : "4000" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0MO" : { "icon" : "<img class='icon' src='https://i.imgur.com/Az0ls7K.png' alt='I0MO' />", "name" : "[한정]도깨비 감투", "type" : "장비", "effects" : ["피격시 1%확률로 HP 10만을 회복합니다."], "stats" : { "str" : "2500", "dex" : "2500", "int" : "2500", "hp" : "300000", "mp" : "300000" }, "mob" : ["에픽보스 도전[파우스트]"], "karta" : "Victoria", "chance" : ["1.5%"] }, "I0I7" : { "icon" : "<img class='icon' src='https://i.imgur.com/PGY9OmQ.png' alt='I0I7' />", "name" : "[할로윈]박쥐 커플", "type" : "장비", "effects" : ["아이템사용시 Lv.1*1000 만큼 영웅 HP 회복[쿨타임:200초]", "설명:『할로윈 이벤트 아이템 완전정복!!』"], "stats" : { "hp" : "25만", "mp" : "25만" }, "mob" : ["에픽보스 도전[타이머]"], "karta" : "Victoria", "chance" : ["1.8%"] }, "I0HZ" : { "icon" : "<img class='icon' src='https://i.imgur.com/dOJ8uFu.png' alt='I0HZ' />", "name" : "[메달]할로윈 메달", "type" : "장비", "effects" : ["[이벤트 인벤토리에 장착해주세요.수고하셨습니다.]"], "stats" : { "str" : "4444", "dex" : "4444", "int" : "4444" }, "mob" : ["에픽보스 도전[세르프]"], "karta" : "Victoria", "chance" : ["1.8%"] }, "I0MS" : { "icon" : "<img class='icon' src='https://i.imgur.com/RRu2cUT.png' alt='I0MS' />", "name" : "[한정]무공의 장갑", "type" : "장비", "effects" : ["공격시3%확률로 30배 크리티컬 데미지를 줍니다.", "특수효과:공격시 15% 확률로 정예,Boss,Riad몬스터 에게 자신 주스텟* 30 만큼 데미지를 줍니다.", "특수효과:공격시:0.1%확률로 HP:30만씩 회복시켜줍니다."], "stats" : { "reqlvl" : "1", "str" : "45000", "dex" : "45000", "int" : "45000", "atkspd" : "50" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["1.7%"] }, "I0MR" : { "icon" : "<img class='icon' src='https://i.imgur.com/5OXfHaA.png' alt='I0MR' />", "name" : "[한정]무공 검은허리띠", "type" : "장비", "effects" : ["특수효과: 피격시 15%확률로 정예,Boss,Riad몬스터에게 자신 HP60% 데미지를 줍니다.", "특수효과:피격시 3%확률로 HP:30만씩 회복시켜줍니다."], "stats" : { "reqlvl" : "1", "str" : "45000", "dex" : "45000", "int" : "45000", "hp" : "200만", "mp" : "200만" }, "mob" : ["『Boss』포장마차"], "karta" : "Victoria", "chance" : ["1.7%"] }, "I046" : { "icon" : "<img class='icon' src='https://i.imgur.com/IMW3yE8.png' alt='I046' />", "name" : "- 2차승급- 영웅의 글라디우스", "type" : "기타", "mob" : "『RAID』마왕 발록", "karta" : "Victoria", "chance" : "2x 100%" }, "I0GH" : { "icon" : "<img class='icon' src='https://i.imgur.com/19FHLWR.png' alt='I0GH' />", "name" : "[유니크]베인 롱보우", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 DEX*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "1800", "hp" : "20000", "dex" : "400", "crit" : "5%*10" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I0BW" : { "icon" : "<img class='icon' src='https://i.imgur.com/TICQPEH.png' alt='I0BW' />", "name" : "[유니크]베인 단검", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 DEX*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "4000", "hp" : "50000", "dex" : "200", "atkspd" : "10" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I049" : { "icon" : "<img class='icon' src='https://i.imgur.com/TICQPEH.png' alt='I049' />", "name" : "[유니크]베인 바이터", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 DEX*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "4000", "hp" : "50000", "dex" : "200", "atkspd" : "10" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I04C" : { "icon" : "<img class='icon' src='https://i.imgur.com/pra3ub4.png' alt='I04C' />", "name" : "[유니크]베인 스워드", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 STR*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "1300", "hp" : "25000", "str" : "500", "hpreg" : "150" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I04A" : { "icon" : "<img class='icon' src='https://i.imgur.com/C1V7WT9.png' alt='I04A' />", "name" : "[유니크]베인 폴암", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 STR*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "4000", "hp" : "50000", "str" : "200", "crit" : "25% 확률로 7배+추뎀 15000" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I04B" : { "icon" : "<img class='icon' src='https://i.imgur.com/FDU6HQe.png' alt='I04B' />", "name" : "[유니크]베인 윙즈", "type" : "장비", "effects" : ["아이템 사용시 발록 메테오시전 INT*30", "[설명:마왕발록 원정대 성공 증표]"], "stats" : { "reqlvl" : "500", "atk" : "1500", "mp" : "50000", "int" : "400", "mpreg" : "40%" }, "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["3% (1 항목 만)"] }, "I03E" : { "icon" : "<img class='icon' src='https://i.imgur.com/FSNqxaM.png' alt='I03E' />", "name" : "[치장]마왕발록 날개", "type" : "치장", "effects" : ["[치장 인벤토리에 장착해주세요.]", "자신 이동속도 +50"], "mob" : ["『RAID』마왕 발록"], "karta" : "Victoria", "chance" : ["1%"] }, "I047" : { "icon" : "<img class='icon' src='https://i.imgur.com/A1M5rfH.png' alt='I047' />", "name" : "『마왕 발록의털』", "type" : "기타", "mob" : "『RAID』마왕 발록", "karta" : "Victoria", "chance" : "3x 100%" }, "I0C8" : { "icon" : "<img class='icon' src='https://i.imgur.com/XdaYDAx.png' alt='I0C8' />", "name" : "『소울조각:마왕발록』", "type" : "기타", "mob" : "『RAID』마왕 발록", "karta" : "Victoria", "chance" : "10%" }, "I06J" : { "icon" : "<img class='icon' src='https://i.imgur.com/pqxcxwk.png' alt='I06J' />", "name" : "『루디통행증』2", "type" : "기타", "mob" : "[파퀘]블록골렘", "karta" : "Victoria", "chance" : "3x 100%" }, "I077" : { "icon" : "<img class='icon' src='https://i.imgur.com/YUK3bvc.png' alt='I077' />", "name" : "『알리샤르의 열쇠』", "type" : "기타", "mob" : "[파퀘]알리샤르", "karta" : "Victoria", "chance" : "10x 100%" }, "I0FI" : { "icon" : "<img class='icon' src='https://i.imgur.com/haz40wT.png' alt='I0FI' />", "name" : "[유니크]금이 간 안경", "type" : "장비", "effects" : ["60초마다.마법방어시전", "[설명]: 찬란하도다.."], "stats" : { "reqlvl" : "1000", "str" : "220", "dex" : "220", "int" : "220", "hp" : "40000", "mp" : "40000" }, "mob" : ["[파퀘]알리샤르"], "karta" : "Victoria", "chance" : ["10%"] }, "I06P" : { "icon" : "<img class='icon' src='https://i.imgur.com/Zm0yqES.png' alt='I06P' />", "name" : "『마법의씨앗』", "type" : "기타", "mob" : "[파퀘]네펜더스", "karta" : "Victoria", "chance" : "3x 100%" }, }
export default (sheetCount) => { let lines = `<?xml version="1.0" ?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` for (let i = 1; i <= sheetCount; i++) { lines += ` <Relationship Id="SheetId`+i+`" Target="worksheets/sheet`+i+`.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"/>` } lines += ` </Relationships>` return lines }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), User = mongoose.model('User'); /** * Extend user's controller */ module.exports = _.extend( require('./users/users.authentication.server.controller'), require('./users/users.authorization.server.controller'), require('./users/users.password.server.controller'), require('./users/users.profile.server.controller') );
/** * Control that will zoom to a specific place. */ (function(L, w, undefined) { L.Control.ZoomerButton = L.Control.extend({ options: { position: 'topleft', place: [0, 0], zoom: 4, title: 'Zoom into a place' }, onAdd: function (map) { this._map = map; var className = 'leaflet-control-zoomer-button'; var container = L.DomUtil.create('div', className); this._createButton(this.options.title, className + '-button', container, this._zoomMap, this); return container; }, _createButton: function (title, className, container, fn, context) { var link = L.DomUtil.create('a', className, container); link.href = '#'; link.title = title; L.DomEvent.addListener(link, 'click', L.DomEvent.stopPropagation); L.DomEvent.addListener(link, 'click', L.DomEvent.preventDefault); L.DomEvent.addListener(link, 'click', fn, context); return link; }, _zoomMap: function (event) { this._map.setView(this.options.place, this.options.zoom); } }); })(L, window);
angular.module('authService', []) // =================================================== // auth factory to login and get information // inject $http for communicating with the API // inject $q to return promise objects // inject AuthToken to manage tokens // =================================================== .factory('Auth', function($http, $q, AuthToken) { // create auth factory object var authFactory = {}; // log a user in authFactory.login = function(username, password) { // return the promise object and its data return $http.post('/api/authenticate', { username: username, password: password }) .success(function(data) { if(!data.token) alert("Error logging. No token "+data.token); AuthToken.setToken(data.token); return data; }) .error(function(xhr, statusmsg, err) { alert("Error logging in "+statusmsg+" "+err); }); }; // log a user out by clearing the token authFactory.logout = function() { // clear the token AuthToken.setToken(); }; // check if a user is logged in // checks if there is a local token authFactory.isLoggedIn = function() { if (AuthToken.getToken()) return true; else return false; }; // get the logged in user authFactory.getUser = function() { if (AuthToken.getToken()) return $http.get('/api/me', { cache: true }); else return $q.reject({ message: 'User has no token.' }); }; authFactory.createSampleUser = function() { $http.post('/api/sample'); }; // return auth factory object return authFactory; }) // =================================================== // factory for handling tokens // inject $window to store token client-side // =================================================== .factory('AuthToken', function($window) { var authTokenFactory = {}; // get the token out of local storage authTokenFactory.getToken = function() { return $window.localStorage.getItem('token'); }; // function to set token or clear token // if a token is passed, set the token // if there is no token, clear it from local storage authTokenFactory.setToken = function(token) { if (token) $window.localStorage.setItem('token', token); else $window.localStorage.removeItem('token'); }; return authTokenFactory; }) // =================================================== // application configuration to integrate token into requests // =================================================== .factory('AuthInterceptor', function($q, $location, AuthToken) { var interceptorFactory = {}; // this will happen on all HTTP requests interceptorFactory.request = function(config) { // grab the token var token = AuthToken.getToken(); // if the token exists, add it to the header as x-access-token if (token) config.headers['x-access-token'] = token; return config; }; // happens on response errors interceptorFactory.responseError = function(response) { // if our server returns a 403 forbidden response if (response.status == 403) { AuthToken.setToken(); $location.path('/login'); } // return the errors from the server as a promise return $q.reject(response); }; return interceptorFactory; });
import angular from 'angular'; import resourceModule from '../resource/resource-module'; import RandomImage from './random-image-service'; import randomImageComponent from './random-image-component'; const dependencies = [ resourceModule.name ]; export default angular .module('app.randomImage', dependencies) .service('randomImage', RandomImage) .component('randomImg', randomImageComponent);
export default class IW { constructor() { } }
// @flow weak import {FormControl, ControlLabel, FormGroup} from "react-bootstrap"; import React from 'react'; import type {Exercise} from '../types'; export function FieldGroup({id, label, help, ...props}) { // eslint-disable-next-line return ( <FormGroup controlId={id}> <ControlLabel>{label}</ControlLabel> <FormControl {...props} /> {help} </FormGroup> ); } export function exerciseLabel(exercise: Exercise): string { return exercise.device + ' - ' + exercise.name; }
/// <reference path="../ts_definitions/xsockets.ts" /> var Xsockets; (function (Xsockets) { var Geo; (function (Geo) { var Connection = (function () { function Connection(map) { this.map = map; this.isOpen = false; this.openConnection(); this.attachEvents(); } Connection.prototype.openConnection = function () { var _this = this; this.connection = new xsockets.client(this.map.XSocketsUrl, ["FenceController"]); this.controller = this.connection.controller("Fence"); this.controller.onOpen = function () { _this.isOpen = true; }; this.connection.open(); }; Connection.prototype.attachEvents = function () { var _this = this; this.controller.on("fencenotice", function (data) { console.log(data); }); this.controller.on("withinfence", function (data) { _this.map.colorPin(data.Id, data.IsInside); }); }; Connection.prototype.testPoint = function (id, point) { this.controller.invoke("withinfence", { id: id, geoJson: point }); }; Connection.prototype.setchannel = function (channel) { this.set("setchannel", channel); }; Connection.prototype.setFence = function (fence) { this.set("setfence", fence); }; Connection.prototype.set = function (invoke, value) { var _this = this; if (this.isOpen) { this.controller.invoke(invoke, value); } else { setTimeout(function () { _this.set(invoke, value); }, 50); } }; return Connection; }()); Geo.Connection = Connection; })(Geo = Xsockets.Geo || (Xsockets.Geo = {})); })(Xsockets || (Xsockets = {}));
if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } var crypto = require('crypto'), sqlite3 = require('sqlite3'); var db = new sqlite3.Database(__dirname + '/../data/db.sqlite3'); db.serialize(function() { db.run('CREATE TABLE IF NOT EXISTS puppies(id integer PRIMARY KEY, source ' + 'text(512), imageUrl text(512) unique null, videoUrl text(512) unique ' + 'null, title TEXT(512) null, ip_address TEXT(64) NOT NULL, approved ' + 'boolean not null default false)'); }); var selectApprovedStmt = 'SELECT * FROM puppies WHERE approved = \'t\'', selectUnapprovedStmt = 'SELECT * FROM puppies WHERE approved = \'f\'', selectAllStmt = 'SELECT * FROM puppies', selectRandom = 'SELECT * FROM puppies WHERE approved = \'t\' ORDER BY RANDOM() LIMIT 1', selectSpecific = 'SELECT * FROM puppies WHERE approved = \'t\' AND id = ? LIMIT 1', selectByImageVideo = 'SELECT * FROM puppies WHERE imageUrl = ? OR videoUrl = ? LIMIT 1', insert = 'INSERT INTO puppies (source, ip_address) VALUES (?, ?)', update = 'UPDATE puppies SET source = ?, imageUrl = ?, videoUrl = ?, title = ? WHERE id = ?', deleteStmt = 'DELETE FROM puppies WHERE id = ?'; module.exports = { byId: function (id, callback) { db.get(selectSpecific, id, function(err, row) { callback(row); }); }, byHash: function(hash) { }, randomPuppy: function (callback) { db.get(selectRandom, function(err, row) { callback(row); }); }, submit: function(url, ip, callback) { db.run(insert, url, ip, function(err) { callback(err === null, this.lastID); }); }, update: function(id, permalink, image, title) { var video = null; if(image.endsWith(".gif") || image.endsWith(".gifv")) { video = image.substring(0, image.lastIndexOf(".")); image = null; } db.get(selectByImageVideo, image, video, function(err, row) { console.log(image, video, err, row); if(err === null && row === undefined) { db.run(update, permalink, image, video, title, id); } else { db.run(deleteStmt, id); } }); } };
'use strict'; module.exports = { app: { title: 'DocADY', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'MongoDB, Express, AngularJS, Node.js' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js' ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
require.config({ baseUrl: '/lib' }); require(["modules/core"], function (sys) { sys.addPanel('Real Time Log',null,'/lib/system/panels/main.html'); });
const re = /([a-z-\s]*[a-z-])(\s+"([^"]*)")?/ export const parseDeclaration = (declaration) => { const match = declaration.value.match(re) declaration.axis = match[1].trim().replace(/\s+/g, '-') declaration.param = match[3] return declaration } export const preprocess = (ctx, next) => { ctx.css.rules.forEach((rule) => rule.declarations .filter((d) => d.property === 'should') .map(parseDeclaration) ) return next() }
var through = require('through2'); var Msg = require('./msg'); var kFieldSeparator = Msg.kFieldSeparator; // length of first field, it is always 8=FIX.#.#<SOH> var kFirstFieldLen = 10; var kChecksumFieldLen = 7; module.exports = function() { var buffer = ''; var stream = through.obj(function(chunk, enc, cb) { var self = this; buffer += chunk; while (buffer.length > 0) { // Step 1: Extract complete FIX message // If we don't have enough data to start extracting body length, wait for more data if (buffer.length < kFirstFieldLen + 14) { return cb(); } if (buffer.slice(0, 6) !== '8=FIX.' || buffer[7] !== '.' || buffer[9] !== kFieldSeparator) { var err = 'Invalid BeginString: ' + buffer.slice(0, kFirstFieldLen); return cb(new Error(err)); } // look for a field separator after the one after 8=FIX.#.#<SOH> var endTag9 = buffer.indexOf(kFieldSeparator, kFirstFieldLen); // don't have all of tag 9 yet if (endTag9 < 0) { // if we have seen 8=FIX.#.#|9=####? and have no end tag 9 // then the message is not valid // tag 9 can only have values 0-9999 if (buffer.length > 17) { var err = 'no valid BodyLength tag found in header: ' + buffer; return cb(new Error(err)); } return cb(); } if (buffer.slice(kFirstFieldLen, kFirstFieldLen + 2) !== '9=') { var err = 'Invalid BodyLength: ' + buffer.slice(kFirstFieldLen, endTag9); return cb(new Error(err)); } // get field separator after tag9 // if unable to get end of tag 9, we haven't received a full message yet // +2 for '9=' var body_len_str = buffer.slice(kFirstFieldLen + 2, endTag9); var body_len = body_len_str - 0; // as parsed above, BodyLength (tag 9) has a limit of 9999 (could be increased) if (isNaN(body_len) || body_len < 0 || body_len > 9999) { var err = 'Invalid BodyLength: ' + body_len_str; return cb(new Error(err)); } // make sure to include checksum field and trailing separator // so we can properly slice away this message from the buffer // endTag9 +1 for <SOH> after tag 9 var msg_len = body_len + endTag9 + 1 + kChecksumFieldLen; // don't have full message yet if (buffer.length < msg_len) { return cb(); } var msg = buffer.slice(0, msg_len); // buffer is what remains after current message is removed buffer = buffer.slice(msg_len); // get just message body without checksum field var msg_body = msg.slice(0, msg.length - kChecksumFieldLen); var expected_checksum = Msg.checksum(msg_body); var actual_checksum = msg.substr(msg.length - 4, 3); if (expected_checksum !== actual_checksum) { var err = 'Invalid CheckSum: ' + msg; return cb(new Error(err)); } // load up proper message type var msg = Msg.parse(msg); cb(null, msg); } }); return stream; }
import chai, {expect} from "chai"; import sinon from "sinon"; import sinonChai from "sinon-chai"; chai.use(sinonChai); import Socket from "../../src/socket"; class SocketConstructorMock { close () {} send () {} } describe("`Socket` class", () => { describe("`send` method", () => { it("sends a message through the `rawSocket`", () => { const socket = new Socket(); socket.rawSocket = { send: sinon.spy() }; socket.send({}); expect(socket.rawSocket.send).to.have.callCount(1); }); it("stringifies the object to send", () => { const socket = new Socket(); socket.rawSocket = { send: sinon.spy() }; const object = { a: "a" }; const expectedMessage = JSON.stringify(object); socket.send(object); expect(socket.rawSocket.send).to.have.been.calledWith(expectedMessage); }); it("emits a `message:out` event", () => { const socket = new Socket(); socket.rawSocket = { send: sinon.spy() }; socket.emit = sinon.spy(); const object = { a: "a" }; socket.send(object); expect(socket.emit).to.have.been.calledWith("message:out", object); }); }); describe("`open` method", () => { it("no-op if `rawSocket` is already defined", () => { const socket = new Socket(SocketConstructorMock); const rawSocket = {}; socket.rawSocket = rawSocket; socket.open(); // Test, for instance, that `rawSocket` has not been replaced. expect(socket.rawSocket).to.equal(rawSocket); }); it("instantiates a `SocketConstructor`", () => { const socket = new Socket(SocketConstructorMock); socket.open(); expect(socket.rawSocket).to.be.an.instanceOf(SocketConstructorMock); }); it("registers handlers for `rawSocket` events", () => { const socket = new Socket(SocketConstructorMock); socket.open(); expect(socket.rawSocket.onopen).to.be.a("function"); expect(socket.rawSocket.onclose).to.be.a("function"); expect(socket.rawSocket.onerror).to.be.a("function"); expect(socket.rawSocket.onmessage).to.be.a("function"); }); }); describe("`close` method", () => { it("closes the `rawSocket`", () => { const socket = new Socket(SocketConstructorMock); socket.open(); socket.rawSocket.close = sinon.spy(); socket.close(); expect(socket.rawSocket.close).to.have.callCount(1); }); it("doesn't throw if there's no `rawSocket`", () => { const socket = new Socket(SocketConstructorMock); const peacemaker = () => { socket.close(); }; expect(peacemaker).not.to.throw(); }); }); describe("`rawSocket` `onopen` handler", () => { it("emits an `open` event", () => { const socket = new Socket(SocketConstructorMock); const handler = sinon.spy(); socket.on("open", handler); socket.open(); socket.rawSocket.onopen(); expect(handler).to.have.callCount(1); }); }); describe("`rawSocket` `onclose` handler", () => { it("emits a `close` event", () => { const socket = new Socket(SocketConstructorMock); const handler = sinon.spy(); socket.on("close", handler); socket.open(); socket.rawSocket.onclose(); expect(handler).to.have.callCount(1); }); it("null-s the `rawSocket` property", () => { const socket = new Socket(SocketConstructorMock); socket.open(); socket.rawSocket.onclose(); expect(socket.rawSocket).to.equal(null); }); }); describe("`rawSocket` `onerror` handler", () => { it("closes `rawSocket` (by calling `rawSocket.close`)", () => { const socket = new Socket(SocketConstructorMock); socket.open(); const rawSocket = socket.rawSocket; rawSocket.close = sinon.spy(); socket.rawSocket.onerror(); expect(rawSocket.close).to.have.callCount(1); }); it("de-registers the `rawSocket.onclose` callback", () => { const socket = new Socket(SocketConstructorMock); socket.open(); const rawSocket = socket.rawSocket; expect(rawSocket).to.have.property("onclose"); socket.rawSocket.onerror(); expect(rawSocket).not.to.have.property("onclose"); }); it("emits a `close` event", () => { const socket = new Socket(SocketConstructorMock); const handler = sinon.spy(); socket.on("close", handler); socket.open(); socket.rawSocket.onerror(); expect(handler).to.have.callCount(1); }); it("null-s the `rawSocket` property", () => { const socket = new Socket(SocketConstructorMock); socket.open(); socket.rawSocket.onerror(); expect(socket.rawSocket).to.equal(null); }); }); describe("`rawSocket` `onmessage` handler", () => { it("parses message data into an object", () => { const socket = new Socket(SocketConstructorMock); sinon.stub(JSON, "parse"); socket.open(); socket.rawSocket.onmessage({data: "message"}); expect(JSON.parse).to.have.been.calledWith("message"); JSON.parse.restore(); }); it("ignores malformed messages", () => { const socket = new Socket(SocketConstructorMock); sinon.stub(JSON, "parse").throws(); socket.open(); expect(socket.rawSocket.onmessage).not.to.throw(); JSON.parse.restore(); }); it("emits `message:in` events", () => { const socket = new Socket(SocketConstructorMock); const handler = sinon.spy(); socket.on("message:in", handler); socket.open(); socket.rawSocket.onmessage({data: JSON.stringify({a: "a"})}); expect(handler).to.have.callCount(1); expect(handler).to.have.been.calledWith({a: "a"}); }); }); });
// PLUGIN: Popup (function ( Popcorn ) { var sounds = {}, events = [], soundIndex = 0, MAX_AUDIO_TIME = 2, _pluginRoot = "/plugins/icons/", FILL_STYLE = "rgb(255, 255, 255)", innerDivTriangles = {}, DEFAULT_FONT = "Tangerine"; // Set up speech innerDiv triangles innerDivTriangles.speech = document.createElement( "canvas" ); innerDivTriangles.thought = document.createElement( "canvas" ); // Creates a triangle for a speech innerDiv function drawSpeech( canvas, lineWidth ) { var ctx = canvas.getContext( "2d" ); ctx.save(); ctx.beginPath(); ctx.moveTo(0.4, 0.3); ctx.bezierCurveTo(0.4, 0.3, 17.8, 26.3, 15.1, 41.9); ctx.bezierCurveTo(15.1, 41.9, 26.2, 26.3, 23.4, 0.3); ctx.fillStyle = FILL_STYLE; ctx.fill(); ctx.lineWidth = lineWidth; ctx.stroke(); ctx.restore(); } // Creates three innerDivs for a "thought" speech innerDiv function drawThought( canvas, lineWidth ) { var ctx = canvas.getContext( "2d" ); // circle1 ctx.save(); ctx.beginPath(); ctx.moveTo(13.5, 7.0); ctx.bezierCurveTo(13.5, 10.6, 10.6, 13.5, 7.0, 13.5); ctx.bezierCurveTo(3.4, 13.5, 0.5, 10.6, 0.5, 7.0); ctx.bezierCurveTo(0.5, 3.4, 3.4, 0.5, 7.0, 0.5); ctx.bezierCurveTo(10.6, 0.5, 13.5, 3.4, 13.5, 7.0); ctx.closePath(); ctx.fillStyle = FILL_STYLE; ctx.fill(); ctx.lineWidth = lineWidth; ctx.stroke(); // circle2 ctx.beginPath(); ctx.moveTo(17.5, 23.8); ctx.bezierCurveTo(17.5, 26.1, 15.6, 28.0, 13.2, 28.0); ctx.bezierCurveTo(10.9, 28.0, 9.0, 26.1, 9.0, 23.8); ctx.bezierCurveTo(9.0, 21.4, 10.9, 19.5, 13.2, 19.5); ctx.bezierCurveTo(15.6, 19.5, 17.5, 21.4, 17.5, 23.8); ctx.closePath(); ctx.fill(); ctx.lineWidth = lineWidth; ctx.stroke(); // circle3 ctx.beginPath(); ctx.moveTo(27.5, 31.8); ctx.bezierCurveTo(27.5, 33.5, 26.0, 35.0, 24.2, 35.0); ctx.bezierCurveTo(22.5, 35.0, 21.0, 33.5, 21.0, 31.8); ctx.bezierCurveTo(21.0, 30.0, 22.5, 28.5, 24.2, 28.5); ctx.bezierCurveTo(26.0, 28.5, 27.5, 30.0, 27.5, 31.8); ctx.closePath(); ctx.fill(); ctx.lineWidth = lineWidth; ctx.stroke(); ctx.restore(); } drawSpeech( innerDivTriangles.speech, 2 ); drawThought( innerDivTriangles.thought, 2 ); Popcorn.plugin( "popup", { manifest: { about: { name: "Popcorn Maker Popup Plugin", version: "0.1", author: "Kate Hudson @k88hudson, Matthew Schranz @mjschranz, Brian Chirls @bchirls", website: "http://github.com/k88hudson, http://github.com/mjschranz, https://github.com/brianchirls/" }, options: { start: { elem: "input", type: "number", label: "In", "units": "seconds" }, end: { elem: "input", type: "number", label: "Out", "units": "seconds" }, text: { elem: "textarea", label: "Text", "default": "Pop!" }, linkUrl: { elem: "input", type: "text", label: "Link URL" }, type: { elem: "select", options: [ "Popup", "Speech", "Thought Bubble" ], values: [ "popup", "speech", "thought" ], label: "Type", "default": "popup" }, triangle: { elem: "select", options: [ "Top Left", "Top Right", "Bottom Left", "Bottom Right" ], values: [ "top left", "top right", "bottom left", "bottom right" ], label: "Tail Position", "default": "bottom left", optional: true }, sound: { elem: "input", type: "checkbox", label: "Sound", "default": false, optional: true }, icon: { elem: "select", options: [ "Error", "Audio", "Broken Heart", "Cone", "Earth", "Eye", "Heart", "Info", "Man", "Money", "Music", "Net", "Skull", "Star", "Thumbs Down", "Thumbs Up", "Time", "Trophy", "Tv", "User", "Virus", "Women", "None" ], values: [ "error", "audio", "brokenheart", "cone", "earth", "eye", "heart", "info", "man", "money", "music", "net", "skull", "star", "thumbsdown", "thumbsup", "time", "trophy", "tv", "user", "virus", "women", "none" ], label: "Pop Icon", "default": "error", optional: true }, flip: { elem: "input", type: "checkbox", label: "Flip Tail?", "default": false, optional: true }, top: { elem: "input", type: "number", label: "Top", units: "%", "default": 5, hidden: true }, left: { elem: "input", type: "number", label: "Left", units: "%", "default": 20, hidden: true }, width: { elem: "input", type: "number", units: "%", label: "Width", "default": 30, hidden: true }, transition: { elem: "select", options: [ "None", "Pop", "Fade", "Slide Up", "Slide Down" ], values: [ "popcorn-none", "popcorn-pop", "popcorn-fade", "popcorn-slide-up", "popcorn-slide-down" ], label: "Transition", "default": "popcorn-fade" }, fontFamily: { elem: "select", label: "Font", styleClass: "", googleFonts: true, "default": "Merriweather", group: "advanced" }, // font size is deprecated fontSize: { elem: "input", type: "number", label: "Font Size", units: "px", group: "advanced" }, fontPercentage: { elem: "input", type: "number", label: "Font Size", "default": 4, units: "%", group: "advanced" }, fontColor: { elem: "input", type: "color", label: "Font colour", "default": "#668B8B", group: "advanced" }, fontDecorations: { elem: "checkbox-group", labels: { bold: "Bold", italics: "Italics", underline: "Underline" }, "default": { bold: false, italics: false, underline: false }, group: "advanced" }, zindex: { hidden: true } } }, _setup: function( options ) { var target = document.getElementById( options.target ), container = document.createElement( "div" ), context = this, audio, width = options.width + "%", top = options.top + "%", left = options.left + "%", fontSheet, originalFamily = options.fontFamily, flip = options.flip ? " flip" : "", innerDiv = document.createElement( "div" ), textContainer = document.createElement( "div" ), link = document.createElement( "a" ), img, TRIANGLE_WIDTH = 40, TRIANGLE_HEIGHT = 60, text = options.text.replace( /\r?\n/gm, "<br>" ), innerSpan = document.createElement( "span" ), linkUrl = options.linkUrl; if ( !target ) { target = context.media.parentNode; } options._target = target; function selectAudio( id, sources ) { var i, j, event, diff, eligibleAudio, audio, source; function resetAudio() { this.currentTime = 0; this.pause(); } if ( !sounds[ id ] ) { audio = document.createElement( "audio" ); for ( i = 0; i < sources.length; i ++ ) { source = document.createElement( "source" ); source.src = _pluginRoot + sources[ i ]; audio.appendChild( source ); } audio.id = "popcorn-pop-sound-" + soundIndex; soundIndex++; audio.preload = true; audio.style.display = "none"; audio.addEventListener( "ended", resetAudio, false ); document.body.appendChild( audio ); sounds[ id ] = [ audio ]; return audio; } audio = sounds[ id ][ 0 ]; if ( audio.duration ) { diff = Math.min( audio.duration, MAX_AUDIO_TIME ); } else { diff = MAX_AUDIO_TIME; } //make sure there are no other events using this sound at the same time eligibleAudio = sounds[ id ].slice( 0 ); for ( i = 0; i < events.length; i++ ) { event = events[ i ]; if ( event.sound === options.sound && event.start <= options.start + diff && event.start + diff >= options.start ) { j = eligibleAudio.indexOf( event.audio ); if ( j >= 0 ) { eligibleAudio.splice( j, 1 ); } } } if ( eligibleAudio.length ) { audio = eligibleAudio[ 0 ]; } else { audio = sounds[ id ][ 0 ].cloneNode( true ); audio.id = "popcorn-pop-sound-" + soundIndex; soundIndex++; // not sure whether cloning copies the events in all browsers, // so remove it and add again just in case audio.removeEventListener( "ended", resetAudio, false ); audio.addEventListener( "ended", resetAudio, false ); document.body.appendChild( audio ); sounds[ id ].push( audio ); } return audio; } function makeTriangle( innerDiv ) { var triangle, ctx; //Set the base classes innerDiv.className = "speechBubble " + options.type + " " + options.triangle + " " + flip; triangle = document.createElement( "canvas" ); ctx = triangle.getContext( "2d" ); triangle.width = TRIANGLE_WIDTH; triangle.height = TRIANGLE_HEIGHT; triangle.className = "canvas"; innerDiv.appendChild( triangle ); //Draw according to the style if ( options.type === "speech" ) { triangle.getContext( "2d" ).drawImage( innerDivTriangles.speech, 0, 0 ); } if ( options.type === "thought" ) { triangle.getContext( "2d" ).drawImage( innerDivTriangles.thought, 0, 0 ); } } //makeTriangle container.style.position = "absolute"; container.style.top = top; container.style.left = left; container.style.width = width; container.style.zIndex = +options.zindex; innerDiv = document.createElement( "div" ); textContainer = document.createElement( "div" ); textContainer.style.fontStyle = options.fontDecorations.italics ? "italic" : "normal"; textContainer.style.color = options.fontColor ? options.fontColor : "#668B8B"; textContainer.style.textDecoration = options.fontDecorations.underline ? "underline" : "none"; if ( options.fontSize ) { textContainer.style.fontSize = options.fontSize + "px"; } else { textContainer.style.fontSize = options.fontPercentage + "%"; } textContainer.style.fontWeight = options.fontDecorations.bold ? "bold" : "normal"; if ( linkUrl ) { if ( !linkUrl.match( /^http(|s):\/\// ) ) { linkUrl = "//" + linkUrl; } link = document.createElement( "a" ); link.href = linkUrl; link.target = "_blank"; link.innerHTML = text; link.addEventListener( "click", function() { context.media.pause(); }, false ); link.style.color = textContainer.style.color; innerSpan.appendChild( link ); } else { innerSpan.innerHTML = text; } textContainer.appendChild( innerSpan ); innerDiv.appendChild( textContainer ); container.appendChild( innerDiv ); if ( options.type === "popup" ) { innerDiv.classList.add( "popup-inner-div" ); container.classList.add( "popcorn-popup" ); if ( options.icon && options.icon !== "none" ) { img = document.createElement( "img" ); img.setAttribute( "class", "popup-icon" ); img.addEventListener( "load", function() { var width = img.width || img.naturalWidth, height = img.height || img.naturalHeight; if ( options.fontSize ) { if ( height > 60 ) { width = 60 * width / height; height = 60; img.style.width = width + "px"; } img.style.left = -( width - 16 ) + "px"; // make sure container is still non-null // if _teardown is called too quickly, it will become null before img loads if ( container && container.offsetHeight ) { img.style.top = ( container.offsetHeight - height ) / 2 - 4 + "px"; } } else { img.classList.add( "popcorn-responsive-image-position" ); } if ( container ) { container.insertBefore( img, container.firstChild ); } }, false ); img.src = _pluginRoot + "images/" + options.icon + ".png"; } //load up sound. if ( options.sound ) { if ( !audio ) { audio = selectAudio( "popup", [ "sounds/mouthpop.ogg", "sounds/mouthpop.wav" ] ); options.audio = audio; } } } else { makeTriangle( innerDiv ); } // Add transition container.classList.add( options.transition ); container.classList.add( "off" ); target.appendChild( container ); options._container = container; fontSheet = document.createElement( "link" ); fontSheet.rel = "stylesheet"; fontSheet.type = "text/css"; options.fontFamily = options.fontFamily ? options.fontFamily : options._natives.manifest.options.fontFamily[ "default" ]; // Store reference to generated sheet for removal later, remove any existing ones options._fontSheet = fontSheet; document.head.appendChild( fontSheet ); fontSheet.onload = function () { // Apply all the styles textContainer.style.fontFamily = options.fontFamily ? originalFamily : DEFAULT_FONT; }; fontSheet.href = "//fonts.googleapis.com/css?family=" + options.fontFamily.replace( /\s/g, "+" ); options.toString = function() { return options.text || options._natives.manifest.options.text[ "default" ]; }; }, start: function( event, options ) { var audio = options.audio, video = this.media, container = options._container, redrawBug; if ( container ) { container.classList.add( "on" ); container.classList.remove( "off" ); // Safari Redraw hack - #3066 container.style.display = "none"; redrawBug = container.offsetHeight; container.style.display = ""; } if ( audio && audio.duration && !video.paused && video.currentTime - 1 < options.start ) { audio.volume = video.volume; audio.muted = video.muted; audio.play(); if ( !audio.duration || isNaN( audio.duration ) || audio.duration > MAX_AUDIO_TIME ) { setTimeout(function() { audio.currentTime = 0; audio.pause(); }, MAX_AUDIO_TIME ); } } }, end: function( event, options ) { if ( options._container ) { options._container.classList.add( "off" ); options._container.classList.remove( "on" ); } }, _teardown: function( options ) { if ( options._container && options._target ) { options._target.removeChild( options._container ); } if ( options._fontSheet ) { document.head.removeChild( options._fontSheet ); } } }); }( Popcorn ));
function NIL() {} Ember.Model.Store = Ember.Service.extend({ modelFor: function(type) { var owner = Ember.getOwner(this); return owner._lookupFactory('model:'+type); }, adapterFor: function(type) { var adapter = this.modelFor(type).adapter, owner = Ember.getOwner(this); var serializer = this.serializerFor(type); if (adapter && adapter.constructor !== Ember.Adapter) { adapter.set('serializer', serializer); return adapter; } else { adapter = owner._lookupFactory('adapter:'+ type) || owner._lookupFactory('adapter:application') || Ember.RESTAdapter; return adapter ? adapter.create({serializer:serializer}) : adapter; } }, serializerFor: function(type) { var owner = Ember.getOwner(this); var serializer = owner._lookupFactory('serializer:'+ type) || owner._lookupFactory('serializer:application') || Ember.JSONSerializer; return serializer ? serializer.create() : serializer; }, createRecord: function(type, props) { var klass = this.modelFor(type); var owner = Ember.getOwner(this); klass.reopenClass({adapter: this.adapterFor(type)}); var record = klass.create(props); Ember.setOwner(record, owner); return record; }, find: function(type, id) { if (arguments.length === 1) { id = NIL; } return this._find(type, id, true); }, _find: function(type, id, async) { var klass = this.modelFor(type); // if (!klass.adapter) { klass.reopenClass({adapter: this.adapterFor(type)}); // } var owner = Ember.getOwner(this); if (id === NIL) { return klass._findFetchAll(async, owner); } else if (Ember.isArray(id)) { return klass._findFetchMany(id, async, owner); } else if (typeof id === 'object') { return klass._findFetchQuery(id, async, owner); } else { return klass._findFetchById(id, async, owner); } }, _findSync: function(type, id) { return this._find(type, id, false); } }); Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function() { var application = arguments[1] || arguments[0]; var store = application.Store || Ember.Model.Store; application.register('service:store', store); application.inject('route', 'store', 'service:store'); application.inject('controller', 'store', 'service:store'); } }); });
var User = require('../models/user'); var Project = require('../models/project'); var Request = require('../models/request'); var ff = require('ff'); module.exports = function(app) { app.get('/users/:userId', function(req, res) { var f = ff(function() { User.findOne({ _id: req.params.userId }).exec(f.slot()); }, function(user) { if (!user) { return res.status(400).send({}); } var alreadyConnected = user.collaborators.concat(user.pendingRequestUsers); User.find({ _id: { $ne: user._id, $nin: alreadyConnected } }).exec(f.slot()); }, function(users) { if (!users) { res.send({}); } else { res.send(users); } }).onError(function(err) { console.log(err.stack); }).onSuccess(function() { console.log('success'); }); }); app.delete('/users/:userId', function(req, res) { User.remove({ _id: req.params.userId }).exec(function(err) { if (err) { console.log(err); } res.status(200).send('completed'); }); }); app.get('/users/:userId/projects', function(req, res) { var f = ff(function() { User.findOne({ _id: req.params.userId }).exec(f.slot()); }, function(user) { if (!user) { return res.status(400).send('no user found'); } Project.find({ contributers: user._id }).exec(f.slot()); }, function(projects) { if (!projects) { return res.send({}); } res.send(projects); }).onError(function(err) { console.log(err); }).onSuccess(function() { console.log('success fetching user projects'); }); }); };
/* * Init shell script module */ (function(global, $) { var codiad = global.codiad; codiad.shellScript = { controller: 'components/shell_script/controller.php', dialog: 'components/shell_script/dialog.php', ////////////////////////////////////////////////////////////////// // Analyze source code ////////////////////////////////////////////////////////////////// analyzeCode: function() { // Run controller to analyze source code of client $.get(this.controller + '?action=analyze_code', function(data) { var analyzeReponse = codiad.jsend.parse(data); if (analyzeReponse !== 'error') { $.msgBox({ title:i18n("Information"), content:i18n("Your request to analyze code is in processing. You will receive the analysis result by mail."), type:"info" }); codiad.message.success(i18n(analyzeReponse)); } else { $.msgBox({ title:i18n("Too many requests in progress"), content:i18n("Too many requests of analyzing code is in processing. Please retry in few minutes later."), type:"error" }); } }); }, ////////////////////////////////////////////////////////////////// // Deploy application ////////////////////////////////////////////////////////////////// deployApp: function() { $.msgBox({ title:i18n("Information"), content:i18n("Your request to deploy application is in processing. You will receive deployment result by mail."), type:"info" }); // Run controller to deploy application $.get(this.controller + '?action=deploy_app', function(data) { var deployReponse = codiad.jsend.parse(data); if (deployReponse !== 'error') { codiad.message.success(i18n(deployReponse)); } }); }, ////////////////////////////////////////////////////////////////// // Finish exam ////////////////////////////////////////////////////////////////// finishExam: function() { $.msgBox({ title:i18n("Information"), content:i18n("This function is not available in this version"), type:"info" }); // Run controller to finish exam //$.get(this.controller + '?action=finish_exam', function(data) { // var testResponse = codiad.jsend.parse(data); // testResponse = testResponse.join('\n'); // if (testResponse !== 'error') { // alert(testResponse.toString()); // codiad.message.success('Exam finished'); // } else { // codiad.message.error('ERROR'); // } //}); }, ////////////////////////////////////////////////////////////////// // Commit active file ////////////////////////////////////////////////////////////////// commit: function() { var _this = this; $.get(this.controller+'?action=check_commit'); codiad.modal.load(600, this.dialog + '?action=load'); $('#modal-content form').live('submit', function(e) { e.preventDefault(); var selectedFiles = $('#txt_selected_files').val(); var commitMessage = $.trim($('textarea[name=commit_message]').val()); $.get(_this.controller + '?action=commit&list=' + selectedFiles + '&message=' + commitMessage, function(data) { var commitResponse = codiad.jsend.parse(data); if (commitResponse !== 'error') { codiad.message.success(i18n(commitResponse)); } }); codiad.modal.unload(); }); }, ////////////////////////////////////////////////////////////////// // Test command line from GUI ////////////////////////////////////////////////////////////////// test: function() { // Run controller to test command line $.get(this.controller + '?action=test_command', function(data) { var testResponse = codiad.jsend.parse(data); testResponse = testResponse.join('\n'); if (testResponse !== 'error') { $.msgBox({ title:"Information", content:testResponse.toString(), type:"info" }); codiad.message.success('Run command with success'); } else { codiad.message.error('ERROR'); } }); } }; })(this, jQuery);
var Actor = function() { this.maxMovementSpeed = 60; this.slashSpeedReduction = 0.5; //speed is capped at max times this when slashing this.acceleration = 256; this.macheteCooldown = 0.4; this.macheteDamage = 1; this.slashAlternatingState = false; this.slashTimer = 0; this.ignoreSpeedMultAbove = 1; this.currentMacheteCooldown = 0; this.queueSwingMachete = false; this.transform = new THREE.Object3D(); GameEngine.scene.add(this.transform); this.velocity = new Vector2(); this.direction = 0; this.desiredMovement = new Vector2(); this.timeToNextFrame = 0; this.currentFrame = 0; // create slashing vfx this.slashParent = new THREE.Object3D(); this.transform.add(this.slashParent); this.slashParent.position.set(0,0,0); this.slashMesh0 = new THREE.Mesh(Actor.slashVfxGeo, Actor.slashVfxMaterials[0]); this.slashParent.add(this.slashMesh0); this.slashMesh0.position.set(20,0,-20); this.slashMesh0.visible = false; this.slashMesh1 = new THREE.Mesh(Actor.slashVfxGeo, Actor.slashVfxMaterials[1]); this.slashParent.add(this.slashMesh1); this.slashMesh1.position.set(20,0,-20); this.slashMesh1.visible = false; } Actor.slashVfxGeo = bmacSdk.GEO.makeSpriteGeo(33,23); Actor.slashVfxMaterials = [ new THREE.MeshBasicMaterial({ map:bmacSdk.GEO.loadPixelTexture("media/vfx_slash1.png"), transparent:true }), new THREE.MeshBasicMaterial({ map:bmacSdk.GEO.loadPixelTexture("media/vfx_slash2.png"), transparent:true }), ] Actor.frameTime = 0.05; Actor.slashVfxLifetime = 0.25; Actor.macheteSounds = [ "media/118792__lmbubec__1-knife-slash-a.wav" ]; Actor.rustleSounds= [ "media/223160__yoyodaman234__grass-footstep-2.wav", "media/223159__yoyodaman234__grass-footstep-3.wav", "media/223169__yoyodaman234__grass-footstep-4.wav", ]; // multiplier on Y movement to account for the iso camera angle Actor.yMotionMultiplier = 1 / Math.sqrt(2); Actor.prototype.update = function() { // cool down machete if (this.currentMacheteCooldown > 0) { this.currentMacheteCooldown -= bmacSdk.deltaSec; } // swing machete if you attempted to do so during the cooldown if (this.queueSwingMachete && this.currentMacheteCooldown <= 0) { this.swingMachete(); } if (this.desiredMovement.x !== 0) { // accelerate this.velocity.x += this.desiredMovement.x * this.acceleration * bmacSdk.deltaSec; this.velocity.x = Math.clamp(this.velocity.x, -this.maxMovementSpeed, this.maxMovementSpeed); } else if (this.velocity.x !== 0) { // decelerate to 0 var oldSig = Math.sign(this.velocity.x); this.velocity.x -= oldSig * this.acceleration * bmacSdk.deltaSec; if (Math.sign(this.velocity.x) !== oldSig) { this.velocity.x = 0; } } if (this.desiredMovement.y !== 0) { // accelerate this.velocity.y += this.desiredMovement.y * this.acceleration * bmacSdk.deltaSec; this.velocity.y = Math.clamp(this.velocity.y, -this.maxMovementSpeed, this.maxMovementSpeed); } else if (this.velocity.y !== 0) { // decelerate to 0 var oldSig = Math.sign(this.velocity.y); this.velocity.y -= oldSig * this.acceleration * bmacSdk.deltaSec; if (Math.sign(this.velocity.y) !== oldSig) { this.velocity.y = 0; } } var velX = this.velocity.x; var velY = this.velocity.y; var lastPosX = this.transform.position.x; var lastPosY = this.transform.position.y; // cap velocity while slashing if (this.slashTimer <= this.macheteCooldown) { velX *= this.slashSpeedReduction; velY *= this.slashSpeedReduction; } // cap velocity moving in growth var currentTile = sampleGame.tileManager.getTileAtWorld(this.transform.position.x, this.transform.position.y); if (currentTile instanceof tile) { var growthSpeedMult = growthKey[currentTile.growthLevel].speedMultiplier; if (growthSpeedMult > this.ignoreSpeedMultAbove) growthSpeedMult = 1; velX *= growthSpeedMult; velY *= growthSpeedMult; } // move based on the desired movement this.transform.position.x += velX * bmacSdk.deltaSec; this.transform.position.y += velY * bmacSdk.deltaSec * Actor.yMotionMultiplier; // if we moved into a blocked tile, move back /*var newTileX = sampleGame.tileManager.worldToTileX(this.transform.position.x); var newTileY = sampleGame.tileManager.worldToTileY(this.transform.position.y); var newTile = sampleGame.tileManager.getTile(newTileX, newTileY); if (newTile != currentTile && terainKey[newTile.terrainType].blocking) { var tileLeft = sampleGame.tileManager.tileToWorldX(newTileX) - tilePixelWidth/2; var tileRight = tileLeft + tilePixelWidth; var tileTop = sampleGame.tileManager.tileToWorldY(newTileY) - tilePixelHeight; var tileBottom = tileTop + tilePixelHeight; //top //console.log(tileLeft + "," + tileTop + " / " + tileRight + "," + tileBottom); //console.log(lastPosX + "," + lastPosY + " / " + this.transform.position.x + "," + this.transform.position.y); if (lineIntersection(lastPosX, lastPosY, this.transform.position.x, this.transform.position.y, tileLeft, tileTop, tileRight, tileTop)) { this.transform.position.y = tileTop-0.1; } //bottom if (lineIntersection(lastPosX, lastPosY, this.transform.position.x, this.transform.position.y, tileLeft, tileBottom, tileRight, tileBottom)) { this.transform.position.y = tileBottom+0.1; } //left if (lineIntersection(lastPosX, lastPosY, this.transform.position.x, this.transform.position.y, tileLeft, tileTop, tileLeft, tileBottom)) { this.transform.position.x = tileLeft-0.1; } //right if (lineIntersection(lastPosX, lastPosY, this.transform.position.x, this.transform.position.y, tileRight, tileTop, tileRight, tileBottom)) { this.transform.position.x = tileRight+0.1; } }*/ // restrict in bounds this.transform.position.x = Math.clamp(this.transform.position.x, sampleGame.getWorldBoundsMinX(), sampleGame.getWorldBoundsMaxX()); this.transform.position.y = Math.clamp(this.transform.position.y, sampleGame.getWorldBoundsMinY(), sampleGame.getWorldBoundsMaxY()); // reset desired movement this.desiredMovement.x = this.desiredMovement.y = 0; // determine walk direction if (Math.abs(this.velocity.x) > 0.5 || Math.abs(this.velocity.y) > 0.5) { if (Math.abs(this.velocity.x) < Math.abs(this.velocity.y)) { if (this.velocity.y < 0) this.direction = 0; else this.direction = 2; } else { if (this.velocity.x < 0) this.direction = 3; else this.direction = 1; } } // rotate the vfx parent this.slashParent.rotation.z = Math.PI * (this.direction-1) / 2; // advance walk animation if (this.velocity.x !== 0 || this.velocity.y !== 0) { this.timeToNextFrame -= bmacSdk.deltaSec; if (this.timeToNextFrame <= 0) { this.timeToNextFrame = Actor.frameTime; this.currentFrame++; while (this.currentFrame >= 9) this.currentFrame -= 9; if (this.geometry) { var tiledir = this.direction; if (this.direction == 1)tiledir=3; else if (this.direction == 3)tiledir=1; bmacSdk.GEO.setTilesheetGeometry(this.geometry, this.currentFrame, tiledir, 9, 4); } } } // hide slash vfx var lastSlashTimer = this.slashTimer; this.slashTimer += bmacSdk.deltaSec; if (lastSlashTimer < Actor.slashVfxLifetime && this.slashTimer >= Actor.slashVfxLifetime) { this.slashMesh0.visible = this.slashMesh1.visible = false; } } Actor.prototype.getFacingX = function() { if (this.direction == 1) return 1; else if (this.direction == 3) return -1; else return 0; } Actor.prototype.getFacingY = function() { if (this.direction == 0) return -1; else if (this.direction == 2) return 1; else return 0; } Actor.prototype.swingMachete = function() { if (this.currentMacheteCooldown > 0) { //this.queueSwingMachete = true; } else { // execute machete swing this.queueSwingMachete = false; var didHit = false; // try to hit the tile I am on var myTile = sampleGame.tileManager.getTileAtWorld(this.transform.position.x, this.transform.position.y); if (myTile.growthLevel > 0) { myTile.growthLevel = Math.max(0, myTile.growthLevel - this.macheteDamage); myTile.drawGrowth(); sampleGame.spawnLeafPlume(myTile.growthMesh.position.x, myTile.growthMesh.position.y); didHit = true; } // try to hit the tile I am facing myTile = sampleGame.tileManager.getTileAtWorld( this.transform.position.x + this.getFacingX() * tilePixelWidth, this.transform.position.y + this.getFacingY() * tilePixelHeight); if (myTile.growthLevel > 0) { myTile.growthLevel = Math.max(0, myTile.growthLevel - this.macheteDamage); myTile.drawGrowth(); sampleGame.spawnLeafPlume(myTile.growthMesh.position.x, myTile.growthMesh.position.y); didHit = true; } //TODO: also try to hit things slightly to the left and right this.slashMesh0.visible = !this.slashAlternatingState; this.slashMesh1.visible = this.slashAlternatingState; this.slashTimer = 0; if (this.isPlayer) { sampleGame.playSoundFallOff(Actor.macheteSounds, 0.13, this.transform.position); } if (didHit) { sampleGame.playSoundFallOff(Actor.rustleSounds, this.isPlayer ? 0.6 : 0.15, this.transform.position); } this.slashAlternatingState = !this.slashAlternatingState; this.currentMacheteCooldown = this.macheteCooldown; } }
/** * Reset Text */ module.exports = function (decl) { var fontFamily = 'sans-serif'; var lineHeight = '1.5'; decl.replaceWith({ prop: 'font-family', value: fontFamily, source: decl.source }, { prop: 'font-style', value: 'normal', source: decl.source }, { prop: 'font-weight', value: 'normal', source: decl.source }, { prop: 'letter-spacing', value: 'normal', source: decl.source }, { prop: 'line-break', value: 'auto', source: decl.source }, { prop: 'line-height', value: lineHeight, source: decl.source }, { prop: 'text-align', value: 'left', source: decl.source }, { prop: 'text-align', value: 'start', source: decl.source }, { prop: 'text-decoration', value: 'none', source: decl.source }, { prop: 'text-shadow', value: 'none', source: decl.source }, { prop: 'text-transform', value: 'none', source: decl.source }, { prop: 'white-space', value: 'normal', source: decl.source }, { prop: 'word-break', value: 'normal', source: decl.source }, { prop: 'word-spacing', value: 'normal', source: decl.source }, { prop: 'word-wrap', value: 'normal', source: decl.source }); };
import Ember from 'ember'; import { initialize } from 'ember-eureka/initializers/eureka-db-init'; var container, application; module('EurekaDbInitInitializer', { setup: function() { Ember.run(function() { application = Ember.Application.create(); container = application.__container__; application.deferReadiness(); }); } }); // Replace this with your real tests. test('it works', function() { initialize(container, application); // you would normally confirm the results of the initializer here ok(true); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { return this.applyWithWalker(new NoFsPathWalker(sourceFile, this.getOptions())); } } Rule.FAILURE_STRING = "Do not use Uri.fsPath or TextDocument.fileName because they lowercase Windows drive letters causing issues with interop with other tools. Use fsPath(uri) instead."; class NoFsPathWalker extends Lint.RuleWalker { visitPropertyAccessExpression(node) { // TODO: Figure out how to get parent type to avoid false positives. if (node.name.text === "fsPath" || node.name.text === "fileName") { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } super.visitPropertyAccessExpression(node); } } exports.Rule = Rule;
(function(module) { mifosX.controllers = _.extend(module, { ViewCodeController: function(scope, routeParams , resourceFactory, location ) { scope.codevalues = []; resourceFactory.codeResources.get({codeId: routeParams.id} , function(data) { scope.code = data; }); resourceFactory.codeValueResource.getAllCodeValues({codeId: routeParams.id} , function(data) { scope.codevalues = data; }); scope.delcode = function(){ resourceFactory.codeResources.remove({codeId: routeParams.id},this.code,function(data){ location.path('/codes'); }); } } }); mifosX.ng.application.controller('ViewCodeController', ['$scope', '$routeParams','ResourceFactory','$location', mifosX.controllers.ViewCodeController]).run(function($log) { $log.info("ViewCodeController initialized"); }); }(mifosX.controllers || {}));
(function (window, angular) { "use strict"; var module = angular.module('player', []); module.factory('player', [function () { var player; return { set: function (data) { player = data; }, get: function () { return player; } }; } ]); })(window, window.angular);
/** * Foreach Statement Processor for the CellScript Parser */ var parserUtils = require("../../../library/parser/utils"), validators = parserUtils.validators, constants = parserUtils.constants; /// methods /// var utils = { foreach_: function(state) { state.next(); //Skip foreach keyword. }, segmentStart: function(state) { if(!validators.isSegmentStart(state)) return state.error(constants.unexpectedToken); state.next(); //Skip segment start. }, var_: function(state) { //if(!validators.isLet(state)) return state.error(constants.unexpectedToken); //state.next(); //Skip let keyword. if(validators.isVar(state)) { state.item.scope = "local"; state.next(); //Skip var keyword. } else if(validators.isLet(state)) { state.item.scope = "block"; state.next(); //Skip var keyword. } else { state.item.scope = "global"; } }, name: function(state) { if(!validators.isIdentifier(state)) return state.error(constants.unexpectedToken); state.item.name = state.token.data; state.next(); }, in_: function(state) { if(!validators.isIn(state)) return state.error(constants.unexpectedToken); state.next(); // Skip semicolon. }, expression: function(state) { state.item.expression = {}; state.prepareLeaf(state.item.expression); if(!state.expressionProcessor.token(state, ["expression"])) return state.error(constants.unexpectedToken); state.clearLeaf(); }, segmentEnd: function(state) { if(!validators.isSegmentEnd(state)) return state.error(constants.unexpectedToken); state.next(); //Skip segment end. }, statement: function(state) { state.item.statement = {}; state.levelDown("iteration"); state.prepareLeaf(state.item.statement); state.processor.token(state); state.clearLeaf(); state.levelUp(); } }; /// public interface /// module.exports = { name: "plus/foreach.js", tokenType: "keyword/"+constants.foreachKeyword, canProcess: function(state) { return validators.isForeach(state); }, process: function(state) { state.leaf(); state.item.type = "iteration"; state.item.subtype = "foreach"; utils.foreach_(state); utils.segmentStart(state); utils.var_(state); utils.name(state); utils.in_(state); utils.expression(state); utils.segmentEnd(state); utils.statement(state); } };
module("page") test("page testing works", function(){ ok(true,"an assert is run") })
import { pageHeaderImageVersions, tshirtImageVersions, imageVersionProps } from './fragments' export default ` ${imageVersionProps} ${pageHeaderImageVersions} ${tshirtImageVersions} query($kind: PageHeaderKind!, $slug: String) { pageHeaders(kind: $kind, slug: $slug) { id kind slug header subheader postToken ctaLink { text url } image { ...pageHeaderImageVersions } category { id } user { id username avatar { ...tshirtImageVersions } } } } `
class Collapse { constructor () { this.props = { 'enter-active-class': 'ant-motion-collapse ant-motion-collapse-active', 'leave-active-class': 'ant-motion-collapse ant-motion-collapse-active' } this.on = { beforeEnter (el) { el.style.height = 0 el.style.opacity = 0 }, enter (el) { el.style.height = `${el.scrollHeight}px` el.style.opacity = 1 }, afterEnter (el) { el.style.height = '' el.style.opacity = '' }, beforeLeave (el) { el.style.height = `${el.offsetHeight}px` el.style.opacity = 1 }, leave (el) { el.scrollHeight && (el.style.height = 0) }, afterLeave (el) { el.style.height = '' el.style.opacity = '' } } } } export default Collapse
var SKUNAMICPU=SKUNAMICPU||{version:"1.0.0"};console.log("Using SKUNAMICPU "+SKUNAMICPU.version);SKUNAMICPU.Obstacle=function(a){this.mesh=a;this.updateAlways=!1;this.update()};SKUNAMICPU.Obstacle.prototype.update=function(){throw Error("Abstract method not implemented");};SKUNAMICPU.Obstacle.prototype.updateObstacleField=function(a){throw Error("Abstract method not implemented");};SKUNAMICPU.Obstacle.prototype.updateFlowObstaclesField=function(a){throw Error("Abstract method not implemented");}; SKUNAMICPU.VoxelizedObstacle=function(a,d,c,b,e){this.voxelizer=new SKVOXCPU.Voxelizer(a,d,c,b,e);SKUNAMICPU.Obstacle.call(this,a)};SKUNAMICPU.VoxelizedObstacle.prototype=Object.create(SKUNAMICPU.Obstacle.prototype);SKUNAMICPU.VoxelizedObstacle.prototype.constructor=SKUNAMICPU.VoxelizedObstacle;SKUNAMICPU.VoxelizedObstacle.prototype.update=function(){this.voxelizer.updateIntersections()}; SKUNAMICPU.VoxelizedObstacle.prototype.updateObstacleField=function(a){this.updateAlways&&this.update();var d=a.mesh.geometry.vertices,c,b,e,f,h;for(e=this.voxelizer.__xMinMultiple;e<=this.voxelizer.__xMaxMultiple+this.voxelizer.__EPSILON;e+=this.voxelizer.voxelSizeX)for(f=this.voxelizer.__zMinMultiple;f<=this.voxelizer.__zMaxMultiple+this.voxelizer.__EPSILON;f+=this.voxelizer.voxelSizeZ)(b=this.voxelizer.intersectionFirstAndLastHeights)&&b[e]&&b[e][f]&&(c=b[e][f][0],b=b[e][f][1],h=a.__calcVertexId(e, f),d[h]&&c<d[h].y&&b>d[h].y&&(a.obstacleField[h]=0))}; SKUNAMICPU.VoxelizedObstacle.prototype.updateFlux=function(a){this.updateAlways&&this.update();var d,c,b,e,f,h,g;for(b=this.voxelizer.__xMinMultiple;b<=this.voxelizer.__xMaxMultiple+this.voxelizer.__EPSILON;b+=this.voxelizer.voxelSizeX)for(e=this.voxelizer.__zMinMultiple;e<=this.voxelizer.__zMaxMultiple+this.voxelizer.__EPSILON;e+=this.voxelizer.voxelSizeZ)(c=this.voxelizer.intersectionFirstAndLastHeights)&&c[b]&&c[b][e]&&(d=c[b][e][0],c=c[b][e][1],f=a.__calcVertexId(b,e),h=f-1,g=a.baseHeights[h]+ a.heights[h],d<g&&c>g&&(a.fluxR[h]=0),h=f+1,g=a.baseHeights[h]+a.heights[h],d<g&&c>g&&(a.fluxL[h]=0),h=f-a.res,g=a.baseHeights[h]+a.heights[h],d<g&&c>g&&(a.fluxB[h]=0),h=f+a.res,g=a.baseHeights[h]+a.heights[h],d<g&&c>g&&(a.fluxT[h]=0))};SKUNAMICPU.TerrainObstacle=function(a){this.intersectionHeights=[];SKUNAMICPU.Obstacle.call(this,a)};SKUNAMICPU.TerrainObstacle.prototype=Object.create(SKUNAMICPU.Obstacle.prototype);SKUNAMICPU.TerrainObstacle.prototype.constructor=SKUNAMICPU.TerrainObstacle; SKUNAMICPU.TerrainObstacle.prototype.update=function(){var a=this.mesh.geometry.vertices,d,c;d=0;for(c=a.length;d<c;d++)this.intersectionHeights[d]=[],this.intersectionHeights[d].push(0),this.intersectionHeights[d].push(a[d].y)}; SKUNAMICPU.TerrainObstacle.prototype.updateObstacleField=function(a){this.updateAlways&&this.update();var d=a.mesh.geometry.vertices,c,b,e,f;e=0;for(f=a.res*a.res;e<f;e++)this.intersectionHeights[e]&&(c=this.intersectionHeights[e][0],b=this.intersectionHeights[e][1],c<d[e].y&&b>d[e].y&&(a.obstacleField[e]=0))};SKUNAMICPU.TerrainObstacle.prototype.updateFlux=function(a){}; SKUNAMICPU.DepthMapObstacleManager={depthMapSize:10,depthMapRes:512,depthMapNear:-2,depthMapFar:2,init:function(){this.__loadScene();this.__prepareDepthMapImageElements()},update:function(){this.depthMapRenderer.autoClear=!1;this.depthMapRenderer.clear();this.depthMapRenderer.render(this.depthMapScene,this.depthMapCamera);this.$depthMapImageObj[0].src=this.depthMapRenderer.domElement.toDataURL()},addObstacle:function(a){var d=new THREE.Mesh(a.geometry,new THREE.MeshDepthMaterial({side:THREE.DoubleSide, overdraw:!0}));d.position=a.position;d.rotation=a.rotation;d.scale=a.scale;this.depthMapScene.add(d)},getObstacleDepthMap:function(){return this.obstacleDepthMapCanvasElemContext.getImageData(0,0,this.depthMapRes,this.depthMapRes).data},__loadScene:function(){if(!this.depthMapRenderer){this.depthMapRenderer=new THREE.CanvasRenderer({antialias:!0});this.depthMapRenderer.setSize(this.depthMapRes,this.depthMapRes);this.depthMapRenderer.setClearColor("#000000",1);this.obstacleDepthMapCanvasElemContext= this.depthMapRenderer.domElement.getContext("2d");this.depthMapScene=new THREE.Scene;var a=this.depthMapSize/2;this.depthMapCamera=new THREE.OrthographicCamera(-a,a,-a,a,this.depthMapNear,this.depthMapFar);this.depthMapCamera.rotation.x=THREE.Math.degToRad(90);this.depthMapCamera.position.y=0}},__prepareDepthMapImageElements:function(){this.$depthMapImageObj||(this.$depthMapImageObj=$(new Image),this.$depthMapImageObj[0].src=this.depthMapRenderer.domElement.toDataURL(),this.$depthMapImageObj.css({position:"fixed", top:"55px",left:0}),$("body").append(this.$depthMapImageObj))}}; SKUNAMICPU.HeightFieldWater=function(a){if("undefined"===typeof a.mesh)throw Error("mesh not specified");this.mesh=a.mesh;if("undefined"===typeof a.size)throw Error("size not specified");this.size=a.size;this.halfSize=this.size/2;if("undefined"===typeof a.res)throw Error("res not specified");this.res=a.res;if("undefined"===typeof a.dampingFactor)throw Error("dampingFactor not specified");this.dampingFactor=a.dampingFactor;this.__meanHeight=a.meanHeight||0;this.geometry=this.mesh.geometry;this.numVertices= this.res*this.res;if(this.numVertices!==this.geometry.vertices.length)throw Error("Number of vertices in mesh does not match res*res");this.segmentSize=this.size/this.res;this.segmentSizeSquared=this.segmentSize*this.segmentSize;this.obstacles={};this.sourceField=[];this.disturbField=[];this.obstacleField=[];this.verticalVelField=[];this.obstaclesActive=!0;this.__worldMatInv=new THREE.Matrix4;this.__localPos=new THREE.Vector3;this.init()}; SKUNAMICPU.HeightFieldWater.prototype.init=function(){var a;for(a=0;a<this.numVertices;a++)this.sourceField[a]=0,this.disturbField[a]=0,this.obstacleField[a]=1,this.verticalVelField[a]=0};SKUNAMICPU.HeightFieldWater.prototype.update=function(a){if(this.obstaclesActive){var d=Object.keys(this.obstacles),c,b,e=d.length;for(b=0;b<e;b++)c=this.obstacles[d[b]],c.updateObstacleField(this)}this.sim(a);this.__clearFields()}; SKUNAMICPU.HeightFieldWater.prototype.sim=function(a){throw Error("Abstract method not implemented");};SKUNAMICPU.HeightFieldWater.prototype.setMeanHeight=function(a){this.__meanHeight=a;a=this.geometry.vertices;var d=this.res-1,c,b,e;for(c=b=0;c<this.res;c++)e=c*this.res+b,a[e].y=this.__meanHeight;b=d;for(c=0;c<this.res;c++)e=c*this.res+b,a[e].y=this.__meanHeight;c=0;for(b=1;b<d;b++)e=c*this.res+b,a[e].y=this.__meanHeight;c=d;for(b=1;b<d;b++)e=c*this.res+b,a[e].y=this.__meanHeight}; SKUNAMICPU.HeightFieldWater.prototype.__calcVertexId=function(a,d){return Math.floor((d+this.halfSize)/this.size*this.res)*this.res+Math.floor((a+this.halfSize)/this.size*this.res)};SKUNAMICPU.HeightFieldWater.prototype.disturb=function(a,d){this.__worldMatInv.getInverse(this.mesh.matrixWorld);this.__localPos.copy(a).applyMatrix4(this.__worldMatInv);var c=this.__calcVertexId(this.__localPos.x,this.__localPos.z);this.disturbById(c,d)}; SKUNAMICPU.HeightFieldWater.prototype.disturbById=function(a,d){this.disturbField[a]=d};SKUNAMICPU.HeightFieldWater.prototype.disturbNeighbours=function(a,d){this.__worldMatInv.getInverse(this.mesh.matrixWorld);this.__localPos.copy(a).applyMatrix4(this.__worldMatInv);var c=this.__calcVertexId(this.__localPos.x,this.__localPos.z);this.disturbNeighboursById(c,d)}; SKUNAMICPU.HeightFieldWater.prototype.disturbNeighboursById=function(a,d){var c=this.geometry.vertices,b=a+this.res;c[b]&&this.disturbById(b,d);b=a-this.res;c[b]&&this.disturbById(b,d);b=a+1;c[b]&&this.disturbById(b,d);b=a-1;c[b]&&this.disturbById(b,d)}; SKUNAMICPU.HeightFieldWater.prototype.source=function(a,d,c){this.__worldMatInv.getInverse(this.mesh.matrixWorld);this.__localPos.copy(a).applyMatrix4(this.__worldMatInv);var b,e;for(a=-c;a<=c;a+=this.segmentSize)for(e=-c;e<=c;e+=this.segmentSize)b=Math.sqrt(a*a+e*e),b<c&&(b=this.__calcVertexId(this.__localPos.x+a,this.__localPos.z+e),this.sourceById(b,d))};SKUNAMICPU.HeightFieldWater.prototype.sourceById=function(a,d){this.sourceField[a]=d}; SKUNAMICPU.HeightFieldWater.prototype.flood=function(a){var d,c,b;for(d=0;d<this.res;d++)for(c=0;c<this.res;c++)b=d*this.res+c,this.disturbField[b]+=a/(this.res*this.res)}; SKUNAMICPU.HeightFieldWater.prototype.addObstacle=function(a,d){if(!(a instanceof SKUNAMICPU.Obstacle))throw Error("obstacle must be of type SKUNAMICPU.Obstacle");if("string"!==typeof d)throw Error("name must be of type string");if(-1!==Object.keys(this.obstacles).indexOf(d))throw Error("obstacle name already exists: "+d);this.obstacles[d]=a};SKUNAMICPU.HeightFieldWater.prototype.setObstaclesActive=function(a){this.obstaclesActive=a}; SKUNAMICPU.HeightFieldWater.prototype.reset=function(){var a,d=this.geometry.vertices;for(a=0;a<this.numVertices;a++)d[a].y=this.__meanHeight;this.__clearFields()};SKUNAMICPU.HeightFieldWater.prototype.__clearFields=function(){var a;for(a=0;a<this.numVertices;a++)this.sourceField[a]=0,this.disturbField[a]=0,this.obstacleField[a]=1}; SKUNAMICPU.HeightFieldWater.prototype.__updateMesh=function(){this.geometry.verticesNeedUpdate=!0;this.geometry.computeFaceNormals();this.geometry.computeVertexNormals();this.geometry.normalsNeedUpdate=!0};SKUNAMICPU.MuellerGdc2008HwWater=function(a){SKUNAMICPU.HeightFieldWater.call(this,a)};SKUNAMICPU.MuellerGdc2008HwWater.prototype=Object.create(SKUNAMICPU.HeightFieldWater.prototype);SKUNAMICPU.MuellerGdc2008HwWater.prototype.constructor=SKUNAMICPU.MuellerGdc2008HwWater; SKUNAMICPU.MuellerGdc2008HwWater.prototype.sim=function(a){var d,c,b=this.geometry.vertices,e=this.res-1;for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,b[c].y+=this.disturbField[c],b[c].y=(b[c].y-this.__meanHeight)*this.obstacleField[c]+this.__meanHeight;for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,this.verticalVelField[c]+=(b[(a-1)*this.res+d].y+b[(a+1)*this.res+d].y+b[a*this.res+(d-1)].y+b[a*this.res+(d+1)].y)/4-b[c].y,this.verticalVelField[c]*=this.dampingFactor;for(a=1;a<e;a++)for(d=1;d<e;d++)c= a*this.res+d,b[c].y+=this.verticalVelField[c];this.__updateMesh()};SKUNAMICPU.MuellerGdc2008Water=function(a){SKUNAMICPU.HeightFieldWater.call(this,a);if("undefined"===typeof a.horizontalSpeed)throw Error("horizontalSpeed not specified");this.horizontalSpeed=a.horizontalSpeed;this.horizontalSpeedSquared=this.horizontalSpeed*this.horizontalSpeed};SKUNAMICPU.MuellerGdc2008Water.prototype=Object.create(SKUNAMICPU.HeightFieldWater.prototype);SKUNAMICPU.MuellerGdc2008Water.prototype.constructor=SKUNAMICPU.MuellerGdc2008Water; SKUNAMICPU.MuellerGdc2008Water.prototype.sim=function(a){a=1/60;var d,c,b,e=this.geometry.vertices,f=this.res-1;for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,e[b].y+=this.disturbField[b],e[b].y=(e[b].y-this.__meanHeight)*this.obstacleField[b]+this.__meanHeight;var h;for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,h=this.horizontalSpeedSquared*(e[b+this.res].y+e[b-this.res].y+e[b+1].y+e[b-1].y-4*e[b].y)/this.segmentSizeSquared,this.verticalVelField[b]+=h*a,this.verticalVelField[b]*=this.dampingFactor; for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,e[b].y+=this.verticalVelField[b]*a;this.__updateMesh()};SKUNAMICPU.XWater=function(a){this.field1=[];this.field2=[];SKUNAMICPU.HeightFieldWater.call(this,a)};SKUNAMICPU.XWater.prototype=Object.create(SKUNAMICPU.HeightFieldWater.prototype);SKUNAMICPU.XWater.prototype.constructor=SKUNAMICPU.XWater;SKUNAMICPU.XWater.prototype.init=function(){var a;for(a=0;a<this.numVertices;a++)this.field1[a]=this.__meanHeight,this.field2[a]=this.__meanHeight;SKUNAMICPU.HeightFieldWater.prototype.init.call(this)}; SKUNAMICPU.XWater.prototype.reset=function(){var a;for(a=0;a<this.numVertices;a++)this.field1[a]=this.__meanHeight,this.field2[a]=this.__meanHeight;SKUNAMICPU.HeightFieldWater.prototype.reset.call(this)}; SKUNAMICPU.XWater.prototype.setMeanHeight=function(a){this.__meanHeight=a;var d=this.res-1,c,b,e;for(c=b=0;c<this.res;c++)e=c*this.res+b,this.field1[e]=this.__meanHeight,this.field2[e]=this.__meanHeight;b=d;for(c=0;c<this.res;c++)e=c*this.res+b,this.field1[e]=this.__meanHeight,this.field2[e]=this.__meanHeight;c=0;for(b=1;b<d;b++)e=c*this.res+b,this.field1[e]=this.__meanHeight,this.field2[e]=this.__meanHeight;c=d;for(b=1;b<d;b++)e=c*this.res+b,this.field1[e]=this.__meanHeight,this.field2[e]=this.__meanHeight; SKUNAMICPU.HeightFieldWater.prototype.setMeanHeight.call(this,a)}; SKUNAMICPU.XWater.prototype.sim=function(a){var d,c,b=this.geometry.vertices,e=this.res-1;for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,this.field1[c]+=this.disturbField[c],this.field1[c]=(this.field1[c]-this.__meanHeight)*this.obstacleField[c]+this.__meanHeight;for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,this.field2[c]=(this.field1[(a-1)*this.res+d]+this.field1[(a+1)*this.res+d]+this.field1[a*this.res+(d-1)]+this.field1[a*this.res+(d+1)])/2-this.field2[c],this.field2[c]=(this.field2[c]-this.__meanHeight)* this.dampingFactor+this.__meanHeight;for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,b[c].y=this.field2[c];this.__updateMesh();for(a=1;a<e;a++)for(d=1;d<e;d++)c=a*this.res+d,b=this.field2[c],this.field2[c]=this.field1[c],this.field1[c]=b}; SKUNAMICPU.TessendorfIWaveWater=function(a){this.prevHeight=[];this.vertDeriv=[];SKUNAMICPU.HeightFieldWater.call(this,a);if("undefined"===typeof a.kernelRadius)throw Error("kernelRadius not specified");this.kernelRadius=a.kernelRadius;if("undefined"===typeof a.substeps)throw Error("substeps not specified");this.substeps=a.substeps;this.gravity=-9.81;this.G={0:{1:0.6782766063331379,2:0.15642080318487095,3:-0.06532739057096157,4:-0.06444781066526209},1:{1:0.4445648954185427,2:0.07225753616898249,3:-0.07377485074364465, 4:-0.059964799734097914},2:{1:0.07225753616898249,2:-0.04993877689422348,3:-0.07593786512383575,4:-0.04726251879247821},3:{1:-0.07377485074364465,2:-0.07593786512383575,3:-0.05553701410671365,4:-0.031433210050842826},4:{1:-0.059964799734097914,2:-0.04726251879247821,3:-0.031433210050842826,4:-0.019006732548424117}}};SKUNAMICPU.TessendorfIWaveWater.prototype=Object.create(SKUNAMICPU.HeightFieldWater.prototype);SKUNAMICPU.TessendorfIWaveWater.prototype.constructor=SKUNAMICPU.TessendorfIWaveWater; SKUNAMICPU.TessendorfIWaveWater.prototype.init=function(){var a;for(a=0;a<this.numVertices;a++)this.prevHeight[a]=0,this.vertDeriv[a]=0;SKUNAMICPU.HeightFieldWater.prototype.init.call(this)};SKUNAMICPU.TessendorfIWaveWater.prototype.reset=function(){var a;for(a=0;a<this.numVertices;a++)this.prevHeight[a]=0,this.vertDeriv[a]=0;SKUNAMICPU.HeightFieldWater.prototype.reset.call(this)}; SKUNAMICPU.TessendorfIWaveWater.prototype.sim=function(a){a=1/60;var d;for(d=0;d<this.substeps;d++){var c,b,e,f=this.geometry.vertices,h=this.res-1;for(c=1;c<h;c++)for(b=1;b<h;b++)e=c*this.res+b,f[e].y+=this.disturbField[e],f[e].y=(f[e].y-this.__meanHeight)*this.obstacleField[e]+this.__meanHeight,f[e].y-=this.__meanHeight;this.__symmetricalConvolve();var g,k=2-this.dampingFactor*a,l=1+this.dampingFactor*a,m=this.gravity*a*a;for(c=1;c<h;c++)for(b=1;b<h;b++)e=c*this.res+b,g=f[e].y,f[e].y=(f[e].y*k- this.prevHeight[e]-this.vertDeriv[e]*m)/l,this.prevHeight[e]=g,f[e].y+=this.__meanHeight}this.__updateMesh()}; SKUNAMICPU.TessendorfIWaveWater.prototype.__symmetricalConvolve=function(){var a,d,c,b,e,f,h,g=this.geometry.vertices;a=this.kernelRadius;for(e=this.res-this.kernelRadius;a<e;a++)for(d=this.kernelRadius,f=this.res-this.kernelRadius;d<f;d++){h=a*this.res+d;this.vertDeriv[h]=g[h].y;c=0;for(b=1;b<=this.kernelRadius;b++)this.vertDeriv[h]+=this.G[c][b]*(g[(a+c)*this.res+(d+b)].y+g[(a+c)*this.res+(d-b)].y+g[(a+b)*this.res+(d+c)].y+g[(a-b)*this.res+(d+c)].y);for(c=1;c<=this.kernelRadius;c++)for(b=1;b<=this.kernelRadius;b++)this.vertDeriv[h]+= this.G[c][b]*(g[(a+c)*this.res+(d+b)].y+g[(a-c)*this.res+(d-b)].y+g[(a+c)*this.res+(d-b)].y+g[(a-c)*this.res+(d+b)].y)}}; SKUNAMICPU.TessendorfIWaveWater.prototype.__convolve=function(){var a,d,c,b,e,f,h,g=this.geometry.vertices;a=this.kernelRadius;for(e=this.res-this.kernelRadius;a<e;a++)for(d=this.kernelRadius,f=this.res-this.kernelRadius;d<f;d++)for(h=a*this.res+d,this.vertDeriv[h]=0,c=-this.kernelRadius;c<=this.kernelRadius;c++)for(b=-this.kernelRadius;b<=this.kernelRadius;b++)this.vertDeriv[h]+=this.G[c][b]*g[(a+c)*this.res+(d+b)].y}; SKUNAMICPU.HeightFieldWaterWithVel=function(a){this.vel=[];this.velColors=[];if("undefined"===typeof a.scene)throw Error("scene not specified");this.scene=a.scene;SKUNAMICPU.HeightFieldWater.call(this,a);this.minVisVel=a.minVisVel||0;this.maxVisVel=a.maxVisVel||0.25;this.minVisVelLength=a.minVisVelLength||0.02;this.maxVisVelLength=a.maxVisVelLength||1;this.lineStartColor=a.lineStartColor||new THREE.Color(26316);this.lineEndColor=a.lineEndColor||new THREE.Color(10092543);this.waterColor=a.waterColor|| new THREE.Color(26316);this.foamColor=a.foamColor||new THREE.Color(10092543);this.__faceIndices=["a","b","c","d"];this.__origMeshMaterialSettings={emissive:this.mesh.material.emissive.clone(),vertexColors:this.mesh.material.vertexColors};this.__visVelLines=this.__visVelColors=!1};SKUNAMICPU.HeightFieldWaterWithVel.prototype=Object.create(SKUNAMICPU.HeightFieldWater.prototype);SKUNAMICPU.HeightFieldWaterWithVel.prototype.constructor=SKUNAMICPU.HeightFieldWaterWithVel; SKUNAMICPU.HeightFieldWaterWithVel.prototype.init=function(){var a,d;a=0;for(d=this.mesh.geometry.vertices.length;a<d;a++)this.vel[a]=new THREE.Vector3,this.velColors[a]=new THREE.Color;var c=new THREE.Geometry;a=0;for(d=2*this.mesh.geometry.vertices.length;a<d;a++)c.vertices.push(new THREE.Vector3),0===a%2?c.colors.push(new THREE.Color(16777215)):c.colors.push(new THREE.Color(16711680));a=new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});this.velLinesMesh=new THREE.Line(c,a,THREE.LinePieces); this.scene.add(this.velLinesMesh);SKUNAMICPU.HeightFieldWater.prototype.init.call(this)};SKUNAMICPU.HeightFieldWaterWithVel.prototype.update=function(){SKUNAMICPU.HeightFieldWater.prototype.update.call(this);this.__visVelColors&&this.updateVelColors();this.__visVelLines&&this.updateVelLines()}; SKUNAMICPU.HeightFieldWaterWithVel.prototype.visualizeVelColors=function(a){(this.__visVelColors=a)?(this.mesh.material.emissive.set("#ffffff"),this.mesh.material.vertexColors=THREE.VertexColors):(this.mesh.material.emissive.set(this.__origMeshMaterialSettings.emissive),this.mesh.material.vertexColors=this.__origMeshMaterialSettings.vertexColors);this.mesh.geometry.buffersNeedUpdate=!0;this.mesh.material.needsUpdate=!0}; SKUNAMICPU.HeightFieldWaterWithVel.prototype.visualizeVelLines=function(a){this.__visVelLines=a;this.velLinesMesh.visible=a}; SKUNAMICPU.HeightFieldWaterWithVel.prototype.updateVelColors=function(){var a,d,c,b,e,f,h;a=0;for(d=this.geometry.faces.length;a<d;a++)for(c=this.geometry.faces[a],e=c instanceof THREE.Face3?3:4,b=0;b<e;b++)f=c[this.__faceIndices[b]],h=this.vel[f].length()/(this.maxVisVel-this.minVisVel)+this.minVisVel,h=THREE.Math.clamp(h,0,1),c.vertexColors[b]=this.velColors[f].set(this.waterColor).lerp(this.foamColor,h);this.geometry.colorsNeedUpdate=!0}; SKUNAMICPU.HeightFieldWaterWithVel.prototype.updateVelLines=function(){var a=this.velLinesMesh.geometry.vertices,d=new THREE.Vector3,c=new THREE.Vector3,b,e,f;b=0;for(e=this.mesh.geometry.vertices.length;b<e;b++)d.copy(this.mesh.geometry.vertices[b]),c.copy(this.vel[b]),f=c.length(),f>this.maxVisVelLength?c.setLength(this.maxVisVelLength):f<this.minVisVelLength&&c.setLength(0),a[2*b].copy(d),a[2*b+1].copy(d).add(c);this.velLinesMesh.geometry.verticesNeedUpdate=!0}; SKUNAMICPU.PipeModelWater=function(a){this.baseHeights=[];this.heights=[];this.extPressures=[];this.fluxR=[];this.fluxB=[];this.fluxL=[];this.fluxT=[];this.minWaterHeight=-0.05;this.dHeights=[];this.terrainMesh="undefined"===typeof a.terrainMesh?null:a.terrainMesh;SKUNAMICPU.HeightFieldWaterWithVel.call(this,a);this.gravity=9.81;this.density=1;this.atmosPressure=0;this.pipeLength=this.segmentSize;this.pipeCrossSectionArea=this.pipeLength*this.pipeLength;this.flowChangers=[]}; SKUNAMICPU.PipeModelWater.prototype=Object.create(SKUNAMICPU.HeightFieldWaterWithVel.prototype);SKUNAMICPU.PipeModelWater.prototype.constructor=SKUNAMICPU.PipeModelWater;SKUNAMICPU.PipeModelWater.prototype.init=function(){var a,d;a=0;for(d=this.numVertices;a<d;a++)this.baseHeights[a]=0,this.heights[a]=0.1,this.extPressures[a]=0,this.fluxR[a]=0,this.fluxB[a]=0,this.fluxL[a]=0,this.fluxT[a]=0,this.dHeights[a]=0;SKUNAMICPU.HeightFieldWaterWithVel.prototype.init.call(this)}; SKUNAMICPU.PipeModelWater.prototype.reset=function(){var a,d;a=0;for(d=this.numVertices;a<d;a++)this.extPressures[a]=0;SKUNAMICPU.HeightFieldWaterWithVel.prototype.reset.call(this)};SKUNAMICPU.PipeModelWater.prototype.update=function(a){if(this.terrainMesh){var d=this.terrainMesh.geometry.vertices,c,b;c=0;for(b=this.numVertices;c<b;c++)this.baseHeights[c]=d[c].y}SKUNAMICPU.HeightFieldWaterWithVel.prototype.update.call(this,a)}; SKUNAMICPU.PipeModelWater.prototype.sim=function(a){var d,c,b,e=this.geometry.vertices,f=this.res-1;a=1/60/5;for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,this.disturbField[b]*=this.obstacleField[b],this.heights[b]+=this.disturbField[b],this.heights[b]+=this.sourceField[b];var h;for(h=0;5>h;h++){var g,k,l=a*this.pipeCrossSectionArea*this.gravity/this.pipeLength;for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,this.heights[b]<=this.minWaterHeight?(this.fluxL[b]=0,this.fluxR[b]=0,this.fluxT[b]=0,this.fluxB[b]= 0):(g=this.baseHeights[b]+this.heights[b],k=g-(this.baseHeights[b+1]+this.heights[b+1]),this.fluxR[b]*=this.dampingFactor,this.fluxR[b]+=k*l,0>this.fluxR[b]&&(this.fluxR[b]=0),k=g-(this.baseHeights[b-1]+this.heights[b-1]),this.fluxL[b]*=this.dampingFactor,this.fluxL[b]+=k*l,0>this.fluxL[b]&&(this.fluxL[b]=0),k=g-(this.baseHeights[b+this.res]+this.heights[b+this.res]),this.fluxB[b]*=this.dampingFactor,this.fluxB[b]+=k*l,0>this.fluxB[b]&&(this.fluxB[b]=0),k=g-(this.baseHeights[b-this.res]+this.heights[b- this.res]),this.fluxT[b]*=this.dampingFactor,this.fluxT[b]+=k*l,0>this.fluxT[b]&&(this.fluxT[b]=0));c=0;for(d=1;d<this.res;d++)b=d*this.res+c,this.fluxL[b+1]=0;c=this.res-1;for(d=1;d<this.res;d++)b=d*this.res+c,this.fluxR[b-1]=0;d=0;for(c=1;c<this.res;c++)b=d*this.res+c,this.fluxT[b+this.res]=0;d=this.res-1;for(c=1;c<this.res;c++)b=d*this.res+c,this.fluxB[b-this.res]=0;if(this.obstaclesActive)for(c=Object.keys(this.obstacles),g=c.length,d=0;d<g;d++)b=this.obstacles[c[d]],b.updateFlux(this);for(d= 1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,g=(this.heights[b]-this.minWaterHeight)*this.segmentSizeSquared,k=a*(this.fluxR[b]+this.fluxL[b]+this.fluxB[b]+this.fluxT[b]),k>g&&(g/=k,isFinite(g)&&(this.fluxL[b]*=g,this.fluxR[b]*=g,this.fluxB[b]*=g,this.fluxT[b]*=g));for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,k=this.fluxR[b]+this.fluxL[b]+this.fluxB[b]+this.fluxT[b],g=this.fluxR[b-1]+this.fluxL[b+1]+this.fluxB[b-this.res]+this.fluxT[b+this.res],g=(g-k)*a,this.dHeights[b]=g/(this.segmentSize*this.segmentSize), g=this.heights[b],this.heights[b]+=this.dHeights[b],this.heights[b]<this.minWaterHeight&&(this.heights[b]=this.minWaterHeight),g=0.5*(g+this.heights[b]),0===g?(this.vel[b].x=0,this.vel[b].z=0):(this.vel[b].x=0.5*(this.fluxR[b-1]-this.fluxL[b]+this.fluxR[b]-this.fluxL[b+1])/(this.segmentSize*g),this.vel[b].z=0.5*(this.fluxB[b-this.res]-this.fluxT[b]+this.fluxB[b]-this.fluxT[b+this.res])/(this.segmentSize*g)),this.vel[b].y=this.dHeights[b]}for(d=1;d<f;d++)for(c=1;c<f;c++)b=d*this.res+c,e[b].y=this.baseHeights[b]+ this.heights[b];this.__matchEdges();this.__updateMesh()}; SKUNAMICPU.PipeModelWater.prototype.__matchEdges=function(){var a,d,c,b=this.geometry.vertices,e=this.res-1;d=0;for(a=1;a<e;a++)c=a*this.res+d,b[c].y=b[c+1].y;d=this.res-1;for(a=1;a<e;a++)c=a*this.res+d,b[c].y=b[c-1].y;a=0;for(d=1;d<e;d++)c=a*this.res+d,b[c].y=b[c+this.res].y;a=this.res-1;for(d=1;d<e;d++)c=a*this.res+d,b[c].y=b[c-this.res].y;c=0;b[c].y=0.5*(b[c+1].y+b[c+this.res].y);c=this.res-1;b[c].y=0.5*(b[c-1].y+b[c+this.res].y);c=this.res*(this.res-1);b[c].y=0.5*(b[c+1].y+b[c-this.res].y);c= this.res*this.res-1;b[c].y=0.5*(b[c-1].y+b[c-this.res].y)};
// author Alexandr V Kurtz // under MIT license // version 2017/05/07 // vote bot // a bot that can do yes or no votes on discord, and also randomly generate ints var Discord = require("discord.js"); var client = new Discord.Client(); var votes=[]; // array of votes bot is processing client.on ( "message", msg => { if (msg.content.toLowerCase().startsWith("==vote")&&msg.content.length>7) { var novote=true; // boolean that checks if vote is going on in current channel if(votes.length>0) for(var i=0;i<votes.length;i++) // look through votes { if(msg.channel.equals(votes[i].channel)) // if the channel already has a vote going on { msg.channel.sendMessage("you can't, there's already a vote going on right now"); novote=false; // don't add vote break; } } if(novote) // if no vote going on { var vote= { channel : msg.channel, // the channel of the vote question : msg.content.substring(6,msg.content.length), // the question being asked y : 0, // votes for yes n : 0, // votes for no voters : [] // list of people who have voted }; msg.channel.sendMessage ( vote.question+"\n"+ "y: "+vote.y+"\n"+ "n: "+vote.n+"\n"+ "type y or yes for y and n or no for no" ); votes.push(vote); // add vote to array of votes } } if(((msg.content.toLowerCase().startsWith("y"))&&msg.content.length==1)||((msg.content.toLowerCase().startsWith("yes"))&&msg.content.length==3)) // if voting yes { if(votes.length>0) for(var i=0;i<votes.length;i++) // look through votes { if(msg.channel.equals(votes[i].channel)) // if vote is going on { var canvote=true; // checks to see if user has already voted for(var n=0;n<votes[i].voters.length;n++) // looks through voters of vote { if(msg.author.equals(votes[i].voters[n])) // if user has already voted { canvote=false; // can't vote break; } } if(canvote) { votes[i].y++; // add yes vote votes[i].voters.push(msg.author); // add user to voter list so he can't vote again } break; } } } if(((msg.content.toLowerCase().startsWith("n"))&&msg.content.length==1)||((msg.content.toLowerCase().startsWith("no"))&&msg.content.length==2)) // if voting no { if(votes.length>0) for(var i=0;i<votes.length;i++) // look through votes { if(msg.channel.equals(votes[i].channel)) // if vote is going on { var canvote=true; // checks to see if user has already voted for(var n=0;n<votes[i].voters.length;n++) // looks through voters of vote { if(msg.author.equals(votes[i].voters[n])) // if user has already voted { canvote=false; // can't vote break; } } if(canvote) { votes[i].n++; // add no vote votes[i].voters.push(msg.author); // add user to voter list so he can't vote again } break; } } } if(msg.content.toLowerCase().startsWith("==results")) { if(votes.length>0) for(var i=0;i<votes.length;i++) // look through votes if(msg.channel.equals(votes[i].channel)) // if vote is happening { msg.channel.sendMessage ( votes[i].question+"\n"+ "y: "+votes[i].y+"\n"+ "n: "+votes[i].n+"\n"+ "type is y or yes for y and n or no for no" ); break; } } if(msg.content.toLowerCase().startsWith("==end")) { if(votes.length>0) for(var i=0;i<votes.length;i++) // look through votes if(msg.channel.equals(votes[i].channel)) // if vote is happening { msg.channel.sendMessage ( votes[i].question+"\n"+ "y: "+votes[i].y+"\n"+ "n: "+votes[i].n+"\n"+ "voting is now over, thank you" ); votes.splice(i,i+1); // officially end vote so new one can start break; } } if(msg.content.toLowerCase().startsWith("==votes")) { msg.channel.sendMessage("there are currently "+votes.length+" votes happening right now"); } if(msg.content.toLowerCase().startsWith("==random ")&&msg.content.toLowerCase().length>11) // generates random number { var sm=msg.content.split(" "); var min=parseInt(sm[1]); var max=parseInt(sm[2]); var dif=max-min; var rand=Math.floor((Math.random()*dif)+min); if(rand.toString()=="NaN") msg.channel.sendMessage ( "format must be \n"+ "'==random <minimum number> <maximum number>'" ); else msg.channel.sendMessage(rand.toString()); } if(msg.content.toLowerCase().startsWith("==help")) { msg.channel.sendMessage ( "if you want to start a vote, type in '==vote' followed by the voting question \n"+ "unfortunately I can only do yes or no questions for now \n"+ "if you ever want to see the current results say '==results' \n"+ "to end voting, say '==end' \n"+ "to see how many votes are currently happen, say ==votes \n"+ "to find a random int, say ==random followed by the minimum and maximum number \n"+ "to see changelog, say '==changelog'\n"+ "made by alex kurtz" ); } if(msg.content.toLowerCase().startsWith("==test")) { msg.channel.sendMessage("I am online and working"); // used to make sure votebot is online } } ); client.on ( 'ready', () => { console.log('should be running'); } ); client.login(""); // client token goes here
function colorfulNumbers(n) { let result = '<ul>\n' for (let i = 1; i <= n; i++) { result += ` <li><span style='color:${color(i)}'>${i}</span></li>\n` } result += '</ul>\n' return result function color(number) { if (number % 2 === 0) { return 'blue' } else { return 'green' } } } console.log(colorfulNumbers(10)) // <ul> // <li><span style='color:green'>1</span></li> // <li><span style='color:blue'>2</span></li> // <li><span style='color:green'>3</span></li> // <li><span style='color:blue'>4</span></li> // <li><span style='color:green'>5</span></li> // <li><span style='color:blue'>6</span></li> // <li><span style='color:green'>7</span></li> // <li><span style='color:blue'>8</span></li> // <li><span style='color:green'>9</span></li> // <li><span style='color:blue'>10</span></li> // </ul> console.log(colorfulNumbers(1)) console.log(colorfulNumbers(0))
const path = require('path') const fs = require('fs') const HtmlWebpackPlugin = require('html-webpack-plugin') const {CleanWebpackPlugin} = require('clean-webpack-plugin') const FaviconsWebpackPlugin = require('favicons-webpack-plugin') const $pug = (x, options={})=> new HtmlWebpackPlugin({ template: `src/${x}.pug`, ...options }) module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', clean: true }, plugins: [ new FaviconsWebpackPlugin(), new CleanWebpackPlugin({ verbose: true }), $pug('index', { art: fs.readdirSync('./src/art').map(f=> path.parse(f).name), covers: fs.readdirSync('./src/covers').map(f=> path.parse(f).name), }), ...fs.readdirSync('./src/items').filter(f=> ~fs.readdirSync('./src/covers').map(g=> path.parse(g).name).indexOf(path.parse(f).name) ).map(f=> new HtmlWebpackPlugin({ filename: `${path.parse(f).name}.html`, template: `src/items/${f}` })) ], module: { rules: [ { test: /\.js$/i, include: path.resolve(__dirname, 'src'), use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, { test: /\.css$/i, include: [ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules/aos/dist') ], use: ['style-loader', 'css-loader', 'postcss-loader'], }, { test: /\.pug$/i, include: path.resolve(__dirname, 'src'), use: ['pug-loader'] }, { test: /\.(png|jpe?g|gif|svg)$/i, include: path.resolve(__dirname, 'src'), type: 'asset' }, { include: [ path.resolve(__dirname, 'src', 'covers'), path.resolve(__dirname, 'src', 'art'), path.resolve(__dirname, 'src', 'old'), path.resolve(__dirname, 'src', 'thumbnails'), path.resolve(__dirname, 'src', 'tiny'), ], type: 'asset/resource' }, ], }, devServer: { contentBase: path.resolve(__dirname, 'dist'), watchContentBase: true, }, }
/** * https://www.npmjs.com/package/axios */ let axios = require('axios') let url = "http://192.168.219.129:3000/api/v1" var assert = require('assert'); axios.get(url+"/topics?page=1&tab=ask&limit=1&mdrender=false").then((res)=>{ console.log(res.data); let issuccess = res.data.success; assert.deepEqual(true, issuccess) let title = res.data.data[0].title; console.log("title",title) assert.deepEqual("请问中国cnodejs社区你好啊",title) })
'use strict'; var _ansiStyles = require('ansi-styles');var _ansiStyles2 = _interopRequireDefault(_ansiStyles); var _collections = require('./collections'); var _asymmetric_matcher = require('./plugins/asymmetric_matcher');var _asymmetric_matcher2 = _interopRequireDefault(_asymmetric_matcher); var _convert_ansi = require('./plugins/convert_ansi');var _convert_ansi2 = _interopRequireDefault(_convert_ansi); var _dom_element = require('./plugins/dom_element');var _dom_element2 = _interopRequireDefault(_dom_element); var _immutable = require('./plugins/immutable');var _immutable2 = _interopRequireDefault(_immutable); var _react_element = require('./plugins/react_element');var _react_element2 = _interopRequireDefault(_react_element); var _react_test_component = require('./plugins/react_test_component');var _react_test_component2 = _interopRequireDefault(_react_test_component);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} const toString = Object.prototype.toString; /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */const toISOString = Date.prototype.toISOString;const errorToString = Error.prototype.toString;const regExpToString = RegExp.prototype.toString;const symbolToString = Symbol.prototype.toString;const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;const NEWLINE_REGEXP = /\n/gi; function isToStringedArrayType(toStringed) { return ( toStringed === '[object Array]' || toStringed === '[object ArrayBuffer]' || toStringed === '[object DataView]' || toStringed === '[object Float32Array]' || toStringed === '[object Float64Array]' || toStringed === '[object Int8Array]' || toStringed === '[object Int16Array]' || toStringed === '[object Int32Array]' || toStringed === '[object Uint8Array]' || toStringed === '[object Uint8ClampedArray]' || toStringed === '[object Uint16Array]' || toStringed === '[object Uint32Array]'); } function printNumber(val) { if (val != +val) { return 'NaN'; } const isNegativeZero = val === 0 && 1 / val < 0; return isNegativeZero ? '-0' : '' + val; } function printFunction(val, printFunctionName) { if (!printFunctionName) { return '[Function]'; } return '[Function ' + (val.name || 'anonymous') + ']'; } function printSymbol(val) { return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); } function printError(val) { return '[' + errorToString.call(val) + ']'; } function printBasicValue( val, printFunctionName, escapeRegex) { if (val === true || val === false) { return '' + val; } if (val === undefined) { return 'undefined'; } if (val === null) { return 'null'; } const typeOf = typeof val; if (typeOf === 'number') { return printNumber(val); } if (typeOf === 'string') { return '"' + val.replace(/"|\\/g, '\\$&') + '"'; } if (typeOf === 'function') { return printFunction(val, printFunctionName); } if (typeOf === 'symbol') { return printSymbol(val); } const toStringed = toString.call(val); if (toStringed === '[object WeakMap]') { return 'WeakMap {}'; } if (toStringed === '[object WeakSet]') { return 'WeakSet {}'; } if ( toStringed === '[object Function]' || toStringed === '[object GeneratorFunction]') { return printFunction(val, printFunctionName); } if (toStringed === '[object Symbol]') { return printSymbol(val); } if (toStringed === '[object Date]') { return toISOString.call(val); } if (toStringed === '[object Error]') { return printError(val); } if (toStringed === '[object RegExp]') { if (escapeRegex) { // https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); } return regExpToString.call(val); } if (val instanceof Error) { return printError(val); } return null; } function printComplexValue( val, config, indentation, depth, refs) { if (refs.indexOf(val) !== -1) { return '[Circular]'; } refs = refs.slice(); refs.push(val); const hitMaxDepth = ++depth > config.maxDepth; const min = config.min; if ( config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === 'function') { return printer(val.toJSON(), config, indentation, depth, refs); } const toStringed = toString.call(val); if (toStringed === '[object Arguments]') { return hitMaxDepth ? '[Arguments]' : (min ? '' : 'Arguments ') + '[' + (0, _collections.printListItems)(val, config, indentation, depth, refs, printer) + ']'; } if (isToStringedArrayType(toStringed)) { return hitMaxDepth ? '[' + val.constructor.name + ']' : (min ? '' : val.constructor.name + ' ') + '[' + (0, _collections.printListItems)(val, config, indentation, depth, refs, printer) + ']'; } if (toStringed === '[object Map]') { return hitMaxDepth ? '[Map]' : 'Map {' + (0, _collections.printIteratorEntries)( val.entries(), config, indentation, depth, refs, printer, ' => ') + '}'; } if (toStringed === '[object Set]') { return hitMaxDepth ? '[Set]' : 'Set {' + (0, _collections.printIteratorValues)( val.values(), config, indentation, depth, refs, printer) + '}'; } return hitMaxDepth ? '[' + (val.constructor ? val.constructor.name : 'Object') + ']' : (min ? '' : (val.constructor ? val.constructor.name : 'Object') + ' ') + '{' + (0, _collections.printObjectProperties)(val, config, indentation, depth, refs, printer) + '}'; } function printPlugin( plugin, val, config, indentation, depth, refs) { const printed = plugin.serialize ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, '\n' + indentationNext)); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner }, config.colors); if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`); } return printed; } function findPlugin(plugins, val) { for (let p = 0; p < plugins.length; p++) { if (plugins[p].test(val)) { return plugins[p]; } } return null; } function printer( val, config, indentation, depth, refs) { const plugin = findPlugin(config.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, config, indentation, depth, refs); } const basicResult = printBasicValue( val, config.printFunctionName, config.escapeRegex); if (basicResult !== null) { return basicResult; } return printComplexValue(val, config, indentation, depth, refs); } const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green' }; const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); const DEFAULT_OPTIONS = { callToJSON: true, escapeRegex: false, highlight: false, indent: 2, maxDepth: Infinity, min: false, plugins: [], printFunctionName: true, theme: DEFAULT_THEME }; function validateOptions(options) { Object.keys(options).forEach(key => { if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { throw new Error(`pretty-format: Unknown option "${key}".`); } }); if (options.min && options.indent !== undefined && options.indent !== 0) { throw new Error( 'pretty-format: Options "min" and "indent" cannot be used together.'); } if (options.theme !== undefined) { if (options.theme === null) { throw new Error(`pretty-format: Option "theme" must not be null.`); } if (typeof options.theme !== 'object') { throw new Error( `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".`); } } } const getColorsHighlight = options => DEFAULT_THEME_KEYS.reduce((colors, key) => { const value = options.theme && options.theme[key] !== undefined ? options.theme[key] : DEFAULT_THEME[key]; const color = _ansiStyles2.default[value]; if ( color && typeof color.close === 'string' && typeof color.open === 'string') { colors[key] = color; } else { throw new Error( `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`); } return colors; }, {}); const getColorsEmpty = () => DEFAULT_THEME_KEYS.reduce((colors, key) => { colors[key] = { close: '', open: '' }; return colors; }, {}); const getPrintFunctionName = options => options && options.printFunctionName !== undefined ? options.printFunctionName : DEFAULT_OPTIONS.printFunctionName; const getEscapeRegex = options => options && options.escapeRegex !== undefined ? options.escapeRegex : DEFAULT_OPTIONS.escapeRegex; const getConfig = options => ({ callToJSON: options && options.callToJSON !== undefined ? options.callToJSON : DEFAULT_OPTIONS.callToJSON, colors: options && options.highlight ? getColorsHighlight(options) : getColorsEmpty(), escapeRegex: getEscapeRegex(options), indent: options && options.min ? '' : createIndent( options && options.indent !== undefined ? options.indent : DEFAULT_OPTIONS.indent), maxDepth: options && options.maxDepth !== undefined ? options.maxDepth : DEFAULT_OPTIONS.maxDepth, min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, plugins: options && options.plugins !== undefined ? options.plugins : DEFAULT_OPTIONS.plugins, printFunctionName: getPrintFunctionName(options), spacingInner: options && options.min ? ' ' : '\n', spacingOuter: options && options.min ? '' : '\n' }); function createIndent(indent) { return new Array(indent + 1).join(' '); } function prettyFormat(val, options) { if (options) { validateOptions(options); if (options.plugins) { const plugin = findPlugin(options.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, getConfig(options), '', 0, []); } } } const basicResult = printBasicValue( val, getPrintFunctionName(options), getEscapeRegex(options)); if (basicResult !== null) { return basicResult; } return printComplexValue(val, getConfig(options), '', 0, []); } prettyFormat.plugins = { AsymmetricMatcher: _asymmetric_matcher2.default, ConvertAnsi: _convert_ansi2.default, DOMElement: _dom_element2.default, Immutable: _immutable2.default, ReactElement: _react_element2.default, ReactTestComponent: _react_test_component2.default }; module.exports = prettyFormat;
//work.js api-doc function //bootrstrap the api-doc module w.api_doc = {}; w.api_doc.mdocs = {}; w.api_doc.fdocs = {}; w.api_doc.mdocs.api_doc = `api_doc module manages the api documentation of modules and api-functions. Use javascript multiline strings! The "w.module" function also creates the module given by its name as property of the global "w" object.`; w.module = function module_doc(name, docstring) { w[name] = {}; w.api_doc.mdocs[name] = docstring; }; const matchfnhead = /function\s*(\S*)\s*(\(\s*[^)]*?\s*\))/; Function.prototype.doc = function doc(docstring){ const src = this.toString(); const m = matchfnhead.exec(src); const m_name = this.name || m[1]; const params = m[2]; // w.api_doc.fdocs[this] = [this.name, params, docstring, src]; w.api_doc.fdocs[this] = {name:m_name, params:params, src:src, doc:docstring, module:null, context:[]}; return(this); }; function api_doc_and_context(fn, mod, ctx) { if (typeof fn === "function") { if (w.api_doc.fdocs[fn]) { w.api_doc.fdocs[fn].context.push(ctx); w.api_doc.fdocs[fn].module = mod; } else { var src = fn.toString(); var m = matchfnhead.exec(src); var m_name = fn.name || m[1]; if (!m_name) return; var params = m[2]; w.api_doc.fdocs[fn] = {name:m_name, params:params, src:src, doc:"not documented", module:mod, context:[ctx]}; }; }; }; w.api_doc.init = function init() { for (var p1 in w) { api_doc_and_context(w[p1], p1, p1); for (var x in w[p1]) { api_doc_and_context(w[p1][x], p1, p1+"."+x); }; for (var x in w[p1].prototype) { api_doc_and_context(w[p1].prototype[x], p1, p1+".prototype."+x); }; }; }.doc(`Initialize api-doc table. WorkJS core/bootstrap calls this when all functions are loaded.`);
//>>built define("dojorama/layers/nls/model_es-es",{"dojorama/model/nls/ReleaseModel":{titleMissing:"Title required",titleInvalid:"Invalid title"}}); //@ sourceMappingURL=model_es-es.js.map
'use strict'; angular.module('itracker') .directive('projectTodo', ['apiService', function(apiService){ return { restrict: 'C', scope: { todos: '=' }, templateUrl: apiService.root+'/angular/proj.projectTodo' }; }]);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _jsx2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/jsx")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _reactI18next = require("react-i18next"); var _ms = _interopRequireDefault(require("ms")); var _Button = _interopRequireDefault(require("@material-ui/core/Button")); var _TableRow = _interopRequireDefault(require("@material-ui/core/TableRow")); var _TableCell = _interopRequireDefault(require("@material-ui/core/TableCell")); var _Avatar = _interopRequireDefault(require("../../../components/Avatar")); var _WithCard = _interopRequireDefault(require("../../../components/Username/WithCard")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var enhance = (0, _reactI18next.translate)(); var avatarStyle = { width: 48, paddingRight: 0 }; var BanRow = function BanRow(_ref) { var t = _ref.t, ban = _ref.ban, onUnbanUser = _ref.onUnbanUser; return (0, _jsx2.default)(_TableRow.default, {}, void 0, (0, _jsx2.default)(_TableCell.default, { style: avatarStyle }, void 0, (0, _jsx2.default)(_Avatar.default, { user: ban.user })), (0, _jsx2.default)(_TableCell.default, {}, void 0, (0, _jsx2.default)(_WithCard.default, { user: ban.user })), (0, _jsx2.default)(_TableCell.default, {}, void 0, (0, _ms.default)(ban.duration, { long: true })), (0, _jsx2.default)(_TableCell.default, {}, void 0, ban.reason || (0, _jsx2.default)("em", {}, void 0, t('admin.bans.noReason'))), (0, _jsx2.default)(_TableCell.default, {}, void 0, (0, _jsx2.default)(_WithCard.default, { user: ban.moderator })), (0, _jsx2.default)(_TableCell.default, {}, void 0, (0, _jsx2.default)(_Button.default, { variant: "raised", onClick: onUnbanUser }, void 0, t('admin.bans.unban')))); }; BanRow.propTypes = process.env.NODE_ENV !== "production" ? { t: _propTypes.default.func.isRequired, ban: _propTypes.default.shape({ user: _propTypes.default.object.isRequired, duration: _propTypes.default.number.isRequired, reason: _propTypes.default.string, moderator: _propTypes.default.object.isRequired }).isRequired, onUnbanUser: _propTypes.default.func.isRequired } : {}; var _default = enhance(BanRow); exports.default = _default; //# sourceMappingURL=Row.js.map
'use strict'; angular.module('myApp.autocomplete', [ 'myApp.autocomplete.autocomplete-directive', 'myApp.autocomplete.autocomplete-service', 'myApp.autocomplete.autocomplete-states', ])
'use babel'; import YamlHelperView from '../lib/yaml-helper-view'; describe('YamlHelperView', () => { it('has one valid test', () => { expect('life').toBe('easy'); }); });