code
stringlengths
2
1.05M
/** * Copyright (C) 2020 tt.bot dev team * * This file is part of tt.bot. * * tt.bot is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * tt.bot is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with tt.bot. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; module.exports = async function (config, guild, user, unban) { let auditLog; if (guild.members.get(guild.shard.client.user.id) .permission.has("viewAuditLogs")) { try { auditLog = await guild.getAuditLogs(50, null, unban ? 23 : 22); } catch {} } const fields = []; if (auditLog) { const entry = auditLog.entries.find(entry => entry.targetID === user.id); if (entry) { fields.push({ name: `${unban? "Unb" : "B"}anned by`, value: `${entry.user.username}#${entry.user.discriminator} (${entry.user.id})` }); if (!unban) fields.push({ name: "Reason", value: entry.reason || "None" }); } } if (!guild.channels.has(config.logChannel)) return; try { await guild.channels.get(config.logChannel).createMessage({ embed: { author: { name: `${user.username}#${user.discriminator} (${user.id})`, icon_url: user.avatarURL }, title: `has got ${unban ? "un" : ""}banned`, fields, color: unban? 0x008800 : 0xFF0000 } }); } catch {} };
/* -*- coding: utf-8 -*- * ---------------------------------------------------------------------------- * Copyright (c) 2013 - Damián Avila * * Distributed under the terms of the Modified BSD License. * * An IPython notebook extension to support *Live* Reveal.js-based slideshows. * ----------------------------------------------------------------------------- */ define([ 'require', 'jquery', 'base/js/utils', 'services/config', ], function(require, $, utils, configmod) { var config_section = new configmod.ConfigSection('livereveal', {base_url: utils.get_body_data("baseUrl")}); config_section.load(); var config = new configmod.ConfigWithDefaults(config_section, { controls: true, progress: true, history: true, width: 1140, height: 855, // 4:3 ratio minScale: 1.0, //we need this for codemirror to work right theme: 'simple', transition: 'linear', slideNumber: true, start_slideshow_at: 'beginning', }); Object.getPrototypeOf(IPython.notebook).get_cell_elements = function () { /* * Version of get_cell_elements that will see cell divs at any depth in the HTML tree, * allowing container divs, etc to be used without breaking notebook machinery. * You'll need to make sure the cells are getting detected in the right order. * NOTE: We use the Object prototype to workaround a firefox issue, check the following * link to know more about the discussion leading to this use: * https://github.com/damianavila/RISE/issues/117#issuecomment-127331816 */ return this.container.find("div.cell"); }; /* Use the slideshow metadata to rearrange cell DOM elements into the * structure expected by reveal.js */ function markupSlides(container) { // Machinery to create slide/subslide <section>s and give them IDs var slide_counter = -1, subslide_counter = -1; var slide_section, subslide_section; function new_slide() { slide_counter++; subslide_counter = -1; return $('<section>').appendTo(container); } function new_subslide() { subslide_counter++; return $('<section>').attr('id', 'slide-'+slide_counter+'-'+subslide_counter) .appendTo(slide_section); } // Containers for the first slide. slide_section = new_slide(); subslide_section = new_subslide(); var current_fragment = subslide_section; var selected_cell_idx = IPython.notebook.get_selected_index(); var selected_cell_slide = [0, 0]; // Special handling for the first slide: it will work even if the user // doesn't start with a 'Slide' cell. But if the user does explicitly // start with slide/subslide, we don't want a blank first slide. So we // don't create a new slide/subslide until there is visible content on // the first slide. var content_on_slide1 = false; var cells = IPython.notebook.get_cells(); var i, cell, slide_type; for (i=0; i < cells.length; i++) { cell = cells[i]; slide_type = (cell.metadata.slideshow || {}).slide_type; //~ console.log('cell ' + i + ' is: '+ slide_type); if (content_on_slide1) { if (slide_type === 'slide') { // Start new slide slide_section = new_slide(); // In each subslide, we insert cells directly into the // <section> until we reach a fragment, when we create a div. current_fragment = subslide_section = new_subslide(); } else if (slide_type === 'subslide') { // Start new subslide current_fragment = subslide_section = new_subslide(); } else if (slide_type === 'fragment') { current_fragment = $('<div>').addClass('fragment') .appendTo(subslide_section); } } else if (slide_type !== 'notes' && slide_type !== 'skip') { // Subsequent cells should be able to start new slides content_on_slide1 = true; } // Record that this slide contains the selected cell if (i === selected_cell_idx) { selected_cell_slide = [slide_counter, subslide_counter]; } // Move the cell element into the slide <section> // N.B. jQuery append takes the element out of the DOM where it was if (slide_type === 'notes') { // Notes are wrapped in an <aside> element subslide_section.append( $('<aside>').addClass('notes').append(cell.element) ); } else { current_fragment.append(cell.element); } // Hide skipped cells if (slide_type === 'skip') { cell.element.addClass('reveal-skip'); } } // Put .end_space back at the end after all the rearrangement $('.end_space').appendTo('div#notebook-container'); return selected_cell_slide; } /* Set the #slide-x-y part of the URL to control where the slideshow will start. * N.B. We do this instead of using Reveal.slide() after reveal initialises, * because that leaves one slide clearly visible on screen for a moment before * changing to the one we want. By changing the URL before setting up reveal, * the slideshow really starts on the desired slide. */ function setStartingSlide(selected) { var start_slideshow = config.get_sync('start_slideshow_at'); if (start_slideshow === 'selected') { // Start from the selected cell window.location.hash = "/slide-"+selected[0]+"-"+selected[1]; } else { // Start from the beginning window.location.hash = "/slide-0-0"; } } function Revealer() { $('body').addClass("rise-enabled"); // Prepare the DOM to start the slideshow //$('div#header').hide(); //$('div#site').css("height", "100%"); //$('div#ipython-main-app').css("position", "static"); $('div#notebook').addClass("reveal"); $('div#notebook-container').addClass("slides"); // Header $('head').prepend('<link rel="stylesheet" href=' + require.toUrl("./reveal.js/css/theme/simple.css") + ' id="theme" />'); $('head').prepend('<link rel="stylesheet" href=' + require.toUrl("./reset_reveal.css") + ' id="revealcss" />'); // Tailer require(['./reveal.js/lib/js/head.min.js', './reveal.js/js/reveal.js'].map(require.toUrl),function(){ // Full list of configuration options available here: https://github.com/hakimel/reveal.js#configuration var options = { controls: config.get_sync('controls'), progress: config.get_sync('progress'), history: config.get_sync('history'), // You can switch width and height to fix the projector width: config.get_sync('width'), height: config.get_sync('height'), minScale: config.get_sync('minScale'), //we need this for codemirror to work right) // available themes are in /css/theme theme: Reveal.getQueryHash().theme || config.get_sync('theme'), // default/cube/page/concave/zoom/linear/none transition: Reveal.getQueryHash().transition || config.get_sync('transition'), slideNumber: config.get_sync('slideNumber'), //parallaxBackgroundImage: 'https://raw.github.com/damianavila/par_IPy_slides_example/gh-pages/figs/star_wars_stormtroopers_darth_vader.jpg', //parallaxBackgroundSize: '2560px 1600px', keyboard: { 13: null, // Enter disabled 27: null, // ESC disabled 38: null, // up arrow disabled 40: null, // down arrow disabled 66: null, // b, black pause disabled, use period or forward slash 72: null, // h, left disabled 74: null, // j, down disabled 75: null, // k, up disabled 76: null, // l, right disabled 78: null, // n, down disable 79: null, // o disabled 80: null, // p, up disable // 83: null, // s, notes, but not working because notes is a plugin 87: function() {Reveal.toggleOverview();}, // w, toggle overview 188: function() {$('#help_b,#exit_b').fadeToggle();}, }, // Optional libraries used to extend on reveal.js // Notes are working partially... it opens the notebooks, not the slideshows... dependencies: [ //{ src: "static/custom/livereveal/reveal.js/lib/js/classList.js", condition: function() { return !document.body.classList; } }, //{ src: "static/custom/livereveal/reveal.js/plugin/highlight/highlight.js", async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, { src: require.toUrl("./reveal.js/plugin/notes/notes.js"), async: true, condition: function() { return !!document.body.classList; } } ] }; // Set up the Leap Motion integration if configured var leap = config.get_sync('leap_motion'); if (leap !== undefined) { options.dependencies.push({ src: require.toUrl('./reveal.js/plugin/leap/leap.js'), async: true }); options.leap = leap; } Reveal.initialize(options); Reveal.addEventListener( 'ready', function( event ) { Unselecter(); window.scrollTo(0,0); Reveal.layout(); $('#start_livereveal').blur(); }); Reveal.addEventListener( 'slidechanged', function( event ) { Unselecter(); window.scrollTo(0,0); }); }); } function Unselecter(){ var cells = IPython.notebook.get_cells(); for(var i in cells){ var cell = cells[i]; cell.unselect(); } } function fixCellHeight(){ // Let's start with all the cell unselected, the unselect the current selected one var scell = IPython.notebook.get_selected_cell() scell.unselect() // This select/unselect code cell triggers the "correct" heigth in the codemirror instance var cells = IPython.notebook.get_cells(); for(var i in cells){ var cell = cells[i]; if (cell.cell_type === "code") { cell.select() cell.unselect(); } } } function setupKeys(mode){ if (mode === 'reveal_mode') { IPython.keyboard_manager.command_shortcuts.set_shortcut("shift-enter", "ipython.execute-in-place") IPython.keyboard_manager.edit_shortcuts.set_shortcut("shift-enter", "ipython.execute-in-place") } else if (mode === 'notebook_mode') { IPython.keyboard_manager.command_shortcuts.set_shortcut("shift-enter", "ipython.run-select-next") IPython.keyboard_manager.edit_shortcuts.set_shortcut("shift-enter", "ipython.run-select-next") } } function KeysMessager() { var message = $('<div/>').append( $("<p/></p>").addClass('dialog').html( "<ul>" + "<li><kbd>Alt</kbd>+<kbd>r</kbd>: Enter/Exit RISE</li>" + "<li><kbd>w</kbd>: Toggle overview mode</li>" + "<li><kbd>,</kbd>: Toggle help and exit buttons</li>" + "<li><kbd>Home</kbd>: First slide</li>" + "<li><kbd>End</kbd>: Last slide</li>" + "<li><kbd>space</kbd>: Next</li>" + "<li><kbd>Shift</kbd>+<kbd>space</kbd>: Previous</li>" + "<li><kbd>PgUp</kbd>: Up</li>" + "<li><kbd>PgDn</kbd>: Down</li>" + "<li><kbd>left</kbd>: Left</li>" + "<li><kbd>right</kbd>: Right</li>" + "<li><kbd>.</kbd> or <kbd>/</kbd>: black screen</li>" + "</ul>" + "<b>NOTE: You have to use these shortcuts in command mode.</b>" ) ); IPython.dialog.modal({ title : "Reveal Shortcuts Help", body : message, buttons : { OK : {class: "btn-danger"} } }); } function buttonHelp() { var help_button = $('<i/>') .attr('id','help_b') .attr('title','Reveal Shortcuts Help') .addClass('fa-question fa-4x fa') .addClass('my-main-tool-bar') .css('position','fixed') .css('bottom','0.5em') .css('left','0.6em') .css('opacity', '0.6') .click( function(){ KeysMessager(); } ); $('.reveal').after(help_button); } function buttonExit() { var exit_button = $('<i/>') .attr('id','exit_b') .attr('title','RISE Exit') .addClass('fa-times-circle fa-4x fa') .addClass('my-main-tool-bar') .css('position','fixed') .css('top','0.5em') .css('left','0.48em') .css('opacity', '0.6') .click( function(){ revealMode('simple', 'zoom'); } ); $('.reveal').after(exit_button); } function Remover() { Reveal.configure({minScale: 1.0}); Reveal.removeEventListeners(); $('body').removeClass("rise-enabled"); IPython.menubar._size_header(); $('div#notebook').removeClass("reveal"); $('div#notebook-container').removeClass("slides"); $('div#notebook-container').css('width',''); $('div#notebook-container').css('height',''); $('div#notebook-container').css('zoom',''); $('#theme').remove(); $('#revealcss').remove(); $('.progress').remove(); $('.controls').remove(); $('.slide-number').remove(); $('.state-background').remove(); $('.pause-overlay').remove(); var cells = IPython.notebook.get_cells(); for(var i in cells){ $('.cell:nth('+i+')').removeClass('reveal-skip'); $('div#notebook-container').append(cells[i].element); } $('div#notebook-container').children('section').remove(); $('.end_space').appendTo('div#notebook'); IPython.page.show_site(); } function revealMode() { /* * We search for a class tag in the maintoolbar to check if reveal mode is "on". * If the tag exits, we exit. Otherwise, we enter the reveal mode. */ var tag = $('#maintoolbar').hasClass('reveal_tagging'); if (!tag) { // Preparing the new reveal-compatible structure var selected_slide = markupSlides($('div#notebook-container')); // Set the hash part of the URL setStartingSlide(selected_slide); // Adding the reveal stuff Revealer(); // Minor modifications for usability setupKeys("reveal_mode"); buttonExit(); buttonHelp(); $('#maintoolbar').addClass('reveal_tagging'); } else { Remover(); setupKeys("notebook_mode"); $('#exit_b').remove(); $('#help_b').remove(); $('#maintoolbar').removeClass('reveal_tagging'); // Workaround... should be a better solution. Need to investigate codemirror fixCellHeight(); } } function setup() { $('head').append('<link rel="stylesheet" href=' + require.toUrl("./main.css") + ' id="maincss" />'); IPython.toolbar.add_buttons_group([ { 'label' : 'Enter/Exit Live Reveal Slideshow', 'icon' : 'fa-bar-chart-o', 'callback': function(){ revealMode(); }, 'id' : 'start_livereveal' }, ]); var document_keydown = function(event) { if (event.which == 82 && event.altKey) { revealMode(); return false; } return true; }; $(document).keydown(document_keydown); } setup.load_ipython_extension = setup; return setup; });
(function() { var WORD_RE; WORD_RE = /([^ ,\/!.?:;\-\n]+[ ,\/!.?:;\-]*)|\n/g; module.exports = { initText: function() { this.x = 0; this.y = 0; this._lineGap = 0; this._textState = { mode: 0, wordSpacing: 0, characterSpacing: 0 }; return this._wrapState = {}; }, lineGap: function(_lineGap) { this._lineGap = _lineGap; return this; }, text: function(text, x, y, options) { var margins, match, matches, _i, _len, _ref, _ref1, _ref2; if (x == null) { x = {}; } if (options == null) { options = {}; } if (typeof x === 'object') { options = x; x = null; } text = '' + text; if ((x != null) || (y != null)) { this.x = x || this.x; this.y = y || this.y; } else { margins = this.page.margins; if ((_ref = options.width) == null) { options.width = this.page.width - this.x - margins.right; } if ((_ref1 = options.height) == null) { options.height = this.page.height - this.y - margins.bottom; } } options.columns || (options.columns = 1); if ((_ref2 = options.columnGap) == null) { options.columnGap = 18; } if (options.wordSpacing) { text = text.replace(/\s+/g, ' '); } if (options.width) { this._wrap(text, options); } else if ((matches = text.split('\n')).length > 1) { for (_i = 0, _len = matches.length; _i < _len; _i++) { match = matches[_i]; this._line(match, options); } } else { this._line(text, options); } return this; }, moveDown: function(lines) { if (lines == null) { lines = 1; } this.y += this.currentLineHeight(true) * lines + this._lineGap; return this; }, moveUp: function(lines) { if (lines == null) { lines = 1; } this.y -= this.currentLineHeight(true) * lines + this._lineGap; return this; }, list: function(array, ox, oy) { var gap, item, x, y, _i, _len; gap = Math.round((this._font.ascender / 1000 * this._fontSize) / 2); this.x = x = ox || this.x; this.y = y = oy || this.y; for (_i = 0, _len = array.length; _i < _len; _i++) { item = array[_i]; this.circle(x + 3, this.y + gap + 3, 3); this.text(item, x + 15); this.y += 3; } this.x = x; return this.fill(); }, _line: function(text, options) { var lineGap, paragraphGap, wrap; wrap = this._wrapState; paragraphGap = (wrap.firstLine && this.y !== wrap.startY && options.paragraphGap) || 0; lineGap = options.lineGap || this._lineGap || 0; this._fragment(text, this.x, this.y + paragraphGap, options); return this.y += this.currentLineHeight(true) + lineGap + paragraphGap; }, _fragment: function(text, x, y, options) { var align, characterSpacing, i, indent, lineWidth, mode, state, textWidth, wordSpacing, words, wrap, _base, _name, _ref; if (options == null) { options = {}; } text = '' + text; if (text.length === 0) { return; } state = this._textState; wrap = this._wrapState; align = options.align || 'left'; indent = (wrap.firstLine && options.indent) || 0; wordSpacing = options.wordSpacing || 0; characterSpacing = options.characterSpacing || 0; if (options.width) { lineWidth = wrap.lineWidth - indent - wrap.extraSpace; switch (align) { case 'right': x += lineWidth - this.widthOfString(text); break; case 'center': x += lineWidth / 2 - this.widthOfString(text) / 2; break; case 'justify': if (wrap.lastLine) { break; } words = text.match(WORD_RE); if (!words) { break; } textWidth = this.widthOfString(text.replace(/\s+/g, '')); wordSpacing = (lineWidth - textWidth) / (words.length - 1) - this.widthOfString(' '); } } x += indent; y = this.page.height - y - (this._font.ascender / 1000 * this._fontSize); if ((_ref = (_base = this.page.fonts)[_name = this._font.id]) == null) { _base[_name] = this._font.ref; } this._font.use(text); text = this._font.encode(text); text = ((function() { var _i, _ref1, _results; _results = []; for (i = _i = 0, _ref1 = text.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) { _results.push(text.charCodeAt(i).toString(16)); } return _results; })()).join(''); this.addContent("BT"); this.addContent("" + x + " " + y + " Td"); this.addContent("/" + this._font.id + " " + this._fontSize + " Tf"); mode = options.fill && options.stroke ? 2 : options.stroke ? 1 : 0; if (mode !== state.mode) { this.addContent("" + mode + " Tr"); } if (wordSpacing !== state.wordSpacing) { this.addContent(wordSpacing + ' Tw'); } if (characterSpacing !== state.characterSpacing) { this.addContent(characterSpacing + ' Tc'); } this.addContent("<" + text + "> Tj"); this.addContent("ET"); state.mode = mode; return state.wordSpacing = wordSpacing; }, _wrap: function(text, options) { var buffer, i, indent, lastLine, len, lineWidth, nextY, spaceLeft, w, width, word, wordWidths, words, wrap, _i, _len, _ref; wrap = this._wrapState; width = this.widthOfString.bind(this); indent = options.indent || 0; lineWidth = (options.width - (options.columnGap * (options.columns - 1))) / options.columns; wrap.column = 1; wrap.startY = this.y; wrap.lineWidth = lineWidth; wrap.firstLine = true; wrap.lastLine = false; wrap.maxY = this.y + options.height - this.currentLineHeight(); words = text.match(WORD_RE) || ['']; wrap.extraSpace = (options.wordSpacing || 0) * (words.length - 1) + (options.characterSpacing || 0) * (text.length - 1); spaceLeft = lineWidth - indent - wrap.extraSpace; wordWidths = {}; len = words.length; buffer = ''; for (i = _i = 0, _len = words.length; _i < _len; i = ++_i) { word = words[i]; w = (_ref = wordWidths[word]) != null ? _ref : wordWidths[word] = width(word); if (w > spaceLeft || word === '\n') { if (wrap.lastLine) { wrap.firstLine = true; wrap.lastLine = false; } if (word === '\n') { wrap.lastLine = true; w += indent; } lastLine = buffer.trim(); this._line(lastLine, options); wrap.firstLine = false; nextY = this.y + this.currentLineHeight(true); if (this.y > wrap.maxY || (wrap.lastLine && nextY > wrap.maxY)) { this._nextSection(options); } spaceLeft = lineWidth - w - wrap.extraSpace; buffer = word === '\n' ? '' : word; } else { spaceLeft -= w; buffer += word; } } wrap.lastLine = true; this._line(buffer.trim(), options); return this._wrapState = {}; }, _nextSection: function(options) { var wrap; wrap = this._wrapState; if (++wrap.column > options.columns) { if (options.callbackPackage && options.callbackPackage.wrapToNewPage) { this.addPage(options); } wrap.column = 1; wrap.startY = this.page.margins.top; return wrap.maxY = this.page.maxY(); } else { this.x += wrap.lineWidth + options.columnGap; return this.y = wrap.startY; } } }; }).call(this); // Generated by CoffeeScript 1.5.0-pre
import React from 'react' import ReactTestUtils from 'react-dom/test-utils' import rtRenderer from 'react-test-renderer' import {findWithType} from 'react-shallow-testutils' import {findAllWithType} from 'react-shallow-testutils' import initialState from '../../../data/StateGetter' const testFunction = (Panel, Table, AEForm, wordType) => { const ucWordType = wordType.charAt(0).toUpperCase() + wordType.slice(1) const addKey = 'add' + ucWordType const panelName = ucWordType + 'Panel' const aeFormName = ucWordType + 'AEForm' const article = ('aeiou'.indexOf(wordType.charAt(0))) ? 'a' : 'an' let state beforeEach(function() { state = {} state[wordType] = initialState[wordType] state.strings = initialState.strings }) it('Renders ' + article + ' ' + panelName + ' w/o add/edit', function() { const renderExpression = <Panel {...state} /> const wordPanel = ReactTestUtils.createRenderer().render(renderExpression) expect(wordPanel.type).toBe('div') expect(findWithType(wordPanel,'button')) expect(findWithType(wordPanel,Table)) // No AEForm const adjectivdAEForm = findAllWithType(wordPanel, AEForm) expect(adjectivdAEForm.length).toBe(0) const tree = rtRenderer.create(renderExpression).toJSON() expect(tree).toMatchSnapshot() }) it('Renders ' + article + ' ' + panelName + ' with ' + article + ' ' + aeFormName + ' in add mode', function() { state[wordType] = state[wordType].setIn(['addedit',addKey],true) const renderExpression = <Panel {...state} /> const wordPanel = ReactTestUtils.createRenderer().render(renderExpression) expect(wordPanel.type).toBe('div') expect(findWithType(wordPanel,'button')) expect(findWithType(wordPanel,AEForm)) expect(findWithType(wordPanel,Table)) const tree = rtRenderer.create(renderExpression).toJSON() expect(tree).toMatchSnapshot() }) it('Renders ' + article + ' ' + panelName + ' with ' + article + ' ' + aeFormName + ' in edit mode', function() { state[wordType] = state[wordType].setIn(['addedit',wordType,'id'],'1') const renderExpression = <Panel {...state} /> const wordPanel = ReactTestUtils.createRenderer().render(renderExpression) expect(wordPanel.type).toBe('div') expect(findWithType(wordPanel,'button')) expect(findWithType(wordPanel,AEForm)) expect(findWithType(wordPanel,Table)) const tree = rtRenderer.create(renderExpression).toJSON() expect(tree).toMatchSnapshot() }) } export {testFunction}
// All symbols in the CJK Compatibility Ideographs Supplement block as per Unicode v6.1.0: [ '\uD87E\uDC00', '\uD87E\uDC01', '\uD87E\uDC02', '\uD87E\uDC03', '\uD87E\uDC04', '\uD87E\uDC05', '\uD87E\uDC06', '\uD87E\uDC07', '\uD87E\uDC08', '\uD87E\uDC09', '\uD87E\uDC0A', '\uD87E\uDC0B', '\uD87E\uDC0C', '\uD87E\uDC0D', '\uD87E\uDC0E', '\uD87E\uDC0F', '\uD87E\uDC10', '\uD87E\uDC11', '\uD87E\uDC12', '\uD87E\uDC13', '\uD87E\uDC14', '\uD87E\uDC15', '\uD87E\uDC16', '\uD87E\uDC17', '\uD87E\uDC18', '\uD87E\uDC19', '\uD87E\uDC1A', '\uD87E\uDC1B', '\uD87E\uDC1C', '\uD87E\uDC1D', '\uD87E\uDC1E', '\uD87E\uDC1F', '\uD87E\uDC20', '\uD87E\uDC21', '\uD87E\uDC22', '\uD87E\uDC23', '\uD87E\uDC24', '\uD87E\uDC25', '\uD87E\uDC26', '\uD87E\uDC27', '\uD87E\uDC28', '\uD87E\uDC29', '\uD87E\uDC2A', '\uD87E\uDC2B', '\uD87E\uDC2C', '\uD87E\uDC2D', '\uD87E\uDC2E', '\uD87E\uDC2F', '\uD87E\uDC30', '\uD87E\uDC31', '\uD87E\uDC32', '\uD87E\uDC33', '\uD87E\uDC34', '\uD87E\uDC35', '\uD87E\uDC36', '\uD87E\uDC37', '\uD87E\uDC38', '\uD87E\uDC39', '\uD87E\uDC3A', '\uD87E\uDC3B', '\uD87E\uDC3C', '\uD87E\uDC3D', '\uD87E\uDC3E', '\uD87E\uDC3F', '\uD87E\uDC40', '\uD87E\uDC41', '\uD87E\uDC42', '\uD87E\uDC43', '\uD87E\uDC44', '\uD87E\uDC45', '\uD87E\uDC46', '\uD87E\uDC47', '\uD87E\uDC48', '\uD87E\uDC49', '\uD87E\uDC4A', '\uD87E\uDC4B', '\uD87E\uDC4C', '\uD87E\uDC4D', '\uD87E\uDC4E', '\uD87E\uDC4F', '\uD87E\uDC50', '\uD87E\uDC51', '\uD87E\uDC52', '\uD87E\uDC53', '\uD87E\uDC54', '\uD87E\uDC55', '\uD87E\uDC56', '\uD87E\uDC57', '\uD87E\uDC58', '\uD87E\uDC59', '\uD87E\uDC5A', '\uD87E\uDC5B', '\uD87E\uDC5C', '\uD87E\uDC5D', '\uD87E\uDC5E', '\uD87E\uDC5F', '\uD87E\uDC60', '\uD87E\uDC61', '\uD87E\uDC62', '\uD87E\uDC63', '\uD87E\uDC64', '\uD87E\uDC65', '\uD87E\uDC66', '\uD87E\uDC67', '\uD87E\uDC68', '\uD87E\uDC69', '\uD87E\uDC6A', '\uD87E\uDC6B', '\uD87E\uDC6C', '\uD87E\uDC6D', '\uD87E\uDC6E', '\uD87E\uDC6F', '\uD87E\uDC70', '\uD87E\uDC71', '\uD87E\uDC72', '\uD87E\uDC73', '\uD87E\uDC74', '\uD87E\uDC75', '\uD87E\uDC76', '\uD87E\uDC77', '\uD87E\uDC78', '\uD87E\uDC79', '\uD87E\uDC7A', '\uD87E\uDC7B', '\uD87E\uDC7C', '\uD87E\uDC7D', '\uD87E\uDC7E', '\uD87E\uDC7F', '\uD87E\uDC80', '\uD87E\uDC81', '\uD87E\uDC82', '\uD87E\uDC83', '\uD87E\uDC84', '\uD87E\uDC85', '\uD87E\uDC86', '\uD87E\uDC87', '\uD87E\uDC88', '\uD87E\uDC89', '\uD87E\uDC8A', '\uD87E\uDC8B', '\uD87E\uDC8C', '\uD87E\uDC8D', '\uD87E\uDC8E', '\uD87E\uDC8F', '\uD87E\uDC90', '\uD87E\uDC91', '\uD87E\uDC92', '\uD87E\uDC93', '\uD87E\uDC94', '\uD87E\uDC95', '\uD87E\uDC96', '\uD87E\uDC97', '\uD87E\uDC98', '\uD87E\uDC99', '\uD87E\uDC9A', '\uD87E\uDC9B', '\uD87E\uDC9C', '\uD87E\uDC9D', '\uD87E\uDC9E', '\uD87E\uDC9F', '\uD87E\uDCA0', '\uD87E\uDCA1', '\uD87E\uDCA2', '\uD87E\uDCA3', '\uD87E\uDCA4', '\uD87E\uDCA5', '\uD87E\uDCA6', '\uD87E\uDCA7', '\uD87E\uDCA8', '\uD87E\uDCA9', '\uD87E\uDCAA', '\uD87E\uDCAB', '\uD87E\uDCAC', '\uD87E\uDCAD', '\uD87E\uDCAE', '\uD87E\uDCAF', '\uD87E\uDCB0', '\uD87E\uDCB1', '\uD87E\uDCB2', '\uD87E\uDCB3', '\uD87E\uDCB4', '\uD87E\uDCB5', '\uD87E\uDCB6', '\uD87E\uDCB7', '\uD87E\uDCB8', '\uD87E\uDCB9', '\uD87E\uDCBA', '\uD87E\uDCBB', '\uD87E\uDCBC', '\uD87E\uDCBD', '\uD87E\uDCBE', '\uD87E\uDCBF', '\uD87E\uDCC0', '\uD87E\uDCC1', '\uD87E\uDCC2', '\uD87E\uDCC3', '\uD87E\uDCC4', '\uD87E\uDCC5', '\uD87E\uDCC6', '\uD87E\uDCC7', '\uD87E\uDCC8', '\uD87E\uDCC9', '\uD87E\uDCCA', '\uD87E\uDCCB', '\uD87E\uDCCC', '\uD87E\uDCCD', '\uD87E\uDCCE', '\uD87E\uDCCF', '\uD87E\uDCD0', '\uD87E\uDCD1', '\uD87E\uDCD2', '\uD87E\uDCD3', '\uD87E\uDCD4', '\uD87E\uDCD5', '\uD87E\uDCD6', '\uD87E\uDCD7', '\uD87E\uDCD8', '\uD87E\uDCD9', '\uD87E\uDCDA', '\uD87E\uDCDB', '\uD87E\uDCDC', '\uD87E\uDCDD', '\uD87E\uDCDE', '\uD87E\uDCDF', '\uD87E\uDCE0', '\uD87E\uDCE1', '\uD87E\uDCE2', '\uD87E\uDCE3', '\uD87E\uDCE4', '\uD87E\uDCE5', '\uD87E\uDCE6', '\uD87E\uDCE7', '\uD87E\uDCE8', '\uD87E\uDCE9', '\uD87E\uDCEA', '\uD87E\uDCEB', '\uD87E\uDCEC', '\uD87E\uDCED', '\uD87E\uDCEE', '\uD87E\uDCEF', '\uD87E\uDCF0', '\uD87E\uDCF1', '\uD87E\uDCF2', '\uD87E\uDCF3', '\uD87E\uDCF4', '\uD87E\uDCF5', '\uD87E\uDCF6', '\uD87E\uDCF7', '\uD87E\uDCF8', '\uD87E\uDCF9', '\uD87E\uDCFA', '\uD87E\uDCFB', '\uD87E\uDCFC', '\uD87E\uDCFD', '\uD87E\uDCFE', '\uD87E\uDCFF', '\uD87E\uDD00', '\uD87E\uDD01', '\uD87E\uDD02', '\uD87E\uDD03', '\uD87E\uDD04', '\uD87E\uDD05', '\uD87E\uDD06', '\uD87E\uDD07', '\uD87E\uDD08', '\uD87E\uDD09', '\uD87E\uDD0A', '\uD87E\uDD0B', '\uD87E\uDD0C', '\uD87E\uDD0D', '\uD87E\uDD0E', '\uD87E\uDD0F', '\uD87E\uDD10', '\uD87E\uDD11', '\uD87E\uDD12', '\uD87E\uDD13', '\uD87E\uDD14', '\uD87E\uDD15', '\uD87E\uDD16', '\uD87E\uDD17', '\uD87E\uDD18', '\uD87E\uDD19', '\uD87E\uDD1A', '\uD87E\uDD1B', '\uD87E\uDD1C', '\uD87E\uDD1D', '\uD87E\uDD1E', '\uD87E\uDD1F', '\uD87E\uDD20', '\uD87E\uDD21', '\uD87E\uDD22', '\uD87E\uDD23', '\uD87E\uDD24', '\uD87E\uDD25', '\uD87E\uDD26', '\uD87E\uDD27', '\uD87E\uDD28', '\uD87E\uDD29', '\uD87E\uDD2A', '\uD87E\uDD2B', '\uD87E\uDD2C', '\uD87E\uDD2D', '\uD87E\uDD2E', '\uD87E\uDD2F', '\uD87E\uDD30', '\uD87E\uDD31', '\uD87E\uDD32', '\uD87E\uDD33', '\uD87E\uDD34', '\uD87E\uDD35', '\uD87E\uDD36', '\uD87E\uDD37', '\uD87E\uDD38', '\uD87E\uDD39', '\uD87E\uDD3A', '\uD87E\uDD3B', '\uD87E\uDD3C', '\uD87E\uDD3D', '\uD87E\uDD3E', '\uD87E\uDD3F', '\uD87E\uDD40', '\uD87E\uDD41', '\uD87E\uDD42', '\uD87E\uDD43', '\uD87E\uDD44', '\uD87E\uDD45', '\uD87E\uDD46', '\uD87E\uDD47', '\uD87E\uDD48', '\uD87E\uDD49', '\uD87E\uDD4A', '\uD87E\uDD4B', '\uD87E\uDD4C', '\uD87E\uDD4D', '\uD87E\uDD4E', '\uD87E\uDD4F', '\uD87E\uDD50', '\uD87E\uDD51', '\uD87E\uDD52', '\uD87E\uDD53', '\uD87E\uDD54', '\uD87E\uDD55', '\uD87E\uDD56', '\uD87E\uDD57', '\uD87E\uDD58', '\uD87E\uDD59', '\uD87E\uDD5A', '\uD87E\uDD5B', '\uD87E\uDD5C', '\uD87E\uDD5D', '\uD87E\uDD5E', '\uD87E\uDD5F', '\uD87E\uDD60', '\uD87E\uDD61', '\uD87E\uDD62', '\uD87E\uDD63', '\uD87E\uDD64', '\uD87E\uDD65', '\uD87E\uDD66', '\uD87E\uDD67', '\uD87E\uDD68', '\uD87E\uDD69', '\uD87E\uDD6A', '\uD87E\uDD6B', '\uD87E\uDD6C', '\uD87E\uDD6D', '\uD87E\uDD6E', '\uD87E\uDD6F', '\uD87E\uDD70', '\uD87E\uDD71', '\uD87E\uDD72', '\uD87E\uDD73', '\uD87E\uDD74', '\uD87E\uDD75', '\uD87E\uDD76', '\uD87E\uDD77', '\uD87E\uDD78', '\uD87E\uDD79', '\uD87E\uDD7A', '\uD87E\uDD7B', '\uD87E\uDD7C', '\uD87E\uDD7D', '\uD87E\uDD7E', '\uD87E\uDD7F', '\uD87E\uDD80', '\uD87E\uDD81', '\uD87E\uDD82', '\uD87E\uDD83', '\uD87E\uDD84', '\uD87E\uDD85', '\uD87E\uDD86', '\uD87E\uDD87', '\uD87E\uDD88', '\uD87E\uDD89', '\uD87E\uDD8A', '\uD87E\uDD8B', '\uD87E\uDD8C', '\uD87E\uDD8D', '\uD87E\uDD8E', '\uD87E\uDD8F', '\uD87E\uDD90', '\uD87E\uDD91', '\uD87E\uDD92', '\uD87E\uDD93', '\uD87E\uDD94', '\uD87E\uDD95', '\uD87E\uDD96', '\uD87E\uDD97', '\uD87E\uDD98', '\uD87E\uDD99', '\uD87E\uDD9A', '\uD87E\uDD9B', '\uD87E\uDD9C', '\uD87E\uDD9D', '\uD87E\uDD9E', '\uD87E\uDD9F', '\uD87E\uDDA0', '\uD87E\uDDA1', '\uD87E\uDDA2', '\uD87E\uDDA3', '\uD87E\uDDA4', '\uD87E\uDDA5', '\uD87E\uDDA6', '\uD87E\uDDA7', '\uD87E\uDDA8', '\uD87E\uDDA9', '\uD87E\uDDAA', '\uD87E\uDDAB', '\uD87E\uDDAC', '\uD87E\uDDAD', '\uD87E\uDDAE', '\uD87E\uDDAF', '\uD87E\uDDB0', '\uD87E\uDDB1', '\uD87E\uDDB2', '\uD87E\uDDB3', '\uD87E\uDDB4', '\uD87E\uDDB5', '\uD87E\uDDB6', '\uD87E\uDDB7', '\uD87E\uDDB8', '\uD87E\uDDB9', '\uD87E\uDDBA', '\uD87E\uDDBB', '\uD87E\uDDBC', '\uD87E\uDDBD', '\uD87E\uDDBE', '\uD87E\uDDBF', '\uD87E\uDDC0', '\uD87E\uDDC1', '\uD87E\uDDC2', '\uD87E\uDDC3', '\uD87E\uDDC4', '\uD87E\uDDC5', '\uD87E\uDDC6', '\uD87E\uDDC7', '\uD87E\uDDC8', '\uD87E\uDDC9', '\uD87E\uDDCA', '\uD87E\uDDCB', '\uD87E\uDDCC', '\uD87E\uDDCD', '\uD87E\uDDCE', '\uD87E\uDDCF', '\uD87E\uDDD0', '\uD87E\uDDD1', '\uD87E\uDDD2', '\uD87E\uDDD3', '\uD87E\uDDD4', '\uD87E\uDDD5', '\uD87E\uDDD6', '\uD87E\uDDD7', '\uD87E\uDDD8', '\uD87E\uDDD9', '\uD87E\uDDDA', '\uD87E\uDDDB', '\uD87E\uDDDC', '\uD87E\uDDDD', '\uD87E\uDDDE', '\uD87E\uDDDF', '\uD87E\uDDE0', '\uD87E\uDDE1', '\uD87E\uDDE2', '\uD87E\uDDE3', '\uD87E\uDDE4', '\uD87E\uDDE5', '\uD87E\uDDE6', '\uD87E\uDDE7', '\uD87E\uDDE8', '\uD87E\uDDE9', '\uD87E\uDDEA', '\uD87E\uDDEB', '\uD87E\uDDEC', '\uD87E\uDDED', '\uD87E\uDDEE', '\uD87E\uDDEF', '\uD87E\uDDF0', '\uD87E\uDDF1', '\uD87E\uDDF2', '\uD87E\uDDF3', '\uD87E\uDDF4', '\uD87E\uDDF5', '\uD87E\uDDF6', '\uD87E\uDDF7', '\uD87E\uDDF8', '\uD87E\uDDF9', '\uD87E\uDDFA', '\uD87E\uDDFB', '\uD87E\uDDFC', '\uD87E\uDDFD', '\uD87E\uDDFE', '\uD87E\uDDFF', '\uD87E\uDE00', '\uD87E\uDE01', '\uD87E\uDE02', '\uD87E\uDE03', '\uD87E\uDE04', '\uD87E\uDE05', '\uD87E\uDE06', '\uD87E\uDE07', '\uD87E\uDE08', '\uD87E\uDE09', '\uD87E\uDE0A', '\uD87E\uDE0B', '\uD87E\uDE0C', '\uD87E\uDE0D', '\uD87E\uDE0E', '\uD87E\uDE0F', '\uD87E\uDE10', '\uD87E\uDE11', '\uD87E\uDE12', '\uD87E\uDE13', '\uD87E\uDE14', '\uD87E\uDE15', '\uD87E\uDE16', '\uD87E\uDE17', '\uD87E\uDE18', '\uD87E\uDE19', '\uD87E\uDE1A', '\uD87E\uDE1B', '\uD87E\uDE1C', '\uD87E\uDE1D', '\uD87E\uDE1E', '\uD87E\uDE1F' ];
a = func(), b = z; for (a++; i < 10; i++)alert(i); var z = 1; g = 2; for (; i < 10; i++)alert(i); var a = 2; for (var i = 1; i < 10; i++)alert(i)
'use strict'; require('./fleet-location-vehicle-details.controller'); require('./fleet-vehicle-property-synchronizer.factory'); require('./vehicle-image-service.factory'); describe('fa.fleet.FleetLocationVehicleDetailsController > ', function describeImpl() { var $q; var $scope; var $state; var fleetLocationVehicleStrategyFactory; var implementationStrategy; var fleetLocationVehicleDetailsModeService; var vehicleImageService; var controller; var vehicle = {id: 1}; var location = {id: '1'}; var selectedMake = { id: 'che', name: 'Chevrolet' }; var makes = [ { id: 'tsl', name: 'Tesla' }, selectedMake ]; var selectedModel = { id: 'cvt', name: 'Corvette' }; var models = [ { id: 'tmx', name: 'Model X' }, selectedModel ]; var years = [2016, 2017]; var colors = ['Black', 'Red', 'Silver']; var initializationData = { vehicle: vehicle, location: location, makes: makes, selectedMake: selectedMake, selectedModel: selectedModel }; var navigationState = { vehicleId: '1000', locationId: 'fooßar'}; var getInitializationDataStub; var synchronizerInitializerSpy; var getSynchronizedDataStub; beforeEach(angular.mock.module('fa.fleet')); beforeEach(inject(function injectImpl(_$q_, _$rootScope_, _faFleetLocationVehicleStrategyFactory_, _faFleetLocationVehicleDetailsModeService_, _faFleetLocationVehicleEditStrategy_, _faFleetVehiclePropertySynchronizer_, _faVehicleImageService_) { $q = _$q_; $scope = _$rootScope_.$new(); fleetLocationVehicleStrategyFactory = _faFleetLocationVehicleStrategyFactory_; fleetLocationVehicleDetailsModeService = _faFleetLocationVehicleDetailsModeService_; implementationStrategy = _faFleetLocationVehicleEditStrategy_; vehicleImageService = _faVehicleImageService_; $state = { params: { vehicleId: navigationState.vehicleId, locationId: navigationState.locationId } }; // We return a known strategy so that // 1) the controller is initialized correctly, and // 2) we can create stubs and spies based on it. fleetLocationVehicleStrategyFactory.getStrategy = function getStrategy() { return implementationStrategy; }; getInitializationDataStub = sinon.stub(implementationStrategy, 'getInitializationData', function getInitializationData() { var deferred = $q.defer(); deferred.resolve(initializationData); return deferred.promise; } ); synchronizerInitializerSpy = sinon.spy(_faFleetVehiclePropertySynchronizer_, 'initialize'); getSynchronizedDataStub = sinon.stub(_faFleetVehiclePropertySynchronizer_, 'getSynchronizedData', function getSynchronizedData(actualVehicle) { return (actualVehicle.id === vehicle.id) ? { models: models, years: years, colors: colors } : null; }); angular.mock.inject([ '$controller', function assignController($controller) { controller = $controller('FaFleetLocationVehicleDetailsController', { '$scope': $scope, '$state': $state, 'faFleetLocationVehicleStrategyFactory': fleetLocationVehicleStrategyFactory, 'faFleetLocationVehicleDetailsModeService': fleetLocationVehicleDetailsModeService, 'faFleetVehiclePropertySynchronizer': _faFleetVehiclePropertySynchronizer_, 'faVehicleImageService': vehicleImageService }); } ]); // Run the controller initialization function... $scope.$apply(); })); describe('initialize', function initializeTest() { it('calls getInitializationData with correct arguments', function testImpl() { getInitializationDataStub.calledWith(navigationState.locationId, navigationState.vehicleId).should.be.true; }); it('sets the correct location', function testImpl() { controller.location.should.deep.equal(initializationData.location); }); it('sets the correct vehicle', function testImpl() { controller.vehicle.should.deep.equal(initializationData.vehicle); }); it('sets the correct makes', function testImpl() { controller.makes.should.deep.equal(initializationData.makes); }); it('sets the selected make', function testImpl() { controller.selectedMake.should.deep.equal(initializationData.selectedMake); }); it('sets the selected model', function testImpl() { controller.selectedModel.should.deep.equal(initializationData.selectedModel); }); it('initializes the synchronizer', function testImpl() { synchronizerInitializerSpy.calledWith(initializationData).should.be.true; }); describe('calls synchLookups and', function synchLookupsTest() { it('synchronizes the lookup data', function testImpl() { getSynchronizedDataStub.calledWith(vehicle).should.be.true; }); it('sets the models', function testImpl() { controller.models.should.deep.equal(models); }); it('sets the years', function testImpl() { controller.years.should.deep.equal(years); }); it('sets the colors', function testImpl() { controller.colors.should.deep.equal(colors); }); }); }); describe('isEditable', function isEditableTest() { var isAddModeStub; var isEditModeStub; beforeEach(function beforeEach() { isAddModeStub = sinon.stub(fleetLocationVehicleDetailsModeService, 'isAddMode'); isEditModeStub = sinon.stub(fleetLocationVehicleDetailsModeService, 'isEditMode'); }); it('returns true if is in Edit mode', function testImpl() { isAddModeStub.returns(false); isEditModeStub.returns(true); controller.isEditable().should.be.true; }); it('returns true if is in Add mode', function testImpl() { isAddModeStub.returns(true); isEditModeStub.returns(false); controller.isEditable().should.be.true; }); it('returns false if is not in Add or Edit mode', function testImpl() { isAddModeStub.returns(false); isEditModeStub.returns(false); controller.isEditable().should.be.false; }); }); it('save saves the correct vehicle', function testImpl() { var saveSpy = sinon.spy(implementationStrategy, 'save'); controller.save(); saveSpy.calledWith(location.id, initializationData.vehicle).should.be.true; }); describe('onLoadImageFile', function onLoadImageFileTests() { var getImageDataStub; var imageData = 'foobar'; var file = {}; var vehicleForm = { $setDirty: function setDirty() { } }; beforeEach(function beforeEach() { getImageDataStub = sinon.stub(vehicleImageService, 'getImageData', function getImageData($file) { return $q.when($file === file ? imageData : 'oops!'); }); $scope.vehicleForm = vehicleForm; }); it('sets error message on invalid file', function testImpl() { controller.onLoadImageFile(null, null, null, null, ['foo']); expect(controller.imageFileErrorMessage).to.equal('File exceeds maximum size of 70KB.'); }); it('returns without processing if $file is null or undefined', function testImpl() { controller.onLoadImageFile(); expect(getImageDataStub.called).to.be.false; }); it('sets the image', function testImpl() { controller.onLoadImageFile(null, file); $scope.$apply(); expect(controller.vehicle.image).to.equal(imageData); }); it('dirties the form', function testImpl() { var setDirtySpy = sinon.spy(vehicleForm, '$setDirty'); controller.onLoadImageFile(null, file); $scope.$apply(); expect(setDirtySpy.called).to.be.true; }); afterEach(function afterEach() { getImageDataStub.reset(); }); }); });
/** * @license * Copyright 2016 Google Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @fileoverview Used within pre-release.sh, this checks a component's package.json * to ensure that if it's a new component (version = "0.0.0"), it will have a proper * "publishConfig.access" property set to "public". * The argument should be the package.json file to check. */ const assert = require('assert'); const fs = require('fs'); const readDirRecursive = require('fs-readdir-recursive'); const path = require('path'); const childProcess = require('child_process'); const {default: traverse} = require('babel-traverse'); const camelCase = require('camel-case'); const recast = require('recast'); const typescriptParser = require('recast/parsers/typescript'); const CLI_PACKAGE_JSON_RELATIVE_PATH = process.argv[2]; if (!CLI_PACKAGE_JSON_RELATIVE_PATH) { console.error(`Usage: node ${path.basename(process.argv[1])} packages/mdc-foo/package.json`); process.exit(1); } const PACKAGE_RELATIVE_PATH = CLI_PACKAGE_JSON_RELATIVE_PATH.replace('package.json', ''); if (!new RegExp('packages/[^/]+/package.json$').test(CLI_PACKAGE_JSON_RELATIVE_PATH)) { console.error(`Invalid argument: "${CLI_PACKAGE_JSON_RELATIVE_PATH}" is not a valid path to a package.json file.`); console.error('Expected format: packages/mdc-foo/package.json'); process.exit(1); } const CLI_PACKAGE_JSON = require(path.resolve(CLI_PACKAGE_JSON_RELATIVE_PATH)); const WEBPACK_CONFIG_RELATIVE_PATH = 'webpack.config.js'; const WEBPACK_CONFIG = require(path.resolve(WEBPACK_CONFIG_RELATIVE_PATH)); const MASTER_TS_RELATIVE_PATH = 'packages/material-components-web/index.ts'; const MASTER_CSS_RELATIVE_PATH = 'packages/material-components-web/material-components-web.scss'; const MASTER_PACKAGE_JSON_RELATIVE_PATH = 'packages/material-components-web/package.json'; const MASTER_PACKAGE_JSON = require(path.resolve(MASTER_PACKAGE_JSON_RELATIVE_PATH)); // These few MDC packages work as foundation or utility packages, and are not // directly included in webpack or the material-component-web module. But they // are necessary since other MDC packages depend on them. const CSS_EXCLUDES = new Set([ 'base', 'animation', 'auto-init', 'density', 'dom', 'feature-targeting', 'focus-ring', 'progress-indicator', 'rtl', 'shape', 'tokens', 'touch-target', ]); const JS_EXCLUDES = new Set([ 'animation', 'progress-indicator', 'tokens', 'chips', // Temporarily added during deprecation migration. ]); const NOT_AUTOINIT = new Set([ 'auto-init', 'base', 'dom', 'progress-indicator', 'tab', // Only makes sense in context of tab-bar 'tab-indicator', // Only makes sense in context of tab-bar 'tab-scroller', // Only makes sense in context of tab-bar ]); main(); function main() { checkPublicConfigForNewComponent(); if (CLI_PACKAGE_JSON.name !== MASTER_PACKAGE_JSON.name) { if (CLI_PACKAGE_JSON.private) { console.log('Skipping private component', CLI_PACKAGE_JSON.name); } else { checkDependencyAddedInWebpackConfig(); checkDependencyAddedInMDCPackage(); checkUsedDependenciesMatchDeclaredDependencies(); } } } function checkPublicConfigForNewComponent() { if (CLI_PACKAGE_JSON.version === '0.0.0') { assert.notEqual(typeof CLI_PACKAGE_JSON.publishConfig, 'undefined', 'Please add publishConfig to' + CLI_PACKAGE_JSON.name + '\'s package.json. Consult our ' + 'docs/authoring-components.md to ensure your component\'s package.json ' + 'is well-formed.'); assert.equal(CLI_PACKAGE_JSON.publishConfig.access, 'public', 'Please set publishConfig.access to "public" in ' + CLI_PACKAGE_JSON.name + '\'s package.json. ' + 'Consult our docs/authoring-components.md to ensure your component\'s package.json ' + 'is well-formed.'); } } function checkDependencyAddedInWebpackConfig() { // Check if css has been added to webpack config checkCSSDependencyAddedInWebpackConfig(); // Check if js component has been added to webpack config if (typeof(CLI_PACKAGE_JSON.main) !== 'undefined') { checkJSDependencyAddedInWebpackConfig(); } } function checkJSDependencyAddedInWebpackConfig() { const name = getPkgName(); if (JS_EXCLUDES.has(name)) { return; } const jsconfig = WEBPACK_CONFIG.find((value) => { return value.name === 'main-js-a-la-carte'; }); const pkgName = CLI_PACKAGE_JSON.name.replace('@material/', ''); assert.notEqual(typeof jsconfig.entry[pkgName], 'undefined', 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' javascript dependency is not added to webpack ' + 'configuration. Please add ' + pkgName + ' to ' + WEBPACK_CONFIG_RELATIVE_PATH + '\'s js-components ' + 'entry before commit. If package @material/' + name + ' has no exported JS, add "' + name + '" to ' + 'the JS_EXCLUDES set in this file.'); } function checkCSSDependencyAddedInWebpackConfig() { const name = getPkgName(); if (CSS_EXCLUDES.has(name)) { return; } const cssconfig = WEBPACK_CONFIG.find((value) => { return value.name === 'main-css-a-la-carte'; }); const nameMDC = CLI_PACKAGE_JSON.name.replace('@material/', 'mdc.'); assert.notEqual(typeof cssconfig.entry[nameMDC], 'undefined', 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' css dependency not added to webpack ' + 'configuration. Please add ' + name + ' to ' + WEBPACK_CONFIG_RELATIVE_PATH + '\'s css ' + 'entry before commit. If package @material/' + name + ' exports no concrete Sass, add ' + '"' + name + '" to the CSS_EXCLUDES set in this file.'); } function checkDependencyAddedInMDCPackage() { // Package is added to package.json checkPkgDependencyAddedInMDCPackage(); // SCSS is added to @import rule checkCSSDependencyAddedInMDCPackage(); // If any, foundation is added to index and autoInit checkJSDependencyAddedInMDCPackage(); } function checkPkgDependencyAddedInMDCPackage() { const name = getPkgName(); if (CSS_EXCLUDES.has(name) && JS_EXCLUDES.has(name)) { return; } assert.notEqual(typeof MASTER_PACKAGE_JSON.dependencies[CLI_PACKAGE_JSON.name], 'undefined', 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not a dependency for MDC Web. ' + 'Please add ' + CLI_PACKAGE_JSON.name +' to ' + MASTER_PACKAGE_JSON_RELATIVE_PATH + '\' dependencies before commit.'); } function checkCSSDependencyAddedInMDCPackage() { const name = getPkgName(); if (CSS_EXCLUDES.has(name)) { return; } const src = fs.readFileSync(path.join(process.env.PWD, MASTER_CSS_RELATIVE_PATH), 'utf8'); const shouldImportCSS = !!src.match(`${CLI_PACKAGE_JSON.name}/`); assert(shouldImportCSS, 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not being imported in MDC Web. ' + 'Please add ' + name + ' to ' + MASTER_CSS_RELATIVE_PATH + ' import rule before commit.'); } function checkJSDependencyAddedInMDCPackage() { const name = getPkgName(); if (typeof (CLI_PACKAGE_JSON.main) === 'undefined' || JS_EXCLUDES.has(name)) { return; } const nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', '')); const src = fs.readFileSync(path.join(process.env.PWD, MASTER_TS_RELATIVE_PATH), 'utf8'); const ast = recast.parse(src, {parser: typescriptParser}); assert(checkComponentImportedAddedInMDCPackage(ast), 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not being imported in MDC Web. ' + 'Please add ' + nameCamel + ' to '+ MASTER_TS_RELATIVE_PATH + ' import rule before commit.'); assert(checkComponentExportedAddedInMDCPackage(ast), 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not being exported in MDC Web. ' + 'Please add ' + nameCamel + ' to '+ MASTER_TS_RELATIVE_PATH + ' export before commit.'); if (!NOT_AUTOINIT.has(name)) { assert(checkAutoInitAddedInMDCPackage(ast) > 0, 'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' seems not being auto inited in MDC Web. ' + 'Please add ' + nameCamel + ' to '+ MASTER_TS_RELATIVE_PATH + ' autoInit statement before commit.'); } } function checkComponentImportedAddedInMDCPackage(ast) { let isImported = false; traverse(ast, { 'ImportDeclaration'({node}) { if (node.source) { const source = node.source.value; const pkgFile = CLI_PACKAGE_JSON.name + '/index'; if (source === pkgFile) { isImported = true; } } }, }); return isImported; } function checkAutoInitAddedInMDCPackage(ast) { let nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', '')); if (nameCamel === 'textfield') { nameCamel = 'textField'; } else if (nameCamel === 'switch') { nameCamel = 'switchControl'; } let autoInitedCount = 0; traverse(ast, { 'ExpressionStatement'({node}) { const callee = node.expression.callee; const args = node.expression.arguments; if (callee.object.name === 'autoInit' && callee.property.name === 'register') { for (let value of args) { // When searching for a MemberExpression, if a typescript "as a" // expression is found, recursively search its expression, since TS // may define something "as a" multiple times. // // Example: object.foo as unknown as any as Interface while (value.type === 'TSAsExpression') { value = value.expression; } // For the given ExpressionStatement node whose callee name is // "autoInit" and call property name is "register": // // autoInit.register('MDCCheckbox', checkbox.MDCCheckbox); // // We are searching the arguments provided to the expression to find // the object with the package name ("checkbox" in the example). // These node expression types which access an object's members are // called MemberExpressions. The name of the object should be the // package name. if (value.type === 'MemberExpression' && value.object.name === nameCamel) { autoInitedCount++; break; } } } }, }); return autoInitedCount; } function checkComponentExportedAddedInMDCPackage(ast) { let nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', '')); if (nameCamel === 'textfield') { nameCamel = 'textField'; } else if (nameCamel === 'switch') { nameCamel = 'switchControl'; } let isExported = false; traverse(ast, { 'ExportNamedDeclaration'({node}) { if (node.specifiers) { if (node.specifiers.find((value) => { return value.exported.name === nameCamel; })) { isExported = true; } } }, }); return isExported; } /** * Checks that all dependencies used in SASS and TypeScript files in the package * match up with those declared in package.json. * * @throws {AssertionError} Will throw an error if dependencies do not strictly match. */ function checkUsedDependenciesMatchDeclaredDependencies() { const files = readDirRecursive( PACKAGE_RELATIVE_PATH, (fileName) => { return fileName[0] !== '.' && fileName !== 'node_modules' && fileName !== 'test'; }, ); const usedDeps = new Set(); const importMatcher = RegExp('(@use|@import|from) ["\'](@material/[^/"\']+)', 'g'); files.forEach((file) => { if (file.endsWith('.scss') || file.endsWith('.ts') && !file.endsWith('.d.ts')) { const src = fs.readFileSync(path.join(PACKAGE_RELATIVE_PATH, file), 'utf8'); while ((dep = importMatcher.exec(src)) !== null) { usedDeps.add(dep[2]); } } }); const declaredDeps = new Set( Object.keys(CLI_PACKAGE_JSON.dependencies ? CLI_PACKAGE_JSON.dependencies : []) .filter((key) => key.startsWith('@material/'))); const usedButNotDeclared = [...usedDeps].filter((x) => !declaredDeps.has(x)); const declaredButNotUsed = [...declaredDeps].filter((x) => !usedDeps.has(x)); assert.equal(usedButNotDeclared.length, 0, getMissingDependencyMsg(usedButNotDeclared)); assert.equal(declaredButNotUsed.length, 0, getUnusedDependencyMsg(declaredButNotUsed)); } function getPkgName() { let name = CLI_PACKAGE_JSON.name.split('/')[1]; if (name === 'textfield') { // Text-field now has a dash in the name. The package cannot be changed, // since it is a lot of effort to rename npm package name = 'text-field'; } return name; } function getMissingDependencyMsg(missingDeps) { const missingDepsWithVersions = getPackageNamesWithVersions(missingDeps); let msg = 'FAILURE: The following MDC dependencies were used in ' + CLI_PACKAGE_JSON.name + ' but were not declared in its package.json:\n' + missingDepsWithVersions.join('\n') + '\n\nPlease add the missing dependencies to package.json manually, or by ' + 'running the following command(s) on the root of the repository:\n'; missingDepsWithVersions.forEach((dep) => { msg += `npx lerna add ${dep} packages/${PACKAGE_RELATIVE_PATH.split('/')[1]}\n`; }); return msg; } function getUnusedDependencyMsg(unusedDeps) { let msg = 'FAILURE: The following MDC dependencies in package ' + CLI_PACKAGE_JSON.name + ' are declared in its package.json but not used:\n' + unusedDeps.join('\n') + '\n\nPlease remove the unused dependencies in package.json manually, or ' + 'by running the following command(s) on the root of the repository:\n'; unusedDeps.forEach((dep) => { msg += `npx lerna exec --scope ${CLI_PACKAGE_JSON.name} -- npm uninstall --no-shrinkwrap ${dep}\n`; }); return msg; } function getPackageNamesWithVersions(packageNames) { const packageNamesWithVersions = []; packageNames.forEach((name) => { const version = childProcess.execSync(`npm show ${name} version`).toString().replace('\n', ''); packageNamesWithVersions.push(`${name}@${version}`); }); return packageNamesWithVersions; }
var escapeRE = /([.*+?^=!:$(){}|[\]\/\\])/g function createName(name){ var escapedName = name.replace(escapeRE, "\\$1") return RegExp(escapedName) } function getRandom(list){ return list[Math.floor(Math.random() * list.length)] } module.exports = function(bot, options){ bot.mention( createName(options.name), function(){ this.queue(getRandom(options.list)) } ) }
var numberGreaterThanOrEqualTo = require('./numberGreaterThanOrEqualTo'); window.legacy = {}; window.legacy.numberGreaterThanOrEqualTo = function() { console.info('numberGreaterThanOrEqualTo(1, 2)', numberGreaterThanOrEqualTo(1, 2)); console.info('numberGreaterThanOrEqualTo(1, "dd")', numberGreaterThanOrEqualTo(1, 'dd')); console.info('numberGreaterThanOrEqualTo(4, 2)', numberGreaterThanOrEqualTo(4, 2)); console.info('numberGreaterThanOrEqualTo(4, 4)', numberGreaterThanOrEqualTo(4, 4)); console.info('numberGreaterThanOrEqualTo(NaN, NaN)', numberGreaterThanOrEqualTo(NaN, NaN)); };
(function( $ ) { var clicked = false; $('.navmenu').on('click',function(){ if(clicked) { $('.navmenu-item').css({"display": "none"}); clicked = false; } else { if ($(window).innerWidth() < 701) { $('.navmenu-item').css({ "display": 'inline'}); } else { $('.navmenu-item').css({ "display": 'inline'}); } clicked = true; } }); $(window).resize(function(){ $('.navmenu-item').each(function() { var item = $(this); if($(item).css("display") != "none") { $(item).css({"display":"none"}); } }); clicked = false; }); })(window.jQuery);
module.exports = (string, times = 1) => { if (typeof string !== 'string') { throw new Error('args[0] must be a string'); } let res = ''; let max = string.length * times; if (times === 1) return string; if (times === 2) return string + string; while (max > res.length && times > 1) { // 3,5,7,... if (times & 1) { res += string; } times >>= 1; string += string; } res += string; res = res.substr(0, max); return res; };
communicationModule.controller('parentController', function($scope, userService, sharedService) { $scope.parentUserData = userService.getUserData(); $scope.parentData = ''; });
Mariachi.Routers.RecepiesRouter = Backbone.Router.extend({ initialize: function() { }, routes: { "": "home", "recepies/add": "addRecepie", "recepies/:id": "getRecepie", "recepies/edit/:id": "editRecepie", "recepies/delete/:id": "deleteRecepie", "recepies/execute/:id": "deployRecepie" }, home: function() { new Mariachi.Views.ListRecepies(); }, getRecepie: function(id) { new Mariachi.Views.ViewRecepie({id: id}); }, addRecepie: function() { new Mariachi.Views.AddRecepie(); }, editRecepie: function(id) { new Mariachi.Views.EditRecepie({id: id}); }, deleteRecepie: function(id) { new Mariachi.Views.DeleteRecepie({id: id}); }, deployRecepie: function(id) { new Mariachi.Views.ExecuteRecepie({id: id}); } });
// Generated on 2013-10-19 using generator-webapp 0.4.3 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // show elapsed time at the end require('time-grunt')(grunt); // load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ // configurable paths yeoman: { app: 'app', dist: 'dist' }, watch: { compass: { files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer'] }, styles: { files: ['<%= yeoman.app %>/styles/{,*/}*.css'], tasks: ['copy:styles', 'autoprefixer'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= yeoman.app %>/*.html', '.tmp/styles/{,*/}*.css', '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, connect: { options: { port: 9000, livereload: 35729, // change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { open: true, base: [ '.tmp', '<%= yeoman.app %>' ] } }, test: { options: { base: [ '.tmp', 'test', '<%= yeoman.app %>' ] } }, dist: { options: { open: true, base: '<%= yeoman.dist %>' } } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js', '!<%= yeoman.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html'] } } }, compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false, assetCacheBuster: false }, dist: { options: { generatedImagesDir: '<%= yeoman.dist %>/images/generated' } }, server: { options: { debugInfo: true } } }, autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // not used since Uglify task does concat, // but still available if needed /*concat: { dist: {} },*/ requirejs: { dist: { // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js options: { // `name` and `out` is set by grunt-usemin baseUrl: '<%= yeoman.app %>/scripts', optimize: 'none', // TODO: Figure out how to make sourcemaps work with grunt-usemin // https://github.com/yeoman/grunt-usemin/issues/30 //generateSourceMaps: true, // required to support SourceMaps // http://requirejs.org/docs/errors.html#sourcemapcomments preserveLicenseComments: false, useStrict: true, wrap: true //uglify2: {} // https://github.com/mishoo/UglifyJS2 } } }, rev: { dist: { files: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}', '<%= yeoman.dist %>/styles/fonts/{,*/}*.*' ] } } }, useminPrepare: { options: { dest: '<%= yeoman.dist %>' }, html: '<%= yeoman.app %>/index.html' }, usemin: { options: { dirs: ['<%= yeoman.dist %>'] }, html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'] }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, cssmin: { // This task is pre-configured if you do not wish to use Usemin // blocks for your CSS. By default, the Usemin block from your // `index.html` will take care of minification, e.g. // // <!-- build:css({.tmp,app}) styles/main.css --> // // dist: { // files: { // '<%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= yeoman.app %>/styles/{,*/}*.css' // ] // } // } }, htmlmin: { dist: { options: { /*removeCommentsFromCDATA: true, // https://github.com/yeoman/grunt-usemin/issues/44 //collapseWhitespace: true, collapseBooleanAttributes: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeOptionalTags: true*/ }, files: [{ expand: true, cwd: '<%= yeoman.app %>', src: '*.html', dest: '<%= yeoman.dist %>' }] } }, // Put files not handled in other tasks here copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'images/{,*/}*.{webp,gif}', 'styles/fonts/{,*/}*.*', 'bower_components/sass-bootstrap/fonts/*.*' ] }] }, styles: { expand: true, dot: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, modernizr: { devFile: '<%= yeoman.app %>/bower_components/modernizr/modernizr.js', outputFile: '<%= yeoman.dist %>/bower_components/modernizr/modernizr.js', files: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '!<%= yeoman.dist %>/scripts/vendor/*' ], uglify: true }, concurrent: { server: [ 'compass', 'copy:styles' ], test: [ 'copy:styles' ], dist: [ 'compass', 'copy:styles', 'imagemin', 'svgmin', 'htmlmin' ] }, bower: { options: { exclude: ['modernizr'] }, all: { rjsConfig: '<%= yeoman.app %>/scripts/main.js' } } }); grunt.registerTask('server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'mocha' ]); grunt.registerTask('build', [ 'clean:dist', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'requirejs', 'concat', 'cssmin', 'uglify', 'modernizr', 'copy:dist', 'rev', 'usemin' ]); grunt.registerTask('default', [ 'jshint', 'test', 'build' ]); };
/* @flow */ import Parser from "./index"; import { SourceLocation } from "../util/location"; // Start an AST node, attaching a start offset. const pp = Parser.prototype; class Node { constructor(pos?: number, loc?: SourceLocation) { this.type = ""; this.start = pos; this.end = 0; this.loc = new SourceLocation(loc); } type: string; start: ?number; end: number; loc: SourceLocation; __clone(): Node { var node2 = new Node; for (var key in this) node2[key] = this[key]; return node2; } } pp.startNode = function () { return new Node(this.state.start, this.state.startLoc); }; pp.startNodeAt = function (pos, loc) { return new Node(pos, loc); }; function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; node.loc.end = loc; this.processComment(node); return node; } // Finish an AST node, adding `type` and `end` properties. pp.finishNode = function (node, type) { return finishNodeAt.call(this, node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); }; // Finish node at given position pp.finishNodeAt = function (node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc); };
//The generic 3D object from which many world items will inherit quack.core.genericObj = function(attr) { //constructor this.id = attr.id || "defaultID"; //can replace this with a random ID this.type = attr.type | "generic"; this.parent = undefined; this.children = []; //this.position = new quack.math.vector3(0, 0, 0); //set position if (attr.position === undefined) { this.position = new quack.math.vector3(0, 0, 0); } else if (!(attr.position instanceof quack.math.vector3)){ this.position = new quack.math.vector3(attr.position.x, attr.position.y, attr.position.z); } else { this.position = attr.position; } //set lookAt if (attr.lookAt === undefined) { this.lookAt = new quack.math.vector3(0, 0, 0); } else if (!(attr.lookAt instanceof quack.math.vector3)){ this.lookAt = new quack.math.vector3(attr.lookAt.x, attr.lookAt.y, attr.lookAt.z); } else { this.lookAt = attr.lookAt; } this.up = new quack.math.vector3(0, 1, 0); //this.lookAt = new quack.math.vector3(0, 0, 0); this.scale = new quack.math.vector3(1, 1, 1); this.modelMatrix = new quack.math.matrix4(); this.setPosition = function(x, y ,z) { this.position.set(x, y ,z); return this; }; this.setUp = function(x, y, z) { this.up.set(x, y, z); return this; }; this.setLookAt = function(x, y, z) { this.lookAt.set(x, y, z); return this; }; this.append = function(obj) { this.children.push(obj); return this; }; };
import alt from '../alt'; class CharacterListActions { constructor(){ this.generateActions( 'getCharacterSuccess', 'getCharacterFail' ); } getCharacters(payload) { let url = '/api/characters/top'; let params = { race: payload.race, bloodline: payload.bloodline }; if(payload.category === 'female') { params.gender = 'female'; }else if(payload.category === 'male') { params.gender = 'male'; } if(payload.category === 'shame') { url = '/api/characters/shame'; } $.ajax({url:url, data:params}).done((data)=>{ this.actions.getCharacterSuccess(data); }).fail((jqXhr)=>{ this.actions.getCharacterFail(jqXhr); }); } } export default alt.createActions(CharacterListActions);
/** @jsx React.DOM */ jest.dontMock('../../../scripts/gebo/objectToQueryString'); var React = require('react/addons'), TestUtils = React.addons.TestUtils; var objectToQueryString = require('../../../scripts/gebo/objectToQueryString'); describe('objectToQueryString', function() { it('should return an URL-friendly parameter string', function() { var params = { response_type: 'token', client_id: 'gebo-hai@capitolhill.ca', client_name: 'gebo-hai', redirect_uri: 'https://localhost:3000/oauth2callback.html', scope: '', }; var expectedString = 'response_type=' + encodeURIComponent('token') + '&' + 'client_id=' + encodeURIComponent('gebo-hai@capitolhill.ca') + '&' + 'client_name=' + encodeURIComponent('gebo-hai') + '&' + 'redirect_uri=' + encodeURIComponent('https://localhost:3000/oauth2callback.html') + '&' + 'scope=' + encodeURIComponent(''); var queryString = objectToQueryString(params); expect(queryString).toEqual(expectedString); }); it('shouldn\'t barf if given an empty object', function() { var queryString = objectToQueryString({}); expect(queryString).toEqual(''); }); });
export { default } from "./../../_gen/openfl/media/SoundLoaderContext";
/** * HTTP server to Axis camera */ var http = require('http'), url = require('url'), es = require('event-stream') var axis = require('./axis').createClient(JSON.parse(require('fs').readFileSync(__dirname + '/../settings.json'))) var raise500 = function(res) { res.statusCode = 500 res.setHeader('Content-Type', 'text/plain') res.end('Error on server') } var handlers = { '/': function(req, res) { res.writeHead(200, {'Content-Type': 'application/json'}) res.end(JSON.stringify({ version: require('../package.json').version, time: new Date, message: 'Welcome to AxisCam' })) }, '/time': function(req, res) { res.statusCode = 200 res.setHeader('Content-Type', 'text/plain') axis.time(function(err, time) { if (err) return raise500(res) res.end(time.toString()) }) }, '/image': function(req, res, query) { res.statusCode = 200 res.setHeader('Content-Type', 'image/jpeg') res.setHeader('cache-control', 'no-cache') res.setHeader('pragma', 'no-cache') axis.image(function(err, image) { res.end(image) }) }, '/video': function(req, res, query) { res.statusCode = 200 res.setHeader('cache-control', 'no-cache') res.setHeader('pragma', 'no-cache') res.setHeader('Content-Type', 'multipart/x-mixed-replace; boundary=myboundary') axis.videoStream().pipe(res) }, '/motion': function(req, res) { res.statusCode = 200 res.setHeader('Content-Type', 'text/plain') axis.createMotionStream(function(err, stream) { if (err) return raise500(res) stream.pipe(es.stringify()).pipe(res) }) } } var route = function(req, res) { var uri = url.parse(req.url, true) var query = uri.query var path = uri.pathname if (handlers[path]) handlers[path](req, res, query) else { // console.log('Invalid URL requested: ' + path); res.writeHead(404, {'Content-Type': 'text/html'}) res.end('<h1>404</h1><p>Page not found</p>') } } http.createServer(route).listen(1337, '0.0.0.0') console.log('Server running at http://127.0.0.1:1337/')
var $ = require('jquery'); var MediaBrowser = require('./media').MediaBrowser; // hold the media browser singleton var browser = null; /** * tinyMCE callback function creator * Return a closure for the tinyMCE media browser callback * @param {[type]} url URL to the TweedeGolfMediaBundle modal page * @return {function} callback for tinyMCE */ exports.tinymce_callback = function (url) { /** * tinyMCE callback function * Triggeres an ajax request that results in a media picker modal * @param {string} field_name name of the field the URL to the file should be inserted */ return function (field_name) { // initiate only one media browser if (browser === null) { browser = new MediaBrowser({ modalUrl: url, afterInit: function (element) { $(element).modal({show: false}); } }); } // calback function that is triggered // after a file is clicked in the modal browser.callback = function (fileURL) { var elem = $('#' + field_name); // check if there is an tinyMCE url field if (elem.length > 0) { // insert the resulting file URL elem.val(fileURL); } // hide the browser modal $(browser.element).modal('hide'); }; // show the browser modal $(browser.element).modal('show'); }; };
export function addComment(comment) { return new Promise(resolve => { setTimeout(resolve, 2000); }); } export function getAllComments() { return Promise.resolve({data: [ { email: 'first@test.com', message: 'New Comment' }, { email: 'second@test.com', message: 'My Comment' }, { email: 'we@nowhere.com', message: '3rd Comment' } ]}); } export function clearComments() { return Promise.resolve(); }
rock.namespace('rock.scene.graphics.scene'); /** * This class is the representation for a ModelNode. * * ATTENTION: * This class is awful. The representations are not thought to be generic... * A representation must know what model it handles but here a generic model is passed instead... * This is why 'updateModel' and 'createRenderables' has no code and there is a function * 'createRenderablesFromModel' that let you initiate the representation from a model. * PLEASE, AVOID TO DO THIS WHENEVER POSSIBLE * * @constructor * @extends rock.game.graphics.scene.AffineTransformationRepresentation * * @author Luis Alberto Jiménez */ rock.scene.graphics.scene.ModelNodeRepresentation = function (representationAttendant, object) { rock.super_(this, arguments); }; rock.extends_(rock.scene.graphics.scene.ModelNodeRepresentation, rock.game.graphics.scene.AffineTransformationRepresentation); rock.scene.graphics.scene.ModelNodeRepresentation.prototype.updateModel = function () { }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.createRenderables = function () { }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.createRenderablesFromModel = function (baseModel) { this.model = baseModel; var renderables = this.renderables; var modelArray = this.getAsModelArray(baseModel); var renderEngine = this.representationAttendant.getRenderEngine(); var i, model, renderable, adapter; for (i = 0; i < modelArray.length; i++) { model = modelArray[i]; renderable = renderEngine.createRenderable(model); adapter = renderEngine.createAdapter(model); adapter.build(); renderable.setModelAdapter(adapter); renderables.addValue(renderable); } }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.releaseRenderables = function () { var renderables = this.renderables; var length = renderables.getLength(); var i, renderable, adapter; for (i = 0; i < length; i++) { renderable = renderables.getValue(i); adapter = renderable.getModelAdapter(); if (adapter != null) { adapter.release(); } } renderables.clear(true); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.getAsModelArray = function (model) { var modelArray = null; if (rock.instanceof_(model, rock.game.graphics.model.GroupModel)) { return model.getModels(); } else { modelArray = []; modelArray.push(model); } return modelArray; }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.update = function () { this.updateModelView(); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.setAffineTransformationValues = function () { this.setCommonValues(); this.setTranslation(); this.setRotation(); this.setScale(); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.setCommonValues = function () { this.applyAffineTransformationsFromModelCenter = this.object.getApplyAffineTransformationsFromModelCenter(); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.setTranslation = function () { var objectNodeTranslation = this.object.getTranslation(); var translation = this.translation; translation.setX(objectNodeTranslation.getX()); translation.setY(objectNodeTranslation.getY()); translation.setZ(objectNodeTranslation.getZ()); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.setRotation = function () { var objectNode = this.object; this.rotationX = objectNode.getRotationX(); this.rotationY = objectNode.getRotationY(); this.rotationZ = objectNode.getRotationZ(); }; rock.scene.graphics.scene.ModelNodeRepresentation.prototype.setScale = function () { var objectNode = this.object; this.scaleX = objectNode.getScaleX(); this.scaleY = objectNode.getScaleY(); this.scaleZ = objectNode.getScaleZ(); };
import { hashSync } from 'bcryptjs'; import genSalt from '../../auth/salt'; import { browserHistory } from 'react-router'; import { take, call, put, fork, race } from 'redux-saga/effects'; import auth from '../../auth'; import { SENDING_REQUEST, REQUEST_ERROR, LOGOUT, SET_AUTH, LOGIN_REQUEST, REGISTER_REQUEST, RESET_FORM, } from './constants'; // All sagas to be loaded // Individual exports for testing export function * authorize({ username, password, isRegistering }) { // We send an action that tells Redux we're sending a request yield put({ type: SENDING_REQUEST, sending: true }); // We then try to register or log in the user, depending on the request try { const salt = genSalt(username); const hash = hashSync(password, salt); let response; // For either log in or registering, we call the proper function in the `auth` // module, which is asynchronous. Because we're using generators, we can work // as if it's synchronous because we pause execution until the call is done // with `yield`! if (isRegistering) { response = yield call(auth.register, username, hash); } else { response = yield call(auth.login, username, hash); } return response; } catch (error) { // If we get an error we send Redux the appropiate action and return yield put({ type: REQUEST_ERROR, error: error.message }); return false; } finally { // When done, we tell Redux we're not in the middle of a request any more yield put({ type: SENDING_REQUEST, sending: false }); } } function forwardTo(location) { browserHistory.push(location); } export function * logout() { // We tell Redux we're in the middle of a request yield put({ type: SENDING_REQUEST, sending: true }); // Similar to above, we try to log out by calling the `logout` function in the // `auth` module. If we get an error, we send an appropiate action. If we don't, // we return the response. try { const response = yield call(auth.logout); yield put({ type: SENDING_REQUEST, sending: false }); return response; } catch (error) { yield put({ type: REQUEST_ERROR, error: error.message }); } return 0; } export function * loginFlow() { // Because sagas are generators, doing `while (true)` doesn't block our program // Basically here we say "this saga is always listening for actions" while (true) { // And we're listening for `LOGIN_REQUEST` actions and destructuring its payload const request = yield take(LOGIN_REQUEST); const { username, password } = request.auth; // A `LOGOUT` action may happen while the `authorize` effect is going on, which may // lead to a race condition. This is unlikely, but just in case, we call `race` which // returns the "winner", i.e. the one that finished first const winner = yield race({ auth: call(authorize, { username, password, isRegistering: false }), logout: take(LOGOUT), }); // If `authorize` was the winner... if (winner.auth) { // ...we send Redux appropiate actions yield put({ type: SET_AUTH, newAuthState: true }); // User is logged in (authorized) yield put({ type: RESET_FORM }); forwardTo('/afterlogin'); // If `logout` won... } else if (winner.logout) { // ...we send Redux appropiate action // yield put({ type: SET_AUTH, newAuthState: false }); // User is not logged in (not authorized) yield call(logout); // Call `logout` effect forwardTo('/'); } } } export function * registerFlow() { while (true) { const request = yield take(REGISTER_REQUEST); const { username, password } = request.auth; const wasSuccessful = yield call(authorize, { username, password, isRegistering: true }); // If we could register a user, we send the appropiate actions console.log(`wasSuccessful is ${wasSuccessful}`); if (wasSuccessful) { // yield put({ type: SET_AUTH, newAuthState: true }); yield put({ type: RESET_FORM }); // forwardTo('/afterlogin'); } } } export function * logoutFlow() { while (true) { yield take(LOGOUT); yield put({ type: SET_AUTH, newAuthState: false }); yield call(logout); forwardTo('/'); } } export function * homeSagas() { yield fork(loginFlow); yield fork(logoutFlow); yield fork(registerFlow); } export default [ homeSagas, ];
angular.module('analyticsApp').factory('chartService', ['$http', 'constants', '$filter', function ($http, constants, $filter) { var cache = {}; return { getData: function (datasets, callback) { var notCached = $filter('filter')(datasets, function (item) { return typeof cache[item] === 'undefined' }); notCached = notCached || []; if (notCached.length >= 1) { $http.post(constants.urls.monthlychart, {datasets: notCached}).success( function (out_data) { angular.forEach(out_data, function (dataset, name) { cache[name] = dataset; }); callback(cache); }); } else { callback(cache); } } } }]);
app.directive("cardList", function() { return { restrict: "E", scope: { type: "@", cards: "=" }, templateUrl: "app/card/card_list.html" } });
import React, {Component} from 'react' import { connect } from 'react-redux' import { moveSection, updateScale, loadSections, slideON, slideOFF, slideVertically, slideHorizontally } from '../actions' import Section from './Section' import Loader from '../components/Loader' import styles from './layout.css' class Layout extends Component { constructor(props){ super(props) this.state = { loaded: false } this.sections this.checkScale = this.checkScale.bind(this) this._onMouseUp = this._onMouseUp.bind(this) this._onMouseMove = this._onMouseMove.bind(this) this._onMouseDown = this._onMouseDown.bind(this) } componentWillMount() { if(!this.props.scale) window.addEventListener('resize', this.checkScale ) } componentWillUnmount() { if(this.props.scale) window.removeEventListener('resize', this.checkScale) } checkScale() { const newScale = scalate(this.props.width, this.props.height)(this.layout.clientWidth,this.layout.clientHeight) this.props.updateScale(newScale) } componentDidMount() { this.checkScale() const sectionURL = add(this.props.source.slice(0,-11)) const promises = this.props.sections.map(section => fetch(sectionURL(section + '/layout.json')).then(res => res.json())) Promise.all(promises) .then(results => { this.props.loadSections(results) this.sections = results this.setState({ loaded: true }) }) } _onMouseDown(e) { this.mousePositionX = e.clientX this.mousePositionY = e.clientY this.maxDistanceX = this.scaledWidth*0.20 this.maxDistanceY = this.scaledHeight*0.15 this.limitX = this.props.sections.length -1 this.limitY = Math.round(this.props.scale*this.sections[this.props.section].layout.style.height/this.props.height) this.props.slideON() } _onMouseMove(e) { if(this.props.isSliding){ const distanceX = e.clientX - this.mousePositionX const distanceY = e.clientY - this.mousePositionY if( (Math.abs(distanceX) > Math.abs(distanceY)) && (Math.abs(distanceX) <= this.maxDistanceX) ){ this.props.slideHorizontally(-distanceX) } else if( (Math.abs(distanceX) < Math.abs(distanceY)) && (Math.abs(distanceY) <= this.maxDistanceY) ){ this.props.slideVertically(-distanceY) } } } _onMouseUp(e) { if(this.props.isSliding){ const distanceX = e.clientX - this.mousePositionX const distanceY = e.clientY - this.mousePositionY if(Math.abs(distanceX) >= this.maxDistanceX){ this.props.slideOFF({move: distanceX > 0 ? 1 : -1, limit: this.limitX}) } else if(Math.abs(distanceY) >= this.maxDistanceY){ this.props.slideOFF(null,{move: distanceY > 0 ? 1 : -1, limit: this.limitY}) } else { this.props.slideOFF() } } } render() { this.scaledHeight = this.props.height*this.props.scale this.scaledWidth = this.props.width*this.props.scale return ( <div className={styles.container} ref={ layout => {this.layout = layout} } onMouseUp={this._onMouseUp} onMouseLeave={this._onMouseUp}> {!this.state.loaded ? <Loader /> : <div style={{height: this.scaledHeight, width: this.scaledWidth}} onMouseDown={this._onMouseDown} onMouseMove={this._onMouseMove}> <div className={styles.content} style={{width: this.scaledWidth*this.sections.length, cursor: this.props.isSliding ? '-webkit-grabbing' : 'auto', transitionDuration: this.props.transitionDuration, transform: `translate3d(-${this.props.section*this.scaledWidth + this.props.distanceX}px, 0,0)`}}> {this.sections.map((section,i) => { const scaledSectionHeight = section.layout.style.height*this.props.scale const scaledSectionWidth = section.layout.style.width*this.props.scale return ( <div key={section.layout.name + i} style={{height: scaledSectionHeight, width: scaledSectionWidth, transitionDuration: this.props.transitionDuration, transform: `translate3d(0,-${this.props.subSection*this.props.height*this.props.scale + this.props.distanceY}px,0)`}}> <Section key={section.layout.name + i} id={i} {...section.layout} /> </div> ) })} </div> </div> } </div> ) } } const scalate = (width, height) => (newWidth, newHeight) => { return Math.round(Math.min(newWidth/width, newHeight/height) * 1000)/1000 } const add = (a) => (b) => a + b const mapStateToProps = (state, ownProps) => { return { scale: state.viewer.scale, section: state.viewer.section, subSection: state.viewer.subSection, isSliding: state.viewer.isSliding, distanceX: state.viewer.distanceX, distanceY: state.viewer.distanceY, transitionDuration: state.viewer.transitionDuration } } const mapDispatchtoProps = (dispatch, ownProps) => { return { slideON: () => dispatch(slideON()), slideHorizontally: distance => dispatch(slideHorizontally(distance)), slideVertically: distance => dispatch(slideVertically(distance)), slideOFF: (horizontal,vertical) => dispatch(slideOFF(horizontal,vertical)), moveSection: (section,limit) => dispatch(moveSection(section,limit)), updateScale: newScale => dispatch(updateScale(newScale)), loadSections: sections => dispatch(loadSections(sections)) } } export default connect(mapStateToProps, mapDispatchtoProps)(Layout)
'use strict'; var escpos = require('../'); var device = new escpos.USB(); var qr = [0x1D, 0x5A, 0x02, 0x1B, 0x5A, 0x03, 0x4C, 0x06, 0x05, 0x00, 0x02, 0x01, 0x01, 0x0D, 0x0A]; var datamatrix = [0x1D, 0x5A, 0x01, 0x1B, 0x5A, 0x03, 0x08, 0x06, 0x05, 0x00, 0x02, 0x01, 0x01, 0x01, 0x02]; device.open(); device.write(new Buffer(qr));
var Mongoose = require('mongoose'); module.exports = Mongoose.model({ email: { type: String, unique: true, required: true }, password: { type: String, required: true }, facebook: { type: String }, google: { type: String }, profile: { type: Mongoose.Schema.Types.ObjectId, ref: 'Profile' }, createdAt: { type: Date, default: Date.now } });
'use strict'; var url = require('url'); var assert = require('assert'); var http = require('http'); var https = require('https'); var Writable = require('stream').Writable; var debug = require('debug')('follow-redirects'); var nativeProtocols = {'http:': http, 'https:': https}; var schemes = {}; var exports = module.exports = { maxRedirects: 21 }; // RFC7231§4.2.1: Of the request methods defined by this specification, // the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. var safeMethods = {GET: true, HEAD: true, OPTIONS: true, TRACE: true}; // Create handlers that pass events from native requests var eventHandlers = Object.create(null); ['abort', 'aborted', 'error'].forEach(function (event) { eventHandlers[event] = function (arg) { this._redirectable.emit(event, arg); }; }); // An HTTP(S) request that can be redirected function RedirectableRequest(options, responseCallback) { // Initialize the request Writable.call(this); this._options = options; this._redirectCount = 0; this._bufferedWrites = []; // Attach a callback if passed if (responseCallback) { this.on('response', responseCallback); } // React to responses of native requests var self = this; this._onNativeResponse = function (response) { self._processResponse(response); }; // Perform the first request this._performRequest(); } RedirectableRequest.prototype = Object.create(Writable.prototype); // Executes the next native request (initial or redirect) RedirectableRequest.prototype._performRequest = function () { // If specified, use the agent corresponding to the protocol // (HTTP and HTTPS use different types of agents) var protocol = this._options.protocol; if (this._options.agents) { this._options.agent = this._options.agents[schemes[protocol]]; } // Create the native request var nativeProtocol = nativeProtocols[this._options.protocol]; var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); this._currentUrl = url.format(this._options); // Set up event handlers request._redirectable = this; for (var event in eventHandlers) { if (event) { request.on(event, eventHandlers[event]); } } // End a redirected request // (The first request must be ended explicitly with RedirectableRequest#end) if (this._currentResponse) { // If no body was written to the original request, or the method was changed to GET, // end the redirected request (without writing a body). var bufferedWrites = this._bufferedWrites; if (bufferedWrites.length === 0 || this._options.method === 'GET') { request.end(); // The body of the original request must be added to the redirected request. } else { var i = 0; (function writeNext() { if (i < bufferedWrites.length) { var bufferedWrite = bufferedWrites[i++]; request.write(bufferedWrite.data, bufferedWrite.encoding, writeNext); } else { request.end(); } })(); } } }; // Processes a response from the current native request RedirectableRequest.prototype._processResponse = function (response) { // RFC7231§6.4: The 3xx (Redirection) class of status code indicates // that further action needs to be taken by the user agent in order to // fulfill the request. If a Location header field is provided, // the user agent MAY automatically redirect its request to the URI // referenced by the Location field value, // even if the specific status code is not understood. var location = response.headers.location; if (location && this._options.followRedirects !== false && response.statusCode >= 300 && response.statusCode < 400) { // RFC7231§6.4: A client SHOULD detect and intervene // in cyclical redirections (i.e., "infinite" redirection loops). if (++this._redirectCount > this._options.maxRedirects) { return this.emit('error', new Error('Max redirects exceeded.')); } // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates // that the target resource resides temporarily under a different URI // and the user agent MUST NOT change the request method // if it performs an automatic redirection to that URI. if (response.statusCode !== 307) { // RFC7231§6.4: Automatic redirection needs to done with // care for methods not known to be safe […], // since the user might not wish to redirect an unsafe request. if (!(this._options.method in safeMethods)) { this._options.method = 'GET'; } } // Perform the redirected request var redirectUrl = url.resolve(this._currentUrl, location); debug('redirecting to', redirectUrl); Object.assign(this._options, url.parse(redirectUrl)); this._currentResponse = response; this._performRequest(); } else { // The response is not a redirect; return it as-is response.responseUrl = this._currentUrl; this.emit('response', response); // Clean up delete this._options; delete this._bufferedWrites; } }; // Aborts the current native request RedirectableRequest.prototype.abort = function () { this._currentRequest.abort(); }; // Flushes the headers of the current native request RedirectableRequest.prototype.flushHeaders = function () { this._currentRequest.flushHeaders(); }; // Sets the noDelay option of the current native request RedirectableRequest.prototype.setNoDelay = function (noDelay) { this._currentRequest.setNoDelay(noDelay); }; // Sets the socketKeepAlive option of the current native request RedirectableRequest.prototype.setSocketKeepAlive = function (enable, initialDelay) { this._currentRequest.setSocketKeepAlive(enable, initialDelay); }; // Sets the timeout option of the current native request RedirectableRequest.prototype.setTimeout = function (timeout, callback) { this._currentRequest.setTimeout(timeout, callback); }; // Writes buffered data to the current native request RedirectableRequest.prototype._write = function (data, encoding, callback) { this._currentRequest.write(data, encoding, callback); this._bufferedWrites.push({data: data, encoding: encoding}); }; // Ends the current native request RedirectableRequest.prototype.end = function (data, encoding, callback) { this._currentRequest.end(data, encoding, callback); if (data) { this._bufferedWrites.push({data: data, encoding: encoding}); } }; // Export a redirecting wrapper for each native protocol Object.keys(nativeProtocols).forEach(function (protocol) { var scheme = schemes[protocol] = protocol.substr(0, protocol.length - 1); var nativeProtocol = nativeProtocols[protocol]; var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); // Executes an HTTP request, following redirects wrappedProtocol.request = function (options, callback) { if (typeof options === 'string') { options = url.parse(options); options.maxRedirects = exports.maxRedirects; } else { options = Object.assign({ maxRedirects: exports.maxRedirects, protocol: protocol }, options); } assert.equal(options.protocol, protocol, 'protocol mismatch'); debug('options', options); return new RedirectableRequest(options, callback); }; // Executes a GET request, following redirects wrappedProtocol.get = function (options, callback) { var request = wrappedProtocol.request(options, callback); request.end(); return request; }; });
module.exports = function(sequelize, DataTypes) { var ThemeSetting = sequelize.define("ThemeSetting", { headerfilename: { type: DataTypes.STRING(50) }, header_backgroundcolor: { type: DataTypes.STRING(6), allowNull: false }, header_fontcolor: { type: DataTypes.STRING(6), allowNull: false }, header_fontsize: { type: DataTypes.INTEGER, allowNull: false }, menu_backgroundcolor: { type: DataTypes.STRING(6), allowNull: false }, menu_fontcolor: { type: DataTypes.STRING(6), allowNull: false }, menu_fontsize: { type: DataTypes.INTEGER, allowNull: false }, post_titlefontcolor: { type: DataTypes.STRING(6), allowNull: false }, post_titlefontsize: { type: DataTypes.INTEGER, allowNull: false }, post_contentfontcolor: { type: DataTypes.STRING(6), allowNull: false }, post_contentfontsize: { type: DataTypes.INTEGER, allowNull: false }, page_titlefontcolor: { type: DataTypes.STRING(6), allowNull: false }, page_titlefontsize: { type: DataTypes.INTEGER, allowNull: false }, page_contentfontcolor: { type: DataTypes.STRING(6), allowNull: false }, page_contentfontsize: { type: DataTypes.INTEGER, allowNull: false } }, { freezeTableName: true }); return ThemeSetting; };
import React from "react" import { Link } from "react-router-dom" import { Component } from "platform/react-support" import { Paper } from "@material-ui/core" import { styleUi } from "theme" export default class Timeout extends Component { render() { return ( <Paper style={styleUi.paper} elevation={1}> <h4>セッションタイムアウト</h4> <div>ログインしていないか一定時間操作がありませんでした。</div> <p> <Link to="login">ログイン画面へ戻る</Link> </p> </Paper> ) } }
version https://git-lfs.github.com/spec/v1 oid sha256:c22b1959fd68b50e46b2fa59b81c132c1996c8034ae560a7bf6abb9a4cb3eebd size 1051
// Regular expression that matches all symbols in the `Deseret` script as per Unicode v4.0.1: /\uD801[\uDC00-\uDC4F]/;
const passport = require('passport'); const connection = require("../connection"); module.exports = function(app) { function renderLocationEditView(name, address, req, res) { connection.query('SELECT * from Location where name=? and address=?', [name, address], function(err, location) { res.render('editlocation', { title: 'Edit Location', message: 'Edit Location', userName: (req.user) ? req.user.username : undefined, flashMessage: req.flash('flashMessage'), location : location }); }); }; function performLocationUpdate(column, name, address, newValue, req, res) { connection.query('UPDATE Location SET ' + column + '=? where name=? and address=?', [newValue, name, address], function(err, result) { if (err) { console.log(err); } else { if (column === "name") { renderLocationEditView(newValue, address, req, res); } else if (column ==="address") { renderLocationEditView(name, newValue, req, res); } else if (column === "capacity") { renderLocationEditView(name, address, req, res); } } }); }; app.get('/editLocation/*', function(req, res) { console.log(req.params); var params = req.params['0'].split("-"); var name = params[0]; var address = params[1]; renderLocationEditView(name, address, req, res); }); app.post('/editLocation', function(req, res) { console.log(req.body); var params = req.body; if (req.body.name) { performLocationUpdate("name", params.oldName, params.oldAddress, params.name, req, res); } else if (req.body.address) { performLocationUpdate("address", params.oldName, params.oldAddress, params.address, req, res); } else if (req.body.capacity) { performLocationUpdate("capacity", params.oldName, params.oldAddress, params.capacity, req, res); } }); }
'use strict'; const Gpio = require('../onoff').Gpio; // Gpio class console.log('Gpio functionality accessible on this computer?', Gpio.accessible);
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7MessagebarSheet extends React.Component { constructor(props, context) { super(props, context); } render() { const props = this.props; const { className, id, style } = props; const classes = Utils.classNames(className, 'messagebar-sheet', Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, className: classes }, this.slots['default']); } get slots() { return __reactComponentSlots(this.props); } } __reactComponentSetProps(F7MessagebarSheet, Object.assign({ id: [String, Number] }, Mixins.colorProps)); F7MessagebarSheet.displayName = 'f7-messagebar-sheet'; export default F7MessagebarSheet;
const _checksum = require('./checksum'); function sha384file(filename, outputFormat='hex'){ // generate hash return _checksum(filename, 'sha384', outputFormat); } module.exports = sha384file;
/** * Created by juanmanuelsanchez on 17/3/16. */ /** * Created by juanmanuelsanchez on 16/3/16. */ (function() { var self = this, mediaWrapper = $("#mediaWrapper"), datos = "data/datos.json", count = 0; function getData(callback) { $.getJSON(datos, function(data) { callback(data); }).error(function (e) { console.log("Sorry, data cannot be loaded!"); }); return false; } getData(function (data) { var linksItems= data['links'], length = linksItems.length; for (var i = 0; i < length; i++) { var linkItem = linksItems[i], linkItemName = linkItem.rowName, rowItems = linkItem.rowItems, rowItemsLength = rowItems.length, container = "<div class='row col-lg-12 col-md-12 col-sm-12' id='container"+i+"'></div>", title = "<h3 class='text-center row-title' id='rowTitle"+i+"'></h3>", mediaHolder = "<div class='row col-lg-12 col-md-12 col-sm-12 mediaHolder' id='mediaHolder"+i+"'></div>"; $("#mediaWrapper:last").append(container); var $container = $('#'+'container'+i); $container.prepend(title); var $title = $('#'+'rowTitle'+i); $title.text(linkItemName); $container.append(mediaHolder); for (var j = 0; j < rowItemsLength; j++){ var element = rowItems[j], elementTitle = element['elementTitle'], src = element['imgSrc'], target = element['dataTarget'], media = element['dataMedia'], domLinkDiv = "<div class='col-lg-4 col-md-4 col-sm-4 col-xs-12' id='linkItem"+count+"'></div>", domLink = "<img src='"+src+"' alt='work image' class='img-responsive modalLink' href= '#' data-toggle='modal' data-target='"+target+"' data-media='"+media+"'>", imageTitle = "<div class='image-title' id='imageTitle"+count+"'></div>"; var $mediaHolder = $('#'+'mediaHolder'+i); $mediaHolder.append(domLinkDiv); var $domLinkDiv = $('#'+'linkItem'+count); $domLinkDiv.append(domLink); $domLinkDiv.prepend(imageTitle); var $imageTitle = $('#'+'imageTitle'+count); $imageTitle.text(elementTitle); count++; } } }); window.addEventListener("load", function (event) { trigger(); }); }());
/*jshint node:true, mocha:true */ 'use strict'; var better = require('betterer').better; var convertTests = require('./convert/convertTests'); var invertConversionTests = require('./invertConversion/invertConversionTests'); var composeConversionsTests = require('./composeConversions/composeConversionsTests'); var coefficientATests = require('./coefficients/coefficientATests'); var coefficientBTests = require('./coefficients/coefficientBTests'); var equivalenceTests = require('./equivalence/equivalenceTests'); var o_o = describe; o_o('converting', function() { var o_O = convertTests; o_o('with a valid conversion', better('convert based on the provided conversion', o_O)); }); o_o('inverting', function() { var o_O = invertConversionTests; o_o('a valid conversion', better('invert the conversion', o_O)); }); o_o('composing', function() { var o_O = composeConversionsTests; o_o('valid conversions', better('compose the conversions', o_O)); }); o_o('computing coefficient a', function() { var o_O = coefficientATests; o_o('when arbitrary precision is available', better('work with arbitrary precision', o_O)); o_o('when arbitrary precision is not available', better('work with floating-point numbers', o_O)); }); o_o('computing coefficient b', function() { var o_O = coefficientBTests; o_o('when arbitrary precision is available', better('work with arbitrary precision', o_O)); o_o('when arbitrary precision is not available', better('work with floating-point numbers', o_O)); }); o_o('checking for equivalence', function() { var o_O = equivalenceTests; o_o('when conversions are equivalent', better('return true', o_O)); o_o('when conversions are not equivalent', better('return false', o_O)); });
var models = require('../models.js'); var fs = require('fs'); var AWS = require('aws-sdk'); //Keeping our secrets secret. var settings; if(fs.existsSync('./settings.js')){ settings = require('../settings.js'); }else{ settings = {}; settings.amazonID = process.env.S3Key; settings.amazonSecret = process.env.S3Secret; } AWS.config.update({ accessKeyId: settings.amazonID, secretAccessKey: settings.amazonSecret, region: 'us-west-2', }); //Returns int var findIndexByAttr = function(array, attr, value) { for(var i = 0; i < array.length; i++) { if(array[i][attr] === value) { return i; } } return -1; } //Allows for easy access to month names in the Date prototype. Date.prototype.monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" ]; Date.prototype.getMonthName = function() { return this.monthNames[this.getMonth()]; }; //Uses the google id to render that particular users past eats. exports.view = function(req, res) { models.User .find({'google_id':req.user.google_id}) .sort() .exec(userCallback); function userCallback(err, users){ if(err){console.log(err); res.send(500)} res.render('pasteats', users[0]); } } //Views each one individually (not implemented) exports.viewById = function(req, res) { var id = req.params.id; models.User .find({'google_id':id}) .sort() .exec(userCallback); function userCallback(err, users){ if(err){console.log(err); res.send(500)} //if(users[0].pasteats.public){ res.render('pasteats', users[0]); // }else{ // res.render('login'); // } } } //Adds a new past eats entry! exports.add = function(req, res) { var time = new Date(); var newEntry = { 'created_timestamp' : Date.now(), 'id': Date.now() + '_' + req.user.google_id, 'formatted_date': time.getMonthName() + " " + time.getDate() + ", " + time.getFullYear(), 'title' : req.body.title, 'summary': req.body.summary, 'caption': req.body.caption, 'gid': req.body.gid }; //Uploads a photo if they attach one //Otherwise just submits it. var s3 = new AWS.S3(); fs.readFile(req.files.photo.path, function(err, photoData){ var oldImageName = req.files.photo.name; if(oldImageName){ var nowTime = Date.now(); var fileName = nowTime + "_" + req.user.google_id + ".jpg"; s3.client.putObject({ Bucket: 'umamiappimages', Key: fileName, Body: photoData, ContentType: 'image/jpeg', ACL: 'public-read' }, function (err, response){ if(err)console.log(err); newEntry['image'] = "http://s3-us-west-2.amazonaws.com/umamiappimages/" + fileName; updateUser(newEntry); }); }else{ newEntry['image'] = ""; updateUser(newEntry) } }); //After creating the entry, associates it with the User function updateUser(entry){ models.User .find({'google_id':req.user.google_id}) .sort() .exec(userCallback); function userCallback (err, users){ if(err){console.log(err); res.send(500)} var pasteats = users[0].pasteats; pasteats.unshift(entry); users[0].update({'pasteats': pasteats}).exec(addCallback); } //Once it's all done, it reloads the past eats page. function addCallback(err){ if(err){console.log(err); res.send(500)} res.redirect('/pasteats'); } } } //Removes the entry from past eats user data. exports.remove= function(req, res) { models.User .find({'google_id':req.user.google_id}) .sort() .exec(userCallback); function userCallback(err, users){ if(err){console.log(err); res.send(500)} var pasteats = users[0].pasteats; var index = findIndexByAttr(pasteats, 'id', req.body.id); if(index != -1){ pasteats.splice(index, 1); //upadates the entry users[0].update({'pasteats': pasteats}).exec(removeCallback); } function removeCallback(err){ if(err){console.log(err); res.send(500)} res.send(200); } } }
(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{196:function(t,e,n){"use strict";n.r(e);var s=n(0),l=Object(s.a)({},function(){var t=this.$createElement;return(this._self._c||t)("ContentSlotsDistributor",{attrs:{"slot-key":this.$parent.slotKey}})},[],!1,null,null,null);e.default=l.exports}}]);
/* With reference to Queue.js A function to represent a queue Created by Stephen Morley - http://code.stephenmorley.org/ - and released under the terms of the CC0 1.0 Universal legal code: http://creativecommons.org/publicdomain/zero/1.0/legalcode */ class Queue{ constructor(){ this.arr = []; this.offset = 0; } getLength(){ return this.arr.length - this.offset; } isEmpty(){ return this.arr.length == 0; } push(val){ this.arr.push(val); } pop(){ if(this.arr.length == 0){ throw 'Cannot pop from empty queue.'; } const res = this.arr[this.offset]; this.offset++; if(this.offset * 2 >= this.arr.length){ this.arr = this.arr.slice(this.offset); this.offset = 0; } return res; } }; module.exports = Queue;
exports.server = { game: { port: 3000, name: 'RockMUD', version: '0.3.0', website: 'https://github.com/MoreOutput/RockMUD', description: 'Websockets MUD Engine Demo', coinage: 'gold', persistenceTick: 245000 }, admins: [] };
import electron from 'electron' import { Map } from 'immutable' import { DATA, emitRTC } from './rtc' // ------------------------------------ // Constants // ------------------------------------ export const MIDI_OPEN = 'MIDI_OPEN' export const MIDI_MESSAGE = 'MIDI_MESSAGE' export const MIDI_OUT_NOTE_DOWN = 'MIDI_OUT_NOTE_DOWN' export const MIDI_OUT_NOTE_UP = 'MIDI_OUT_NOTE_UP' export const MIDI_CONTROL = 'MIDI_CONTROL' // ------------------------------------ // Actions // ------------------------------------ export function open() { return (dispatch, getState) => { return new Promise((resolve) => { electron.ipcRenderer.on('midi', (event, message) => { dispatch(midiMessage(message)) }) resolve() }) } } export function midiMessage (message) { return (dispatch, getState) => { return new Promise((resolve) => { dispatch(emitRTC(message)) resolve() }) } } // ------------------------------------ // Action Handlers // ------------------------------------ const MIDI_MESSAGES = { noteON : 144, noteOFF : 128, control : 176 } const ACTION_HANDLERS = { [DATA]: (state, action) => { }, [MIDI_MESSAGE]: (state, action) => { }, } // ------------------------------------ // Reducer // ------------------------------------ const initialState = Map({ 'outPortId': '766085233'}) export default function midiReducer (state: object = initialState, action: Action): object { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
var modMemory = require("module.memory"); var bodyObj = require('module.bodyTypes'); var modUtil = require('module.utility'); var modManual ={ spawn:function(type, tier, roomName, pos){ var memoryObj = modMemory.getInitalCreepMem(type); memoryObj.manualDest = pos; memoryObj.room = roomName; var obj = { description:"Manual-"+type, body: null, role: type, name: undefined, memory:memoryObj }; obj.body = bodyObj.getBody(type, tier); Memory.rooms[roomName].spawnQ.unshift(obj); //unshift it so it is priority modUtil.incrementCreepNum(type,roomName); return "Scheduled"; }, recountCreeps:function(roomName){ var roles = Memory.rooms[roomName].roles; var gameCreeps = _.filter(Game.creeps, (creep) => creep.room.name == roomName); var spawnQ = Memory.rooms[roomName].spawnQ; roles.numCreeps = gameCreeps.length + spawnQ.length; roles.numHarvesters = 0; roles.numUpgraders =0; roles.numBuilders = 0; roles.numRepair = 0; roles.numArchitects = 0; roles.numMiners = 0; roles.numHaulers = 0; roles.numFeeders = 0; roles.numGeo = 0; roles.numGeoH = 0; roles.numMerchant = 0; for(var c in gameCreeps){ var creep = gameCreeps[c]; if(creep.room.name == roomName){ if(creep.memory.role == 'harvester') { roles.numHarvesters++; }else if(creep.memory.role == 'upgrader') { roles.numUpgraders++; }else if(creep.memory.role == 'builder'){ roles.numBuilders++; }else if(creep.memory.role == 'repair'){ roles.numRepair++; }else if(creep.memory.role == 'architect'){ roles.numArchitects++; }else if(creep.memory.role == 'miner'){ roles.numMiners++; }else if(creep.memory.role == 'hauler'){ roles.numHaulers++; }else if(creep.memory.role == 'feeder'){ roles.numFeeders++; }else if(creep.memory.role == 'geo'){ roles.numGeo++; }else if(creep.memory.role == 'geoH'){ roles.numGeoH++; }else if(creep.memory.role == 'merchant'){ roles.numMerchant++; } } } for(var s in spawnQ){ var spawnee = spawnQ[s]; if(spawnee.memory.role == 'harvester') { roles.numHarvesters++; }else if(spawnee.memory.role == 'upgrader') { roles.numUpgraders++; }else if(spawnee.memory.role == 'builder'){ roles.numBuilders++; }else if(spawnee.memory.role == 'repair'){ roles.numRepair++; }else if(spawnee.memory.role == 'architect'){ roles.numArchitects++; }else if(spawnee.memory.role == 'miner'){ roles.numMiners++; }else if(spawnee.memory.role == 'hauler'){ roles.numHaulers++; }else if(spawnee.memory.role == 'feeder'){ roles.numFeeders++; }else if(spawnee.memory.role == 'geo'){ roles.numGeo++; }else if(spawnee.memory.role == 'geoH'){ roles.numGeoH++; }else if(spawnee.memory.role == 'merchant'){ roles.numMerchant++; } } }, clearQueue:function(roomName){ var roles = Memory.rooms[roomName].roles; var spawnQ = Memory.rooms[roomName].spawnQ; for(var s in spawnQ){ var spawnee = spawnQ[s]; if(spawnee.memory.role == 'harvester') { roles.numHarvesters--; }else if(spawnee.memory.role == 'upgrader') { roles.numUpgraders--; }else if(spawnee.memory.role == 'builder'){ roles.numBuilders--; }else if(spawnee.memory.role == 'repair'){ roles.numRepair--; }else if(spawnee.memory.role == 'architect'){ roles.numArchitects--; }else if(spawnee.memory.role == 'miner'){ roles.numMiners--; }else if(spawnee.memory.role == 'hauler'){ roles.numHaulers--; }else if(spawnee.memory.role == 'feeder'){ roles.numFeeders--; }else if(spawnee.memory.role == 'geo'){ roles.numGeo--; }else if(spawnee.memory.role == 'geoH'){ roles.numGeoH--; }else if(spawnee.memory.role == 'merchant'){ roles.numMerchant--; } roles.numCreeps--; } Memory.rooms[roomName].spawnQ = []; } }; module.exports = modManual;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-6-a-206 description: > Object.defineProperties - 'O' is an Array, 'P' is an array index named property, 'P' makes no change if every field in 'desc' is absent (name is data property) (15.4.5.1 step 4.c) includes: [propertyHelper.js] ---*/ var arr = []; arr[0] = 101; // default value of attributes: writable: true, configurable: true, enumerable: true Object.defineProperties(arr, { "0": {} }); verifyEqualTo(arr, "0", 101); verifyWritable(arr, "0"); verifyEnumerable(arr, "0"); verifyConfigurable(arr, "0");
(function(){ QUnit.config.reorder = false; /*************************************/ QUnit.module('CordovaPromiseFS'); /*************************************/ window.fs = null; QUnit.test('fs = CordovaPromiseFS()',function(assert){ fs = CordovaPromiseFS({ Promise:Promise, persistent: typeof cordova !== 'undefined' }); assert.ok(!!fs); }); QUnit.asyncTest('fs.deviceready',function(assert){ fs.deviceready.then(ok(assert,true),err(assert)); }); QUnit.test('fs.filename("bla/bla/test.txt") = "test.txt"',function(assert){ assert.equal(fs.filename('bla/bla/test.txt'),'test.txt'); }); QUnit.test('fs.dirname("bla/bla/test.txt") = "bla/bla/"',function(assert){ assert.equal(fs.dirname('bla/bla/test.txt'),'bla/bla/'); }); QUnit.test('fs.normalize: "/dir/dir/file.txt => dir/file.txt; /dir => dir/; ./ => ""',function(assert){ assert.equal(fs.normalize('./'), '', '"./" => ""'); assert.equal(fs.normalize('test'), 'test/', 'test => test/'); assert.equal(fs.normalize('test/'), 'test/', 'test/ => test/'); assert.equal(fs.normalize('/test'), 'test/', '/test => test/'); assert.equal(fs.normalize('/test/'), 'test/', '/test/ => test/'); assert.equal(fs.normalize('/dir.txt/'),'dir.txt/', '/dir.txt/ => dir.txt/ (directory with a dot)'); assert.equal(fs.normalize('file.txt'), 'file.txt', 'file.txt => file.txt'); assert.equal(fs.normalize('/file.txt'), 'file.txt', '/file.txt => file.txt'); assert.equal(fs.normalize('/dir/sub/sub/text.txt'), 'dir/sub/sub/text.txt', 'subdirectories with file'); assert.equal(fs.normalize('/dir/sub/sub/sub'), 'dir/sub/sub/sub/', 'subdirectories'); }); /*************************************/ // CREATE /*************************************/ QUnit.asyncTest('fs.create (in root)',function(assert){ fs.create('create.txt') .then(function(){ return fs.file('create.txt'); }) .then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.create (in subdirectory)',function(assert){ fs.create('sub/sub/create.txt') .then(function(){ return fs.file('sub/sub/create.txt'); }) .then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.ensure (in root)',function(assert){ fs.ensure('testdir') .then(function(){ return fs.dir('testdir'); }) .then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.ensure (in subdirectory)',function(assert){ fs.ensure('testdir2/testdir2') .then(function(){ return fs.dir('testdir2/testdir2'); }) .then(ok(assert,truthy),err(assert)); }); /*************************************/ // ENTRY /*************************************/ QUnit.asyncTest('fs.file (ok - fileEntry)',function(assert){ fs.file('create.txt').then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.file (error - does not exist)',function(assert){ fs.file('does-not-exist.txt').then(err(assert),function(err){ assert.equal(err.code,1); QUnit.start(); }); }); QUnit.asyncTest('fs.exists (ok - true)',function(assert){ fs.exists('create.txt').then(function(fileEntry){ assert.ok(fileEntry); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.exists (error - does not exist)',function(assert){ fs.exists('does-not-exist.txt').then(ok(assert,false),err(assert)); }); QUnit.asyncTest('fs.dir (ok - dirEntry)',function(assert){ fs.dir('testdir').then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.dir (error - does not exist)',function(assert){ fs.dir('does-not-exist').then(err(assert),function(err){ assert.equal(err.code,1); QUnit.start(); }); }); QUnit.asyncTest('fs.toInternalURL',function(assert){ var result = fs.toInternalURLSync('create.txt'); fs.toInternalURL('create.txt').then(ok(assert,result),err(assert)); }); QUnit.asyncTest('fs.toURL',function(assert){ fs.toURL('create.txt').then(function(url){ assert.equal(url.substr(0,4),'file'); QUnit.start(); },err(assert)); }); /*************************************/ // LIST /*************************************/ QUnit.asyncTest('fs.list (f)',function(assert){ var files = ['list/1.txt','list/2.txt','list/3.txt', 'list/sub/4.txt','list/sub/sub/5.txt']; var promises = files.map(function(file){ return fs.create(file); }); Promise.all(promises) .then(function(){ return fs.list('list','f'); }) .then(function(actual){ assert.deepEqual(actual,[ "/list/3.txt", "/list/2.txt", "/list/1.txt" ]); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.list (d)',function(assert){ fs.list('list','d') .then(function(actual){ assert.deepEqual(actual,[ "/list/sub" ]); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.list (rf)',function(assert){ fs.list('list','rf') .then(function(actual){ assert.deepEqual(actual,[ "/list/3.txt", "/list/2.txt", "/list/1.txt", "/list/sub/4.txt", "/list/sub/sub/5.txt", ]); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.list (rd)',function(assert){ fs.list('list','rd') .then(function(actual){ assert.deepEqual(actual,[ "/list/sub", "/list/sub/sub", ]); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.list (fe)',function(assert){ fs.list('list','fe') .then(function(actual){ assert.equal(actual.length,3); assert.equal(typeof actual[0],'object'); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.list (error when not exist)',function(assert){ fs.list('does-not-exist','r') .then(err(assert),function(err){ assert.equal(err.code,1); QUnit.start(); }); }); /*************************************/ // WRITE /*************************************/ var obj = {hello:'world'}; var string = JSON.stringify(obj); QUnit.asyncTest('fs.write',function(assert){ fs.write('write.txt',string).then(ok(assert,truthy),err(assert)); }); /*************************************/ // READ /*************************************/ QUnit.asyncTest('fs.read',function(assert){ fs.read('write.txt').then(ok(assert,string),err(assert)); }); QUnit.asyncTest('fs.readJSON',function(assert){ fs.readJSON('write.txt').then(function(actual){ assert.ok(actual); assert.equal(actual.hello,obj.hello); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.toDataURL (plain text)',function(assert){ fs.toDataURL('write.txt').then(ok(assert,'data:text/plain;base64,eyJoZWxsbyI6IndvcmxkIn0='),err(assert)); }); // QUnit.asyncTest('fs.toDataURL (json)',function(assert){ // fs.write('write.json',obj).then(function(){ // return fs.toDataURL('write.json'); // }) // .then( // ok(assert,'data:application/json;base64,eyJoZWxsbyI6IndvcmxkIn0='), // err(assert) // ); // }); /*************************************/ // REMOVE /*************************************/ QUnit.asyncTest('fs.remove = true (when file exists)',function(assert){ fs.remove('create.txt').then(ok(assert,true),err(assert)); }); QUnit.asyncTest('fs.remove = false (when file does not exists)',function(assert){ fs.remove('create.txt').then(ok(assert,false),err(assert)); }); /*************************************/ // MOVE AND COPY /*************************************/ QUnit.asyncTest('fs.move',function(assert){ fs.move('write.txt','moved.txt') .then(function(){ return fs.exists('write.txt'); }) .then(function(val){ assert.equal(val,false,'old file should not exist'); }) .then(function(){ return fs.exists('moved.txt'); }) .then(ok(assert,truthy),err(assert)); }); QUnit.asyncTest('fs.copy',function(assert){ fs.copy('moved.txt','copied.txt') .then(function(){ return fs.exists('moved.txt'); }) .then(function(val){ assert.ok(val,'old file should exist'); }) .then(function(){ return fs.exists('copied.txt'); }) .then(ok(assert,truthy),err(assert)); }); /*************************************/ // DOWNLOAD /*************************************/ QUnit.asyncTest('fs.download (ok)',function(assert){ fs.download('http://data.madebymark.nl/cordova-promise-fs/download.txt','download.txt') .then(function(){ return fs.read('download.txt'); }) .then(function(val){ assert.equal(val,'hello world'); QUnit.start(); },err(assert)); }); QUnit.asyncTest('fs.download (404 returns false - should see 3 retry attempts)',function(assert){ fs.download('http://data.madebymark.nl/cordova-promise-fs/does-not-exist.txt','download-error.txt',{retry:[0,0]}) .then(err(assert),function(){ assert.ok(true); QUnit.start(); }); }); QUnit.asyncTest('fs.download : progress when starting download',function(assert){ var called = false; fs.download('http://data.madebymark.nl/cordova-promise-fs/download.txt', 'download-error.txt', function(){ called = true; }) .then(function(){ assert.ok(called,'should call "onprogress"'); QUnit.start(); },err(assert)); }); /*************************************/ // Helper methods for promises var truthy = 'TRUTHY'; function print(){ console.log(arguments); } function ok(assert,expected){ return function(actual){ if(expected === truthy){ assert.ok(actual); } else { assert.equal(actual,expected); } QUnit.start(); }; } function err(assert){ return function(err){ assert.equal(err,'an error'); QUnit.start(); }; } })();
'use strict'; var $$Array = 0; var Bytes = 0; var List = 0; var $$String = 0; exports.$$Array = $$Array; exports.Bytes = Bytes; exports.List = List; exports.$$String = $$String; /* No side effect */
const jwt = require('jwt-simple'); const User = require('../models/user'); const config = require('../config/index'); function tokenForUser(user) { const timestamp = new Date().getTime(); return jwt.encode({ sub: user.id, name: user.username, iat: timestamp }, config.secret); } exports.signin = function(req, res, next) { // user has already had their username and password auth'd // We just need to give them a token res.send({ token: tokenForUser(req.user) }); } exports.signup = function(req, res, next) { const username = req.body.username; const password = req.body.password; if (!username || !password) { return res.status(422).send({ error: 'You must provide username and password '}); } // See if a user with the given username exists User.findOne({ username: username }, function(err, existingUser) { if (err) { return next(err) }; // If a user with username does exist, return an error if (existingUser) { return res.status(422).send({ error: 'Username is in use' }); } // If a user with username does NOT exist, create and save user record const user = new User({ username: username, password: password }); user.hashPassword(next); user.save(function(err) { if (err) { return next(err); } // Respond to request indicating the user was created res.json({ token: tokenForUser(user) }); }); }); }
module.exports = { "name": "ATmega329A", "timeout": 200, "stabDelay": 100, "cmdexeDelay": 25, "syncLoops": 32, "byteDelay": 0, "pollIndex": 3, "pollValue": 83, "preDelay": 1, "postDelay": 1, "pgmEnable": [172, 83, 0, 0], "erase": { "cmd": [172, 128, 0, 0], "delay": 45, "pollMethod": 1 }, "flash": { "write": [64, 76, 0], "read": [32, 0, 0], "mode": 65, "blockSize": 128, "delay": 10, "poll2": 0, "poll1": 0, "size": 32768, "pageSize": 128, "pages": 256, "addressOffset": null }, "eeprom": { "write": [193, 194, 0], "read": [160, 0, 0], "mode": 65, "blockSize": 4, "delay": 10, "poll2": 0, "poll1": 0, "size": 1024, "pageSize": 4, "pages": 256, "addressOffset": 0 }, "sig": [30, 149, 3], "signature": { "size": 3, "startAddress": 0, "read": [48, 0, 0, 0] }, "fuses": { "startAddress": 0, "write": { "low": [172, 160, 0, 0], "high": [172, 168, 0, 0], "ext": [172, 164, 0, 0] }, "read": { "low": [80, 0, 0, 0], "high": [88, 8, 0, 0], "ext": [80, 8, 0, 0] } } }
/* jshint esversion: 6 */ var http = require('http'); var fs = require('fs'); var express = require('express'); var app = express(); const PORT = 8080; app.use('/tests', express.static(__dirname + '/tests/')); app.use('/', (req, res)=>{ res.redirect('/tests/#/'); }); //Lets start our server app.listen(PORT, function(){ console.log("Server listening on: http://localhost:%s", PORT); });
Object.defineProperty(exports,"__esModule",{value:true});var _this=this;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;}; var _graphql=require('graphql'); var _graphqlRelay=require('graphql-relay'); var _HousesConnection=require('./HousesConnection');var _HousesConnection2=_interopRequireDefault(_HousesConnection); var _HouseType=require('./HouseType');var _HouseType2=_interopRequireDefault(_HouseType);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}exports.default= { Houses:{ type:_HousesConnection2.default.connectionType, args:_extends({ OfficeId:{type:_graphql.GraphQLInt}},_graphqlRelay.connectionArgs), resolve:function resolve( obj,_ref, context,_ref2){var args=_objectWithoutProperties(_ref,[]);var objectManager=_ref2.rootValue;var arr;return regeneratorRuntime.async(function resolve$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return regeneratorRuntime.awrap( objectManager.getObjectList('House',{ index:'sale', type:'house', body:{ query:{ bool:{ filter:{ term:{ 'OfficeId.keyword':'3913'}}}}}}));case 2:arr=_context.sent;return _context.abrupt('return', (0,_graphqlRelay.connectionFromArray)(arr,args));case 4:case'end':return _context.stop();}}},null,_this);}}, House:{ type:_HouseType2.default, args:_extends({id:{type:_graphql.GraphQLID}}), resolve:function resolve(parent,_ref3,context,_ref4){var id=_ref3.id;var objectManager=_ref4.rootValue;return( objectManager.getOneObject('House',{id:(0,_graphqlRelay.fromGlobalId)(id).id}));}}}; //# sourceMappingURL=_ViewerFields.js.map
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // Test that having a bunch of streams piping in parallel // doesn't break anything. require('../common'); const assert = require('assert'); const Stream = require('stream').Stream; const rr = []; const ww = []; const cnt = 100; const chunks = 1000; const chunkSize = 250; const data = Buffer.allocUnsafe(chunkSize); let wclosed = 0; let rclosed = 0; function FakeStream() { Stream.apply(this); this.wait = false; this.writable = true; this.readable = true; } FakeStream.prototype = Object.create(Stream.prototype); FakeStream.prototype.write = function(chunk) { console.error(this.ID, 'write', this.wait); if (this.wait) { process.nextTick(this.emit.bind(this, 'drain')); } this.wait = !this.wait; return this.wait; }; FakeStream.prototype.end = function() { this.emit('end'); process.nextTick(this.close.bind(this)); }; // noop - closes happen automatically on end. FakeStream.prototype.close = function() { this.emit('close'); }; // expect all streams to close properly. process.on('exit', function() { assert.strictEqual(cnt, wclosed); assert.strictEqual(cnt, rclosed); }); for (let i = 0; i < chunkSize; i++) { data[i] = i; } for (let i = 0; i < cnt; i++) { const r = new FakeStream(); r.on('close', function() { console.error(this.ID, 'read close'); rclosed++; }); rr.push(r); const w = new FakeStream(); w.on('close', function() { console.error(this.ID, 'write close'); wclosed++; }); ww.push(w); r.ID = w.ID = i; r.pipe(w); } // now start passing through data // simulate a relatively fast async stream. rr.forEach(function(r) { let cnt = chunks; let paused = false; r.on('pause', function() { paused = true; }); r.on('resume', function() { paused = false; step(); }); function step() { r.emit('data', data); if (--cnt === 0) { r.end(); return; } if (paused) return; process.nextTick(step); } process.nextTick(step); });
define( 'specs/plugin/a', function(){ return 'a'; } );
/*=== RangeError: aiee done ===*/ function yielder() { var yield = Duktape.Thread.yield; t = {}; throw new RangeError('aiee'); } var t = Duktape.Thread(yielder); try { Duktape.Thread.resume(t); } catch (e) { print(e); } print('done');
import PropTypes from 'prop-types'; import React from 'react'; class DaySlot extends React.Component { render() { return ( <div className=""> <div className="topbar"> <div className="info-title">Appointment info</div> <div className="icons"> <ul> <li><a className="edit" href="#" onClick={(e) => this.hoverDialogActions(event, e, 'edit')}><i className="fa fa-pencil-square-o" aria-hidden="true"></i></a></li> <li><a className="trash" href="#" onClick={(e) => this.hoverDialogActions(event, e, 'delete')}><i className="fa fa-trash-o" aria-hidden="true"></i></a></li> </ul> </div> </div> <div className="info-content"> <div className="personal-info"> <div className="info-pic"> <img src={Img} width="80px" height="80px" /> </div> <div className="info-p"> <div className="name">Dr {patientName}</div> {/*<p><b>Phone: </b><span>897-876-6543</span></p>*/} <a href="#" onClick={(e) => this.hoverDialogActions(event, e, 'view_profile')}>View Client Profile</a> <a href="#" onClick={(e) => this.hoverDialogActions(event, e, 'soap_note')}>View Client Profile</a> </div> </div> <div className="about-event"> <div className="info-p"> <p><b>Appointment: </b><span>New Patient Consultation</span></p> <p><b>Time: </b><span>02:00-02:30 p.m</span></p> <p><b>Co-Pay: </b><span><i className="fa fa-usd" aria-hidden="true"></i> 00.00</span></p> </div> </div> </div> </div> ) } } export default DaySlot;
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var createClass = require('create-react-class'); var NotificationSyncDisabled = createClass({ displayName: 'NotificationSyncDisabled', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z' }) ); } }); module.exports = NotificationSyncDisabled;
var searchData= [ ['lgssm',['Lgssm',['../classLgssm.html',1,'']]] ];
export clone from './clone' export parseToInstance from './parseToInstance'
chart("static/data/data.csv", "orange"); var datearray = []; var colorrange = []; function chart(csvpath, color) { if (color == "blue") { colorrange = ["#045A8D", "#2B8CBE", "#74A9CF", "#A6BDDB", "#D0D1E6", "#F1EEF6"]; } else if (color == "pink") { colorrange = ["#980043", "#DD1C77", "#DF65B0", "#C994C7", "#D4B9DA", "#F1EEF6"]; } else if (color == "orange") { colorrange = ["#B30000", "#E34A33", "#FC8D59", "#FDBB84", "#FDD49E", "#FEF0D9"]; } strokecolor = colorrange[0]; var format = d3.time.format("%m/%d/%y"); var margin = {top: 20, right: 40, bottom: 30, left: 30}; var width = document.body.clientWidth - margin.left - margin.right; var height = 400 - margin.top - margin.bottom; var tooltip = d3.select("body") .append("div") .attr("class", "remove") .style("position", "absolute") .style("z-index", "20") .style("visibility", "hidden") .style("top", "30px") .style("left", "55px"); var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height-10, 0]); var z = d3.scale.ordinal() .range(colorrange); var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(d3.time.weeks); var yAxis = d3.svg.axis() .scale(y); var yAxisr = d3.svg.axis() .scale(y); var stack = d3.layout.stack() .offset("silhouette") .values(function(d) { return d.values; }) .x(function(d) { return d.date; }) .y(function(d) { return d.value; }); var nest = d3.nest() .key(function(d) { return d.key; }); var area = d3.svg.area() .interpolate("cardinal") .x(function(d) { return x(d.date); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }); var svg = d3.select(".chart").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var graph = d3.csv(csvpath, function(data) { data.forEach(function(d) { d.date = format.parse(d.date); d.value = +d.value; }); var layers = stack(nest.entries(data)); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]); svg.selectAll(".layer") .data(layers) .enter().append("path") .attr("class", "layer") .attr("d", function(d) { return area(d.values); }) .style("fill", function(d, i) { return z(i); }); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + width + ", 0)") .call(yAxis.orient("right")); svg.append("g") .attr("class", "y axis") .call(yAxis.orient("left")); svg.selectAll(".layer") .attr("opacity", 1) .on("mouseover", function(d, i) { svg.selectAll(".layer").transition() .duration(250) .attr("opacity", function(d, j) { return j != i ? 0.6 : 1; })}) .on("mousemove", function(d, i) { mousex = d3.mouse(this); mousex = mousex[0]; var invertedx = x.invert(mousex); invertedx = invertedx.getMonth() + invertedx.getDate(); var selected = (d.values); for (var k = 0; k < selected.length; k++) { datearray[k] = selected[k].date datearray[k] = datearray[k].getMonth() + datearray[k].getDate(); } mousedate = datearray.indexOf(invertedx); pro = d.values[mousedate].value; d3.select(this) .classed("hover", true) .attr("stroke", strokecolor) .attr("stroke-width", "0.5px"), tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "visible"); }) .on("mouseout", function(d, i) { svg.selectAll(".layer") .transition() .duration(250) .attr("opacity", "1"); d3.select(this) .classed("hover", false) .attr("stroke-width", "0px"), tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "hidden"); }) var vertical = d3.select(".chart") .append("div") .attr("class", "remove") .style("position", "absolute") .style("z-index", "19") .style("width", "1px") .style("height", "380px") .style("top", "10px") .style("bottom", "30px") .style("left", "0px") .style("background", "#fff"); d3.select(".chart") .on("mousemove", function(){ mousex = d3.mouse(this); mousex = mousex[0] + 5; vertical.style("left", mousex + "px" )}) .on("mouseover", function(){ mousex = d3.mouse(this); mousex = mousex[0] + 5; vertical.style("left", mousex + "px")}); }); }
Settings = { chart: { padding: { right: 40, bottom: 80 }, margins: { top: 30, bottom: 0, right: 35 }, }, defaultData: { title: 'Bar Chart', mode: 'single', // other mode: 'multi', refers to the number of indicators. byYear: false, chosenYear: '', sorted: false, // sort by value. When false, the x-axis is sorted by name instead. x: { single: { indicator: ["isr", "ita", "mex", "mar", "kor", "gbr", "usa"] }, multi: { indicator: ['downloadkbps', 'speedkbps'] // Average download speed, % of people using the internet. temp. } }, y: { single: { indicator: 'ipr' // % of people using the internet }, multi: { indicator: 'kor' // temp } } } }; IMonBarchartWidget = function(doc) { Widget.call(this, doc); _.defaults(this.data, Settings.defaultData); }; IMonBarchartWidget.prototype = Object.create(Widget.prototype); IMonBarchartWidget.prototype.constructor = IMonBarchartWidget; IMonBarchart = { widget: { name: 'Bar Chart', description: 'Shows a bar chart comparing an indicator across several countries.', url: 'https://thenetmonitor.org/sources', dimensions: { width: 3, height: 2 }, resize: { mode: 'cover' }, constructor: IMonBarchartWidget, typeIcon: 'bar-chart', indicators: 'all', country: 'multi', countries: 'all' }, org: { name: 'Internet Monitor', shortName: 'IM', url: 'http://thenetmonitor.org' } };
/* MIT License Copyright (c) 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function toggleDivInfo(element) { //console.log("checkbox Info" + element.elementid); if(element.checked) { document.getElementById("divInfo" + element.elementid).style.display = "block"; //console.log("checked"); } else { document.getElementById("divInfo" + element.elementid).style.display = "none"; //console.log("not checked"); } } function showInfo() { hideAllConfigurations(); document.getElementById("gbInfo").style.display = "block"; } function hideInfo() { document.getElementById("gbInfo").style.display = "none"; } function initInfo() { var gbInfo = document.createElement("div"); gbInfo.id = "gbInfo"; document.getElementById("configurator").appendChild(gbInfo); var gbInfoGroup = document.createElement("div"); gbInfoGroup.className = "gbPeripherals"; var head4 = document.createElement("h4"); var node = document.createTextNode("About " + board.info["board-name"]); head4.appendChild(node); gbInfoGroup.appendChild(head4); gbInfo.appendChild(gbInfoGroup); gbInfoGroup = document.createElement("div"); gbInfoGroup.className = "gbPeripherals"; head4 = document.createElement("h4"); node = document.createTextNode("Microcontroller details"); head4.appendChild(node); gbInfoGroup.appendChild(head4); gbInfo.appendChild(gbInfoGroup); var divHell1 = document.createElement("div"); gbInfoGroup.appendChild(divHell1); addSimpleTxt(divHell1,"Type: ",board.info.microcontroller.manufacturer + " " + board.info.microcontroller.name); addSimpleTxt(divHell1,"Description: ", board.info.microcontroller.short_description); for(var t = 0; t < board.info.microcontroller.docs.length;t++) { addSimpleLink(divHell1,board.info.microcontroller.docs[t].type + ": ","open" ,board.info.microcontroller.docs[t].url); } } function addSimpleLink(parent, title, link_txt, link_url) { var span = document.createElement("span"); var node = document.createTextNode(title); span.style.fontWeight = "bold"; span.appendChild(node); var p = document.createElement("p"); p.appendChild(span); var link = document.createElement("a"); node = document.createTextNode(link_txt); link.appendChild(node); link.href = link_url; link.target = "_blank"; p.appendChild(link); parent.appendChild(p); } function addSimpleTxt(parent, title, txt) { var span = document.createElement("span"); var node = document.createTextNode(title); span.style.fontWeight = "bold"; span.appendChild(node); node = document.createTextNode(txt); var p = document.createElement("p"); p.appendChild(span); p.appendChild(node); parent.appendChild(p); }
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define("require exports ../../../core/tsSupport/declareExtendsHelper ../../../core/tsSupport/decorateHelper ../../../core/Accessor ../../../core/accessorSupport/decorators ./directionsUtils".split(" "),function(h,k,f,c,g,b,d){return function(e){function a(){return null!==e&&e.apply(this,arguments)||this}f(a,e);Object.defineProperty(a.prototype,"primary",{get:function(){var a=this.get("directionsViewModel.lastRoute.routeResults.0.directions"),b=this.directionsViewModel.impedanceAttribute,c=this.get("directionsViewModel.routeParameters.directionsLengthUnits"); return d.isTimeUnits(b.units)?d.formatTime(a.totalTime,{unit:b.units.replace("esriNAU","")}):d.formatDistance(a.totalLength,{toUnits:c})},enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"secondary",{get:function(){var a=this.get("directionsViewModel.lastRoute.routeResults.0.directions"),b=this.get("directionsViewModel.routeParameters.directionsLengthUnits");return d.isTimeUnits(this.directionsViewModel.impedanceAttribute.units)?d.formatDistance(a.totalLength,{toUnits:b}):d.formatTime(a.totalTime)}, enumerable:!0,configurable:!0});c([b.property()],a.prototype,"directionsViewModel",void 0);c([b.property({dependsOn:["directionsViewModel"],readOnly:!0})],a.prototype,"primary",null);c([b.property({dependsOn:["directionsViewModel"],readOnly:!0})],a.prototype,"secondary",null);return a=c([b.subclass("esri.widgets.Directions.support.CostSummary")],a)}(b.declared(g))});
/** * @param {Range} range * @param {Node} node * @returns {boolean} */ export default function rangeIntersectsNode(range, node) { const nodeRange = document.createRange(); nodeRange.selectNode(node); return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) === -1 && range.compareBoundaryPoints(Range.START_TO_END, nodeRange) === 1; }
// Download the Node helper library from twilio.com/docs/node/install // These vars are your accountSid and authToken from twilio.com/user/account const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); client.recordings('RE557ce644e5ab84fa21cc21112e22c485').delete((err, data) => { if (err) { console.log(err.status); throw err.message; } else { console.log('Sid RE557ce644e5ab84fa21cc21112e22c485 deleted successfully.'); } });
/* AngularJS v1.2.9-build.2130+sha.02a4582 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(H,a,A){'use strict';function D(p,g){g=g||{};a.forEach(g,function(a,c){delete g[c]});for(var c in p)p.hasOwnProperty(c)&&("$"!==c.charAt(0)&&"$"!==c.charAt(1))&&(g[c]=p[c]);return g}var v=a.$$minErr("$resource"),C=/^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;a.module("ngResource",["ng"]).factory("$resource",["$http","$q",function(p,g){function c(a,c){this.template=a;this.defaults=c||{};this.urlParams={}}function t(n,w,l){function r(h,d){var e={};d=x({},w,d);s(d,function(b,d){u(b)&&(b=b());var k;if(b&& b.charAt&&"@"==b.charAt(0)){k=h;var a=b.substr(1);if(null==a||""===a||"hasOwnProperty"===a||!C.test("."+a))throw v("badmember",a);for(var a=a.split("."),f=0,c=a.length;f<c&&k!==A;f++){var g=a[f];k=null!==k?k[g]:A}}else k=b;e[d]=k});return e}function e(a){return a.resource}function f(a){D(a||{},this)}var F=new c(n);l=x({},B,l);s(l,function(h,d){var c=/^(POST|PUT|PATCH)$/i.test(h.method);f[d]=function(b,d,k,w){var q={},n,l,y;switch(arguments.length){case 4:y=w,l=k;case 3:case 2:if(u(d)){if(u(b)){l= b;y=d;break}l=d;y=k}else{q=b;n=d;l=k;break}case 1:u(b)?l=b:c?n=b:q=b;break;case 0:break;default:throw v("badargs",arguments.length);}var t=this instanceof f,m=t?n:h.isArray?[]:new f(n),z={},B=h.interceptor&&h.interceptor.response||e,C=h.interceptor&&h.interceptor.responseError||A;s(h,function(a,b){"params"!=b&&("isArray"!=b&&"interceptor"!=b)&&(z[b]=G(a))});c&&(z.data=n);F.setUrlParams(z,x({},r(n,h.params||{}),q),h.url);q=p(z).then(function(b){var d=b.data,k=m.$promise;if(d){if(a.isArray(d)!==!!h.isArray)throw v("badcfg", h.isArray?"array":"object",a.isArray(d)?"array":"object");h.isArray?(m.length=0,s(d,function(b){m.push(new f(b))})):(D(d,m),m.$promise=k)}m.$resolved=!0;b.resource=m;return b},function(b){m.$resolved=!0;(y||E)(b);return g.reject(b)});q=q.then(function(b){var a=B(b);(l||E)(a,b.headers);return a},C);return t?q:(m.$promise=q,m.$resolved=!1,m)};f.prototype["$"+d]=function(b,a,k){u(b)&&(k=a,a=b,b={});b=f[d].call(this,b,this,a,k);return b.$promise||b}});f.bind=function(a){return t(n,x({},w,a),l)};return f} var B={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}},E=a.noop,s=a.forEach,x=a.extend,G=a.copy,u=a.isFunction;c.prototype={setUrlParams:function(c,g,l){var r=this,e=l||r.template,f,p,h=r.urlParams={};s(e.split(/\W/),function(a){if("hasOwnProperty"===a)throw v("badname");!/^\d+$/.test(a)&&(a&&RegExp("(^|[^\\\\]):"+a+"(\\W|$)").test(e))&&(h[a]=!0)});e=e.replace(/\\:/g,":");g=g||{};s(r.urlParams,function(d,c){f=g.hasOwnProperty(c)? g[c]:r.defaults[c];a.isDefined(f)&&null!==f?(p=encodeURIComponent(f).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"%20").replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+"),e=e.replace(RegExp(":"+c+"(\\W|$)","g"),p+"$1")):e=e.replace(RegExp("(/?):"+c+"(\\W|$)","g"),function(a,c,d){return"/"==d.charAt(0)?d:c+d})});e=e.replace(/\/+$/,"")||"/";e=e.replace(/\/\.(?=\w+($|\?))/,".");c.url=e.replace(/\/\\\./,"/.");s(g,function(a,e){r.urlParams[e]|| (c.params=c.params||{},c.params[e]=a)})}};return t}])})(window,window.angular);
export default input => { const result = input.replace(/-\w/g, match => match.charAt(1).toUpperCase()); if (input.charAt(0) === '-' && input.charAt(2) === 's') { // -ms- return 'm' + result.substr(1); // lower case the first char } return result; };
import { connect } from 'react-redux'; import Modal from '../components/Modal'; import { closeModal } from '../actions/modal'; const mapStateToProps = (state) => { return { open: state.modal.open, form: state.modal.form, }; }; const mapDispatchToProps = (dispatch) => { return { closeModal: () => { dispatch(closeModal()); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(Modal);
/*global define, exports, require */ (function (global, definition) { 'use strict'; if (typeof define === 'function' && define.amd) { define(definition); } else if (typeof exports === 'object' && typeof require === 'function') { module.exports = definition(); } else { if (typeof global.hansi === 'undefined') global.hansi = {}; global.hansi.iter = definition(); } })((typeof window === 'undefined' ? this : window), function () { 'use strict'; var ANSI = /(\0x1b[@-_])([0-?]*)([ -\/]*[@-~])/; function splitArgs(str) { var args = str.split(';'); for (var i = 0; i < args.length; i++) { args[i] = parseInt(args[i], 10); } return args; } function Iter(str) { if (!(this instanceof Iter)) return new Iter(str); this.str = str || ''; this.match = null; } Iter.prototype = { constructor: Iter, write: function write(str) { if (str) this.str += str; return this; }, read: function read(length) { var str; if (typeof length === 'undefined') { str = this.str; this.str = ''; } else { str = this.str.substring(0, length); this.str = this.str.substring(length); } return str; }, next: function next(str) { var seq; if (str) this.write(str); if (!this.str) return null; if (!this.match) { this.match = ANSI.exec(this.str); if (!this.match) { return this.read(); } else if (this.match.index) { return this.read(this.match.index); } } if (this.match) { seq = { start: this.match[1], args: this.match[2] ? splitArgs(this.match[2]) : [], end: this.match[3], str: this.read(this.match[0].length) }; this.match = null; return seq; } throw new Error('this code should never be reached'); } }; function iter(str) { var i = new Iter(str); return function next() { return i.next.apply(i, arguments); }; } iter.Iter = Iter; return iter; });
import React from "react"; import PropTypes from "prop-types"; import {connect} from "react-redux"; import Home from "./Home"; import {Route, Switch} from "react-router-dom"; import {AppBar, FlatButton} from "material-ui"; import {logout} from "../store/GlobalAction"; class App extends React.Component { render() { const {logout} = this.props; return ( <div> <AppBar title="Title" showMenuIconButton={false} iconElementRight={<FlatButton label="Logout" onClick={logout}/>} /> <div className="container"> <Switch> <Route exact={true} path={Location.ROOT} component={Home}/> </Switch> </div> </div> ) } } App.propTypes = { logout: PropTypes.func.isRequired }; const mapStateToProps = state => { return { globalStore: state.globalReducer, store: state, } }; const mapDispatchToProps = dispatch => { return { logout: () => { dispatch(logout()); }, } }; App = connect( mapStateToProps, mapDispatchToProps )(App); export default App;
var React = require('react'); var ReactDOM = require('react-dom'); var Main = React.createClass({ render: function(){ return ( <div> Hello World </div> ) } }); ReactDOM.render(<Main />, document.getElementById('app'));
/** * Loading Screen * <Loading text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ 'use strict'; /* Setup ==================================================================== */ import React, { Component } from 'react' import { View, ActivityIndicator, Text } from 'react-native' // App Globals import AppStyles from '../styles' import AppConfig from '../config' /* Component ==================================================================== */ class Loading extends Component { static propTypes = { text: React.PropTypes.string, transparent: React.PropTypes.bool, } render = () => { let { text, transparent } = this.props; let colorOfSpinner = "#AAA"; if (transparent) colorOfSpinner = "#000"; return ( <View style={[AppStyles.container, AppStyles.containerCentered, transparent && {backgroundColor: 'rgba(255,255,255,0.75)'} ]}> <ActivityIndicator animating={true} size="large" color={colorOfSpinner} /> <View style={[AppStyles.spacer_10]} /> {text && <Text style={[AppStyles.baseText]}> {text} </Text> } </View> ); } } /* Export Component ==================================================================== */ export default Loading
#pragma strict //var WalkDest : GameObject; var WayPoints : GameObject[]; private var CurrentDest : int = 0; var agent : NavMeshAgent ; var player : GameObject; var excl : GameObject; var status : String = "patrolling"; var lastseen : GameObject; function Start() { agent = GetComponent(NavMeshAgent); agent.destination = WayPoints[CurrentDest].transform.position; player = GameObject.Find("Char"); excl = transform.Find("excl/exclr").gameObject; lastseen = GameObject.Find("lastseen"); } function Update() { if (status == "investigating") { agent.destination = lastseen.transform.position; } if (agent.remainingDistance <= 1.5f) { if (status != "investigating") { CurrentDest++; } status = "patrolling"; if (CurrentDest == WayPoints.length) { CurrentDest=0; } if (status == "patrolling") { agent.destination = WayPoints[CurrentDest].transform.position; } } var hit : RaycastHit; if (Physics.Linecast (transform.position, player.transform.position, hit)) { if (hit.transform.gameObject.name == "Char" && hit.distance < 14) { var targetDir = player.transform.position - transform.position; var forward = transform.forward; var angle = Vector3.Angle(targetDir, forward); if (angle < 15.0 || (angle < 80.0 && hit.distance < 5)) { excl.transform.localPosition.y = 0; Caught(); } else { excl.transform.localPosition.y = 1000; } } else { excl.transform.localPosition.y = 1000; } } } function Caught() { if (!GameObject.Find("ogard").GetComponent.<AudioSource>().isPlaying) { GameObject.Find("ogard").GetComponent.<AudioSource>().Play(); } GameObject.Find("Char").transform.position = GameObject.Find("start").transform.position; GameObject.Find("caught").transform.localPosition.y = 0; yield WaitForSeconds(3); GameObject.Find("caught").transform.localPosition.y = 999; } function Investigate() { status = "investigating"; }
import _ from 'lodash'; import moment from 'moment'; import control from 'control'; import RepoActions from 'actions/RepoActions'; import { PULSE_TIME_STAMPS, PULSE_TIME_LABELS, } from 'constants/dashboard'; class RepoStore { constructor() { this.bindActions(RepoActions); this.state = { repos: [], overviews: [], commits: [], repoPulses: [], }; } onLoadInitData(data) { let repos = data.repoList; _.forEach(repos, (repo, index) => { repos[index].visible = true; repos[index].rgb = this._hexToRgb(repo.color); }); this.setState({ repos, overviews: data.overview, commits: data.commits, repoPulses: this._createPulseData(data.commits, repos), }); } onLoadRepoList(repos) { _.forEach(repos, (repo, index) => { repos[index].visible = true; repos[index].rgb = this._hexToRgb(repos[index].color); }); this.setState({ repos, }); } onSwitchRepoVisibility(repoId) { let repos = this.state.repos; let repoIndex = _.findIndex(repos, (repo) => { return repo.id === repoId; }); if (repoIndex >= 0) { repos[repoIndex].visible = !repos[repoIndex].visible; this.setState({ repos, }); } } onLoadCommitsOverview(data) { let overviews = this.state.commitsOverviews; let repoIndex = _.findIndex(overviews, (overview) => { return overview.repoId === data.repoId; }); if (repoIndex >= 0) { overviews[repoIndex] = data; } else { overviews.push(data); } this.setState({ commitsOverviews: overviews, }); } onLoadCommits(allCommitsData) { let commitsData = this.state.commitsData; _.forEach(allCommitsData, (data) => { let repoIndex = _.findIndex(commitsData, (commitData) => { return commitData.repoId === data.repoId; }); if (repoIndex >= 0) { commitsData[repoIndex].commits = _.uniq(_.merge( commitsData[repoIndex].commits, data.commits )); } else { commitsData.push(data); } }); this.setState({ commitsData }); } onLoadContributors(newContributorsData) { let contributorsData = this.state.contributorsData; _.forEach(newContributorsData, (data) => { let repoIndex = _.findIndex(contributorsData, (repoContributorsData) => { return repoContributorsData.repoId === data.repoId; }); if (repoIndex >= 0) { contributorsData[repoIndex] = data.authors; } else { contributorsData.push(data); } }); this.setState({ contributorsData }); } onLoadHours(newHoursData) { let hoursData = this.state.hoursData; _.forEach(newHoursData, (data) => { let repoIndex = _.findIndex(hoursData, (repoHoursData) => { return repoHoursData.repoId === data.repoId; }); if (repoIndex > 0) { hoursData[repoIndex] = data.hours; } else { hoursData.push(data); } }); this.setState({ hoursData }); } _hexToRgb(hex) { let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), } : null; } _rgba(rgb, a) { return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${a})`; } _createPulseData(commits, repos) { let repoPulses = []; _.forEach(commits, commitData => { let repoId = commitData.repoId; let repo = _.find(repos, repoData => { return repoData.id === repoId; }); let rgb = repo.rgb; let pulseData = { repoId, chartData: { labels: PULSE_TIME_LABELS, datasets: [ { label: 'Commit count', fillColor: this._rgba(rgb, 0.5), strokeColor: this._rgba(rgb, 1), pointColor: this._rgba(rgb, 1), data: [], }, ], }, }; for (let i = 0; i < PULSE_TIME_STAMPS.length - 1; i++) { let commitCount = _.filter(commitData.commits, commit => { let timeStamp = moment(new Date(commit.author_time)).unix(); return timeStamp >= PULSE_TIME_STAMPS[i] && timeStamp < PULSE_TIME_STAMPS[i + 1]; }).length; pulseData.chartData.datasets[0].data.push(commitCount); } repoPulses.push(pulseData); }); return repoPulses; } } export default control.createStore(RepoStore, 'RepoStore');
import {TaskQueue} from '../src/index'; import {initialize} from 'aurelia-pal-browser'; describe('TaskQueue', () => { let sut; beforeAll(() => initialize()); beforeEach(() => { sut = new TaskQueue(); }); it('queueTask does not provide immediate execution', () => { let count = 0; let task = () => (count += 1); sut.queueTask(task); sut.queueTask(task); expect(count).toBe(0); }); it('flushTaskQueue provides immediate execution', () => { let count = 0; let task = () => (count += 1); sut.queueTask(task); sut.flushTaskQueue(); expect(count).toBe(1); }); it('flushTaskQueue does not affect microTaskQueue', () => { let count = 0; let task = () => (count += 1); sut.queueMicroTask(task); sut.queueMicroTask(task); sut.flushTaskQueue(); expect(count).toBe(0); }); it('queueMicroTask does not provide immediate execution', () => { let count = 0; let task = () => (count += 1); sut.queueMicroTask(task); sut.queueMicroTask(task); expect(count).toBe(0); }); it('flushMicroTaskQueue provides immediate execution', () => { let count = 0; let task = () => (count += 1); sut.queueMicroTask(task); sut.flushMicroTaskQueue(); expect(count).toBe(1); }); it('flushMicroTaskQueue does not affect taskQueue', () => { let count = 0; let task = () => (count += 1); sut.queueTask(task); sut.queueTask(task); sut.flushMicroTaskQueue(); expect(count).toBe(0); }); it('will execute tasks in the correct order', done => { let task1HasRun = false; let task1 = () => { expect(sut.flushing).toBe(true); task1HasRun = true; }; let task2 = () => { expect(sut.flushing).toBe(true); expect(task1HasRun).toBe(true); setTimeout(() => { expect(sut.flushing).toBe(false); done(); }); }; expect(sut.flushing).toBe(false); sut.queueTask(task1); sut.queueTask(task2); }); it('will use an onError handler on a task', done => { let task = () => { expect(sut.flushing).toBe(true); throw new Error('oops'); }; task.onError = ex => { expect(ex.message).toBe('oops'); setTimeout(() => { expect(sut.flushing).toBe(false); done(); }); }; expect(sut.flushing).toBe(false); sut.queueTask(task); }); });
import React, { Component, PropTypes } from 'react'; import Module from '../Shared/Module'; import EuclideanSolution from './EuclideanSolution'; const inputs = [ { name: "big", type: "number", validations: "isInt", fullWidth: true, floatingLabelText: "First Number (m)" }, { name: "small", type: "number", fullWidth: true, validations: "isInt", floatingLabelText: "Second Number (n)" } ] export default class EuclideanModule extends Component { render () { return <Module solution={EuclideanSolution} inputs={inputs}/> } } EuclideanModule.id = 'euclidean'; EuclideanModule.title = 'Euclidean Algorithm';
const error_404 = require('./error_404.js'); const error_503 = require('./error_503.js'); const content_types = require('../mongo_documents/content_types.js'); const Tags = require('../mongo_documents/tags.js'); const Tag_types = require('../mongo_documents/tag_types.js').tag_types; const Artefacts = require('../mongo_documents/artefacts.js'); const Editions = require('../mongo_documents/editions.js'); const singular = require('pluralize').singular; const stream_from = require('rillet').from; const result_set = require('../json_format/result_set.js'); const format_artefact = require('../json_format/artefacts.js'); ////////////////////////////////////////////////////////////// async function tag_param(req, res, db, url_helper) { const tag = req.query["tag"]; const tags = await Tags.by_ids(tag, db); const modifiers = modifier_params(req); const possible_tags = tags.filter(uniq_by_tag_type()); // If we can unambiguously determine the tag type, redirect to its correct URL if (possible_tags.length == 1) res.redirect(url_helper.with_tag_url(tags, modifiers)); else if (content_types.some(ct => ct == singular(tag))) res.redirect(url_helper.with_type_url(tag, modifiers)); else error_404(res); } // tag_param function type_param(req, res, db, url_helper) { const type = singular(req.query["type"]); const description = `All content with the ${type} type`; const artefacts = Artefacts.by_type(db, type, req.query["role"], { sort: req.query["sort"] }); send_artefacts(res, artefacts, description, db, url_helper); } // type_param async function handle_params(req, res, db, url_helper) { const request_tags = stream_from(Tag_types). map(t => req.query[t.singular]). filter(q => q). join(); // nothing requested, so bail if (request_tags == '') return error_404(res); // so are what we've been asked for real tags? const tags = await Tags.by_ids(request_tags, db); if (tags.length == 0) // nope! return error_404(res); const tag_ids = tags.map(t => t.tag_id).join(','); const description = `All content with the ${tag_ids} ${tags[0].tag_type}`; const artefacts = Artefacts.by_tags(db, tag_ids, req.query["role"], { sort: req.query["sort"], filter: tag_extra_params(req) }); send_artefacts(res, artefacts, description, db, url_helper); } // handle_params function send_artefacts(res, artefacts, description, db, url_helper) { if (!artefacts) return error_404(res); artefacts. then(as => as.map(a => format_artefact(a, url_helper))). then(as => res.json(result_set(as, description))). catch(err => { console.log(err); error_503(res); }); } // artefacts function with_tag_formatter(req, res, db, url_helper) { if (req.query["tag"]) return tag_param(req, res, db, url_helper); if (req.query["type"]) return type_param(req, res, db, url_helper); return handle_params(req, res, db, url_helper); } // with_tags_formatter function make_with_tag_formatter(db, url_helper) { return (req, res) => with_tag_formatter(req, res, db, url_helper); } // make_with_tag_formatter module.exports = make_with_tag_formatter; /////////////////////////// /////////////////////////// const modifiers = [ 'sort', 'author', 'node', 'organization_name', 'role', 'whole_body', 'page', 'order_by', 'summary' ]; const tag_extras = [ 'author', 'node', 'organization_name' ]; function tag_extra_params(req) { return grab_request_params(req, tag_extras); } // tag_extras function modifier_params(req) { return grab_request_params(req, modifiers); } // modifiers function grab_request_params(req, names) { const m = {}; for (const p of names) if (req.query[p]) m[p] = req.query[p]; return m; } // grab_request_params function uniq_by_tag_type() { const seen = {}; return (tag) => { if (seen[tag.tag_type]) return false; return seen[tag.tag_type] = true; }; } // uniq
let dbMongoTest = require('./dbMongoTest'); let dbMysqlTest = require('./dbMysqlTest'); let routeTest = require('./routeTest'); dbMongoTest(); dbMysqlTest(); routeTest();
const testUtils = require('./testUtils'); const { generateAPITests } = require('./generateAPITests'); const matTestUtilsFactory = require('./matTestUtils'); const readExampleImagesFactory = require('./readExampleImages'); const generateClassMethodTestsFactory = require('./generateClassMethodTests'); const getNodeMajorVersion = () => parseInt(process.version.split('.')[0].slice(1)) module.exports = function(cv) { const cvVersionGreaterEqual = (major, minor, revision) => cv.version.major > major || (cv.version.major === major && cv.version.minor > minor) || (cv.version.major === major && cv.version.minor === minor && cv.version.revision >= revision) const cvVersionLowerThan = (major, minor, revision) => !cvVersionGreaterEqual(major, minor, revision) const cvVersionEqual = (major, minor, revision) => cv.version.major === major && cv.version.minor === minor && cv.version.revision === revision const matTestUtils = matTestUtilsFactory(cv); const readExampleImages = readExampleImagesFactory(cv); const generateClassMethodTests = generateClassMethodTestsFactory(cv); return Object.assign( {}, testUtils, matTestUtils, readExampleImages, { cvVersionGreaterEqual, cvVersionLowerThan, cvVersionEqual, generateAPITests, generateClassMethodTests, getNodeMajorVersion } ); };
import { PropTypes } from 'react'; import classNames from 'classnames'; import { Breakpoints, FloatTypes } from './enums'; /** * Property types for general properties. * * @returns {Object} */ export const GeneralPropTypes = { showFor: PropTypes.oneOf([Breakpoints.MEDIUM, Breakpoints.LARGE]), showOnlyFor: PropTypes.oneOf(objectValues(Breakpoints)), hideFor: PropTypes.oneOf([Breakpoints.MEDIUM, Breakpoints.LARGE]), hideOnlyFor: PropTypes.oneOf(objectValues(Breakpoints)), isHidden: PropTypes.bool, isInvisible: PropTypes.bool, showForLandscape: PropTypes.bool, showForPortrait: PropTypes.bool, showForSr: PropTypes.bool, showOnFocus: PropTypes.bool, isClearfix: PropTypes.bool, float: PropTypes.oneOf(objectValues(FloatTypes)) }; /** * Creates class names from the given arguments. * * @param {*} args * @returns {string} */ export function createClassName(...args) { return classNames(...args); } /** * Parses the general class names from the given properties. * * @param {Object} props * @returns {Object} */ export function generalClassNames(props) { return { 'show-for-medium': props.showFor === Breakpoints.MEDIUM, 'show-for-large': props.showFor === Breakpoints.LARGE, 'show-for-small-only': props.showOnlyFor === Breakpoints.SMALL, 'show-for-medium-only': props.showOnlyFor === Breakpoints.MEDIUM, 'show-for-large-only': props.showOnlyFor === Breakpoints.LARGE, 'hide-for-medium': props.hideFor === Breakpoints.MEDIUM, 'hide-for-large': props.hideFor === Breakpoints.LARGE, 'hide-for-small-only': props.hideOnlyFor === Breakpoints.SMALL, 'hide-for-medium-only': props.hideOnlyFor === Breakpoints.MEDIUM, 'hide-for-large-only': props.hideOnlyFor === Breakpoints.LARGE, 'hide': props.isHidden, 'invisible': props.isInvisible, 'show-for-landscape': props.showForLandscape, 'show-for-portrait': props.showForPortrait, 'show-for-sr': props.showForSr, 'show-on-focus': props.showOnFocus, 'clearfix': props.isClearfix, 'float-left': props.float === FloatTypes.LEFT, 'float-center': props.float === FloatTypes.CENTER, 'float-right': props.float === FloatTypes.RIGHT }; } /** * Returns the values for the given object. * This method is used for getting the values for enumerables. * * @param {Object} object * @returns {Array} */ export function objectValues(object) { const values = []; for (const property in object) { if (object.hasOwnProperty(property)) { values.push(object[property]); } } return values; } /** * Removes properties from the given object. * This method is used for removing valid attributes from component props prior to rendering. * * @param {Object} object * @param {Array} remove * @returns {Object} */ export function removeProps(object, remove) { const result = {}; for (const property in object) { if (object.hasOwnProperty(property) && remove.indexOf(property) === -1) { result[property] = object[property]; } } return result; }
((w) => { let settings = { className: 'form__block', params: ['login', 'password', 'email', 'surname', 'forename'], filter: { login: { events: ['change', 'blur'] }, password: { events: ['change', 'blur'] }, email: { events: ['change', 'blur'] } } }; let logger = new Logger('.logger'); let validator = new Validate('.form', logger, settings); let storage = new Account(validator, settings); let gridReader = GridReader(storage, logger, settings); let errors = JSON.parse(localStorage.getItem('newAccountsErrors')); localStorage.removeItem('newAccountsErrors'); if (errors) { if (errors.length) { for (let i = 0; i < errors.length; i++) { logger.write(errors[i], 'error'); } } else { if (localStorage.getItem('isSuccess') === 'true') { logger.write('Registration successful', 'success'); localStorage.removeItem('isSuccess'); } } } localStorage.setItem('newAccountsErrors', '[]'); function generateAccount() { let account = {}; let elements = document.getElementsByClassName('form__input'); for (let i = 0; i < elements.length; i++) { let element = elements[i]; account[element.name] = element.value; } return account; } document.querySelector('.js-validate').addEventListener('click', () => { let errors = validator.validate(); let account = generateAccount(); if (errors.length) { errors = errors.length === 1 ? errors[0] : errors.join(', '); logger.clear(); logger.write(`Account ${account.login} have several errors: ${ errors }`, 'error'); return; } try { storage.addAccount(account); localStorage.setItem('isSuccess', true); } catch (ex) { localStorage.setItem('newAccountsErrors', JSON.stringify([ex.message])); } location.reload(); }); })(this);
var random = require('geojson-random') var fs = require('fs') var path = require('path') var geo = random.polygon(10000, 4, 1) fs.writeFileSync(path.join(__dirname, 'data.geojson'), JSON.stringify(geo))
/** * * ramroll on 2016/10/24. */ export const COLOR_PRIMARY = "#188ae4" export const COLOR_NAV_DARK = '#082c48' export const COLOR_TITLE = "#222" export const COLOR_TEXT_LIGHT = "#777" export const COLOR_PRICE = "#ee4339" export const COLOR_INFO = '#3596e2' export const COLOR_LIGHT_BLUE = '#d8edfe' export const color={ theme: '#06C1AE', border: '#e9e9e9', background: '#f3f3f3' }
module.exports = function(grunt) { grunt.initConfig({ connect: { server: { options: { port: 9001, base: './' } } }, qunit: { all: { options: { urls: [ 'http://localhost:9001/test/test-for-jquery.html', 'http://localhost:9001/test/test-for-zepto.html' ] } } } }); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-connect'); // A convenient task alias. grunt.registerTask('test', ['connect', 'qunit']); };
import test from 'ava'; import * as datatypes from '../.fixtures/datatypes.fixture'; import * as describeType from '../index.next'; import infinity from './infinity.next'; test('describeType.is.infinity exposure', (t) => { t.is(toString.call(describeType.is.infinity), '[object Function]', 'should be a function'); }); test('infinity exposure', (t) => { t.is(toString.call(infinity), '[object Function]', 'should be a function'); }); datatypes.infinity.iterate((datatype) => { test(`${datatype.id} • infinity(${datatype.label});`, (t) => { t.is(infinity(datatype.value), true, 'should be true'); }); }); datatypes.all.remove(datatypes.infinity); datatypes.all.iterate((datatype) => { test(`${datatype.id} • infinity(${datatype.label});`, (t) => { t.is(infinity(datatype.value), false, 'should be false'); }); }); datatypes.all.add(datatypes.infinity);
/** * @author: @AngularClass */ require('ts-node/register'); var helpers = require('./helpers'); var SpecReporter = require('jasmine-spec-reporter').SpecReporter; exports.config = { baseUrl: 'http://localhost:3000/', // use `npm run e2e` specs: [ helpers.root('src/**/**.e2e-spec.ts'), helpers.root('src/**/*.e2e-spec.ts') ], exclude: [], framework: 'jasmine2', allScriptsTimeout: 110000, jasmineNodeOpts: { showTiming: true, showColors: true, isVerbose: false, includeStackTrace: false, defaultTimeoutInterval: 400000, print: () => {} }, directConnect: true, capabilities: { 'browserName': 'chrome' }, onPrepare: function() { browser.ignoreSynchronization = true; jasmine.getEnv().addReporter(new SpecReporter()); }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` */ useAllAngular2AppRoots: true };
import ReactDOM from 'react-dom'; import {root} from 'baobab-react/higher-order'; import Tree from './state/'; import Main from './components/main'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const tree = new Tree(); tree.load(() => { const RootedApp = root(Main, tree); ReactDOM.render(<RootedApp/>, document.getElementById('app')); });
const MIN_LOGIN_LENGTH = 4; const MIN_PASSWORD_LENGTH = 6; const validateLogin = (login) => { if (!login) { return 'Required'; } return login.length < MIN_LOGIN_LENGTH ? 'Login is too short' : ''; }; const validatePassword = (password) => { if (!password) { return 'Required'; } return password.length < MIN_PASSWORD_LENGTH ? 'Password is too short' : ''; }; export const loginValidation = (vals) => { const values = vals.toJS(); return { login: validateLogin(values.login), password: validatePassword(values.password), }; }; export const schemaConstructorValidation = (vals) => { const values = vals.toJS(); return { name: !values.name ? 'Required' : '', namespace: !values.namespace ? 'Required' : '', }; }; export const addFieldValidation = (vals) => { const values = vals.toJS(); return { fieldName: !values.fieldName ? 'Required' : '', fieldType: !values.fieldType ? 'Required' : '', }; };
var babelHelpers = require('./babel-helpers.js'); 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _angular = require('angular'); var _angular2 = babelHelpers.interopRequireDefault(_angular); var moduleName = 'mui.dropdown'; /** * MUI Angular Dropdown Component * @module angular/dropdown */ _angular2.default.module(moduleName, []).directive('muiDropdown', ['$timeout', '$compile', function ($timeout, $compile) { return { restrict: 'AE', transclude: true, replace: true, scope: { variant: '@', color: '@', size: '@', open: '=?', ngDisabled: '=' }, template: '<div class="mui-dropdown">' + '<mui-button ' + 'variant="{{variant}}" ' + 'color="{{color}}" ' + 'size="{{size}}" ' + 'ng-click="onClick($event);" ' + '></mui-button>' + '<ul class="mui-dropdown__menu" ng-transclude></ul>' + '</div>', link: function link(scope, element, attrs) { var dropdownClass = 'mui-dropdown', menuClass = 'mui-dropdown__menu', openClass = 'mui--is-open', rightClass = 'mui-dropdown__menu--right', isUndef = _angular2.default.isUndefined, menuEl, buttonEl; // save references menuEl = _angular2.default.element(element[0].querySelector('.' + menuClass)); buttonEl = _angular2.default.element(element[0].querySelector('.mui-btn')); menuEl.css('margin-top', '-3px'); // handle is-open if (!isUndef(attrs.open)) scope.open = true; // handle disabled if (!isUndef(attrs.disabled)) { buttonEl.attr('disabled', true); } // handle right-align if (!isUndef(attrs.rightAlign)) menuEl.addClass(rightClass); // handle no-caret if (!isUndef(attrs.noCaret)) buttonEl.html(attrs.label);else buttonEl.html(attrs.label + ' <mui-caret></mui-caret>'); function closeDropdownFn() { scope.open = false; scope.$apply(); } // handle menu open scope.$watch('open', function (newValue) { if (newValue === true) { menuEl.addClass(openClass); document.addEventListener('click', closeDropdownFn); } else if (newValue === false) { menuEl.removeClass(openClass); document.removeEventListener('click', closeDropdownFn); } }); // click handler scope.onClick = function ($event) { // exit if disabled if (scope.disabled) return; // prevent form submission $event.preventDefault(); $event.stopPropagation(); // toggle open if (scope.open) scope.open = false;else scope.open = true; }; } }; }]); /** Define module API */ exports.default = moduleName; module.exports = exports['default'];
var mongoose = require( 'mongoose' ), autoIncrement = require( 'mongoose-auto-increment' ); /** * Access Token Schema */ var AccessToken = mongoose.Schema({ userId: { type: Number, required: true }, clientId: { type: String, required: true }, token: { type: String, unique: true, required: true }, created: { type: Date, default: Date.now } }); /** * @typedef AccessToken */ AccessToken.plugin( autoIncrement.plugin, 'AccessToken' ); module.exports = mongoose.model( 'AccessToken', AccessToken );
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.cheetah = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
import value from "./value"; // TODO sparse arrays? export default function(a, b) { var x = [], c = [], na = a ? a.length : 0, nb = b ? b.length : 0, n0 = Math.min(na, nb), i; for (i = 0; i < n0; ++i) x.push(value(a[i], b[i])); for (; i < na; ++i) c[i] = a[i]; for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; };
window.addEventListener('load', function() { var webAuth = new auth0.WebAuth({ domain: AUTH_CONFIG.domain, clientID: AUTH_CONFIG.clientID, redirectUri: AUTH_CONFIG.callbackURL, audience: 'https://' + AUTH_CONFIG.domain + '/userinfo', responseType: 'token id_token' }) var loginStatus = document.querySelector('.container h4') var loginView = document.getElementById('login-view') var homeView = document.getElementById('home-view') // buttons and event listeners var homeViewBtn = document.getElementById('btn-home-view') var loginViewBtn = document.getElementById('btn-login-view') var logoutBtn = document.getElementById('btn-logout') var loginBtn = document.getElementById('btn-login') var signupBtn = document.getElementById('btn-signup') var googleLoginBtn = document.getElementById('btn-google-login') homeViewBtn.addEventListener('click', function() { homeView.style.display = 'inline-block' loginView.style.display = 'none' }) loginViewBtn.addEventListener('click', function() { loginView.style.display = 'inline-block' homeView.style.display = 'none' }) signupBtn.addEventListener('click', function() { var email = document.getElementById('email').value var password = document.getElementById('password').value signup(email, password) }) loginBtn.addEventListener('click', function() { var email = document.getElementById('email').value var password = document.getElementById('password').value login(email, password) }) logoutBtn.addEventListener('click', logout) googleLoginBtn.addEventListener('click', loginWithGoogle) function login(username, password) { webAuth.client.login({ realm: 'Username-Password-Authentication', username: username, password: password }, function (err, data) { if (err) { console.log(err) return } setUser(data) loginView.style.display = 'none' homeView.style.display = 'inline-block' displayButtons() }) } function signup(email, password) { webAuth.redirect.signupAndLogin({ connection: 'Username-Password-Authentication', email: email, password: password, }, function(err) { if (err) { console.log(err) } }) } function loginWithGoogle() { webAuth.authorize({ connection: 'google-oauth2', }, function(err) { if (err) { console.log('Error:' + err) } }) } function logout() { // Remove token from localStorage localStorage.removeItem('access_token') localStorage.removeItem('id_token') displayButtons() } function isAuthenticated() { // return tokenNotExpired() // need JS helper library - for now we'll assume they're logged in if they // have an `access_token` and `id_token` in their localStorage return localStorage['id_token'] && localStorage['access_token'] } function setUser(authResult) { localStorage.setItem('access_token', authResult.accessToken) localStorage.setItem('id_token', authResult.idToken) } function displayButtons() { if (isAuthenticated()) { loginViewBtn.style.display = 'none' logoutBtn.style.display = 'inline-block' loginStatus.innerHTML = 'You are logged in!' } else { loginViewBtn.style.display = 'inline-block' logoutBtn.style.display = 'none' loginStatus.innerHTML = 'You are not logged in! Please log in to continue.' } } function handleAuthentication() { webAuth.parseHash(function(err, authResult) { if (authResult && authResult.accessToken && authResult.idToken) { window.location.hash = '' setUser(authResult) loginView.style.display = 'none' homeView.style.display = 'inline-block' } else if (authResult && authResult.error) { alert('Error: ' + authResult.error) } displayButtons() }) } handleAuthentication() })
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/watnottoeat', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.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.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
const cons = (a, b) => (fn) => fn(a, b); const car = (c) => { if(typeof(c) === "function") return c((a, b) => a); else throw new Error("Cannot car on an empty list"); }; const cdr = (c) => { if(typeof(c) === "function") return c((a, b) => b); else throw new Error("Cannot cdr on an empty list"); }; const isNullList = (lst) => lst === void 0; const length = (lst) => { const length_iter = (ls, n) => { if(ls === void 0) { return n; } else { try{ return length_iter(cdr(ls), n + 1); } catch(e) { throw new Error("length only works for a proper list"); } } }; return length_iter(lst, 0); }; const listRef = (lst, n) => { if((lst === void 0)) { throw new Error("Out of range"); } if(n === 0) { return car(lst); } else { return listRef(cdr(lst), n - 1); } }; const iota = (count, start, step) => { if(count < 0) { throw new Error("count must be non-negative"); } if(!start) { start = 0; } if(!step) { step = 1; } if(count <= 0 ) { return void 0; } else { return cons(start, iota(count - 1, start + step, step)); } }; const arrayToList = (a) => { var list = void 0; for(let i = a.length - 1; i >= 0; --i) { list = cons(a[i], list); } return list; }; const list = (...args) => arrayToList(args); const listToArray = (lst) => { var a = []; forEach((x) => a.push(x), lst); return a; }; const map = (fn, lst) => { if(isNullList(lst)) { return void 0; } else { return cons(fn(car(lst)), map(fn, cdr(lst))); } }; const filter = (predicate, lst) => { if(isNullList(lst)) { return void 0; } else { if(predicate(car(lst))) { return cons(car(lst), filter(predicate, cdr(lst))); } else { return filter(predicate, cdr(lst)); } } }; const reduce = (op, init, lst) => { if(isNullList(lst)) { return init; } else { return reduce(op, op(init, car(lst)), cdr(lst)); } }; const forEach = (fn, lst) => { if(isNullList(lst)) { return void 0; } else { fn(car(lst)); return forEach(fn, cdr(lst)); } }; const isPair = (lst) => (typeof(lst) === "function" && (cdr(lst) === void 0 || typeof (cdr(lst)) === "function")); //given item, find the position in lst //if not found, return undefined const find = (item, lst) => { var find_iter = (item, lst, n) => { if(isNullList(lst)) { return void 0; } else if(car(lst) === item) { return n; } else { return find_iter(item, cdr(lst), n + 1); } }; return find_iter(item, lst, 0); }; const reverse = (lst) => { if(isNullList(lst)) { return (void 0); } else { return reduce((x, y) => cons(y, x), void 0, lst); } }; export {cons, car, cdr, length, listRef, iota, arrayToList, list, map, filter, reduce, forEach, isPair, find, reverse};
/* Prototype-UI, version trunk * * Prototype-UI is freely distributable under the terms of an MIT-style license. * For details, see the PrototypeUI web site: http://www.prototype-ui.com/ * *--------------------------------------------------------------------------*/ if(typeof Prototype == 'undefined' || !Prototype.Version.match("1.7")) throw("Prototype-UI library require Prototype library >= 1.7.0"); if (Prototype.Browser.WebKit) { Prototype.Browser.WebKitVersion = parseFloat(navigator.userAgent.match(/AppleWebKit\/([\d\.\+]*)/)[1]); Prototype.Browser.Safari2 = (Prototype.Browser.WebKitVersion < 420); } if (Prototype.Browser.IE) { Prototype.Browser.IEVersion = parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]); Prototype.Browser.IE6 = Prototype.Browser.IEVersion == 6; Prototype.Browser.IE7 = Prototype.Browser.IEVersion == 7; } Prototype.falseFunction = function() { return false }; Prototype.trueFunction = function() { return true }; /* Namespace: UI Introduction: Prototype-UI is a library of user interface components based on the Prototype framework. Its aim is to easilly improve user experience in web applications. It also provides utilities to help developers. Guideline: - Prototype conventions are followed - Everything should be unobstrusive - All components are themable with CSS stylesheets, various themes are provided Warning: Prototype-UI is still under deep development, this release is targeted to developers only. All interfaces are subjects to changes, suggestions are welcome. DO NOT use it in production for now. Authors: - Sébastien Gruhier, <http://www.xilinus.com> - Samuel Lebeau, <http://gotfresh.info> */ var UI = { Abstract: { }, Ajax: { } }; Object.extend(Class.Methods, { extend: Object.extend.methodize(), addMethods: Class.Methods.addMethods.wrap(function(proceed, source) { // ensure we are not trying to add null or undefined if (!source) return this; // no callback, vanilla way if (!source.hasOwnProperty('methodsAdded')) return proceed(source); var callback = source.methodsAdded; delete source.methodsAdded; proceed(source); callback.call(source, this); source.methodsAdded = callback; return this; }), addMethod: function(name, lambda) { var methods = {}; methods[name] = lambda; return this.addMethods(methods); }, method: function(name) { return this.prototype[name].valueOf(); }, classMethod: function() { $A(arguments).flatten().each(function(method) { this[method] = (function() { return this[method].apply(this, arguments); }).bind(this.prototype); }, this); return this; }, // prevent any call to this method undefMethod: function(name) { this.prototype[name] = undefined; return this; }, // remove the class' own implementation of this method removeMethod: function(name) { delete this.prototype[name]; return this; }, aliasMethod: function(newName, name) { this.prototype[newName] = this.prototype[name]; return this; }, aliasMethodChain: function(target, feature) { feature = feature.camelcase(); this.aliasMethod(target+"Without"+feature, target); this.aliasMethod(target, target+"With"+feature); return this; } }); Object.extend(Number.prototype, { // Snap a number to a grid snap: function(round) { return parseInt(round == 1 ? this : (this / round).floor() * round); } }); /* Interface: String */ Object.extend(String.prototype, { camelcase: function() { var string = this.dasherize().camelize(); return string.charAt(0).toUpperCase() + string.slice(1); }, /* Method: makeElement toElement is unfortunately already taken :/ Transforms html string into an extended element or null (when failed) > '<li><a href="#">some text</a></li>'.makeElement(); // => LI href# > '<img src="foo" id="bar" /><img src="bar" id="bar" />'.makeElement(); // => IMG#foo (first one) Returns: Extended element */ makeElement: function() { var wrapper = new Element('div'); wrapper.innerHTML = this; return wrapper.down(); } }); Object.extend(Array.prototype, { empty: function() { return !this.length; }, extractOptions: function() { return this.last().constructor === Object ? this.pop() : { }; }, removeAt: function(index) { var object = this[index]; this.splice(index, 1); return object; }, remove: function(object) { var index; while ((index = this.indexOf(object)) != -1) this.removeAt(index); return object; }, insert: function(index) { var args = $A(arguments); args.shift(); this.splice.apply(this, [ index, 0 ].concat(args)); return this; } }); Element.addMethods({ getScrollDimensions: function(element) { return { width: element.scrollWidth, height: element.scrollHeight } }, getScrollOffset: function(element) { return Element._returnOffset(element.scrollLeft, element.scrollTop); }, setScrollOffset: function(element, offset) { element = $(element); if (arguments.length == 3) offset = { left: offset, top: arguments[2] }; element.scrollLeft = offset.left; element.scrollTop = offset.top; return element; }, // returns "clean" numerical style (without "px") or null if style can not be resolved // or is not numeric getNumStyle: function(element, style) { var value = parseFloat($(element).getStyle(style)); return isNaN(value) ? null : value; }, // by Tobie Langel (http://tobielangel.com/2007/5/22/prototype-quick-tip) appendText: function(element, text) { element = $(element); text = String.interpret(text); element.appendChild(document.createTextNode(text)); return element; } }); document.whenReady = function(callback) { if (document.loaded) callback.call(document); else document.observe('dom:loaded', callback); }; Object.extend(document.viewport, { // Alias this method for consistency getScrollOffset: document.viewport.getScrollOffsets, setScrollOffset: function(offset) { Element.setScrollOffset(Prototype.Browser.WebKit ? document.body : document.documentElement, offset); }, getScrollDimensions: function() { return Element.getScrollDimensions(Prototype.Browser.WebKit ? document.body : document.documentElement); } }); /* Interface: UI.Options Mixin to handle *options* argument in initializer pattern. TODO: find a better example than Circle that use an imaginary Point function, this example should be used in tests too. It assumes class defines a property called *options*, containing default options values. Instances hold their own *options* property after a first call to <setOptions>. Example: > var Circle = Class.create(UI.Options, { > > // default options > options: { > radius: 1, > origin: Point(0, 0) > }, > > // common usage is to call setOptions in initializer > initialize: function(options) { > this.setOptions(options); > } > }); > > var circle = new Circle({ origin: Point(1, 4) }); > > circle.options > // => { radius: 1, origin: Point(1,4) } Accessors: There are builtin methods to automatically write options accessors. All those methods can take either an array of option names nor option names as arguments. Notice that those methods won't override an accessor method if already present. * <optionsGetter> creates getters * <optionsSetter> creates setters * <optionsAccessor> creates both getters and setters Common usage is to invoke them on a class to create accessors for all instances of this class. Invoking those methods on a class has the same effect as invoking them on the class prototype. See <classMethod> for more details. Example: > // Creates getter and setter for the "radius" options of circles > Circle.optionsAccessor('radius'); > > circle.setRadius(4); > // 4 > > circle.getRadius(); > // => 4 (circle.options.radius) Inheritance support: Subclasses can refine default *options* values, after a first instance call on setOptions, *options* attribute will hold all default options values coming from the inheritance hierarchy. */ (function() { UI.Options = { methodsAdded: function(klass) { klass.classMethod($w(' setOptions allOptions optionsGetter optionsSetter optionsAccessor ')); }, // Group: Methods /* Method: setOptions Extends object's *options* property with the given object */ setOptions: function(options) { if (!this.hasOwnProperty('options')) this.options = this.allOptions(); this.options = Object.extend(this.options, options || {}); }, /* Method: allOptions Computes the complete default options hash made by reverse extending all superclasses default options. > Widget.prototype.allOptions(); */ allOptions: function() { var superclass = this.constructor.superclass, ancestor = superclass && superclass.prototype; return (ancestor && ancestor.allOptions) ? Object.extend(ancestor.allOptions(), this.options) : Object.clone(this.options); }, /* Method: optionsGetter Creates default getters for option names given as arguments. With no argument, creates getters for all option names. */ optionsGetter: function() { addOptionsAccessors(this, arguments, false); }, /* Method: optionsSetter Creates default setters for option names given as arguments. With no argument, creates setters for all option names. */ optionsSetter: function() { addOptionsAccessors(this, arguments, true); }, /* Method: optionsAccessor Creates default getters/setters for option names given as arguments. With no argument, creates accessors for all option names. */ optionsAccessor: function() { this.optionsGetter.apply(this, arguments); this.optionsSetter.apply(this, arguments); } }; // Internal function addOptionsAccessors(receiver, names, areSetters) { names = $A(names).flatten(); if (names.empty()) names = Object.keys(receiver.allOptions()); names.each(function(name) { var accessorName = (areSetters ? 'set' : 'get') + name.camelcase(); receiver[accessorName] = receiver[accessorName] || (areSetters ? // Setter function(value) { return this.options[name] = value } : // Getter function() { return this.options[name] }); }); } })(); /* Class: UI.Carousel Main class to handle a carousel of elements in a page. A carousel : * could be vertical or horizontal * works with liquid layout * is designed by CSS Assumptions: * Elements should be from the same size Example: > ... > <div id="horizontal_carousel"> > <div class="previous_button"></div> > <div class="container"> > <ul> > <li> What ever you like</li> > </ul> > </div> > <div class="next_button"></div> > </div> > <script> > new UI.Carousel("horizontal_carousel"); > </script> > ... */ UI.Carousel = Class.create(UI.Options, { // Group: Options options: { // Property: direction // Can be horizontal or vertical, horizontal by default direction : "horizontal", // Property: previousButton // Selector of previous button inside carousel element, ".previous_button" by default, // set it to false to ignore previous button previousButton : ".previous_button", // Property: nextButton // Selector of next button inside carousel element, ".next_button" by default, // set it to false to ignore next button nextButton : ".next_button", // Property: container // Selector of carousel container inside carousel element, ".container" by default, container : ".carousel-container", // Property: scrollInc // Define the maximum number of elements that gonna scroll each time, auto by default scrollInc : "auto", // Property: disabledButtonSuffix // Define the suffix classanme used when a button get disabled, to '_disabled' by default // Previous button classname will be previous_button_disabled disabledButtonSuffix : '_disabled', // Property: overButtonSuffix // Define the suffix classanme used when a button has a rollover status, '_over' by default // Previous button classname will be previous_button_over overButtonSuffix : '_over' }, /* Group: Attributes Property: element DOM element containing the carousel Property: id DOM id of the carousel's element Property: container DOM element containing the carousel's elements Property: elements Array containing the carousel's elements as DOM elements Property: previousButton DOM id of the previous button Property: nextButton DOM id of the next button Property: posAttribute Define if the positions are from left or top Property: dimAttribute Define if the dimensions are horizontal or vertical Property: elementSize Size of each element, it's an integer Property: nbVisible Number of visible elements, it's a float Property: animating Define whether the carousel is in animation or not */ /* Group: Events List of events fired by a carousel Notice: Carousel custom events are automatically namespaced in "carousel:" (see Prototype custom events). Examples: This example will observe all carousels > document.observe('carousel:scroll:ended', function(event) { > alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled"); > }); This example will observe only this carousel > new UI.Carousel('horizontal_carousel').observe('scroll:ended', function(event) { > alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled"); > }); Property: previousButton:enabled Fired when the previous button has just been enabled Property: previousButton:disabled Fired when the previous button has just been disabled Property: nextButton:enabled Fired when the next button has just been enabled Property: nextButton:disabled Fired when the next button has just been disabled Property: scroll:started Fired when a scroll has just started Property: scroll:ended Fired when a scroll has been done, memo.shift = number of elements scrolled, it's a float Property: sizeUpdated Fired when the carousel size has just been updated. Tips: memo.carousel.currentSize() = the new carousel size */ // Group: Constructor /* Method: initialize Constructor function, should not be called directly Parameters: element - DOM element options - (Hash) list of optional parameters Returns: this */ initialize: function(element, options) { this.setOptions(options); this.element = $(element); this.id = this.element.id; this.container = this.element.down(this.options.container).firstDescendant(); this.elements = this.container.childElements(); this.previousButton = this.options.previousButton == false ? null : this.element.down(this.options.previousButton); this.nextButton = this.options.nextButton == false ? null : this.element.down(this.options.nextButton); this.posAttribute = (this.options.direction == "horizontal" ? "left" : "top"); this.dimAttribute = (this.options.direction == "horizontal" ? "width" : "height"); this.elementSize = this.computeElementSize(); this.nbVisible = this.currentSize() / this.elementSize; var scrollInc = this.options.scrollInc; if (scrollInc == "auto") scrollInc = Math.floor(this.nbVisible); [ this.previousButton, this.nextButton ].each(function(button) { if (!button) return; var className = (button == this.nextButton ? "next_button" : "previous_button") + this.options.overButtonSuffix; button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize); button.observe("click", button.clickHandler) .observe("mouseover", function() {button.addClassName(className)}.bind(this)) .observe("mouseout", function() {button.removeClassName(className)}.bind(this)); }, this); this.updateButtons(); }, // Group: Destructor /* Method: destroy Cleans up DOM and memory */ destroy: function($super) { [ this.previousButton, this.nextButton ].each(function(button) { if (!button) return; button.stopObserving("click", button.clickHandler); }, this); this.element.remove(); this.fire('destroyed'); }, // Group: Event handling /* Method: fire Fires a carousel custom event automatically namespaced in "carousel:" (see Prototype custom events). The memo object contains a "carousel" property referring to the carousel. Example: > document.observe('carousel:scroll:ended', function(event) { > alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled"); > }); Parameters: eventName - an event name memo - a memo object Returns: fired event */ fire: function(eventName, memo) { memo = memo || { }; memo.carousel = this; return this.element.fire('carousel:' + eventName, memo); }, /* Method: observe Observe a carousel event with a handler function automatically bound to the carousel Parameters: eventName - an event name handler - a handler function Returns: this */ observe: function(eventName, handler) { this.element.observe('carousel:' + eventName, handler.bind(this)); return this; }, /* Method: stopObserving Unregisters a carousel event, it must take the same parameters as this.observe (see Prototype stopObserving). Parameters: eventName - an event name handler - a handler function Returns: this */ stopObserving: function(eventName, handler) { this.element.stopObserving('carousel:' + eventName, handler); return this; }, // Group: Actions /* Method: checkScroll Check scroll position to avoid unused space at right or bottom Parameters: position - position to check updatePosition - should the container position be updated ? true/false Returns: position */ checkScroll: function(position, updatePosition) { //----- mychange begin ------------ var limit = 0; //--------------- //----- mychange end ------------ if (position > 0) position = 0; else { //----- mychange begin ------------ if(this.elements.last()){ limit = this.elements.last().positionedOffset()[this.posAttribute] + this.elementSize; } //----- mychange end ------------ var carouselSize = this.currentSize(); if (position + limit < carouselSize) position += carouselSize - (position + limit); position = Math.min(position, 0); } if (updatePosition) this.container.style[this.posAttribute] = position + "px"; return position; }, /* Method: scroll Scrolls carousel from maximum deltaPixel Parameters: deltaPixel - a float Returns: this */ scroll: function(deltaPixel) { if (this.animating) return this; // Compute new position var position = this.currentPosition() + deltaPixel; // Check bounds position = this.checkScroll(position, false); // Compute shift to apply deltaPixel = position - this.currentPosition(); if (deltaPixel != 0) { this.animating = true; this.fire("scroll:started"); var that = this; // Move effects this.container.morph("opacity:0.5", {duration: 0.2, afterFinish: function() { that.container.morph(that.posAttribute + ": " + position + "px", { duration: 0.4, delay: 0.2, afterFinish: function() { that.container.morph("opacity:1", { duration: 0.2, afterFinish: function() { that.animating = false; that.updateButtons() .fire("scroll:ended", { shift: deltaPixel / that.currentSize() }); } }); } }); }}); } return this; }, /* Method: scrollTo Scrolls carousel, so that element with specified index is the left-most. This method is convenient when using carousel in a tabbed navigation. Clicking on first tab should scroll first container into view, clicking on a fifth - fifth one, etc. Indexing starts with 0. Parameters: Index of an element which will be a left-most visible in the carousel Returns: this */ scrollTo: function(index) { if (this.animating || index < 0 || index > this.elements.length || index == this.currentIndex() || isNaN(parseInt(index))) return this; return this.scroll((this.currentIndex() - index) * this.elementSize); }, /* Method: updateButtons Update buttons status to enabled or disabled Them status is defined by classNames and fired as carousel's custom events Returns: this */ updateButtons: function() { this.updatePreviousButton(); this.updateNextButton(); return this; }, updatePreviousButton: function() { var position = this.currentPosition(); var previousClassName = "previous_button" + this.options.disabledButtonSuffix; if (this.previousButton.hasClassName(previousClassName) && position != 0) { this.previousButton.removeClassName(previousClassName); this.fire('previousButton:enabled'); } if (!this.previousButton.hasClassName(previousClassName) && position == 0) { this.previousButton.addClassName(previousClassName); this.fire('previousButton:disabled'); } }, updateNextButton: function() { var lastPosition = this.currentLastPosition(); var size = this.currentSize(); var nextClassName = "next_button" + this.options.disabledButtonSuffix; if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) { this.nextButton.removeClassName(nextClassName); this.fire('nextButton:enabled'); } if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size) { this.nextButton.addClassName(nextClassName); this.fire('nextButton:disabled'); } }, // Group: Size and Position /* Method: computeElementSize Return elements size in pixel, height or width depends on carousel orientation. Returns: an integer value */ computeElementSize: function() { return this.elements.first().getDimensions()[this.dimAttribute]; }, /* Method: currentIndex Returns current visible index of a carousel. For example, a horizontal carousel with image #3 on left will return 3 and with half of image #3 will return 3.5 Don't forget that the first image have an index 0 Returns: a float value */ currentIndex: function() { return - this.currentPosition() / this.elementSize; }, /* Method: currentLastPosition Returns the current position from the end of the last element. This value is in pixel. Returns: an integer value, if no images a present it will return 0 */ currentLastPosition: function() { if (this.container.childElements().empty()) return 0; return this.currentPosition() + this.elements.last().positionedOffset()[this.posAttribute] + this.elementSize; }, /* Method: currentPosition Returns the current position in pixel. Tips: To get the position in elements use currentIndex() Returns: an integer value */ currentPosition: function() { return this.container.getNumStyle(this.posAttribute); }, /* Method: currentSize Returns the current size of the carousel in pixel Returns: Carousel's size in pixel */ currentSize: function() { return this.container.parentNode.getDimensions()[this.dimAttribute]; }, /* Method: updateSize Should be called if carousel size has been changed (usually called with a liquid layout) Returns: this */ updateSize: function() { this.nbVisible = this.currentSize() / this.elementSize; var scrollInc = this.options.scrollInc; if (scrollInc == "auto") scrollInc = Math.floor(this.nbVisible); [ this.previousButton, this.nextButton ].each(function(button) { if (!button) return; button.stopObserving("click", button.clickHandler); button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize); button.observe("click", button.clickHandler); }, this); this.checkScroll(this.currentPosition(), true); this.updateButtons().fire('sizeUpdated'); return this; } }); /* Class: UI.Ajax.Carousel Gives the AJAX power to carousels. An AJAX carousel : * Use AJAX to add new elements on the fly Example: > new UI.Ajax.Carousel("horizontal_carousel", > {url: "get-more-elements", elementSize: 250}); */ UI.Ajax.Carousel = Class.create(UI.Carousel, { // Group: Options // // Notice: // It also include of all carousel's options options: { // Property: elementSize // Required, it define the size of all elements elementSize : -1, // Property: url // Required, it define the URL used by AJAX carousel to request new elements details url : null }, /* Group: Attributes Notice: It also include of all carousel's attributes Property: elementSize Size of each elements, it's an integer Property: endIndex Index of the last loaded element Property: hasMore Flag to define if there's still more elements to load Property: requestRunning Define whether a request is processing or not Property: updateHandler Callback to update carousel, usually used after request success Property: url URL used to request additional elements */ /* Group: Events List of events fired by an AJAX carousel, it also include of all carousel's custom events Property: request:started Fired when the request has just started Property: request:ended Fired when the request has succeed */ // Group: Constructor /* Method: initialize Constructor function, should not be called directly Parameters: element - DOM element options - (Hash) list of optional parameters Returns: this */ initialize: function($super, element, options) { if (!options.url) throw("url option is required for UI.Ajax.Carousel"); if (!options.elementSize) throw("elementSize option is required for UI.Ajax.Carousel"); $super(element, options); this.endIndex = 0; this.hasMore = true; // Cache handlers this.updateHandler = this.update.bind(this); this.updateAndScrollHandler = function(nbElements, transport, json) { this.update(transport, json); this.scroll(nbElements); }.bind(this); // Run first ajax request to fill the carousel this.runRequest.bind(this).defer({parameters: {from: 0, to: Math.ceil(this.nbVisible) - 1}, onSuccess: this.updateHandler}); }, // Group: Actions /* Method: runRequest Request the new elements details Parameters: options - (Hash) list of optional parameters Returns: this */ runRequest: function(options) { this.requestRunning = true; new Ajax.Request(this.options.url, Object.extend({method: "GET"}, options)); this.fire("request:started"); return this; }, /* Method: scroll Scrolls carousel from maximum deltaPixel Parameters: deltaPixel - a float Returns: this */ scroll: function($super, deltaPixel) { if (this.animating || this.requestRunning) return this; var nbElements = (-deltaPixel) / this.elementSize; // Check if there is not enough if (this.hasMore && nbElements > 0 && this.currentIndex() + this.nbVisible + nbElements - 1 > this.endIndex) { var from = this.endIndex + 1; var to = Math.ceil(from + this.nbVisible - 1); this.runRequest({parameters: {from: from, to: to}, onSuccess: this.updateAndScrollHandler.curry(deltaPixel).bind(this)}); return this; } else $super(deltaPixel); }, /* Method: update Update the carousel Parameters: transport - XMLHttpRequest object json - JSON object Returns: this */ update: function(transport, json) { this.requestRunning = false; this.fire("request:ended"); if (!json) json = transport.responseJSON; this.hasMore = json.more; this.endIndex = Math.max(this.endIndex, json.to); this.elements = this.container.insert({bottom: json.html}).childElements(); return this.updateButtons(); }, // Group: Size and Position /* Method: computeElementSize Return elements size in pixel Returns: an integer value */ computeElementSize: function() { return this.options.elementSize; }, /* Method: updateSize Should be called if carousel size has been changed (usually called with a liquid layout) Returns: this */ updateSize: function($super) { var nbVisible = this.nbVisible; $super(); // If we have enough space for at least a new element if (Math.floor(this.nbVisible) - Math.floor(nbVisible) >= 1 && this.hasMore) { if (this.currentIndex() + Math.floor(this.nbVisible) >= this.endIndex) { var nbNew = Math.floor(this.currentIndex() + Math.floor(this.nbVisible) - this.endIndex); this.runRequest({parameters: {from: this.endIndex + 1, to: this.endIndex + nbNew}, onSuccess: this.updateHandler}); } } return this; }, updateNextButton: function($super) { var lastPosition = this.currentLastPosition(); var size = this.currentSize(); var nextClassName = "next_button" + this.options.disabledButtonSuffix; if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) { this.nextButton.removeClassName(nextClassName); this.fire('nextButton:enabled'); } if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size && !this.hasMore) { this.nextButton.addClassName(nextClassName); this.fire('nextButton:disabled'); } } });
// https://github.com/babel/minify/issues/130 // https://github.com/babel/minify/pull/132 function outer() { const inner = d => d.x; return inner; }
export default function routes($stateProvider) { $stateProvider .state('main', { url: '/', template: require('./main.html'), controller: 'MainController', controllerAs: 'main' }); }