code
stringlengths
2
1.05M
/** * Created by c13lbm on 4/27/16. */ var StudentRecordVideo = React.createClass({ submitbutton: <div id="studentSubmit" className="button primary-button SCButtonDisabled" >Submit answer</div>, componentDidMount: function() { this.setEnabled(false); }, formDataBuilder: function (blob, fileName) { var fd = new FormData(); fd.append("studentVideo", blob); fd.append('submission', new Blob([JSON.stringify({ // Submission data studentID: this.props.studentID, assignmentID: this.props.assignmentID, courseID: this.props.courseID, studentPublishConsent: false })], { type: "application/json" })); return fd; }, playVideo: function (fName) { }, render: function () { var autoRecord = this.props.autoRecord; if(typeof autoRecord === "undefined") autoRecord = "true"; var submissionURL = "assignments/"+this.props.assignmentID+"/submissions/"+this.props.studentID; return ( <div> <div id="recorder-div"> <Recorder id="recorder" contID="studentPreview" playCallback={this.playVideo} postURL={submissionURL} formDataBuilder={this.formDataBuilder} stopButtonID="studentSubmit" autoRecord={autoRecord} siteView="submission" fileName="submission.webm" camOnLoad="true" maxRecordTime={this.props.maxRecordTime} minRecordTime={this.props.minRecordTime} endAssignment={this.props.endAssignment} setSubmitEnabled={this.setEnabled} /> </div> {this.submitbutton} <BlankBox postURL={submissionURL} assignmentID={this.props.assignmentID} studentID={this.props.studentID} courseID={this.props.courseID} endAssignment={this.props.endAssignment} /> </div> ); }, setEnabled: function(enabled) { if(enabled) { this.submitbutton = <div id="studentSubmit" className="button primary-button SCButton" >Submit answer</div> } else { this.submitbutton = <div id="studentSubmit" className="button primary-button SCButtonDisabled" >Submit answer</div> } }, componentDidMount: function() { var vid = document.getElementById("recorder-div"); vid.oncontextmenu = function (e) {e.preventDefault();}; } }); window.StudentRecordVideo = StudentRecordVideo;
/* * GET home page. */ exports.index = function(req, res){ res.render('index', { title: 'Merkle | 5th Finger PING PONG MATCH' }); };
function() { // Load required classes var FlatInformationGain = Java.type( 'external_measures.information_based.FlatInformationGain' ); var FlatEntropy2 = Java.type( 'external_measures.information_based.FlatEntropy2' ); var logBase = 2; // Create and return the result holder object var measureData = {}; measureData.measure = new FlatInformationGain( logBase, new FlatEntropy2() ); measureData.id = 'Flat Information Gain (2, FlatEntropy2)'; measureData.isApplicable = function ( hierarchy ) { // Applicable only to hierarchies with ground truth attribute return hierarchy.getNumberOfClasses() > 0; } measureData.callback = function ( hierarchy ) { return this.measure.getMeasure( hierarchy ); } return measureData; }
/* SQB ------------------------ (c) 2017-present Panates SQB may be freely distributed under the MIT license. For details and documentation: https://panates.github.io/sqb/ */ 'use strict'; /** * Module dependencies. * @private */ const CompOperator = require('./CompOperator'); /** * * @class */ class OpLt extends CompOperator { /** * @param {String|Serializable} expression * @param {*} value * @constructor * @public */ constructor(expression, value) { super(expression, value); this._operatorType = 'lt'; this._symbol = '<'; } } /** * Expose `OpLt`. */ module.exports = OpLt;
'use strict'; /* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/ext/searchbox', ['require', 'exports', 'module', 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/event', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function (require, exports, module) { var dom = require("../lib/dom"); var lang = require("../lib/lang"); var event = require("../lib/event"); var searchboxCss = "\ /* ------------------------------------------------------------------------------------------\ * Editor Search Form\ * --------------------------------------------------------------------------------------- */\ .ace_search {\ background-color: #ddd;\ border: 1px solid #cbcbcb;\ border-top: 0 none;\ max-width: 297px;\ overflow: hidden;\ margin: 0;\ padding: 4px;\ padding-right: 6px;\ padding-bottom: 0;\ position: absolute;\ top: 0px;\ z-index: 99;\ white-space: normal;\ }\ .ace_search.left {\ border-left: 0 none;\ border-radius: 0px 0px 5px 0px;\ left: 0;\ }\ .ace_search.right {\ border-radius: 0px 0px 0px 5px;\ border-right: 0 none;\ right: 0;\ }\ .ace_search_form, .ace_replace_form {\ border-radius: 3px;\ border: 1px solid #cbcbcb;\ float: left;\ margin-bottom: 4px;\ overflow: hidden;\ }\ .ace_search_form.ace_nomatch {\ outline: 1px solid red;\ }\ .ace_search_field {\ background-color: white;\ border-right: 1px solid #cbcbcb;\ border: 0 none;\ -webkit-box-sizing: border-box;\ -moz-box-sizing: border-box;\ box-sizing: border-box;\ display: block;\ float: left;\ height: 22px;\ outline: 0;\ padding: 0 7px;\ width: 214px;\ margin: 0;\ }\ .ace_searchbtn,\ .ace_replacebtn {\ background: #fff;\ border: 0 none;\ border-left: 1px solid #dcdcdc;\ cursor: pointer;\ display: block;\ float: left;\ height: 22px;\ margin: 0;\ padding: 0;\ position: relative;\ }\ .ace_searchbtn:last-child,\ .ace_replacebtn:last-child {\ border-top-right-radius: 3px;\ border-bottom-right-radius: 3px;\ }\ .ace_searchbtn:disabled {\ background: none;\ cursor: default;\ }\ .ace_searchbtn {\ background-position: 50% 50%;\ background-repeat: no-repeat;\ width: 27px;\ }\ .ace_searchbtn.prev {\ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \ }\ .ace_searchbtn.next {\ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \ }\ .ace_searchbtn_close {\ background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\ border-radius: 50%;\ border: 0 none;\ color: #656565;\ cursor: pointer;\ display: block;\ float: right;\ font-family: Arial;\ font-size: 16px;\ height: 14px;\ line-height: 16px;\ margin: 5px 1px 9px 5px;\ padding: 0;\ text-align: center;\ width: 14px;\ }\ .ace_searchbtn_close:hover {\ background-color: #656565;\ background-position: 50% 100%;\ color: white;\ }\ .ace_replacebtn.prev {\ width: 54px\ }\ .ace_replacebtn.next {\ width: 27px\ }\ .ace_button {\ margin-left: 2px;\ cursor: pointer;\ -webkit-user-select: none;\ -moz-user-select: none;\ -o-user-select: none;\ -ms-user-select: none;\ user-select: none;\ overflow: hidden;\ opacity: 0.7;\ border: 1px solid rgba(100,100,100,0.23);\ padding: 1px;\ -moz-box-sizing: border-box;\ box-sizing: border-box;\ color: black;\ }\ .ace_button:hover {\ background-color: #eee;\ opacity:1;\ }\ .ace_button:active {\ background-color: #ddd;\ }\ .ace_button.checked {\ border-color: #3399ff;\ opacity:1;\ }\ .ace_search_options{\ margin-bottom: 3px;\ text-align: right;\ -webkit-user-select: none;\ -moz-user-select: none;\ -o-user-select: none;\ -ms-user-select: none;\ user-select: none;\ }"; var HashHandler = require("../keyboard/hash_handler").HashHandler; var keyUtil = require("../lib/keys"); dom.importCssString(searchboxCss, "ace_searchbox"); var html = '<div class="ace_search right">\ <button type="button" action="hide" class="ace_searchbtn_close"></button>\ <div class="ace_search_form">\ <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\ <button type="button" action="findNext" class="ace_searchbtn next"></button>\ <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\ </div>\ <div class="ace_replace_form">\ <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\ <button type="button" action="replaceAndFindNext" class="ace_replacebtn">Replace</button>\ <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\ </div>\ <div class="ace_search_options">\ <span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\ <span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\ <span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\ </div>\ </div>'.replace(/>\s+/g, ">"); var SearchBox = function SearchBox(editor, range, showReplaceForm) { var div = dom.createElement("div"); div.innerHTML = html; this.element = div.firstChild; this.$init(); this.setEditor(editor); }; (function () { this.setEditor = function (editor) { editor.searchBox = this; editor.container.appendChild(this.element); this.editor = editor; }; this.$initElements = function (sb) { this.searchBox = sb.querySelector(".ace_search_form"); this.replaceBox = sb.querySelector(".ace_replace_form"); this.searchOptions = sb.querySelector(".ace_search_options"); this.regExpOption = sb.querySelector("[action=toggleRegexpMode]"); this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]"); this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]"); this.searchInput = this.searchBox.querySelector(".ace_search_field"); this.replaceInput = this.replaceBox.querySelector(".ace_search_field"); }; this.$init = function () { var sb = this.element; this.$initElements(sb); var _this = this; event.addListener(sb, "mousedown", function (e) { setTimeout(function () { _this.activeInput.focus(); }, 0); event.stopPropagation(e); }); event.addListener(sb, "click", function (e) { var t = e.target || e.srcElement; var action = t.getAttribute("action"); if (action && _this[action]) _this[action]();else if (_this.$searchBarKb.commands[action]) _this.$searchBarKb.commands[action].exec(_this); event.stopPropagation(e); }); event.addCommandKeyListener(sb, function (e, hashId, keyCode) { var keyString = keyUtil.keyCodeToString(keyCode); var command = _this.$searchBarKb.findKeyCommand(hashId, keyString); if (command && command.exec) { command.exec(_this); event.stopEvent(e); } }); this.$onChange = lang.delayedCall(function () { _this.find(false, false); }); event.addListener(this.searchInput, "input", function () { _this.$onChange.schedule(20); }); event.addListener(this.searchInput, "focus", function () { _this.activeInput = _this.searchInput; _this.searchInput.value && _this.highlight(); }); event.addListener(this.replaceInput, "focus", function () { _this.activeInput = _this.replaceInput; _this.searchInput.value && _this.highlight(); }); }; this.$closeSearchBarKb = new HashHandler([{ bindKey: "Esc", name: "closeSearchBar", exec: function exec(editor) { editor.searchBox.hide(); } }]); this.$searchBarKb = new HashHandler(); this.$searchBarKb.bindKeys({ "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function CtrlFCommandFCtrlHCommandOptionF(sb) { var isReplace = sb.isReplace = !sb.isReplace; sb.replaceBox.style.display = isReplace ? "" : "none"; sb[isReplace ? "replaceInput" : "searchInput"].focus(); }, "Ctrl-G|Command-G": function CtrlGCommandG(sb) { sb.findNext(); }, "Ctrl-Shift-G|Command-Shift-G": function CtrlShiftGCommandShiftG(sb) { sb.findPrev(); }, "esc": function esc(sb) { setTimeout(function () { sb.hide(); }); }, "Return": function Return(sb) { if (sb.activeInput == sb.replaceInput) sb.replace(); sb.findNext(); }, "Shift-Return": function ShiftReturn(sb) { if (sb.activeInput == sb.replaceInput) sb.replace(); sb.findPrev(); }, "Tab": function Tab(sb) { (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus(); } }); this.$searchBarKb.addCommands([{ name: "toggleRegexpMode", bindKey: { win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/" }, exec: function exec(sb) { sb.regExpOption.checked = !sb.regExpOption.checked; sb.$syncOptions(); } }, { name: "toggleCaseSensitive", bindKey: { win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I" }, exec: function exec(sb) { sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked; sb.$syncOptions(); } }, { name: "toggleWholeWords", bindKey: { win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W" }, exec: function exec(sb) { sb.wholeWordOption.checked = !sb.wholeWordOption.checked; sb.$syncOptions(); } }]); this.$syncOptions = function () { dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked); dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked); dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked); this.find(false, false); }; this.highlight = function (re) { this.editor.session.highlight(re || this.editor.$search.$options.re); this.editor.renderer.updateBackMarkers(); }; this.find = function (skipCurrent, backwards) { var range = this.editor.find(this.searchInput.value, { skipCurrent: skipCurrent, backwards: backwards, wrap: true, regExp: this.regExpOption.checked, caseSensitive: this.caseSensitiveOption.checked, wholeWord: this.wholeWordOption.checked }); var noMatch = !range && this.searchInput.value; dom.setCssClass(this.searchBox, "ace_nomatch", noMatch); this.editor._emit("findSearchBox", { match: !noMatch }); this.highlight(); }; this.findNext = function () { this.find(true, false); }; this.findPrev = function () { this.find(true, true); }; this.replace = function () { if (!this.editor.getReadOnly()) this.editor.replace(this.replaceInput.value); }; this.replaceAndFindNext = function () { if (!this.editor.getReadOnly()) { this.editor.replace(this.replaceInput.value); this.findNext(); } }; this.replaceAll = function () { if (!this.editor.getReadOnly()) this.editor.replaceAll(this.replaceInput.value); }; this.hide = function () { this.element.style.display = "none"; this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb); this.editor.focus(); }; this.show = function (value, isReplace) { this.element.style.display = ""; this.replaceBox.style.display = isReplace ? "" : "none"; this.isReplace = isReplace; if (value) this.searchInput.value = value; this.searchInput.focus(); this.searchInput.select(); this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb); }; }).call(SearchBox.prototype); exports.SearchBox = SearchBox; exports.Search = function (editor, isReplace) { var sb = editor.searchBox || new SearchBox(editor); sb.show(editor.session.getTextRange(), isReplace); }; }); ; (function () { window.require(["ace/ext/searchbox"], function () {}); })();
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, View, Text, Image, TouchableHighlight, PixelRatio } from 'react-native'; export default class MeItemCell extends Component { static defaultProps = { name: '我的首页Cell' } constructor(props) { super(props); this.state = { obj:this.props.obj, }; } render(){ return (<TouchableHighlight onPress={this.props.onSelect} underlayColor='#ffffff'> <View style={[{width:global.CONSTANST.screen_width,flexDirection:'row',height:44,marginBottom:(this.props.isBottom ? 10 : 0)},(this.props.rowID == 0) ? styles.topLine : null]}> <View style={[styles.leftContent,(!this.props.isBottom) ? null : styles.line]}> <Image style={styles.icon} source={ (this.props.sectionID == 'items') ? this.state.obj.specialIcon : {uri:this.state.obj.specialIcon}}/> </View> <View style={[styles.centerContent,styles.line]}> <Text>{this.state.obj.specialName}</Text> </View> <View style={styles.rightContent}> <Image style={styles.arrow} source={require('../../res/images/[email protected]')}/> </View> </View> </TouchableHighlight>); } } const styles = StyleSheet.create({ leftContent:{ flex:1, flexDirection:'row', justifyContent:'flex-start', alignItems:'center', backgroundColor:'#ffffff', }, icon:{ width:23, height:23, backgroundColor:'#ffffff', margin:15, marginRight:10, borderRadius:11.5, }, centerContent:{ flex:7, flexDirection:'row', padding : 5, backgroundColor : '#ffffff', alignItems:'center', justifyContent:'flex-start' }, rightContent:{ flexDirection:'row', backgroundColor : '#ffffff', flex:1, alignItems:'center', justifyContent:'center', borderBottomWidth : 1/PixelRatio.get(), borderBottomColor : '#cccccc', borderStyle : 'solid', }, arrow:{ width:8, height:13, backgroundColor:'#ffffff', }, itemStyle:{ flex:1, }, line:{ borderBottomWidth : 1/PixelRatio.get(), borderBottomColor : '#cccccc', borderStyle : 'solid', }, topLine:{ borderTopWidth : 1/PixelRatio.get(), borderTopColor : '#cccccc', borderStyle : 'solid', }, noLine:{ borderTopWidth : 0/PixelRatio.get(), borderTopColor : '#ffffff', } });
module.exports = Way; var util = require('util'); var _ = require('underscore'); var BoundingBox = require('../boundingbox'); var Entity = require('./entity'); function Way() { Entity.call(this); this.nodeReferences = []; this._nodes = []; } util.inherits(Way, Entity); Way.prototype.getId = function () { return 'w' + this.id; }; Way.prototype.getDistance = function (latitude, longitude) { if (this._nodes.length === 0) return; var nearestNode = _.min(this._nodes, function (node) { var deltaLatitude = latitude - node.latitude; var deltaLongitude = longitude - node.longitude; return (deltaLatitude * deltaLatitude) + (deltaLongitude * deltaLongitude); }); return nearestNode.getDistance(latitude, longitude); }; Way.prototype.getCenter = function () { return this.getBoundingBox().getCenter(); }; Way.prototype.getBoundingBox = function () { return new BoundingBox( _.min(this._nodes, function (n) { return n.longitude; }).longitude, _.min(this._nodes, function (n) { return n.latitude; }).latitude, _.max(this._nodes, function (n) { return n.longitude; }).longitude, _.max(this._nodes, function (n) { return n.latitude; }).latitude); };
#!/usr/bin/env node /* eslint no-console: 0 */ 'use strict'; const program = require('commander'); const fnlint = require('./module'); const assert = require('assert'); const path = require('path'); require('colors'); program .version(require('../package.json').version) .option('-c --config [configPath]', 'Path to a config file') .parse(process.argv); if (!program.config) { console.log(' --config is required.'.red); return program.outputHelp(); } let config; try { config = require(path.resolve(program.config)); } catch (e) { console.error(e.message.red); process.exit(1); } fnlint(config, function(err, results) { assert.ifError(err); if (!results.ok) { process.exit(1); } });
angular.module('Directives.MyModule') .directive('gameWon', function () { return { restrict: 'E', templateUrl: 'partials/game-won.html' }; });
(function () { 'use strict'; let message = 'Your browser supports service workers!'; if ('serviceWorker' in navigator) { console.info(message); return; } message = 'Sorry bud, your browser does not support service workers. Try Chrome?'; alert(message); console.warn(message); }());
'use strict'; var filters = require('./../../Utils/Filters'); function Datepicker (baseElement){ var base = baseElement; var datepickerInput = base.$('[date-time]'); var datepickerWrapper = base.$('[date-picker-wrapper]'); /** * @description clicks the datepicker input - should open the datepicker and enable free text typing */ function openDatepicker(){ datepickerInput.click(); } /** * @description types the inputted timestamp into the datepicker Input */ function typeTimestamp(timestamp){ if(!timestamp || timestamp === ''){ return datepickerInput.clear(); } else{ return datepickerInput.sendKeys(timestamp); } } /** * @description enables you to choose a date within the last three months * All options are picked on the current month unless, nextMonth/previousMonth is true and than it applies to them * * @param dayNumber - the day number to pick. either format, 9 or 09 is accepted * @param hour - the hour to pick. either format, 9, 09 or 19 is accepted * @param minutes - the number of minutes to pick. either format, 9 or 09 is accepted. It should be divided by 5(as any of the options * or it will choose default of 00 minutes. * @param nextMonth - should we pick all options on the next month. * @param previousMonth - should we pick all options on the previous month. */ function chooseTimestamp(dayNumber, hour, minutes, nextMonth, previousMonth){ //opening the datepicker datepickerInput.click(); //moving to previous month view if(previousMonth){ datepickerWrapper.$('[ng-click="prev()"]').click(); } //moving to next month view if(nextMonth){ datepickerWrapper.$('[ng-click="next()"]').click(); } //choosing the day dayNumber = ''+dayNumber; if(dayNumber.length === 1){ dayNumber = '0'+dayNumber; } var dayElement = filters.filterByText(datepickerWrapper.$$('table tbody tr td span'), dayNumber); //when previous month last week has the date you chose dayElement.count().then(function(count){ if(count > 1){ if(dayNumber >= 22) { dayElement = dayElement.get(1); } else{ dayElement = dayElement.get(0); } } dayElement.click(); }); //choosing the hour hour = ''+hour; if(hour.length === 1){ hour = '0'+hour; } hour = hour+':00'; var hourElement = filters.filterByText(datepickerWrapper.$$('table tbody tr td span'), hour); hourElement.click(); //choosing the minutes minutes = ''+minutes; if(minutes.length === 1){ minutes = '0'+minutes; } if(Number(minutes) % 5 === 0){ minutes = hour.replace('00', minutes); }else{ minutes = hour; } var minutesElement = filters.filterByText(datepickerWrapper.$$('table tbody tr td span'), minutes); return minutesElement.click(); } /** * @description returns the current value of the datepicker input */ function getDatepickerValue(){ return datepickerInput.getAttribute('value'); } /** * @description returns is the icon is empty or not */ function isDatepickerIconFull(){ return base.$('i').getAttribute('class').then(function (classes) { return classes.indexOf('fa-calendar-o') === -1; }); } this.openDatepicker = openDatepicker; this.getDatepickerValue = getDatepickerValue; this.typeTimestamp = typeTimestamp; this.chooseTimestamp = chooseTimestamp; this.isDatepickerIconFull = isDatepickerIconFull; } module.exports = Datepicker;
/* eslint-disable import/no-extraneous-dependencies, react/jsx-filename-extension */ /* eslint-env jest */ import React from 'react' import { mount } from 'enzyme' import snap from 'snap' import Menu from './menu' import { mapDispatchToProps } from './menu.container' const snapshot = props => snap(Menu)({ onHeaderClick: () => {}, onFooterClick: () => {}, ...props }) describe('common/Menu', () => { it('should have a default behaviour', snapshot({})) it('should add custom className', snapshot({ className: 'custom' })) it('should add custom style', snapshot({ style: { backgroundColor: 'red' } })) it('should add a header', snapshot({ header: <div>header</div> })) it('should add a footer', snapshot({ footer: <div>footer</div> })) it('should add items', snapshot({ children: [<div key={1}>1</div>, <div key={2}>2</div>] })) describe('callbacks', () => { const clickTest = (props, selector) => { const wrapper = mount( <Menu {...props} />, ) wrapper.find(selector).first().simulate('click') } it('should trigger a header click event', () => { const onFooterClick = jest.fn() const onHeaderClick = jest.fn() clickTest({ onFooterClick, onHeaderClick, header: <div>header</div> }, '.header') expect(onFooterClick.mock.calls.length).toBe(0) expect(onHeaderClick.mock.calls.length).toBe(1) }) it('should trigger a footer click event', () => { const onFooterClick = jest.fn() const onHeaderClick = jest.fn() clickTest({ onFooterClick, onHeaderClick, footer: <div>footer</div> }, '.footer') expect(onFooterClick.mock.calls.length).toBe(1) expect(onHeaderClick.mock.calls.length).toBe(0) }) }) describe('container', () => { it('should trigger a header click', () => { const dispatch = jest.fn() const result = mapDispatchToProps(dispatch) result.onHeaderClick() expect(dispatch.mock.calls.length).toBe(1) expect(dispatch.mock.calls[0]).toEqual([{ type: 'MENU_HEADER_CLICKED' }]) }) it('should trigger a footer click', () => { const dispatch = jest.fn() const result = mapDispatchToProps(dispatch) result.onFooterClick() expect(dispatch.mock.calls.length).toBe(1) expect(dispatch.mock.calls[0]).toEqual([{ type: 'MENU_FOOTER_CLICKED' }]) }) }) }) /* eslint-enable import/no-extraneous-dependencies, react/jsx-filename-extension */
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame, assertTrue } = Assert; // 22.1.3.1 Array.prototype.concat function assertSameArray(array1, array2) { assertSame(array1.length, array2.length); for (let i = 0, len = array1.length; i < len; ++i) { assertSame(array1[i], array2[i]); } } // concat() with same realm constructor { class MyArray extends Array { } const obj1 = {}, obj2 = {}; let array1 = new MyArray(obj1, obj2); let array2 = array1.concat(); // array1.constructor is from the same realm, concat() creates Array sub-class instances assertTrue(Array.isArray(array2)); assertSame(MyArray, array2.constructor); assertSame(MyArray.prototype, Object.getPrototypeOf(array2)); assertSameArray(array1, array2); } // concat() with different realm constructor (1) { const ForeignMyArray = new Realm().eval(` class MyArray extends Array { } MyArray; `); const obj1 = {}, obj2 = {}; let array1 = new ForeignMyArray(obj1, obj2); let array2 = Array.prototype.concat.call(array1); // array1.constructor is from a different realm, concat() creates default Array instances assertTrue(Array.isArray(array2)); assertSame(Array, array2.constructor); assertSame(Array.prototype, Object.getPrototypeOf(array2)); assertSameArray(array1, array2); } // concat() with different realm constructor (2) { class MyArray extends Array { } const ForeignArray = new Realm().eval("Array"); const obj1 = {}, obj2 = {}; let array1 = new MyArray(obj1, obj2); let array2 = ForeignArray.prototype.concat.call(array1); // array1.constructor is from a different realm, concat() creates default Array instances assertTrue(Array.isArray(array2)); assertSame(ForeignArray, array2.constructor); assertSame(ForeignArray.prototype, Object.getPrototypeOf(array2)); assertSameArray(array1, array2); } // concat() with proxied constructor { class MyArray extends Array { } const obj1 = {}, obj2 = {}; let array1 = new MyArray(obj1, obj2); array1.constructor = new Proxy(array1.constructor, {}); let array2 = array1.concat(); // Proxy (function) objects do not have a [[Realm]] internal slot, concat() creates default Array instances assertTrue(Array.isArray(array2)); assertSame(Array, array2.constructor); assertSame(Array.prototype, Object.getPrototypeOf(array2)); assertSameArray(array1, array2); } // concat() with bound constructor { class MyArray extends Array { } const obj1 = {}, obj2 = {}; let array1 = new MyArray(obj1, obj2); array1.constructor = array1.constructor.bind(null); let array2 = array1.concat(); // Bound function objects do not have a [[Realm]] internal slot, concat() creates default Array instances assertTrue(Array.isArray(array2)); assertSame(Array, array2.constructor); assertSame(Array.prototype, Object.getPrototypeOf(array2)); assertSameArray(array1, array2); }
'use strict'; describe('Moments E2E Tests:', function () { describe('Test Moments page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3001/moments'); expect(element.all(by.repeater('moment in moments')).count()).toEqual(0); }); }); });
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('scripts', function() { return browserify('./index') .bundle() .pipe(source('backfire.js')) .pipe(gulp.dest('.')); }); gulp.task('uglify', function() { return gulp.src('backfire.js') .pipe(rename('backfire.min.js')) .pipe(uglify({ outSourceMap: true, preserveComments: 'some' })) .pipe(gulp.dest('.')); }); gulp.task('default', ['scripts', 'uglify']);
angular.module('casualApp') .controller('AppCtrl', function($scope, $ionicModal, $timeout, contactService, userData) { //if user loged in => exit //otherwise user needs to log in if (userData.model.id !== undefined) return; //get position contactService.getUserPosition(function (position) { //DONE! }); // Form data for the login modal $scope.loginData = {}; // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; $scope.modal.show(); }); // Triggered in the login modal to close it $scope.closeLogin = function() { // $scope.modal.hide(); }; // Perform the login action when the user submits the login form $scope.doLogin = function() { contactService.getContactByAlias($scope.loginData.username).$promise.then(function (data) { console.log(data); userData.model = data; $scope.modal.hide(); }, function (reason) { //console.log(reason); }); }; }) ;
// Sorts an array // sortFunction is the function to determine if an element is <, ==, or > than another var Sort = function(inputArray) { // Utility method to sort by field // breakTie is a function that is called in case these fields are equal to break the tie var sortByField = function (field, ascending, breakTie) { return function (left, right) { if (left[field] == right[field]) { if (breakTie) { return breakTie(left, right); } return 0; } if (ascending) { return left[field] < right[field] ? -1 : 1; } else { return left[field] < right[field] ? 1 : -1; } } } // Keep track of the requested sorts var sortArray = ko.observableArray(); // Change the primary sort, pushing the existing primary to secondary, etc. // The way ko calls this, this actually needs to return a function that does the work var addSort = function (field, ascending) { return function () { sortArray.remove(function (item) { return item.field == field; }); sortArray.push({ "field": field, "ascending": ascending }); } } // Anytime the sorts change, recompute a sort function var sortFunc = ko.computed(function () { if (sortArray().length == 0) { return null; } var ret = null; // Build up a chained list of closures, with the most important sort as the outer closure ko.utils.arrayForEach(sortArray(), function (item) { // Pass in the previous closure as the breakTie parameter, this leaves the most important sort as the outer function ret = sortByField(item.field, item.ascending, ret); }); return ret; }, this); var outputArray = ko.computed(function () { if (sortFunc() == null) { return inputArray(); } return inputArray().sort(sortFunc()); }, this); // Public interface var self = this; self.addSort = addSort; self.outputArray = outputArray; };
import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; export const DefaultComponent = ({ componentClass: ComponentClass, ...restProps, }) => <ComponentClass {...restProps} />; DefaultComponent.propTypes = { componentClass: elementType, }; DefaultComponent.defaultProps = { componentClass: 'div', }; export default DefaultComponent;
/* =================================================== * bootstrap-transition.js v2.0.4 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ ! function($) { $(function() { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $.support.transition = (function() { var transitionEnd = (function() { var el = document.createElement('bootstrap'), transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' }, name for (name in transEndEventNames) { if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); /* ============================================================ * bootstrap-dropdown.js v2.0.4 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ ! function($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle="dropdown"]', Dropdown = function(element) { var $el = $(element) .on('click.dropdown.data-api', this.toggle) $('html') .on('click.dropdown.data-api', function() { $el.parent() .removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function(e) { var $this = $(this), $parent, selector, isActive if ($this.is('.disabled, :disabled')) return selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) $parent.length || ($parent = $this.parent()) isActive = $parent.hasClass('open') clearMenus() if (!isActive) $parent.toggleClass('open') return false } } function clearMenus() { $(toggle) .parent() .removeClass('open') } /* DROPDOWN PLUGIN DEFINITION * ========================== */ $.fn.dropdown = function(option) { return this.each(function() { var $this = $(this), data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(function() { $('html') .on('click.dropdown.data-api', clearMenus) $('body') .on('click.dropdown', '.dropdown form', function(e) { e.stopPropagation() }) .on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle) }) }(window.jQuery); /* ============================================================= * bootstrap-collapse.js v2.0.4 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ ! function($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function(element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function() { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function() { var dimension, scroll, actives, hasData if (this.transitioning) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') this.$element[dimension](this.$element[0][scroll]) } , hide: function() { var dimension if (this.transitioning) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function(size) { var dimension = this.dimension() this.$element .removeClass('collapse')[dimension](size || 'auto')[0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function(method, startEvent, completeEvent) { var that = this, complete = function() { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function() { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSIBLE PLUGIN DEFINITION * ============================== */ $.fn.collapse = function(option) { return this.each(function() { var $this = $(this), data = $this.data('collapse'), options = typeof option == 'object' && option if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSIBLE DATA-API * ==================== */ $(function() { $('body') .on('click.collapse.data-api', '[data-toggle=collapse]', function(e) { var $this = $(this), href, target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target) .data('collapse') ? 'toggle' : $this.data() $(target) .collapse(option) }) }) }(window.jQuery);
// Generated by CoffeeScript 1.8.0 (function() { var CollectionsSchema, mongoose; mongoose = require('./mongoose'); CollectionsSchema = mongoose.Schema({ username: String, created: Number, type: Number, url: String }); module.exports = mongoose.model('Collections', CollectionsSchema); }).call(this); //# sourceMappingURL=collections.js.map
pinion.EventDispatcher = (function() { var constr; constr = function() {}; constr.prototype = { /** * @param string event * @param object data * @param function|string callback * @param context object * * @example on(event, callback) * @example on(event, callback, context) * @example on(event, data, callback) * @example on(event, data, callback, context) */ on: function(event, data, callback, context) { if(this.handlers[event] === undefined) { this.handlers[event] = []; } if(data instanceof Function || typeof data === "string") { context = callback || this; callback = data; data = {}; } this.handlers[event].push({ data: data, callback: callback, context: context || this }); return this; }, one: function(event, data, callback, context) { if(this.handlers[event] === undefined) { this.handlers[event] = []; } if(data instanceof Function || typeof data === "string") { context = callback || this; callback = data; data = {}; } this.handlers[event].push({ data: data, callback: callback, context: context || this, one: true }); return this; }, /** * @param string event * @param function|string callback * @param object context * * @example off() * @example off(event) * @example off(event, callback) * @example off(event, callback, context) * @example off(event, context) */ off: function(event, callback, context) { var i, length, handler; if(event === undefined) { // off() this.handlers = {}; } else if(this.handlers[event] !== undefined) { if(callback === undefined) { // off(event) delete this.handlers[event]; } else if(context === undefined) { if(typeof callback === "string") { // off(event, callback) for(i = this.handlers[event].length; i--; ) { handler = this.handlers[event][i]; if(handler.callback === callback) { this.handlers[event].splice(i, 1); } } } else { // off(event, context) context = callback; for(i = this.handlers[event].length; i--; ) { handler = this.handlers[event][i]; if(handler.context === context) { this.handlers[event].splice(i, 1); } } } } else { // off(event, callback, context) for(i = this.handlers[event].length; i--; ) { handler = this.handlers[event][i]; if(handler.callback === callback && handler.context === context) { this.handlers[event].splice(i, 1); } } } } return this; }, hasOn: function(event, context) { if(context === undefined) { context = this; } if(this.handlers[event] === undefined) { return false; } for(var i = this.handlers[event].length; i--; ) { var handler = this.handlers[event][i]; if(context === handler.context) { return true; } } }, /** * @param string event * @param object info * * @example fire(event) * @example fire(event, info) */ fire: function(event, info) { var toReturn = true; if(this.handlers[event] !== undefined) { for(var i = this.handlers[event].length; i--; ) { var handler = this.handlers[event][i], context = handler.context, data = handler.data, one = handler.one; var completeInfo = jQuery.extend({sender: this}, info); if(handler.callback instanceof Function) { if(handler.callback.call(context, completeInfo, data) === false) { toReturn = false; } } else if(typeof handler.callback === "string") { if(context[handler.callback](completeInfo, data) === false) { toReturn = false; } } if(one) { delete this.handlers[event].splice(i, 1); } } } return toReturn; }, fireRecursive: function(event, info) { this.fire(event, info); for(var i = this.children.length; i--; ) { var child = this.children[i]; child.fireRecursive(event, info); } } }; return constr; }()); pinion.handlers = {}; jQuery.extend(pinion, pinion.EventDispatcher.prototype);
var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); rl.on('line', function (cmd) { console.log('You just typed: '+cmd); });
{ expect(validateDOMNesting.isTagValidInContext(tag, null)).toBe(true); }
import { combineReducers } from 'redux'; function page(state = { time: parseInt(Math.random() * 10, 10) + 1, accordion: false, activePanelKey: [null], text: 'A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world.', sortBy: 'title' }, action) { switch(action.type) { case 'CHANGE_ACTIVE_PANEL': if (action.activePanelKey) { return Object.assign({}, state, { activePanelKey: action.activePanelKey }); } else { return state; } case 'TOGGLE_ACCORDION': return Object.assign({}, state, { accordion: !state.accordion }); case 'RE_RENDER': return Object.assign({}, state, { time: parseInt(Math.random() * 10, 10) + 1 }); case 'SORT_BY': if (action.sortBy === 'title') { return Object.assign({}, state, { sortBy: 'title' }); } else if (action.sortBy === 'author') { return Object.assign({}, state, { sortBy: 'author' }); } else if (action.sortBy === 'date') { return Object.assign({}, state, { sortBy: 'date' }); } else { return state; } default: return state; } } const contentPage = combineReducers({ page }); export default contentPage;
name = "denseSilverPlate"; addToCreative[0] = true; creativeTab = "materials"; maxStack = 64; textureFile[0] = "denseSilverPlate.png";
function redirectToCourses({services}) { services.router.redirectToSignal('courses.opened'); } export default redirectToCourses;
/*! * Stylus - Evaluator * Copyright(c) 2010 LearnBoost <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var Visitor = require('./') , nodes = require('../nodes') , Stack = require('../stack') , Frame = require('../stack/frame') , Scope = require('../stack/scope') , utils = require('../utils') , bifs = require('../functions') , dirname = require('path').dirname , colors = require('../colors') , fs = require('fs'); /** * Initialize a new `Evaluator` with the given `root` Node * and the following `options`. * * Options: * * - `compress` Compress the css output, defaults to false * - `warn` Warn the user of duplicate function definitions etc * * @param {Node} root * @api private */ var Evaluator = module.exports = function Evaluator(root, options) { options = options || {}; Visitor.call(this, root); this.stack = new Stack; this.imports = options.imports || []; this.functions = options.functions || {}; this.globals = options.globals || {}; this.paths = options.paths || []; this.filename = options.filename; this.paths.push(dirname(options.filename || '.')); this.stack.push(this.global = new Frame(root)); this.warnings = options.warn; this.options = options; this.calling = []; // TODO: remove, use stack this.importStack = []; }; /** * Inherit from `Visitor.prototype`. */ Evaluator.prototype.__proto__ = Visitor.prototype; /** * Proxy visit to expose node line numbers. * * @param {Node} node * @return {Node} * @api private */ var visit = Visitor.prototype.visit; Evaluator.prototype.visit = function(node){ try { return visit.call(this, node); } catch (err) { if (err.filename) throw err; err.lineno = node.lineno; err.filename = node.filename; err.stylusStack = this.stack.toString(); try { err.input = fs.readFileSync(err.filename, 'utf8'); } catch (err) { // ignore } throw err; } }; /** * Perform evaluation setup: * * - populate global scope * - iterate imports * * @api private */ Evaluator.prototype.setup = function(){ this.populateGlobalScope(); this.imports.forEach(function(file){ var expr = new nodes.Expression; expr.push(new nodes.String(file)); this.visit(new nodes.Import(expr)); }, this); }; /** * Populate the global scope with: * * - css colors * - user-defined globals * * @api private */ Evaluator.prototype.populateGlobalScope = function(){ var scope = this.global.scope; Object.keys(colors).forEach(function(name){ var rgb = colors[name] , rgba = new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1) , node = new nodes.Ident(name, rgba); scope.add(node); }); var globals = this.globals; Object.keys(globals).forEach(function(name){ scope.add(new nodes.Ident(name, globals[name])); }); }; /** * Evaluate the tree. * * @return {Node} * @api private */ Evaluator.prototype.evaluate = function(){ this.setup(); return this.visit(this.root); }; /** * Visit Group. */ Evaluator.prototype.visitGroup = function(group){ group.nodes = group.nodes.map(function(selector){ selector.val = this.interpolate(selector); return selector; }, this); group.block = this.visit(group.block); return group; }; /** * Visit Charset. */ Evaluator.prototype.visitCharset = function(charset){ return charset; }; /** * Visit Return. */ Evaluator.prototype.visitReturn = function(ret){ ret.expr = this.visit(ret.expr); throw ret; }; /** * Visit Media. */ Evaluator.prototype.visitMedia = function(media){ media.block = this.visit(media.block); return media; }; /** * Visit Keyframes. */ Evaluator.prototype.visitKeyframes = function(keyframes){ keyframes.name = this.visit(keyframes.name).first.name; return keyframes; }; /** * Visit Function. */ Evaluator.prototype.visitFunction = function(fn){ // check local var local = this.stack.currentFrame.scope.lookup(fn.name); if (local) this.warn('local ' + local.nodeName + ' "' + fn.name + '" previously defined in this scope'); // user-defined var user = this.functions[fn.name]; if (user) this.warn('user-defined function "' + fn.name + '" is already defined'); // BIF var bif = bifs[fn.name]; if (bif) this.warn('built-in function "' + fn.name + '" is already defined'); return fn; }; /** * Visit Each. */ Evaluator.prototype.visitEach = function(each){ var expr = utils.unwrap(this.visit(utils.unwrap(each.expr))) , len = expr.nodes.length , val = new nodes.Ident(each.val) , key = new nodes.Ident(each.key || '__index__') , scope = this.currentScope , block = this.currentBlock , vals = [] , body; each.block.scope = false; for (var i = 0; i < len; ++i) { val.val = expr.nodes[i]; key.val = new nodes.Unit(i); scope.add(val); scope.add(key); body = this.visit(each.block.clone()); vals = vals.concat(body.nodes); } this.mixin(vals, block); return vals[vals.length - 1] || nodes.null; }; /** * Visit Call. */ Evaluator.prototype.visitCall = function(call){ var fn = this.lookup(call.name) , ret; // Variable function if (fn && 'expression' == fn.nodeName) { fn = fn.nodes[0]; } // Not a function? try user-defined or built-ins if (fn && 'function' != fn.nodeName) { fn = this.lookupFunction(call.name); } // Undefined function, render literal css if (!fn || fn.nodeName != 'function') return this.literalCall(call); this.calling.push(call.name); // Massive stack if (this.calling.length > 200) { throw new RangeError('Maximum call stack size exceeded'); } // First node in expression if ('expression' == fn.nodeName) fn = fn.first; // Evaluate arguments var _ = this.return; this.return = true; var args = this.visit(call.args); for (var key in call.args.map) { call.args.map[key] = this.visit(call.args.map[key]); } this.return = _; // Built-in if (fn.fn) { ret = this.invokeBuiltin(fn.fn, args); // User-defined } else if ('function' == fn.nodeName) { ret = this.invokeFunction(fn, args); } this.calling.pop(); return ret; }; /** * Visit Ident. */ Evaluator.prototype.visitIdent = function(ident){ // Lookup if (ident.val.isNull) { var val = this.lookup(ident.name); return val ? this.visit(val) : ident; // Assign } else { var _ = this.return; this.return = true; ident.val = this.visit(ident.val); this.return = _; this.currentScope.add(ident); return ident.val; } }; /** * Visit BinOp. */ Evaluator.prototype.visitBinOp = function(binop){ // Special-case "is defined" pseudo binop if ('is defined' == binop.op) return this.isDefined(binop.left); var _ = this.return; this.return = true; // Visit operands var op = binop.op , left = this.visit(binop.left) , right = this.visit(binop.right); this.return = _; // HACK: ternary var val = binop.val ? this.visit(binop.val) : null; // Operate try { return this.visit(left.operate(op, right, val)); } catch (err) { // disregard coercion issues in equality // checks, and simply return false if ('CoercionError' == err.name) { switch (op) { case '==': return nodes.false; case '!=': return nodes.true; } } throw err; } }; /** * Visit UnaryOp. */ Evaluator.prototype.visitUnaryOp = function(unary){ var op = unary.op , node = this.visit(unary.expr).first.clone(); if ('!' != op) utils.assertType(node, 'unit'); switch (op) { case '-': node.val = -node.val; break; case '+': node.val = +node.val; break; case '~': node.val = ~node.val; break; case '!': return node.toBoolean().negate(); } return node; }; /** * Visit TernaryOp. */ Evaluator.prototype.visitTernary = function(ternary){ var ok = this.visit(ternary.cond).toBoolean(); return ok.isTrue ? this.visit(ternary.trueExpr) : this.visit(ternary.falseExpr); }; /** * Visit Expression. */ Evaluator.prototype.visitExpression = function(expr){ for (var i = 0, len = expr.nodes.length; i < len; ++i) { expr.nodes[i] = this.visit(expr.nodes[i]); } return expr; }; /** * Visit Arguments. */ Evaluator.prototype.visitArguments = Evaluator.prototype.visitExpression; /** * Visit Property. */ Evaluator.prototype.visitProperty = function(prop){ var name = this.interpolate(prop) , fn = this.lookup(name) , call = fn && 'function' == fn.nodeName , literal = ~this.calling.indexOf(name); // Function of the same name if (call && !literal && !prop.literal) { this.calling.push(name); var args = nodes.Arguments.fromExpression(prop.expr); var ret = this.visit(new nodes.Call(name, args)); this.calling.pop(); return ret; // Regular property } else { var _ = this.return; this.return = true; prop.name = name; prop.literal = true; this.property = prop; prop.expr = this.visit(prop.expr); delete this.property; this.return = _; return prop; } }; /** * Visit Root. */ Evaluator.prototype.visitRoot = function(block){ for (var i = 0; i < block.nodes.length; ++i) { block.index = this.rootIndex = i; block.nodes[i] = this.visit(block.nodes[i]); } return block; }; /** * Visit Block. */ Evaluator.prototype.visitBlock = function(block){ this.stack.push(new Frame(block)); for (block.index = 0; block.index < block.nodes.length; ++block.index) { try { block.nodes[block.index] = this.visit(block.nodes[block.index]); } catch (err) { if ('return' == err.nodeName) { if (this.return) { this.stack.pop(); throw err; } else { block.nodes[block.index] = err; break; } } else { throw err; } } } this.stack.pop(); return block; }; /** * Visit If. */ Evaluator.prototype.visitIf = function(node){ var ret , _ = this.return , block = this.currentBlock , negate = node.negate; this.return = true; var ok = this.visit(node.cond).first.toBoolean(); this.return = _; // Evaluate body if (negate) { // unless if (ok.isFalse) { ret = this.visit(node.block); } } else { // if if (ok.isTrue) { ret = this.visit(node.block); // else } else if (node.elses.length) { var elses = node.elses , len = elses.length; for (var i = 0; i < len; ++i) { // else if if (elses[i].cond) { if (this.visit(elses[i].cond).first.toBoolean().isTrue) { ret = this.visit(elses[i].block); break; } // else } else { ret = this.visit(elses[i]); } } } } // mixin conditional statements within a selector group if (ret && !node.postfix && block.node && 'group' == block.node.nodeName) { this.mixin(ret.nodes, block); return nodes.null; } return ret || nodes.null; }; /** * Visit Import. */ Evaluator.prototype.visitImport = function(import){ var found , root = this.root , Parser = require('../parser') , path = this.visit(import.path).first; // Enusre string if (!path.string) throw new Error('@import string expected'); var name = path = path.string; // Literal if (/\.css$/.test(path)) return import; path += '.styl'; // Lookup found = utils.lookup(path, this.paths, this.filename); found = found || utils.lookup(name + '/index.styl', this.paths, this.filename); // Expose imports import.path = found; import.dirname = dirname(found); this.paths.push(import.dirname); if (this.options._imports) this.options._imports.push(import); // Throw if import failed if (!found) throw new Error('failed to locate @import file ' + path); // Parse the file this.importStack.push(found); nodes.filename = found; var str = fs.readFileSync(found, 'utf8') , block = new nodes.Block , parser = new Parser(str, utils.merge({ root: block }, this.options)); try { block = parser.parse(); } catch (err) { err.filename = found; err.lineno = parser.lexer.lineno; err.input = str; throw err; } // Evaluate imported "root" block.parent = root; block.scope = false; var ret = this.visit(block); this.paths.pop(); this.importStack.pop(); return ret; }; /** * Invoke `fn` with `args`. * * @param {Function} fn * @param {Array} args * @return {Node} * @api private */ Evaluator.prototype.invokeFunction = function(fn, args){ var block = new nodes.Block(fn.block.parent); fn.block.parent = block; // Clone the function body // to prevent mutation of subsequent calls // inject argument scope var body = fn.block.clone(); // mixin block var mixinBlock = this.stack.currentFrame.block; // new block scope this.stack.push(new Frame(block)); var scope = this.currentScope; // arguments local scope.add(new nodes.Ident('arguments', args)); // mixin scope introspection scope.add(new nodes.Ident('mixin', this.return ? nodes.false : new nodes.String(mixinBlock.nodeName))); // current property if (this.property) { var prop = this.propertyExpression(this.property, fn.name); scope.add(new nodes.Ident('current-property', prop)); } else { scope.add(new nodes.Ident('current-property', nodes.null)); } // inject arguments as locals var i = 0 , len = args.nodes.length; fn.params.nodes.forEach(function(node){ // rest param support if (node.rest) { node.val = new nodes.Expression; for (; i < len; ++i) node.val.push(args.nodes[i]); node.val.preserve = true; // argument default support } else { var arg = args.map[node.name] || args.nodes[i++]; node = node.clone(); node.val = arg && !arg.isEmpty ? arg : node.val; // required argument not satisfied if (node.val.isNull) { throw new Error('argument "' + node + '" required for ' + fn); } } scope.add(node); }); // invoke return this.invoke(body, true); }; /** * Invoke built-in `fn` with `args`. * * @param {Function} fn * @param {Array} args * @return {Node} * @api private */ Evaluator.prototype.invokeBuiltin = function(fn, args){ // Map arguments to first node // providing a nicer js api for // BIFs. Functions may specify that // they wish to accept full expressions // via .raw if (fn.raw) { args = args.nodes; } else { args = utils.params(fn).reduce(function(ret, param){ var arg = args.map[param] || args.nodes.shift(); if (arg) ret.push(arg.first); return ret; }, []); } // Invoke the BIF var body = fn.apply(this, args); // Always wrapping allows js functions // to return several values with a single // Expression node var expr = new nodes.Expression; expr.push(body); body = expr; // Invoke return this.invoke(body); }; /** * Invoke the given function `body`. * * @param {Block} body * @return {Node} * @api private */ Evaluator.prototype.invoke = function(body, stack){ var self = this , ret; // Return if (this.return) { ret = this.eval(body.nodes); if (stack) this.stack.pop(); // Mixin } else { body = this.visit(body); if (stack) this.stack.pop(); this.mixin(body.nodes, this.currentBlock); ret = nodes.null; } return ret; }; /** * Mixin the given `nodes` to the given `block`. * * @param {Array} nodes * @param {Block} block * @api private */ Evaluator.prototype.mixin = function(nodes, block){ var len = block.nodes.length , head = block.nodes.slice(0, block.index) , tail = block.nodes.slice(block.index + 1, len); this._mixin(nodes, head); block.nodes = head.concat(tail); }; /** * Mixin the given `nodes` to the `dest` array. * * @param {Array} nodes * @param {Array} dest * @api private */ Evaluator.prototype._mixin = function(nodes, dest){ var node , len = nodes.length; for (var i = 0; i < len; ++i) { switch ((node = nodes[i]).nodeName) { case 'return': return; case 'block': this._mixin(node.nodes, dest); break; default: dest.push(node); } } }; /** * Evaluate the given `vals`. * * @param {Array} vals * @return {Node} * @api private */ Evaluator.prototype.eval = function(vals){ if (!vals) return nodes.null; var len = vals.length , node = nodes.null; try { for (var i = 0; i < len; ++i) { node = vals[i]; switch (node.nodeName) { case 'if': if ('block' != node.block.nodeName) { node = this.visit(node); break; } case 'each': case 'block': node = this.visit(node); if (node.nodes) node = this.eval(node.nodes); break; default: node = this.visit(node); } } } catch (err) { if ('return' == err.nodeName) { return err.expr; } else { throw err; } } return node; }; /** * Literal function `call`. * * @param {Call} call * @return {call} * @api private */ Evaluator.prototype.literalCall = function(call){ call.args = this.visit(call.args); return call; }; /** * Lookup `name`, with support for JavaScript * functions, and BIFs. * * @param {String} name * @return {Node} * @api private */ Evaluator.prototype.lookup = function(name){ var val; if (val = this.stack.lookup(name)) { return utils.unwrap(val); } else { return this.lookupFunction(name); } }; /** * Map segments in `node` returning a string. * * @param {Node} node * @return {String} * @api private */ Evaluator.prototype.interpolate = function(node){ var self = this; return node.segments.map(function(node){ function toString(node) { switch (node.nodeName) { case 'function': case 'ident': return node.name; case 'literal': case 'string': case 'unit': return node.val; case 'expression': var _ = self.return; self.return = true; var ret = toString(self.visit(node).first); self.return = _; return ret; } } return toString(node); }).join(''); }; /** * Lookup JavaScript user-defined or built-in function. * * @param {String} name * @return {Function} * @api private */ Evaluator.prototype.lookupFunction = function(name){ var fn = this.functions[name] || bifs[name]; if (fn) return new nodes.Function(name, fn); }; /** * Check if the given `node` is an ident, and if it is defined. * * @param {Node} node * @return {Boolean} * @api private */ Evaluator.prototype.isDefined = function(node){ if ('ident' == node.nodeName) { return nodes.Boolean(this.lookup(node.name)); } else { throw new Error('invalid "is defined" check on non-variable ' + node); } }; /** * Return `Expression` based on the given `prop`, * replacing cyclic calls to the given function `name` * with "__CALL__". * * @param {Property} prop * @param {String} name * @return {Expression} * @api private */ Evaluator.prototype.propertyExpression = function(prop, name){ var expr = new nodes.Expression , val = prop.expr.clone(); // name expr.push(new nodes.String(prop.name)); // replace cyclic call with __CALL__ val.nodes = val.nodes.map(function(node){ if ('call' == node.nodeName && name == node.name) { return new nodes.Literal('__CALL__'); } return node; }); expr.push(val); return expr; }; /** * Warn with the given `msg`. * * @param {String} msg * @api private */ Evaluator.prototype.warn = function(msg){ if (!this.warnings) return; console.warn('\033[33mWarning:\033[0m ' + msg); }; /** * Return the current `Block`. * * @return {Block} * @api private */ Evaluator.prototype.__defineGetter__('currentBlock', function(){ return this.stack.currentFrame.block; }); /** * Return the closest mixin-able `Block`. * * @return {Block} * @api private */ Evaluator.prototype.__defineGetter__('closestBlock', function(){ var i = this.stack.length , block; while (i--) { block = this.stack[i].block; if (block.node) { switch (block.node.nodeName) { case 'group': case 'function': return block; } } } }); /** * Return the current frame `Scope`. * * @return {Scope} * @api private */ Evaluator.prototype.__defineGetter__('currentScope', function(){ return this.stack.currentFrame.scope; }); /** * Return the current `Frame`. * * @return {Frame} * @api private */ Evaluator.prototype.__defineGetter__('currentFrame', function(){ return this.stack.currentFrame; });
'use strict'; var async = require('async'); var colors = require('colors/safe'); var format = require('stringformat'); var path = require('path'); var _ = require('underscore'); var getComponentsDependencies = require('../domain/get-components-deps'); var getMissingDeps = require('../domain/get-missing-deps'); var getMockedPlugins = require('../domain/get-mocked-plugins'); var npmInstaller = require('../domain/npm-installer'); var oc = require('../../index'); var strings = require('../../resources/index'); var watch = require('../domain/watch'); var wrapCliCallback = require('../wrap-cli-callback'); module.exports = function(dependencies){ var local = dependencies.local, logger = dependencies.logger; var log = { err: function(msg){ return logger.log(colors.red(msg)); }, ok: function(msg){ return logger.log(colors.green(msg)); }, warn: function(msg, noNewLine){ return logger[!!noNewLine ? 'logNoNewLine' : 'log'](colors.yellow(msg)); } }; return function(opts, callback){ var componentsDir = opts.dirName, port = opts.port || 3000, baseUrl = opts.baseUrl || format('http://localhost:{0}/', port), packaging = false, errors = strings.errors.cli; callback = wrapCliCallback(callback); var installMissingDeps = function(missing, cb){ if(_.isEmpty(missing)){ return cb(); } log.warn(format(strings.messages.cli.INSTALLING_DEPS, missing.join(', '))); npmInstaller(missing, componentsDir, function(err, result){ if(!!err){ log.err(err.toString()); throw err; } cb(); }); }; var watchForChanges = function(components, cb){ watch(components, componentsDir, function(err, changedFile){ if(!!err){ log.err(format(strings.errors.generic, err)); } else { log.warn(format(strings.messages.cli.CHANGES_DETECTED, changedFile)); cb(components); } }); }; var packageComponents = function(componentsDirs, cb){ cb = _.isFunction(cb) ? cb : _.noop; var i = 0; if(!packaging){ packaging = true; log.warn(strings.messages.cli.PACKAGING_COMPONENTS, true); async.eachSeries(componentsDirs, function(dir, cb){ local.package(dir, false, function(err){ if(!err){ i++; } cb(err); }); }, function(error){ if(!!error){ var errorDescription = ((error instanceof SyntaxError) || !!error.message) ? error.message : error; log.err(format(strings.errors.cli.PACKAGING_FAIL, componentsDirs[i], errorDescription)); log.warn(strings.messages.cli.RETRYING_10_SECONDS); setTimeout(function(){ packaging = false; packageComponents(componentsDirs); }, 10000); } else { packaging = false; log.ok('OK'); cb(); } }); } }; var loadDependencies = function(components, cb){ log.warn(strings.messages.cli.CHECKING_DEPENDENCIES, true); var dependencies = getComponentsDependencies(components), missing = getMissingDeps(dependencies, components); if(_.isEmpty(missing)){ log.ok('OK'); return cb(dependencies); } log.err('FAIL'); installMissingDeps(missing, function(){ loadDependencies(components, cb); }); }; var registerPlugins = function(registry){ var mockedPlugins = getMockedPlugins(logger); mockedPlugins.forEach(function(p){ registry.register(p); }); registry.on('request', function(data){ if(data.errorCode === 'PLUGIN_MISSING_FROM_REGISTRY'){ log.err(format(strings.errors.cli.PLUGIN_MISSING_FROM_REGISTRY, data.errorDetails, colors.blue(strings.commands.cli.MOCK_PLUGIN))); } else if(data.errorCode === 'PLUGIN_MISSING_FROM_COMPONENT'){ log.err(format(strings.errors.cli.PLUGIN_MISSING_FROM_COMPONENT, data.errorDetails)); } }); }; log.warn(strings.messages.cli.SCANNING_COMPONENTS, true); local.getComponentsByDir(componentsDir, function(err, components){ if(err){ callback(err); return log.err(err); } else if(_.isEmpty(components)){ err = format(errors.DEV_FAIL, errors.COMPONENTS_NOT_FOUND); callback(err); return log.err(err); } log.ok('OK'); _.forEach(components, function(component){ logger.log(colors.green('├── ') + component); }); loadDependencies(components, function(dependencies){ packageComponents(components, function(){ var registry = new oc.Registry({ local: true, discovery: true, verbosity: 1, path: path.resolve(componentsDir), port: port, baseUrl: baseUrl, env: { name: 'local' }, dependencies: dependencies }); registerPlugins(registry); log.warn(format(strings.messages.cli.REGISTRY_STARTING, baseUrl)); registry.start(function(err, app){ if(err){ if(err.code === 'EADDRINUSE'){ err = format(strings.errors.cli.PORT_IS_BUSY, port); } callback(err); return log.err(err); } watchForChanges(components, packageComponents); callback(null, registry); }); }); }); }); }; };
describe('tooltip', function() { var elm, elmBody, scope, elmScope, tooltipScope; // load the tooltip code beforeEach(module('ui.bootstrap.tooltip')); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); beforeEach(inject(function($rootScope, $compile) { elmBody = angular.element( '<div><span tooltip="tooltip text" tooltip-animation="false">Selector Text</span></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it('should not be open initially', inject(function() { expect( tooltipScope.isOpen ).toBe( false ); // We can only test *that* the tooltip-popup element wasn't created as the // implementation is templated and replaced. expect( elmBody.children().length ).toBe( 1 ); })); it('should open on mouseenter', inject(function() { elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); // We can only test *that* the tooltip-popup element was created as the // implementation is templated and replaced. expect( elmBody.children().length ).toBe( 2 ); })); it('should close on mouseleave', inject(function() { elm.trigger( 'mouseenter' ); elm.trigger( 'mouseleave' ); expect( tooltipScope.isOpen ).toBe( false ); })); it('should not animate on animation set to false', inject(function() { expect( tooltipScope.animation ).toBe( false ); })); it('should have default placement of "top"', inject(function() { elm.trigger( 'mouseenter' ); expect( tooltipScope.placement ).toBe( 'top' ); })); it('should allow specification of placement', inject( function( $compile ) { elm = $compile( angular.element( '<span tooltip="tooltip text" tooltip-placement="bottom">Selector Text</span>' ) )( scope ); scope.$apply(); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; elm.trigger( 'mouseenter' ); expect( tooltipScope.placement ).toBe( 'bottom' ); })); it('should update placement dynamically', inject( function( $compile, $timeout ) { scope.place = 'bottom'; elm = $compile( angular.element( '<span tooltip="tooltip text" tooltip-placement="{{place}}">Selector Text</span>' ) )( scope ); scope.$apply(); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; elm.trigger( 'mouseenter' ); expect( tooltipScope.placement ).toBe( 'bottom' ); scope.place = 'right'; scope.$digest(); $timeout.flush(); expect(tooltipScope.placement).toBe( 'right' ); })); it('should work inside an ngRepeat', inject( function( $compile ) { elm = $compile( angular.element( '<ul>'+ '<li ng-repeat="item in items">'+ '<span tooltip="{{item.tooltip}}">{{item.name}}</span>'+ '</li>'+ '</ul>' ) )( scope ); scope.items = [ { name: 'One', tooltip: 'First Tooltip' } ]; scope.$digest(); var tt = angular.element( elm.find('li > span')[0] ); tt.trigger( 'mouseenter' ); expect( tt.text() ).toBe( scope.items[0].name ); tooltipScope = tt.scope().$$childTail; expect( tooltipScope.content ).toBe( scope.items[0].tooltip ); tt.trigger( 'mouseleave' ); })); it('should show correct text when in an ngRepeat', inject( function( $compile, $timeout ) { elm = $compile( angular.element( '<ul>'+ '<li ng-repeat="item in items">'+ '<span tooltip="{{item.tooltip}}">{{item.name}}</span>'+ '</li>'+ '</ul>' ) )( scope ); scope.items = [ { name: 'One', tooltip: 'First Tooltip' }, { name: 'Second', tooltip: 'Second Tooltip' } ]; scope.$digest(); var tt_1 = angular.element( elm.find('li > span')[0] ); var tt_2 = angular.element( elm.find('li > span')[1] ); tt_1.trigger( 'mouseenter' ); tt_1.trigger( 'mouseleave' ); $timeout.flush(); tt_2.trigger( 'mouseenter' ); expect( tt_1.text() ).toBe( scope.items[0].name ); expect( tt_2.text() ).toBe( scope.items[1].name ); tooltipScope = tt_2.scope().$$childTail; expect( tooltipScope.content ).toBe( scope.items[1].tooltip ); expect( elm.find( '.tooltip-inner' ).text() ).toBe( scope.items[1].tooltip ); tt_2.trigger( 'mouseleave' ); })); it('should only have an isolate scope on the popup', inject( function ( $compile ) { var ttScope; scope.tooltipMsg = 'Tooltip Text'; scope.alt = 'Alt Message'; elmBody = $compile( angular.element( '<div><span alt={{alt}} tooltip="{{tooltipMsg}}" tooltip-animation="false">Selector Text</span></div>' ) )( scope ); $compile( elmBody )( scope ); scope.$digest(); elm = elmBody.find( 'span' ); elmScope = elm.scope(); elm.trigger( 'mouseenter' ); expect( elm.attr( 'alt' ) ).toBe( scope.alt ); ttScope = angular.element( elmBody.children()[1] ).isolateScope(); expect( ttScope.placement ).toBe( 'top' ); expect( ttScope.content ).toBe( scope.tooltipMsg ); elm.trigger( 'mouseleave' ); //Isolate scope contents should be the same after hiding and showing again (issue 1191) elm.trigger( 'mouseenter' ); ttScope = angular.element( elmBody.children()[1] ).isolateScope(); expect( ttScope.placement ).toBe( 'top' ); expect( ttScope.content ).toBe( scope.tooltipMsg ); })); it('should not show tooltips if there is nothing to show - issue #129', inject(function ($compile) { elmBody = $compile(angular.element( '<div><span tooltip="">Selector Text</span></div>' ))(scope); scope.$digest(); elmBody.find('span').trigger('mouseenter'); expect(elmBody.children().length).toBe(1); })); it( 'should close the tooltip when its trigger element is destroyed', inject( function() { elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); elm.remove(); elmScope.$destroy(); expect( elmBody.children().length ).toBe( 0 ); })); it('issue 1191 - scope on the popup should always be child of correct element scope', function () { var ttScope; elm.trigger( 'mouseenter' ); ttScope = angular.element( elmBody.children()[1] ).scope(); expect( ttScope.$parent ).toBe( tooltipScope ); elm.trigger( 'mouseleave' ); // After leaving and coming back, the scope's parent should be the same elm.trigger( 'mouseenter' ); ttScope = angular.element( elmBody.children()[1] ).scope(); expect( ttScope.$parent ).toBe( tooltipScope ); elm.trigger( 'mouseleave' ); }); describe('with specified enable expression', function() { beforeEach(inject(function ($compile) { scope.enable = false; elmBody = $compile(angular.element( '<div><span tooltip="tooltip text" tooltip-enable="enable">Selector Text</span></div>' ))(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it('should not open ', inject(function () { elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBeFalsy(); expect(elmBody.children().length).toBe(1); })); it('should open', inject(function () { scope.enable = true; scope.$digest(); elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBeTruthy(); expect(elmBody.children().length).toBe(2); })); }); describe('with specified popup delay', function () { beforeEach(inject(function ($compile) { scope.delay='1000'; elm = $compile(angular.element( '<span tooltip="tooltip text" tooltip-popup-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>' ))(scope); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; scope.$digest(); })); it('should open after timeout', inject(function ($timeout) { elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBe(false); $timeout.flush(); expect(tooltipScope.isOpen).toBe(true); })); it('should not open if mouseleave before timeout', inject(function ($timeout) { elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBe(false); elm.trigger('mouseleave'); $timeout.flush(); expect(tooltipScope.isOpen).toBe(false); })); it('should use default popup delay if specified delay is not a number', function(){ scope.delay='text1000'; scope.$digest(); elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBe(true); }); it('should not open if disabled is present', inject(function($timeout) { elm.trigger('mouseenter'); expect(tooltipScope.isOpen).toBe(false); $timeout.flush(500); expect(tooltipScope.isOpen).toBe(false); elmScope.disabled = true; elmScope.$digest(); $timeout.flush(); expect(tooltipScope.isOpen).toBe(false); })); }); describe( 'with an is-open attribute', function() { beforeEach(inject(function ($compile) { scope.isOpen = false; elm = $compile(angular.element( '<span tooltip="tooltip text" tooltip-is-open="isOpen" >Selector Text</span>' ))(scope); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; scope.$digest(); })); it( 'should show and hide with the controller value', function() { expect(tooltipScope.isOpen).toBe(false); elmScope.isOpen = true; elmScope.$digest(); expect(tooltipScope.isOpen).toBe(true); elmScope.isOpen = false; elmScope.$digest(); expect(tooltipScope.isOpen).toBe(false); }); it( 'should update the controller value', function() { elm.trigger('mouseenter'); expect(elmScope.isOpen).toBe(true); elm.trigger('mouseleave'); expect(elmScope.isOpen).toBe(false); }); }); describe( 'with a trigger attribute', function() { var scope, elmBody, elm, elmScope; beforeEach( inject( function( $rootScope ) { scope = $rootScope; })); it( 'should use it to show but set the hide trigger based on the map for mapped triggers', inject( function( $compile ) { elmBody = angular.element( '<div><input tooltip="Hello!" tooltip-trigger="focus" /></div>' ); $compile(elmBody)(scope); scope.$apply(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('focus'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('blur'); expect( tooltipScope.isOpen ).toBeFalsy(); })); it( 'should use it as both the show and hide triggers for unmapped triggers', inject( function( $compile ) { elmBody = angular.element( '<div><input tooltip="Hello!" tooltip-trigger="fakeTriggerAttr" /></div>' ); $compile(elmBody)(scope); scope.$apply(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('fakeTriggerAttr'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('fakeTriggerAttr'); expect( tooltipScope.isOpen ).toBeFalsy(); })); it('should only set up triggers once', inject( function ($compile) { scope.test = true; elmBody = angular.element( '<div>' + '<input tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' + '<input tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' + '</div>' ); $compile(elmBody)(scope); scope.$apply(); var elm1 = elmBody.find('input').eq(0); var elm2 = elmBody.find('input').eq(1); var elmScope1 = elm1.scope(); var elmScope2 = elm2.scope(); var tooltipScope2 = elmScope2.$$childTail; scope.$apply('test = false'); // click trigger isn't set elm2.click(); expect( tooltipScope2.isOpen ).toBeFalsy(); // mouseenter trigger is still set elm2.trigger('mouseenter'); expect( tooltipScope2.isOpen ).toBeTruthy(); })); it( 'should accept multiple triggers based on the map for mapped triggers', inject( function( $compile ) { elmBody = angular.element( '<div><input tooltip="Hello!" tooltip-trigger="focus fakeTriggerAttr" /></div>' ); $compile(elmBody)(scope); scope.$apply(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('focus'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('blur'); expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('fakeTriggerAttr'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('fakeTriggerAttr'); expect( tooltipScope.isOpen ).toBeFalsy(); })); it( 'should not show when trigger is set to "none"', inject( function( $compile ) { elmBody = angular.element( '<div><input tooltip="Hello!" tooltip-trigger="none" /></div>' ); $compile(elmBody)(scope); scope.$apply(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('mouseenter'); expect( tooltipScope.isOpen ).toBeFalsy(); })); }); describe( 'with an append-to-body attribute', function() { var scope, elmBody, elm, elmScope, $body; beforeEach( inject( function( $rootScope ) { scope = $rootScope; })); afterEach(function () { $body.find('.tooltip').remove(); }); it( 'should append to the body', inject( function( $compile, $document ) { $body = $document.find( 'body' ); elmBody = angular.element( '<div><span tooltip="tooltip text" tooltip-append-to-body="true">Selector Text</span></div>' ); $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; var bodyLength = $body.children().length; elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); expect( elmBody.children().length ).toBe( 1 ); expect( $body.children().length ).toEqual( bodyLength + 1 ); })); }); describe('cleanup', function () { var elmBody, elm, elmScope, tooltipScope; function inCache() { var match = false; angular.forEach(angular.element.cache, function (item) { if (item.data && item.data.$scope === tooltipScope) { match = true; } }); return match; } beforeEach(inject(function ( $compile, $rootScope ) { elmBody = angular.element('<div><input tooltip="Hello!" tooltip-trigger="fooTrigger" /></div>'); $compile(elmBody)($rootScope); $rootScope.$apply(); elm = elmBody.find('input'); elmScope = elm.scope(); elm.trigger('fooTrigger'); tooltipScope = elmScope.$$childTail.$$childTail; })); it( 'should not contain a cached reference when not visible', inject( function( $timeout ) { expect( inCache() ).toBeTruthy(); elmScope.$destroy(); expect( inCache() ).toBeFalsy(); })); }); }); describe('tooltipWithDifferentSymbols', function() { var elmBody; // load the tooltip code beforeEach(module('ui.bootstrap.tooltip')); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); // configure interpolate provider to use [[ ]] instead of {{ }} beforeEach(module( function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.startSymbol(']]'); })); it( 'should show the correct tooltip text', inject( function ( $compile, $rootScope ) { elmBody = angular.element( '<div><input type="text" tooltip="My tooltip" tooltip-trigger="focus" tooltip-placement="right" /></div>' ); $compile(elmBody)($rootScope); $rootScope.$apply(); var elmInput = elmBody.find('input'); elmInput.trigger('focus'); expect( elmInput.next().find('div').next().html() ).toBe('My tooltip'); })); }); describe( 'tooltip positioning', function() { var elm, elmBody, elmScope, tooltipScope, scope; var $position; // load the tooltip code beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) { $tooltipProvider.options({ animation: false }); })); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); beforeEach(inject(function($rootScope, $compile, _$position_) { $position = _$position_; spyOn($position, 'positionElements').and.callThrough(); scope = $rootScope; scope.text = 'Some Text'; elmBody = $compile( angular.element( '<div><span tooltip="{{ text }}">Selector Text</span></div>' ))( scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it( 'should re-position when value changes', inject( function ($timeout) { elm.trigger( 'mouseenter' ); scope.$digest(); $timeout.flush(); var startingPositionCalls = $position.positionElements.calls.count(); scope.text = 'New Text'; scope.$digest(); $timeout.flush(); expect(elm.attr('tooltip')).toBe( 'New Text' ); expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1); // Check that positionElements was called with elm expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0]) .toBe(elm[0]); scope.$digest(); $timeout.verifyNoPendingTasks(); expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1); expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0]) .toBe(elm[0]); scope.$digest(); })); }); describe( 'tooltipHtml', function() { var elm, elmBody, elmScope, tooltipScope, scope; // load the tooltip code beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) { $tooltipProvider.options({ animation: false }); })); // load the template beforeEach(module('template/tooltip/tooltip-html-popup.html')); beforeEach(inject(function($rootScope, $compile, $sce) { scope = $rootScope; scope.html = 'I say: <strong class="hello">Hello!</strong>'; scope.safeHtml = $sce.trustAsHtml(scope.html); elmBody = $compile( angular.element( '<div><span tooltip-html="safeHtml">Selector Text</span></div>' ))( scope ); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it( 'should render html properly', inject( function () { elm.trigger( 'mouseenter' ); expect( elmBody.find('.tooltip-inner').html() ).toBe( scope.html ); })); it( 'should not open if html is empty', function () { scope.safeHtml = null; scope.$digest(); elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( false ); }); it( 'should show on mouseenter and hide on mouseleave', inject( function ($sce) { expect( tooltipScope.isOpen ).toBe( false ); elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); expect( elmBody.children().length ).toBe( 2 ); expect( $sce.getTrustedHtml(tooltipScope.contentExp()) ).toEqual( scope.html ); elm.trigger( 'mouseleave' ); expect( tooltipScope.isOpen ).toBe( false ); expect( elmBody.children().length ).toBe( 1 ); })); }); describe( 'tooltipHtmlUnsafe', function() { var elm, elmBody, elmScope, tooltipScope, scope; var logWarnSpy; // load the tooltip code beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) { $tooltipProvider.options({ animation: false }); })); // load the template beforeEach(module('template/tooltip/tooltip-html-unsafe-popup.html')); beforeEach(inject(function($rootScope, $compile, $log) { scope = $rootScope; scope.html = 'I say: <strong class="hello">Hello!</strong>'; logWarnSpy = spyOn($log, 'warn'); elmBody = $compile( angular.element( '<div><span tooltip-html-unsafe="{{html}}">Selector Text</span></div>' ))( scope ); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it( 'should warn that this is deprecated', function () { expect(logWarnSpy).toHaveBeenCalledWith(jasmine.stringMatching('deprecated')); }); it( 'should render html properly', inject( function () { elm.trigger( 'mouseenter' ); expect( elmBody.find('.tooltip-inner').html() ).toBe( scope.html ); })); it( 'should show on mouseenter and hide on mouseleave', inject( function () { expect( tooltipScope.isOpen ).toBe( false ); elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); expect( elmBody.children().length ).toBe( 2 ); expect( tooltipScope.content ).toEqual( scope.html ); elm.trigger( 'mouseleave' ); expect( tooltipScope.isOpen ).toBe( false ); expect( elmBody.children().length ).toBe( 1 ); })); }); describe( '$tooltipProvider', function() { var elm, elmBody, scope, elmScope, tooltipScope; describe( 'popupDelay', function() { beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){ $tooltipProvider.options({popupDelay: 1000}); })); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); beforeEach(inject(function($rootScope, $compile) { elmBody = angular.element( '<div><span tooltip="tooltip text">Selector Text</span></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; })); it('should open after timeout', inject(function($timeout) { elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( false ); $timeout.flush(); expect( tooltipScope.isOpen ).toBe( true ); })); }); describe('appendToBody', function() { var $body; beforeEach(module('template/tooltip/tooltip-popup.html')); beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) { $tooltipProvider.options({ appendToBody: true }); })); afterEach(function () { $body.find('.tooltip').remove(); }); it( 'should append to the body', inject( function( $rootScope, $compile, $document ) { $body = $document.find( 'body' ); elmBody = angular.element( '<div><span tooltip="tooltip text">Selector Text</span></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; var bodyLength = $body.children().length; elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); expect( elmBody.children().length ).toBe( 1 ); expect( $body.children().length ).toEqual( bodyLength + 1 ); })); it('should close on location change', inject( function( $rootScope, $compile) { elmBody = angular.element( '<div><span tooltip="tooltip text">Selector Text</span></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; elm.trigger( 'mouseenter' ); expect( tooltipScope.isOpen ).toBe( true ); scope.$broadcast('$locationChangeSuccess'); scope.$digest(); expect( tooltipScope.isOpen ).toBe( false ); })); }); describe( 'triggers', function() { describe( 'triggers with a mapped value', function() { beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){ $tooltipProvider.options({trigger: 'focus'}); })); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); it( 'should use the show trigger and the mapped value for the hide trigger', inject( function ( $rootScope, $compile ) { elmBody = angular.element( '<div><input tooltip="tooltip text" /></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('focus'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('blur'); expect( tooltipScope.isOpen ).toBeFalsy(); })); it( 'should override the show and hide triggers if there is an attribute', inject( function ( $rootScope, $compile ) { elmBody = angular.element( '<div><input tooltip="tooltip text" tooltip-trigger="mouseenter"/></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('mouseenter'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('mouseleave'); expect( tooltipScope.isOpen ).toBeFalsy(); })); }); describe( 'triggers with a custom mapped value', function() { beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){ $tooltipProvider.setTriggers({ 'customOpenTrigger': 'customCloseTrigger' }); $tooltipProvider.options({trigger: 'customOpenTrigger'}); })); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); it( 'should use the show trigger and the mapped value for the hide trigger', inject( function ( $rootScope, $compile ) { elmBody = angular.element( '<div><input tooltip="tooltip text" /></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('input'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('customOpenTrigger'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('customCloseTrigger'); expect( tooltipScope.isOpen ).toBeFalsy(); })); }); describe( 'triggers without a mapped value', function() { beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){ $tooltipProvider.options({trigger: 'fakeTrigger'}); })); // load the template beforeEach(module('template/tooltip/tooltip-popup.html')); it( 'should use the show trigger to hide', inject( function ( $rootScope, $compile ) { elmBody = angular.element( '<div><span tooltip="tooltip text">Selector Text</span></div>' ); scope = $rootScope; $compile(elmBody)(scope); scope.$digest(); elm = elmBody.find('span'); elmScope = elm.scope(); tooltipScope = elmScope.$$childTail; expect( tooltipScope.isOpen ).toBeFalsy(); elm.trigger('fakeTrigger'); expect( tooltipScope.isOpen ).toBeTruthy(); elm.trigger('fakeTrigger'); expect( tooltipScope.isOpen ).toBeFalsy(); })); }); }); });
var Errors = require('./errors'); var q = require('q'); var tls = require('tls'); var sysu = require('util'); var util = require('./util'); var events = require('events'); var Device = require('./device'); var CredentialLoader = require('./credentials'); var createSocket = require('./socket'); var debug = function() {}; var trace = function() {}; if(process.env.DEBUG) { try { debug = require('debug')('apn'); trace = require('debug')('apn:trace'); } catch (e) { console.log("Notice: 'debug' module is not available. This should be installed with `npm install debug` to enable debug messages", e); debug = function() {}; } } /** * Create a new connection to the APN service. * @constructor * @param {Object} [options] * @config {Buffer|String} [cert="cert.pem"] The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. * @config {Buffer|String} [key="key.pem"] The filename of the connection key to load from disk, or a Buffer/String containing the key data. * @config {Buffer[]|String[]} [ca] An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). * @config {Buffer|String} [pfx] File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer/String containing the PFX data. If supplied will be used instead of certificate and key above. * @config {String} [passphrase] The passphrase for the connection key, if required * @config {Boolean} [production=(NODE_ENV=='production')] Specifies which environment to connect to: Production (if true) or Sandbox. (Defaults to false, unless NODE_ENV == "production") * @config {Number} [port=2195] Gateway port * @config {Boolean} [rejectUnauthorized=true] Reject Unauthorized property to be passed through to tls.connect() * @config {Boolean} [enhanced=true] Whether to use the enhanced notification format (recommended) * @config {Function} [errorCallback] A callback which accepts 2 parameters (err, notification). Use `transmissionError` event instead. * @config {Number} [cacheLength=1000] Number of notifications to cache for error purposes (See doc/apn.markdown) * @config {Boolean} [autoAdjustCache=false] Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) * @config {Number} [maxConnections=1] The maximum number of connections to create for sending messages. * @config {Number} [connectionTimeout=0] The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. * @config {Boolean} [buffersNotifications=true] Whether to buffer notifications and resend them after failure. * @config {Boolean} [fastMode=false] Whether to aggresively empty the notification buffer while connected. * @config {Boolean} [legacy=false] Whether to use the old (pre-iOS 7) protocol format. */ function Connection (options) { if(false === (this instanceof Connection)) { return new Connection(options); } this.options = { cert: 'cert.pem', key: 'key.pem', ca: null, pfx: null, passphrase: null, production: (process.env.NODE_ENV === "production"), address: null, port: 2195, rejectUnauthorized: true, enhanced: true, cacheLength: 1000, autoAdjustCache: true, maxConnections: 1, connectTimeout: 10000, connectionTimeout: 0, connectionRetryLimit: 10, buffersNotifications: true, fastMode: false, legacy: false, disableNagle: false, disableEPIPEFix: false, largePayloads: false }; for (var key in options) { if (options[key] == null) { debug("Option [" + key + "] set to null. This may cause unexpected behaviour."); } } util.extend(this.options, options); if (this.options.gateway != null) { this.options.address = this.options.gateway; } if (this.options.address == null) { if (this.options.production) { this.options.address = "gateway.push.apple.com"; } else { this.options.address = "gateway.sandbox.push.apple.com"; this.options.largePayloads = true; } } if (this.options.pfx || this.options.pfxData) { if (!options.cert) { this.options.cert = null; } if (!options.key) { this.options.key = null; } } // Set cache length to 1 to ensure transmitted notifications can be sent. this.options.cacheLength = Math.max(this.options.cacheLength, 1); this.options.maxConnections = Math.max(this.options.maxConnections, 1); this.initializationPromise = null; this.deferredConnection = null; this.sockets = []; this.notificationBuffer = []; this.socketId = 0; this.failureCount = 0; this.connectionTimer = null; // when true, we end all sockets after the pending notifications reach 0 this.shutdownPending = false; // track when notifications are queued so transmitCompleted is only emitted one when // notifications are transmitted rather than after socket timeouts this.notificationsQueued = false; this.terminated = false; events.EventEmitter.call(this); } sysu.inherits(Connection, events.EventEmitter); /** * You should never need to call this method, initialization and connection is handled by {@link Connection#sendNotification} * @private */ Connection.prototype.initialize = function () { if (!this.initializationPromise) { debug("Initialising module"); this.initializationPromise = CredentialLoader(this.options); } return this.initializationPromise; }; /** * You should never need to call this method, initialisation and connection is handled by {@link Connection#pushNotification} * @private */ Connection.prototype.connect = function () { if (this.deferredConnection) { return this.deferredConnection.promise; } debug("Initialising connection"); this.deferredConnection = q.defer(); this.initialize().spread(function (pfxData, certData, keyData, caData) { var socketOptions = {}; socketOptions.port = this.options.port; socketOptions.host = this.options.address; socketOptions.disableEPIPEFix = this.options.disableEPIPEFix; socketOptions.disableNagle = this.options.disableNagle; socketOptions.connectionTimeout = this.options.connectionTimeout; socketOptions.pfx = pfxData; socketOptions.cert = certData; socketOptions.key = keyData; socketOptions.ca = caData; socketOptions.passphrase = this.options.passphrase; socketOptions.rejectUnauthorized = this.options.rejectUnauthorized; this.socket = createSocket(this, socketOptions, function () { debug("Connection established"); this.emit('connected', this.sockets.length + 1); this.deferredConnection.resolve(); clearTimeout(this.connectionTimer); this.connectionTimer = null; }.bind(this)); this.socket.on("error", this.errorOccurred.bind(this, this.socket)); this.socket.on("timeout", this.socketTimeout.bind(this, this.socket)); this.socket.on("data", this.handleTransmissionError.bind(this, this.socket)); this.socket.on("drain", this.socketDrained.bind(this, this.socket, true)); this.socket.once("close", this.socketClosed.bind(this, this.socket)); if (this.options.connectTimeout > 0) { this.connectionTimer = setTimeout(function () { this.deferredConnection.reject(new Error("Connect timed out")); this.socket.end(); }.bind(this), this.options.connectTimeout); } }.bind(this)).fail(function (error) { debug("Module initialisation error:", error); // This is a pretty fatal scenario, we don't have key/certificate to connect to APNS, there's not much we can do, so raise errors and clear the queue. this.rejectBuffer(Errors['moduleInitialisationFailed']); this.deferredConnection.reject(error); this.terminated = true; }.bind(this)); return this.deferredConnection.promise; }; /** * @private */ Connection.prototype.createConnection = function() { if (this.initialisingConnection() || this.sockets.length >= this.options.maxConnections) { return; } // Delay here because Apple will successfully authenticate production certificates // in sandbox, but will then immediately close the connection. Necessary to wait for a beat // to see if the connection stays before sending anything because the connection will be closed // without error and messages could be lost. this.connect().delay(100).then(function () { if (this.socket.apnRetired) { throw new Error("Socket unusable after connection. Hint: You may be using a certificate for the wrong environment"); } this.failureCount = 0; this.socket.apnSocketId = this.socketId++; this.socket.apnCurrentId = 0; this.socket.apnCachedNotifications = []; this.sockets.push(this.socket); trace("connection established", this.socketId); }.bind(this)).fail(function (error) { // Exponential backoff when connections fail. var delay = Math.pow(2, this.failureCount++) * 1000; trace("connection failed", delay); this.raiseError(error); this.emit('error', error); if (this.options.connectionRetryLimit > 0 && this.failureCount > this.options.connectionRetryLimit && this.sockets.length == 0) { this.rejectBuffer(Errors['connectionRetryLimitExceeded']); this.shutdown(); this.terminated = true; return; } return q.delay(delay); }.bind(this)).finally(function () { trace("create completed", this.sockets.length); this.deferredConnection = null; this.socket = undefined; this.serviceBuffer(); }.bind(this)).done(); }; /** * @private */ Connection.prototype.initialisingConnection = function() { if(this.deferredConnection !== null) { return true; } return false; }; /** * @private */ Connection.prototype.serviceBuffer = function() { var socket = null; var repeat = false; var socketsAvailable = 0; if(this.options.fastMode) { repeat = true; } do { socketsAvailable = 0; for (var i = 0; i < this.sockets.length; i++) { socket = this.sockets[i]; if(!this.socketAvailable(socket)) { continue; } if (this.notificationBuffer.length === 0) { socketsAvailable += 1; continue; } // If a socket is available then transmit. If true is returned then manually call socketDrained if (this.transmitNotification(socket, this.notificationBuffer.shift())) { // Only set socket available here because if transmit returns false then the socket // is blocked so shouldn't be used in the next loop. socketsAvailable += 1; this.socketDrained(socket, !repeat); } } } while(repeat && socketsAvailable > 0 && this.notificationBuffer.length > 0); if (this.notificationBuffer.length > 0 && socketsAvailable == 0) { this.createConnection(); } if (this.notificationBuffer.length === 0 && socketsAvailable == this.sockets.length){ if (this.notificationsQueued) { this.emit('completed'); this.notificationsQueued = false; } if (this.shutdownPending) { debug("closing connections"); for (var i = 0; i < this.sockets.length; i++) { var socket = this.sockets[i]; // We delay before closing connections to ensure we don't miss any error packets from the service. setTimeout(socket.end.bind(socket), 2500); this.retireSocket(socket); } if (this.sockets.length == 0) { this.shutdownPending = false; } } } debug("%d left to send", this.notificationBuffer.length); }; /** * @private */ Connection.prototype.errorOccurred = function(socket, err) { debug("Socket error occurred", socket.apnSocketId, err); if(socket.transmissionErrorOccurred && err.code == 'EPIPE') { debug("EPIPE occurred after a transmission error which we can ignore"); return; } this.emit('socketError', err); if(this.socket == socket && this.deferredConnection && this.deferredConnection.promise.isPending()) { this.deferredConnection.reject(err); } else { this.raiseError(err, null); } if(socket.apnBusy && socket.apnCachedNotifications.length > 0) { // A notification was in flight. It should be buffered for resending. this.bufferNotification(socket.apnCachedNotifications[socket.apnCachedNotifications.length - 1]); } this.destroyConnection(socket); }; /** * @private */ Connection.prototype.socketAvailable = function(socket) { if (!socket || !socket.writable || socket.apnRetired || socket.apnBusy || socket.transmissionErrorOccurred) { return false; } return true; }; /** * @private */ Connection.prototype.socketDrained = function(socket, serviceBuffer) { debug("Socket drained", socket.apnSocketId); socket.apnBusy = false; if((!this.options.legacy || this.options.enhanced) && socket.apnCachedNotifications.length > 0) { var notification = socket.apnCachedNotifications[socket.apnCachedNotifications.length - 1]; this.emit('transmitted', notification.notification, notification.recipient); } if(serviceBuffer === true && !this.runningOnNextTick) { // There is a possibility that this could add multiple invocations to the // call stack unnecessarily. It will be resolved within one event loop but // should be mitigated if possible, this.nextTick aims to solve this, // ensuring "serviceBuffer" is only called once per loop. util.setImmediate(function() { this.runningOnNextTick = false; this.serviceBuffer(); }.bind(this)); this.runningOnNextTick = true; } }; /** * @private */ Connection.prototype.socketTimeout = function(socket) { debug("Socket timeout", socket.apnSocketId); this.emit('timeout'); this.destroyConnection(socket); this.serviceBuffer(); }; /** * @private */ Connection.prototype.destroyConnection = function(socket) { debug("Destroying connection", socket.apnSocketId); if (socket) { this.retireSocket(socket); socket.destroy(); } }; /** * @private */ Connection.prototype.socketClosed = function(socket) { debug("Socket closed", socket.apnSocketId); if (socket === this.socket && this.deferredConnection.promise.isPending()) { debug("Connection error occurred before TLS Handshake"); this.deferredConnection.reject(new Error("Unable to connect")); } else { this.retireSocket(socket); this.emit('disconnected', this.sockets.length); } this.serviceBuffer(); }; /** * @private */ Connection.prototype.retireSocket = function(socket) { debug("Removing socket from pool", socket.apnSocketId); socket.apnRetired = true; var index = this.sockets.indexOf(socket); if (index > -1) { this.sockets.splice(index, 1); } } /** * Use this method to modify the cache length after initialisation. */ Connection.prototype.setCacheLength = function(newLength) { this.options.cacheLength = newLength; }; /** * @private */ Connection.prototype.bufferNotification = function (notification) { if (notification.retryLimit === 0) { this.raiseError(Errors['retryLimitExceeded'], notification); this.emit('transmissionError', Errors['retryLimitExceeded'], notification.notification, notification.recipient); return; } notification.retryLimit -= 1; this.notificationBuffer.push(notification); this.notificationsQueued = true; }; /** * @private */ Connection.prototype.rejectBuffer = function (errCode) { while(this.notificationBuffer.length > 0) { var notification = this.notificationBuffer.shift(); this.raiseError(errCode, notification.notification, notification.recipient); this.emit('transmissionError', errCode, notification.notification, notification.recipient); } } /** * @private */ Connection.prototype.prepareNotification = function (notification, device) { var recipient = device; // If a device token hasn't been given then we should raise an error. if (recipient === undefined) { util.setImmediate(function () { this.raiseError(Errors['missingDeviceToken'], notification); this.emit('transmissionError', Errors['missingDeviceToken'], notification); }.bind(this)); return; } // If we have been passed a token instead of a `Device` then we should convert. if (!(recipient instanceof Device)) { try { recipient = new Device(recipient); } catch (e) { // If an exception has been thrown it's down to an invalid token. util.setImmediate(function () { this.raiseError(Errors['invalidToken'], notification, device); this.emit('transmissionError', Errors['invalidToken'], notification, device); }.bind(this)); return; } } var retryLimit = (notification.retryLimit < 0) ? -1 : notification.retryLimit + 1; this.bufferNotification( { "notification": notification, "recipient": recipient, "retryLimit": retryLimit } ); }; /** * @private */ Connection.prototype.cacheNotification = function (socket, notification) { socket.apnCachedNotifications.push(notification); if (socket.apnCachedNotifications.length > this.options.cacheLength) { debug("Clearing notification %d from the cache", socket.apnCachedNotifications[0]['_uid']); socket.apnCachedNotifications.splice(0, socket.apnCachedNotifications.length - this.options.cacheLength); } }; /** * @private */ Connection.prototype.handleTransmissionError = function (socket, data) { if (data[0] == 8) { socket.transmissionErrorOccurred = true; if (!this.options.enhanced && this.options.legacy) { return; } var errorCode = data[1]; var identifier = data.readUInt32BE(2); var notification = null; var foundNotification = false; var temporaryCache = []; debug("Notification %d caused an error: %d", identifier, errorCode); while (socket.apnCachedNotifications.length) { notification = socket.apnCachedNotifications.shift(); if (notification['_uid'] == identifier) { foundNotification = true; break; } temporaryCache.push(notification); } if (foundNotification) { while (temporaryCache.length) { temporaryCache.shift(); } this.emit('transmissionError', errorCode, notification.notification, notification.recipient); this.raiseError(errorCode, notification.notification, notification.recipient); } else { socket.apnCachedNotifications = temporaryCache; if(socket.apnCachedNotifications.length > 0) { var differentialSize = socket.apnCachedNotifications[0]['_uid'] - identifier; this.emit('cacheTooSmall', differentialSize); if(this.options.autoAdjustCache) { this.options.cacheLength += differentialSize * 2; } } this.emit('transmissionError', errorCode, null); this.raiseError(errorCode, null); } var count = socket.apnCachedNotifications.length; if(this.options.buffersNotifications) { debug("Buffering %d notifications for resending", count); for (var i = 0; i < count; ++i) { notification = socket.apnCachedNotifications.shift(); this.bufferNotification(notification); } } } else { debug("Unknown data received: ", data); } }; /** * @private */ Connection.prototype.raiseError = function(errorCode, notification, recipient) { debug("Raising error:", errorCode, notification, recipient); if(errorCode instanceof Error) { debug("Error occurred with trace:", errorCode.stack); } if (notification && typeof notification.errorCallback == 'function' ) { notification.errorCallback(errorCode, recipient); } else if (typeof this.options.errorCallback == 'function') { this.options.errorCallback(errorCode, notification, recipient); } }; /** * @private * @return {Boolean} Write completed, returns true if socketDrained should be called by the caller of this method. */ Connection.prototype.transmitNotification = function(socket, notification) { if (!this.socketAvailable(socket)) { this.bufferNotification(notification); return; } var token = notification.recipient.token; var encoding = notification.notification.encoding || 'utf8'; var message = notification.notification.compile(); var messageLength = Buffer.byteLength(message, encoding); var position = 0; var data; notification._uid = socket.apnCurrentId++; if (socket.apnCurrentId > 0xffffffff) { socket.apnCurrentId = 0; } if (this.options.legacy) { if (this.options.enhanced) { data = new Buffer(1 + 4 + 4 + 2 + token.length + 2 + messageLength); // Command data[position] = 1; position++; // Identifier data.writeUInt32BE(notification._uid, position); position += 4; // Expiry data.writeUInt32BE(notification.notification.expiry, position); position += 4; this.cacheNotification(socket, notification); } else { data = new Buffer(1 + 2 + token.length + 2 + messageLength); //Command data[position] = 0; position++; } // Token Length data.writeUInt16BE(token.length, position); position += 2; // Device Token position += token.copy(data, position, 0); // Payload Length data.writeUInt16BE(messageLength, position); position += 2; //Payload position += data.write(message, position, encoding); } else { // New Protocol uses framed notifications consisting of multiple items // 1: Device Token // 2: Payload // 3: Notification Identifier // 4: Expiration Date // 5: Priority // Each item has a 3 byte header: Type (1), Length (2) followed by data // The frame layout is hard coded for now as original dynamic system had a // significant performance penalty var frameLength = 3 + token.length + 3 + messageLength + 3 + 4; if(notification.notification.expiry > 0) { frameLength += 3 + 4; } if(notification.notification.priority != 10) { frameLength += 3 + 1; } // Frame has a 5 byte header: Type (1), Length (4) followed by items. data = new Buffer(5 + frameLength); data[position] = 2; position += 1; // Frame Length data.writeUInt32BE(frameLength, position); position += 4; // Token Item data[position] = 1; position += 1; data.writeUInt16BE(token.length, position); position += 2; position += token.copy(data, position, 0); // Payload Item data[position] = 2; position += 1; data.writeUInt16BE(messageLength, position); position += 2; position += data.write(message, position, encoding); // Identifier Item data[position] = 3; position += 1; data.writeUInt16BE(4, position); position += 2; data.writeUInt32BE(notification._uid, position); position += 4; if(notification.notification.expiry > 0) { // Expiry Item data[position] = 4; position += 1; data.writeUInt16BE(4, position); position += 2; data.writeUInt32BE(notification.notification.expiry, position); position += 4; } if(notification.notification.priority != 10) { // Priority Item data[position] = 5; position += 1; data.writeUInt16BE(1, position); position += 2; data[position] = notification.notification.priority; position += 1; } this.cacheNotification(socket, notification); } socket.apnBusy = true; return socket.write(data); }; Connection.prototype.validNotification = function (notification, recipient) { var messageLength = notification.length(); if (messageLength > (this.options.largePayloads ? 2048 : 256)) { util.setImmediate(function () { this.raiseError(Errors['invalidPayloadSize'], notification, recipient); this.emit('transmissionError', Errors['invalidPayloadSize'], notification, recipient); }.bind(this)); return false; } return true; }; /** * Queue a notification for delivery to recipients * @param {Notification} notification The Notification object to be sent * @param {Device|String|Buffer|Device[]|String[]|Buffer[]} recipient The token(s) for devices the notification should be delivered to. * @since v1.3.0 */ Connection.prototype.pushNotification = function (notification, recipient) { if (this.terminated) { this.emit('transmissionError', Errors['connectionTerminated'], notification, recipient); return false; } if (!this.validNotification(notification, recipient)) { return; } if (sysu.isArray(recipient)) { for (var i = recipient.length - 1; i >= 0; i--) { this.prepareNotification(notification, recipient[i]); } } else { this.prepareNotification(notification, recipient); } this.serviceBuffer(); }; /** * Send a notification to the APN service * @param {Notification} notification The notification object to be sent * @deprecated Since v1.3.0, use pushNotification instead */ Connection.prototype.sendNotification = function (notification) { return this.pushNotification(notification, notification.device); }; /** * End connections with APNS once we've finished sending all notifications */ Connection.prototype.shutdown = function () { debug("Shutdown pending"); this.shutdownPending = true; }; module.exports = Connection;
import Component from './component.js'; export default class Panel extends Component { constructor(SL, config) { super(SL, config); this.DOM = {}; } reset() { super.reset(); this.resetDOM(); } get element() { return (this.DOM && this.DOM.panel); } close() { if (this.manager) { this.manager.closePanel(this); } else { this.reset(); } } positionPanel() { if (this.DOM && this.DOM.panel) { let bounds = this.SL.Paper.view.bounds.clone(); bounds = bounds.scale(0.5, 0.6); this.DOM.panel.css('top', '10%'); this.DOM.panel.css('left', bounds.left+'px'); this.DOM.panel.css('width', bounds.width+'px'); } } setData(data={}) { this.data = data; } setTitle(title='') { if (title) { if (!this.DOM.title) { this.assertDOMHeader(); this.DOM.title = $(`<h3 class="panel-title">${title}</h3>`); this.DOM.header.prepend(this.DOM.title); } } else if (this.DOM && this.DOM.title) { this.DOM.title.remove(); this.DOM.title = undefined; delete this.DOM.title; } } getPanelClass() { return ['sl-panel']; } getPanelID() { if (this.id) { return `sl-panel-${this.id}`; } } assertDOM() { if (!this.DOM) { this.DOM = {}; } } assertDOMHeader() { this.assertDOM(); if (!this.DOM.header) { this.DOM.header = $('<div class="panel-header"></div>'); if (this.DOM.panel) { this.DOM.panel.prepend(this.DOM.header); } } return this.DOM.header; } assertDOMContent() { this.assertDOM(); if (!this.DOM.content) { this.DOM.content = $('<div class="panel-content"></div>'); if (this.DOM.panel) { this.DOM.panel.append(this.DOM.content); } } return this.DOM.content; } assertDOMControls() { this.assertDOM(); if (!this.DOM.controls) { this.DOM.controls = $('<div class="panel-controls"></div>'); this.DOM.panel.append(this.DOM.controls); } if (!this.DOM.Control) { this.DOM.Control = {}; } } assertDOMControlCloseButton() { this.assertDOMControls(); if (!this.DOM.Control.closeButton) { this.DOM.Control.closeButton = $('<button><i class="icon icon-close"></i></button>'); this.DOM.Control.closeButton.on('click', (event) => { this.close(); }); this.DOM.controls.append(this.DOM.Control.closeButton); } } generateDOM() { this.assertDOM(); if (this.DOM.panel) { return this.DOM.panel; } this.DOM.panel = $('<div class="sl-panel"></div>'); this.DOM.panel.addClass(this.getPanelClass().join(' ')); this.DOM.panel.attr('id', this.getPanelID()); // add header if it's waiting if (this.DOM.header) { this.DOM.panel.append(this.DOM.header); } // content let content = this.assertDOMContent(); // position and size let bounds = this.SL.Paper.view.bounds.clone(); bounds = bounds.scale(0.5, 0.6); this.DOM.panel.css('top', '10%'); this.DOM.panel.css('left', bounds.left+'px'); this.DOM.panel.css('width', bounds.width+'px'); // panel controls this.assertDOMControls(); // close button this.assertDOMControlCloseButton(); this.positionPanel(); return this.DOM.panel; } resetDOM() { if (!this.DOM) { return; } this.resetDOMPanel(); } resetDOMTitle() { if (this.DOM.title) { this.DOM.title.remove(); this.DOM.title = undefined; } } resetDOMHeader() { this.resetDOMTitle(); if (this.DOM.header) { this.DOM.header.remove(); this.DOM.header = undefined; } } resetDOMPanel() { this.resetDOMHeader(); this.resetDOMControls(); if (this.DOM.panel) { this.DOM.panel.remove(); this.DOM.panel = undefined; } } resetDOMControls() { this.resetDOMControlCloseButton(); if (this.DOM.controls) { this.DOM.controls.remove(); this.DOM.controls = undefined; } } resetDOMControlCloseButton() { if (this.DOM.Control && this.DOM.Control.closeButton) { this.DOM.Control.closeButton.remove(); this.DOM.Control.closeButton = undefined; } } }
module.exports = { // Replace with a dummy date for testing. Date: Date, // Test a log entry for acceptance. json: function () {}, // Additional properties added to every message. properties: { pid: process.pid } } /* sink.json = function (level, qualifier, label, body) { var header = { when: this.Date.now(), pid: process.pid, level: level, qualifier: qualifier, label: label, qualified: qualifier + '#' + label } if (triage(LEVEL[level], header, body, this.properties)) { for (var key in system) { header[key] = system[key] } for (var key in body) { header[key] = body[key] } this.queue.push(entry) } } sink.json = function (level, qualifier, label, body) { this.queue.push({ level: level, qualifier: qualifier, label: label, body: body, system: this.properties }) } sink.setTriage(function (level, header, body, system, append) { append.header = header append.body = body append.system = system return true }) */
/* eslint-disable no-unused-expressions */ 'use strict'; const Promise = require('bluebird'); const expect = require('chai').expect; const chai = require('chai') .use(require('chai-http')); const server = require('../server/server'); const cpx = require('cpx'); const {fromGlobalId} = require('graphql-relay'); const gql = require('graphql-tag'); // var _ = require('lodash'); describe('Pagination', () => { it('should query first 2 entities', () => { const query = gql `{ viewer { sites(first: 2) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id name } cursor } } } }`; return chai.request(server) .post('/graphql') .set('Authorization', 'jHLCT0e7rup6pPXOtzC9TvM0ov68DnmfwrGqJcKykg929gjC63I281GfZwqlRzVh') .send({ query, }) .then((res) => { expect(res).to.have.status(200); expect(res.body.data.viewer.sites).not.to.equal(null); expect(res.body.data.viewer.sites.edges.length).to.equal(2); expect(res.body.data.viewer.sites.totalCount).to.equal(3); }); }); it('should query entity after cursor', () => { const query = gql `{ viewer { sites(after: "Y29ubmVjdGlvbi4x", first: 1) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id name } cursor } } } }`; return chai.request(server) .post('/graphql') .set('Authorization', 'jHLCT0e7rup6pPXOtzC9TvM0ov68DnmfwrGqJcKykg929gjC63I281GfZwqlRzVh') .send({ query, }) .then((res) => { expect(res).to.have.status(200); res = res.body.data; expect(res.viewer.sites.totalCount).to.equal(3); expect(res.viewer.sites.edges.length).to.be.above(0); expect(fromGlobalId(res.viewer.sites.edges[0].node.id).id).to.equal('2'); expect(res.viewer.sites.pageInfo.hasNextPage).to.be.true; }); }); it('should query related entity on edge', () => { const query = gql `{ viewer { sites (after: "U2l0ZTox", first: 1) { pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id name books { totalCount edges { node { name } } } } cursor } } } }`; return chai.request(server) .post('/graphql') .set('Authorization', 'jHLCT0e7rup6pPXOtzC9TvM0ov68DnmfwrGqJcKykg929gjC63I281GfZwqlRzVh') .send({ query, }) .then((res) => { expect(res).to.have.status(200); res = res.body.data; expect(res.viewer.sites.edges[0].node.name).to.equal('Site B of owner 5'); expect(res.viewer.sites.edges[0].node.books.totalCount).to.be.above(0); expect(res.viewer.sites.edges[0].cursor).not.to.be.empty; }); }); });
/** * Module dependencies */ var pkg = require('../package'); var map = require('map'); /** * hyperImg */ pkg.directive('hyperImg', [ 'hyper', 'hyperStatus', function(hyper, status) { return { scope: true, restrict: 'A', link: function($scope, elem, attrs) { status.loading(elem); hyper.get(attrs.hyperImg, $scope, function(value) { var isLoaded = status.isLoaded(value); var src = isLoaded ? (value.src || value.href || value) : ''; var title = isLoaded ? (value.title || value.alt || '') : ''; if (angular.isArray(src)) { var srcset = map(src, function(img) { return img.src + ' ' + (img.size || ''); }).join(', '); elem.prop('srcset', srcset); src = src[0].src; } elem.prop('src', src); elem.prop('alt', title); if (isLoaded) return status.loaded(elem); return status.undef(elem); }); } }; } ]);
angular.module('restaurantPOS', ['ui.router', 'ui.materialize']) .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '/', templateUrl:'/views/landingpage.html', controller: 'MainCtrl' }) .state('search', { url: '/search', templateUrl: '/views/search.html', controller: 'MainCtrl' }) .state('jobs', { url: '/jobs', templateUrl: '/views/jobs.html', params: { jobs: null }, controller: 'JobsCtrl' }) .state('careers', { url: '/careers', templateUrl: '/views/careers.html', params: { careers: null }, controller: 'CareersCtrl' }) .state('companies', { url: '/companies', templateUrl: '/views/companies.html', params: { companies: null }, controller: 'CompaniesCtrl' }) .state('login', { url: '/login', templateUrl: '/views/login.html', controller: 'MainCtrl' }) .state('register', { url: '/register', templateUrl: '/views/register.html', controller: 'MainCtrl' }) .state('profile', { url: '/profile', views: { '': { templateUrl: '/views/profile.html', controller: 'ProfileCtrl' }, 'myjobs@profile': { templateUrl: '/views/myjobs.html', controller: 'MyJobsCtrl' } } }) .state('jobdetails', { url: '/jobdetails', templateUrl: '/views/jobdetails.html', params: { details: null }, controller: 'JobDetailCtrl' }) .state('logout', { url: '/logout', controller: function($window, $state) { // User.logout(); $state.go('logout'); $window.location.reload(); } }) $locationProvider.html5Mode(true); }])
/* *********************************************************** * This file was automatically generated on 2014-12-10. * * * * Bindings Version 2.0.4 * * * * If you have a bugfix for this file and want to commit it, * * please fix the bug in the generator. You can find a link * * to the generator git on tinkerforge.com * *************************************************************/ var Device = require('./Device'); BrickletSegmentDisplay4x7.DEVICE_IDENTIFIER = 237; BrickletSegmentDisplay4x7.CALLBACK_COUNTER_FINISHED = 5; BrickletSegmentDisplay4x7.FUNCTION_SET_SEGMENTS = 1; BrickletSegmentDisplay4x7.FUNCTION_GET_SEGMENTS = 2; BrickletSegmentDisplay4x7.FUNCTION_START_COUNTER = 3; BrickletSegmentDisplay4x7.FUNCTION_GET_COUNTER_VALUE = 4; BrickletSegmentDisplay4x7.FUNCTION_GET_IDENTITY = 255; function BrickletSegmentDisplay4x7(uid, ipcon) { //Device for controling four 7-segment displays /* Creates an object with the unique device ID *uid* and adds it to the IP Connection *ipcon*. */ Device.call(this, this, uid, ipcon); BrickletSegmentDisplay4x7.prototype = Object.create(Device); this.responseExpected = {}; this.callbackFormats = {}; this.APIVersion = [2, 0, 0]; this.responseExpected[BrickletSegmentDisplay4x7.FUNCTION_SET_SEGMENTS] = Device.RESPONSE_EXPECTED_FALSE; this.responseExpected[BrickletSegmentDisplay4x7.FUNCTION_GET_SEGMENTS] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE; this.responseExpected[BrickletSegmentDisplay4x7.FUNCTION_START_COUNTER] = Device.RESPONSE_EXPECTED_FALSE; this.responseExpected[BrickletSegmentDisplay4x7.FUNCTION_GET_COUNTER_VALUE] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE; this.responseExpected[BrickletSegmentDisplay4x7.CALLBACK_COUNTER_FINISHED] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE; this.responseExpected[BrickletSegmentDisplay4x7.FUNCTION_GET_IDENTITY] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE; this.callbackFormats[BrickletSegmentDisplay4x7.CALLBACK_COUNTER_FINISHED] = ''; this.setSegments = function(segments, brightness, colon, returnCallback, errorCallback) { /* The 7-segment display can be set with bitmaps. Every bit controls one segment: .. image:: /Images/Bricklets/bricklet_segment_display_4x7_bit_order.png :scale: 100 % :alt: Bit order of one segment :align: center For example to set a "5" you would want to activate segments 0, 2, 3, 5 and 6. This is represented by the number 0b01101101 = 0x6d = 109. The brightness can be set between 0 (dark) and 7 (bright). The colon parameter turns the colon of the display on or off. */ this.ipcon.sendRequest(this, BrickletSegmentDisplay4x7.FUNCTION_SET_SEGMENTS, [segments, brightness, colon], 'B4 B ?', '', returnCallback, errorCallback); }; this.getSegments = function(returnCallback, errorCallback) { /* Returns the segment, brightness and color data as set by :func:`SetSegments`. */ this.ipcon.sendRequest(this, BrickletSegmentDisplay4x7.FUNCTION_GET_SEGMENTS, [], '', 'B4 B ?', returnCallback, errorCallback); }; this.startCounter = function(valueFrom, valueTo, increment, length, returnCallback, errorCallback) { /* Starts a counter with the *from* value that counts to the *to* value with the each step incremented by *increment*. The *length* of the increment is given in ms. Example: If you set *from* to 0, *to* to 100, *increment* to 1 and *length* to 1000, a counter that goes from 0 to 100 with 1 second pause between each increment will be started. The maximum values for *from*, *to* and *increment* is 9999, the minimum value is -999. You can stop the counter at every time by calling :func:`SetSegments`. */ this.ipcon.sendRequest(this, BrickletSegmentDisplay4x7.FUNCTION_START_COUNTER, [valueFrom, valueTo, increment, length], 'h h h I', '', returnCallback, errorCallback); }; this.getCounterValue = function(returnCallback, errorCallback) { /* Returns the counter value that is currently shown on the display. If there is no counter running a 0 will be returned. */ this.ipcon.sendRequest(this, BrickletSegmentDisplay4x7.FUNCTION_GET_COUNTER_VALUE, [], '', 'H', returnCallback, errorCallback); }; this.getIdentity = function(returnCallback, errorCallback) { /* Returns the UID, the UID where the Bricklet is connected to, the position, the hardware and firmware version as well as the device identifier. The position can be 'a', 'b', 'c' or 'd'. The device identifier numbers can be found :ref:`here <device_identifier>`. |device_identifier_constant| */ this.ipcon.sendRequest(this, BrickletSegmentDisplay4x7.FUNCTION_GET_IDENTITY, [], '', 's8 s8 c B3 B3 H', returnCallback, errorCallback); }; } module.exports = BrickletSegmentDisplay4x7;
// Introducing Scope // // Understanding scope is critical to understanding many JavaScript // patterns. In this video I'll show you a few examples of where scope // is used, and how to think about scope. // Scope는 변수를 look-up한다. // 여기서 a, b var a = 10; function add () { var b = 20; return a + b; } // IIFE (function () { // dynamically scoped: add 함수의 변수 a가 적용되지 않음 var a = 20; var result = add (); console.log('result: ', result); }()); // Scope look-up process는 prototype look-up 프로세스와 유사함 // 1) 자바스크립트의 Lexically scoped // static scoped
'use strict'; import { assert, expect, should, eventually } from 'chai'; import taxonomy from '../../src/processor/taxonomy'; describe('Processor: Taxonomy', () => { it('Up & Running', () => { expect(taxonomy).to.be.ok; }); });
angular.module('starter.services', ['ngResource']) /** * A simple example service that returns some data. */ .factory('ListService',['$resource', function($resource) { return $resource('http://115.113.151.200:8081/user/maphook/mobile/list_trends\\/', {}, { query: {method:'GET', params:{}, isArray:false, cache:true} }) }]) .factory('DetailService',['$resource', function($resource) { return $resource('http://115.113.151.200:8081/view_trend/:hookId/:hookType/', {}, { query: {method:'GET', params:{}, isArray:false, cache:true} }); }]);
version https://git-lfs.github.com/spec/v1 oid sha256:90aa6e5218a18ecb6725bef9d52a224dc5f478ffb489b093707fd1d41099fd47 size 368416
var expect = require('chai').expect; var test = require('./lib/test.js'); describe('Eval', function() { it('should support eval tags', function() { test({ fixture: 'Eval', done: function($) { expect($('strong').length).to.equal(10); } }); }); it('should expose current data context as data', function() { test({ fixture: 'Eval within for each', data: { items: [ 'Item 1', 'Item 2', ] }, done: function($) { expect($('strong')[0].textContent).to.equal('0: Item 1'); expect($('strong')[1].textContent).to.equal('1: Item 2'); expect($('strong')[2].textContent).to.equal('2: Item 3'); } }); }); it('should allow reassignment of data', function() { test({ fixture: 'Eval with reassignment', data: { name: 'Original' }, done: function($) { expect($('h1').text()).to.equal('New'); } }); }); });
// All code points with the `Diacritic` property as per Unicode v6.1.0: [ 0x5E, 0x60, 0xA8, 0xAF, 0xB4, 0xB7, 0xB8, 0x2B0, 0x2B1, 0x2B2, 0x2B3, 0x2B4, 0x2B5, 0x2B6, 0x2B7, 0x2B8, 0x2B9, 0x2BA, 0x2BB, 0x2BC, 0x2BD, 0x2BE, 0x2BF, 0x2C0, 0x2C1, 0x2C2, 0x2C3, 0x2C4, 0x2C5, 0x2C6, 0x2C7, 0x2C8, 0x2C9, 0x2CA, 0x2CB, 0x2CC, 0x2CD, 0x2CE, 0x2CF, 0x2D0, 0x2D1, 0x2D2, 0x2D3, 0x2D4, 0x2D5, 0x2D6, 0x2D7, 0x2D8, 0x2D9, 0x2DA, 0x2DB, 0x2DC, 0x2DD, 0x2DE, 0x2DF, 0x2E0, 0x2E1, 0x2E2, 0x2E3, 0x2E4, 0x2E5, 0x2E6, 0x2E7, 0x2E8, 0x2E9, 0x2EA, 0x2EB, 0x2EC, 0x2ED, 0x2EE, 0x2EF, 0x2F0, 0x2F1, 0x2F2, 0x2F3, 0x2F4, 0x2F5, 0x2F6, 0x2F7, 0x2F8, 0x2F9, 0x2FA, 0x2FB, 0x2FC, 0x2FD, 0x2FE, 0x2FF, 0x300, 0x301, 0x302, 0x303, 0x304, 0x305, 0x306, 0x307, 0x308, 0x309, 0x30A, 0x30B, 0x30C, 0x30D, 0x30E, 0x30F, 0x310, 0x311, 0x312, 0x313, 0x314, 0x315, 0x316, 0x317, 0x318, 0x319, 0x31A, 0x31B, 0x31C, 0x31D, 0x31E, 0x31F, 0x320, 0x321, 0x322, 0x323, 0x324, 0x325, 0x326, 0x327, 0x328, 0x329, 0x32A, 0x32B, 0x32C, 0x32D, 0x32E, 0x32F, 0x330, 0x331, 0x332, 0x333, 0x334, 0x335, 0x336, 0x337, 0x338, 0x339, 0x33A, 0x33B, 0x33C, 0x33D, 0x33E, 0x33F, 0x340, 0x341, 0x342, 0x343, 0x344, 0x345, 0x346, 0x347, 0x348, 0x349, 0x34A, 0x34B, 0x34C, 0x34D, 0x34E, 0x350, 0x351, 0x352, 0x353, 0x354, 0x355, 0x356, 0x357, 0x35D, 0x35E, 0x35F, 0x360, 0x361, 0x362, 0x374, 0x375, 0x37A, 0x384, 0x385, 0x483, 0x484, 0x485, 0x486, 0x487, 0x559, 0x591, 0x592, 0x593, 0x594, 0x595, 0x596, 0x597, 0x598, 0x599, 0x59A, 0x59B, 0x59C, 0x59D, 0x59E, 0x59F, 0x5A0, 0x5A1, 0x5A3, 0x5A4, 0x5A5, 0x5A6, 0x5A7, 0x5A8, 0x5A9, 0x5AA, 0x5AB, 0x5AC, 0x5AD, 0x5AE, 0x5AF, 0x5B0, 0x5B1, 0x5B2, 0x5B3, 0x5B4, 0x5B5, 0x5B6, 0x5B7, 0x5B8, 0x5B9, 0x5BA, 0x5BB, 0x5BC, 0x5BD, 0x5BF, 0x5C1, 0x5C2, 0x5C4, 0x64B, 0x64C, 0x64D, 0x64E, 0x64F, 0x650, 0x651, 0x652, 0x657, 0x658, 0x6DF, 0x6E0, 0x6E5, 0x6E6, 0x6EA, 0x6EB, 0x6EC, 0x730, 0x731, 0x732, 0x733, 0x734, 0x735, 0x736, 0x737, 0x738, 0x739, 0x73A, 0x73B, 0x73C, 0x73D, 0x73E, 0x73F, 0x740, 0x741, 0x742, 0x743, 0x744, 0x745, 0x746, 0x747, 0x748, 0x749, 0x74A, 0x7A6, 0x7A7, 0x7A8, 0x7A9, 0x7AA, 0x7AB, 0x7AC, 0x7AD, 0x7AE, 0x7AF, 0x7B0, 0x7EB, 0x7EC, 0x7ED, 0x7EE, 0x7EF, 0x7F0, 0x7F1, 0x7F2, 0x7F3, 0x7F4, 0x7F5, 0x818, 0x819, 0x8E4, 0x8E5, 0x8E6, 0x8E7, 0x8E8, 0x8E9, 0x8EA, 0x8EB, 0x8EC, 0x8ED, 0x8EE, 0x8EF, 0x8F0, 0x8F1, 0x8F2, 0x8F3, 0x8F4, 0x8F5, 0x8F6, 0x8F7, 0x8F8, 0x8F9, 0x8FA, 0x8FB, 0x8FC, 0x8FD, 0x8FE, 0x93C, 0x94D, 0x951, 0x952, 0x953, 0x954, 0x971, 0x9BC, 0x9CD, 0xA3C, 0xA4D, 0xABC, 0xACD, 0xB3C, 0xB4D, 0xBCD, 0xC4D, 0xCBC, 0xCCD, 0xD4D, 0xDCA, 0xE47, 0xE48, 0xE49, 0xE4A, 0xE4B, 0xE4C, 0xE4E, 0xEC8, 0xEC9, 0xECA, 0xECB, 0xECC, 0xF18, 0xF19, 0xF35, 0xF37, 0xF39, 0xF3E, 0xF3F, 0xF82, 0xF83, 0xF84, 0xF86, 0xF87, 0xFC6, 0x1037, 0x1039, 0x103A, 0x1087, 0x1088, 0x1089, 0x108A, 0x108B, 0x108C, 0x108D, 0x108F, 0x109A, 0x109B, 0x17C9, 0x17CA, 0x17CB, 0x17CC, 0x17CD, 0x17CE, 0x17CF, 0x17D0, 0x17D1, 0x17D2, 0x17D3, 0x17DD, 0x1939, 0x193A, 0x193B, 0x1A75, 0x1A76, 0x1A77, 0x1A78, 0x1A79, 0x1A7A, 0x1A7B, 0x1A7C, 0x1A7F, 0x1B34, 0x1B44, 0x1B6B, 0x1B6C, 0x1B6D, 0x1B6E, 0x1B6F, 0x1B70, 0x1B71, 0x1B72, 0x1B73, 0x1BAA, 0x1BAB, 0x1C36, 0x1C37, 0x1C78, 0x1C79, 0x1C7A, 0x1C7B, 0x1C7C, 0x1C7D, 0x1CD0, 0x1CD1, 0x1CD2, 0x1CD3, 0x1CD4, 0x1CD5, 0x1CD6, 0x1CD7, 0x1CD8, 0x1CD9, 0x1CDA, 0x1CDB, 0x1CDC, 0x1CDD, 0x1CDE, 0x1CDF, 0x1CE0, 0x1CE1, 0x1CE2, 0x1CE3, 0x1CE4, 0x1CE5, 0x1CE6, 0x1CE7, 0x1CE8, 0x1CED, 0x1CF4, 0x1D2C, 0x1D2D, 0x1D2E, 0x1D2F, 0x1D30, 0x1D31, 0x1D32, 0x1D33, 0x1D34, 0x1D35, 0x1D36, 0x1D37, 0x1D38, 0x1D39, 0x1D3A, 0x1D3B, 0x1D3C, 0x1D3D, 0x1D3E, 0x1D3F, 0x1D40, 0x1D41, 0x1D42, 0x1D43, 0x1D44, 0x1D45, 0x1D46, 0x1D47, 0x1D48, 0x1D49, 0x1D4A, 0x1D4B, 0x1D4C, 0x1D4D, 0x1D4E, 0x1D4F, 0x1D50, 0x1D51, 0x1D52, 0x1D53, 0x1D54, 0x1D55, 0x1D56, 0x1D57, 0x1D58, 0x1D59, 0x1D5A, 0x1D5B, 0x1D5C, 0x1D5D, 0x1D5E, 0x1D5F, 0x1D60, 0x1D61, 0x1D62, 0x1D63, 0x1D64, 0x1D65, 0x1D66, 0x1D67, 0x1D68, 0x1D69, 0x1D6A, 0x1DC4, 0x1DC5, 0x1DC6, 0x1DC7, 0x1DC8, 0x1DC9, 0x1DCA, 0x1DCB, 0x1DCC, 0x1DCD, 0x1DCE, 0x1DCF, 0x1DFD, 0x1DFE, 0x1DFF, 0x1FBD, 0x1FBF, 0x1FC0, 0x1FC1, 0x1FCD, 0x1FCE, 0x1FCF, 0x1FDD, 0x1FDE, 0x1FDF, 0x1FED, 0x1FEE, 0x1FEF, 0x1FFD, 0x1FFE, 0x2CEF, 0x2CF0, 0x2CF1, 0x2E2F, 0x302A, 0x302B, 0x302C, 0x302D, 0x302E, 0x302F, 0x3099, 0x309A, 0x309B, 0x309C, 0x30FC, 0xA66F, 0xA67C, 0xA67D, 0xA67F, 0xA6F0, 0xA6F1, 0xA717, 0xA718, 0xA719, 0xA71A, 0xA71B, 0xA71C, 0xA71D, 0xA71E, 0xA71F, 0xA720, 0xA721, 0xA788, 0xA7F8, 0xA7F9, 0xA8C4, 0xA8E0, 0xA8E1, 0xA8E2, 0xA8E3, 0xA8E4, 0xA8E5, 0xA8E6, 0xA8E7, 0xA8E8, 0xA8E9, 0xA8EA, 0xA8EB, 0xA8EC, 0xA8ED, 0xA8EE, 0xA8EF, 0xA8F0, 0xA8F1, 0xA92B, 0xA92C, 0xA92D, 0xA92E, 0xA953, 0xA9B3, 0xA9C0, 0xAA7B, 0xAABF, 0xAAC0, 0xAAC1, 0xAAC2, 0xAAF6, 0xABEC, 0xABED, 0xFB1E, 0xFE20, 0xFE21, 0xFE22, 0xFE23, 0xFE24, 0xFE25, 0xFE26, 0xFF3E, 0xFF40, 0xFF70, 0xFF9E, 0xFF9F, 0xFFE3, 0x110B9, 0x110BA, 0x11133, 0x11134, 0x111C0, 0x116B6, 0x116B7, 0x16F8F, 0x16F90, 0x16F91, 0x16F92, 0x16F93, 0x16F94, 0x16F95, 0x16F96, 0x16F97, 0x16F98, 0x16F99, 0x16F9A, 0x16F9B, 0x16F9C, 0x16F9D, 0x16F9E, 0x16F9F, 0x1D167, 0x1D168, 0x1D169, 0x1D16D, 0x1D16E, 0x1D16F, 0x1D170, 0x1D171, 0x1D172, 0x1D17B, 0x1D17C, 0x1D17D, 0x1D17E, 0x1D17F, 0x1D180, 0x1D181, 0x1D182, 0x1D185, 0x1D186, 0x1D187, 0x1D188, 0x1D189, 0x1D18A, 0x1D18B, 0x1D1AA, 0x1D1AB, 0x1D1AC, 0x1D1AD ];
$(function(){ $("#addItem").click(function() { $("#schedulerItems").append(template); }); $(".deleteItem").click(function(){ $(this).parent().remove(); }); }); var template = $("#row").html();
/** * Export environment variables. */ const process = require('process'); const envVars = process.env; const env = { DB_PASSWORD: envVars.POSTGRES_PASSWORD, DB_USER: envVars.POSTGRES_USER, DB_DATABASE: envVars.POSTGRES_DATABASE, DB_HOST: envVars.POSTGRES_HOST, DB_PORT: envVars.POSTGRES_PORT, }; Object.keys(env).forEach(name => { if (env[name] === undefined) { throw new Error(`Envrionment property '${name}' is not specified.`); } }); module.exports = env;
/* * This file is part of the Sententiaregum project. * * (c) Maximilian Bosch <[email protected]> * (c) Ben Bieler <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict'; import createStoreRefreshHandler from './util/createStoreRefreshStateHandler'; import EventEmitter from 'events'; import connect from './util/connect'; import connector from './connector'; import invariant from 'invariant'; import parseArrayBrackets from './util/parseArrayBrackets'; /** * Creates a flux store. * * @param {Object} subscriptions The configured subscriptions. * @param {*} initialState The initial state or callback handler. * * @returns {{getState:Function,getStateValue:Function,getToken:Function}} */ export default (subscriptions, initialState) => { let state = initialState; const emitter = new EventEmitter(); let tokens = connectSubscriptions(subscriptions, []); /** * Factory which creates a function that updates state if something changed. * * @returns {Function} The change handler. */ function getStateSaveHandler() { return (newState, emitter) => { // refresh store internals state = newState; tokens = connectSubscriptions(subscriptions, Object.values(tokens)); // emit change emitter.emit('change'); }; } /** * Connects subscriptions. * * @param {Object} subscriptions The subscriptions to connect with the store. * @param {Array} oldTokens The old event tokens. * * @returns {Object.<String>} The processed subscriptions represented as tokens. */ function connectSubscriptions(subscriptions, oldTokens) { return connect( Object.keys(subscriptions).reduce((config, eventName) => { const subscription = subscriptions[eventName]; return Object.assign({}, config, { [eventName]: { function: createStoreRefreshHandler(getStateSaveHandler(), emitter, subscription, evaluateState(state)), dependencies: typeof subscription.dependencies === 'undefined' ? subscription.dependencies : [] } }); }, {}), oldTokens ); } /** * Evaluates a property path written as dot notation. * So "foo.bar.baz" will be evaluated as o['foo']['bar']['baz']. * * @param {Array|Object} state The state to evaluate. * @param {String} path The property path. * * @returns {*} The result of the path evaluation. */ function evaluatePropertyPath(state, path) { invariant( Array.isArray(state) || typeof state === 'object', 'To evaluate a property path, the value must be an object or an array!' ); return parseArrayBrackets(path).split('.').reduce((o, i) => { if (typeof o === 'undefined' || typeof o[i] === 'undefined') { return; } return o[i]; }, state); } /** * Evaluates the state inline. * The state might be a lazy callback, so it needs to be checked whether this is true or * the state can be returned as-is. * * @param {*} state The state to evaluate. * * @returns {*} The evaluated state. */ function evaluateState(state) { return typeof state === 'function' ? state() : state; } return new class { /** * Constructor. * Instantiates the class and registers the store's instance at the store<>view connector. * * @returns {void} */ constructor() { connector(this).register(emitter); } /** * Getter for the store's internal state. * The state built by an internal handler will be stored as local variable in the store's scope. * A function might be returned which will be executed lazily when the state needs to be received. * * @returns {*} */ getState() { return state = evaluateState(state); } /** * In a lot of cases a single item of the state is needed, nothing more. * To fulfill this use-case this provider returns a single value of the state and provides * a default value if the item can't be received. * * @param {String} path The property path. * @param {*} defaultValue The default value. * * @returns {*} The value of the state to be fetched. */ getStateValue(path, defaultValue = null) { const search = evaluatePropertyPath(this.getState(), path); if (typeof search === 'undefined') { return defaultValue; } return search; } /** * Provider for a dispatch token. * The store listens to certain actions published by the dispatcher. Every event handler has its own * ID generated by the dispatcher. To declare proper callback dependencies, this token is needed. * * @param {String} eventName The event name to look for. * * @returns {String} */ getToken(eventName) { invariant( eventName in tokens, `A handler for event name "${eventName}" must be registered in this store!` ); return tokens[eventName]; } }; }
function BancoRioTransfer() { this.numero_de_envio = new Date().getTime() * 100; this.rows = []; this.active = false; this.codigos_concepto_transferencia = [ "ALQ", "VAR", "EXP", "CUO", "FAC", "PRE", "SEG", "HON" ]; }; BancoRioTransfer.prototype.fill = function ( cuenta_debito, sucursal_cuenta_debito, tipo_cuenta_debito, numero_cuenta_debito ) { this.cuenta_debito = cuenta_debito;; this.sucursal_cuenta_debito = sucursal_cuenta_debito;; this.tipo_cuenta_debito = tipo_cuenta_debito;; this.numero_cuenta_debito = numero_cuenta_debito; this.active = true; }; BancoRioTransfer.prototype.addRow = function(row) { this.rows.push(row); }; BancoRioTransfer.prototype.getImporteTotal = function() { return this.rows .map(function(node){ return node.getImporte(); }) .reduce(function(sum, importe){ return sum + importe; }, 0.0); } BancoRioTransfer.prototype.getFormattedImporteTotal = function() { return formatImporte(this.getImporteTotal()); } BancoRioTransfer.prototype.getHeader = function() { var elements = [ 'H', this.cuenta_debito, this.sucursal_cuenta_debito, this.tipo_cuenta_debito, pad(this.numero_cuenta_debito, 7), this.getFormattedImporteTotal(), pad(this.numero_de_envio.toString().slice(-7), 7) ]; return elements.join(';') } BancoRioTransfer.prototype.getFooter = function() { var elements = [ 'T', pad(this.rows.length, 4) ]; return elements.join(';') } BancoRioTransfer.prototype.getBody = function() { return this.rows.map(function(node){ return node.getFormattedBody(); }); } BancoRioTransfer.prototype.dump = function() { var content = [] content.push(this.getHeader()); if(this.getBody().length > 0) { content.push(this.getBody().join("\n")); } content.push(this.getFooter()); return content.join("\n"); }
/* Settings file for allowing project to work in different environments. Only make different copies of this file. */ var Settings = { /* server */ host:'localhost', command_port:4000, http_port:8000, redis_port:6379, canvasClient:8084, canvasSource:8082, audio_port:9000, width:320, height:240, logLevel:0, home:[44.646875, -68.95869], ip:'127.0.0.1', udp_port:9000 }; try{ exports.Settings = Settings; } catch(e){}
import * as THREE from 'three'; const vector = new THREE.Vector3(); const quaternion = new THREE.Quaternion(); export default class Entity extends THREE.Mesh { constructor( ...args ) { super( ...args ); this.velocity = new THREE.Vector3(); this.acceleration = new THREE.Vector3(); this.angularVelocity = new THREE.Vector3(); } update( dt ) { this.velocity.addScaledVector( this.acceleration, dt ); this.position.addScaledVector( this.velocity, dt ); vector.copy( this.angularVelocity ).multiplyScalar( dt / 2 ); quaternion.set( vector.x, vector.y, vector.z, 1 ).normalize(); this.quaternion.multiply( quaternion ); } }
var assert = require('chai').assert, PArray = require('..'), when = require('when'), delay = require('when/delay'); describe('has own implementation', function () { Object.getOwnPropertyNames(Array.prototype) .filter(function (name) { return !(name in Object.prototype) }) .forEach(function (name) { it('of ' + name, function () { assert.ok(PArray.prototype.hasOwnProperty(name)); }); }); }); describe('rejects modifying methods', function () { var a = new PArray([1, 2, 3]); function assertReject(promise) { return promise.then( function () { assert.ok(false) }, function () { assert.ok(true) } ); } it('push', function () { return assertReject(a.push(4)); }); it('pop', function () { return assertReject(a.pop()); }); it('push', function () { return assertReject(a.shift()); }); it('unshift', function () { return assertReject(a.unshift(0)); }); it('splice', function () { return when.all([ assertReject(a.splice(0, 1)), assertReject(a.splice(1, 1, 10)) ]); }); }); describe('length', function () { it('for array', function () { return new PArray([1, 2, 3]).length.then(function (length) { assert.equal(length, 3); }); }); it('for promised array', function () { return new PArray(delay(1, [1, 2, 3])).length.then(function (length) { assert.equal(length, 3); }); }); });
'use strict'; /** * Module dependencies. */ var ResponderServer = require('./server') , ResponderClient = require('./client'); /** * Expose modules. */ module.exports = { client: function(){} , server: ResponderServer , library: ResponderClient.source , PrimusResponder: ResponderServer };
module.exports = function(Project) { Project.afterRemote('create', function(ctx, project, next) { ctx.result = { bError: false, message: 'Create project successfully.', result: project } next(); }); // cannot return clean message. // Project.validatesUniquenessOf('name', {message: 'Project name is duplicated'}); // can package to a common class? Project.observe('before save', function(ctx, next) { // check duplication if (ctx.instance && ctx.isNewInstance) { _checkDuplication(ctx.instance, ctx, next); } else if (ctx.data && ctx.isNewInstance) { _checkDuplication(ctx.data, ctx, next); } else if (!ctx.isNewInstance) { // update next(); } else { var err = new Error(); err.statusCode = 422; err.bError = true; err.message = 'No data receieved.'; err.stack = ''; // less info to be sent next(err); } }); var _checkDuplication = function(project, ctx, next) { Project.find({ where: { name: project.name } }, function(err, projects) { if (err) throw err; if (projects.length > 0) { _afterCheck(true, ctx, next); } else { _afterCheck(false, ctx, next); } }); }; var _afterCheck = function(bDuplicated, ctx, next) { if (bDuplicated) { delete ctx.instance; delete ctx.data; var err = new Error(); err.statusCode = 422; err.bError = true; err.message = 'Project name is duplicated'; err.stack = ''; // less info to be sent next(err); } else { next(); } }; Project.execBowerInstall = function(folderUrl, req, res, cb) { Project.app.models.userModel.findById(req.accessToken.userId, function(err, user) { var spawn = require('child_process').spawn; var cmd = spawn('bower', ['install'], { detached: true, // stdio: 'inherit' cwd: __dirname + '/' + folderUrl }); cmd.stdout.on('data', function(data) { console.log('stdout: ' + data); Project.app.io.emit('add new team info', 'USER: ' + user.username + '---> ' + data.toString('utf8')); }); cmd.stderr.on('data', function(data) { console.log('stderr: ' + data); Project.app.io.emit('add new team info', 'USER: ' + user.username + '---> ' + data.toString('utf8')); }); cmd.on('close', function(code) { console.log('child process exited with code ' + code); if (code !== -2) { cb(null, { bError: false, message: 'Finish bower install', result: { code: code } }); } }); cmd.on('error', function(err) { cb(null, { bError: true, message: 'Fail bower install', result: { error: err } }); }); }); }; Project.remoteMethod('execBowerInstall', { http: { path: '/execBowerInstall', verb: 'post' }, accepts: [{ arg: 'folderUrl', type: 'String' }, { arg: 'req', type: 'object', 'http': { source: 'req' } }, { arg: 'res', type: 'object', 'http': { source: 'res' } }], returns: { arg: 'result', type: 'Object' } }); Project.execNpmInstall = function(folderUrl, req, res, cb) { // get user info Project.app.models.userModel.findById(req.accessToken.userId, function(err, user) { var spawn = require('child_process').spawn; var cmd = spawn('npm', ['install'], { detached: true, // stdio: 'inherit' cwd: __dirname + '/' + folderUrl }); cmd.stdout.on('data', function(data) { console.log('stdout: ' + data); // TODO: add user info Project.app.io.emit('add new team info', 'USER: ' + user.username + '---> ' + data.toString('utf8')); }); cmd.stderr.on('data', function(data) { console.log('stderr: ' + data); Project.app.io.emit('add new team info', 'USER: ' + user.username + '---> ' + data.toString('utf8')); }); cmd.on('close', function(code) { console.log('child process exited with code ' + code); if (code !== -2) { cb(null, { bError: false, message: 'Finish npm install', result: { code: code } }); } }); cmd.on('error', function(err) { cb(null, { bError: true, message: 'Fail bower install', result: { error: err } }); }); }); }; Project.remoteMethod('execNpmInstall', { http: { path: '/execNpmInstall', verb: 'post' }, accepts: [{ arg: 'folderUrl', type: 'String' }, { arg: 'req', type: 'object', 'http': { source: 'req' } }, { arg: 'res', type: 'object', 'http': { source: 'res' } }], returns: { arg: 'result', type: 'Object' } }); };
/* Load configuration variables */ // Local environment require("dotenv").config(); // Docker environment if (process.env.FGLAB_PORT_5000_TCP_ADDR) { process.env.FGLAB_URL = "http://" + process.env.FGLAB_PORT_5000_TCP_ADDR + ":" + process.env.FGLAB_PORT_5000_TCP_PORT; }
kiso.geom.Point = kiso.Class(/** @lends kiso.geom.Point.prototype */{ _x: 0, _y: 0, /** * @constructs * @description Create a new <code>Point</code> from another <code>Point</code> or from XY coordinates. * @param {Number|Point} xOrPoint Either another <code>Point</code> or X coordinate * @param {Number} [y] Y coordinate * If a <code>Point</code> is specified then the X and Y are copied from it to the new point. * If both X and Y are specified then a new point is created with those coordinates. */ initialize: function(xOrPoint, y) { if (arguments.length == 2) { this.setXY(xOrPoint, y); } else if (arguments.length == 1) { this.setXY(xOrPoint._x, xOrPoint._y); } else { this.setXY(0, 0); } }, /** * @description Set the coordinates of the the point. * @param {Number} x The X coordinate * @param {Number} y The Y coordinate */ setXY: function(x, y) { this._x = x; this._y = y; }, /** * @description Get the X coordinate * @returns {Number} The X coordinate. */ getX: function() { return this._x; }, /** * @description Get the Y coordinate * @returns {Number} The Y coordinate. */ getY: function() { return this._y; }, /** * @description Creates a copy of the point * Clone creates a new point with the same X and Y coordinates. */ clone: function() { return new kiso.geom.Point(this); }, /** * @description Returns true if the given point has the same X and Y coordinates. * @returns {Boolean} True if the given point has the same X and Y coordinates. */ equals: function(point) { return (this._x === point._x & this._y === point._y); }, /** * @description Determines if the point is to the left of the vector from <code>point0</code> * to <code>point1</code>, where the order of the points determines the direction of the * vector. * @param {Point} point0 The starting point of the vector * @param {Point} point1 The end point of the vector * @returns {Boolean} True if the point is left of the vector from <code>point0</code> * to <code>point1</code>. * @see kiso.geom.Point#isRightOfVector */ isLeftOfVector: function(point0, point1) { return ( (point0._x - this._x)*(point1._y - this._y) >= (point1._x - this._x)*(point0._y - this._y) ); }, //TODO: Check formulas for point being on line (add flag to include/exclude case?) /** * @description Determines if the point is to the right of the vector from <code>point0</code> * to <code>point1</code>, where the order of the points determines the direction of the * vector. * @param {Point} point0 The starting point of the vector * @param {Point} point1 The end point of the vector * @returns {Boolean} True if the point is right of the vector from <code>point0</code> * to <code>point1</code>. * @see kiso.geom.Point#isLeftOfVector */ isRightOfVector: function(point0, point1) { return ( (point0._x - this._x)*(point1._y - this._y) <= (point1._x - this._x)*(point0._y - this._y) ); }, /** * @description Computes the slope of the line from the point to the given point. * @param {Point} point The ending point of the line to compute the slope of. * @returns {Number} The slope of the line from the point to the given point. * Note that if the line is vertical (i.e. both Xs are the same) the slope of the line will be * <code>Infinity</code>. */ slopeTo: function(point) { return (point._y - this._y)/(point._x - this._x); }, /** * @description Computes the square of the distance to the given point. * @param {Point} point The point to compute the distance to. * @returns {Number} The square of the distance to the given point. * @see kiso.geom.Point#distanceTo */ distanceSquaredTo: function(point) { return (point._x - this._x)*(point._x - this._x) + (point._y - this._y)*(point._y - this._y); }, /** * @description Computes the distance to the given point. * @param {Point} point The point to compute the distance to. * @returns {Number} The distance to the given point. * This function requires taking a square root and so is slower than computing the square of the * distance. * @see kiso.geom.Point#distanceSquaredTo */ distanceTo: function(point) { return Math.sqrt(this.distanceSquaredTo(point)); }, /** * @description Computes the square of the shortest distance to the line connecting the two specified points. * @param {Point} point0 The first end point of the line * @param {Point} point1 The second endo point of the line * @returns {Number} The square of the distance to the line formed by the two specified points. * @see distanceToLine */ distanceSquaredToLine: function(point0, point1) { var distance; if (point0._x == point1._x && point0._y == point1._y) { distance = this.distanceSquaredTo(point0); } else { distance = (point1._x - point0._x)*(point0._y - this._y) - (point0._x - this._x)*(point1._y - point0._y); distance = distance*distance/point0.distanceSquaredTo(point1); } return distance; }, /** * @description Computes the shortest distance to the line connecting the two specified points. * @param {Point} point0 The first end point of the line * @param {Point} point1 The second endo point of the line * @returns {Number} The distance to the line formed by the two specified points. * Note that this function requres taking a square root. * @see distanceSquaredToLine */ distanceToLine: function(point0, point1) { return Math.sqrt(this.distanceSquaredToLine(point0, point1)); } });
'use babel' import {React, update} from 'react-for-atom'; export default React.createClass({ getInitialState: function() { return { text: "" }; }, componentDidMount: function() { this.inputField.focus(); }, componentDidUpdate: function(prevProps) { if (prevProps != this.props) { this.setState(update(this.state, { text: {$set: ""} })); } }, answer: function() { this.props.onAnswered({value: this.state.text != "" ? this.state.text : this.props.default}) }, render: function() { return ( <div className="yeoman-input-prompt"> <input type="text" ref={elem => this.inputField = elem} placeholder={`Default value: ${this.props.default}`} className="native-key-bindings" value={this.state.text} onChange={(e) => this.setState({text: e.target.value})} onKeyPress={e => e.key == "Enter" && this.answer()} /> <button type="button" className="validate" onClick={() => this.answer()}>Validate</button> </div> ); } });
// ./src/reducers/index.js import { combineReducers } from 'redux'; import books from './bookReducers' export default combineReducers({ books: books, // More reducers if there are // can go here });
import Ember from 'ember'; import DS from 'ember-data'; export default DS.RESTSerializer.extend({ primaryKey: 'objectId', extractArray: function (store, primaryType, payload) { var namespacedPayload = {}; namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.results; return this._super(store, primaryType, namespacedPayload); }, extractSingle: function (store, primaryType, payload, recordId) { var namespacedPayload = {}; namespacedPayload[primaryType.typeKey] = payload; // this.normalize(primaryType, payload); return this._super(store, primaryType, namespacedPayload, recordId); }, typeForRoot: function (key) { return Ember.String.dasherize(Ember.String.singularize(key)); }, /** * Because Parse only returns the updatedAt/createdAt values on updates * we have to intercept it here to assure that the adapter knows which * record ID we are dealing with (using the primaryKey). */ extract: function (store, type, payload, id, requestType) { if (id !== null && ( 'updateRecord' === requestType || 'deleteRecord' === requestType )) { payload[this.get('primaryKey')] = id; } return this._super(store, type, payload, id, requestType); }, /** * Extracts count from the payload so that you can get the total number * of records in Parse if you're using skip and limit. */ extractMeta: function (store, type, payload) { if (payload && payload.count) { store.setMetadataFor(type, {count: payload.count}); delete payload.count; } }, /** * Special handling for the Date objects inside the properties of * Parse responses. */ normalizeAttributes: function (type, hash) { type.eachAttribute(function (key, meta) { if ('date' === meta.type && 'object' === Ember.typeOf(hash[key]) && hash[key].iso) { hash[key] = hash[key].iso; //new Date(hash[key].iso).toISOString(); } }); this._super(type, hash); }, /** * Special handling of the Parse relation types. In certain * conditions there is a secondary query to retrieve the "many" * side of the "hasMany". */ normalizeRelationships: function (type, hash) { var store = this.get('store'), serializer = this; type.eachRelationship(function (key, relationship) { var options = relationship.options; // Handle the belongsTo relationships if (hash[key] && 'belongsTo' === relationship.kind) { hash[key] = hash[key].objectId; } // Handle the hasMany relationships if (hash[key] && 'hasMany' === relationship.kind) { // If this is a Relation hasMany then we need to supply // the links property so the adapter can async call the // relationship. // The adapter findHasMany has been overridden to make use of this. if (options.relation) { // hash[key] contains the response of Parse.com: eg {__type: Relation, className: MyParseClassName} // this is an object that make ember-data fail, as it expects nothing or an array ids that represent the records hash[key] = []; // ember-data expects the link to be a string // The adapter findHasMany will parse it if (!hash.links) { hash.links = {}; } hash.links[key] = JSON.stringify({typeKey: relationship.type.typeKey, key: key}); } if (options.array) { // Parse will return [null] for empty relationships if (hash[key].length && hash[key]) { hash[key].forEach(function (item, index, items) { // When items are pointers we just need the id // This occurs when request was made without the include query param. if ('Pointer' === item.__type) { items[index] = item.objectId; } else { // When items are objects we need to clean them and add them to the store. // This occurs when request was made with the include query param. delete item.__type; delete item.className; item.id = item.objectId; delete item.objectId; item.type = relationship.type; serializer.normalizeAttributes(relationship.type, item); serializer.normalizeRelationships(relationship.type, item); store.push(relationship.type, item); } }); } } } }, this); this._super(type, hash); }, serializeIntoHash: function (hash, type, snapshot, options) { Ember.merge(hash, this.serialize(snapshot, options)); }, serializeAttribute: function (snapshot, json, key, attribute) { // These are Parse reserved properties and we won't send them. if ('createdAt' === key || 'updatedAt' === key || 'emailVerified' === key || 'sessionToken' === key ) { delete json[key]; } else { this._super(snapshot, json, key, attribute); } }, serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key, belongsToId = snapshot.belongsTo(key, {id: true}); if (belongsToId) { json[key] = { '__type': 'Pointer', 'className': this.parseClassName(relationship.type.typeKey), 'objectId': belongsToId }; } }, parseClassName: function (key) { if ('parseUser' === key || 'parse-user' === key) { return '_User'; } else { return Ember.String.capitalize(Ember.String.camelize(key)); } }, /** * Serialize Has Many * * Array pointers are better off * being handled without the * 'AddUnique'/'Remove' operations. * It seems that model.save() sends * the whole array anyways when saving * parent objects. * * More importantly, objects were not * being removed from arrays because * the 'AddUnique' op was added * when it shouldn't be. * * @param snapshot * @param json * @param relationship */ serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key, hasMany = snapshot.hasMany(key), options = relationship.options, _this = this; if (hasMany && hasMany.get('length') > 0) { json[key] = []; if (options.relation) { json[key].__op = 'AddRelation'; } hasMany.forEach(function (child) { json[key].push({ '__type': 'Pointer', 'className': _this.parseClassName(child.type.typeKey), 'objectId': child.id }); }); } else { json[key] = []; } } });
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('trivium', params.trivium_id); } });
//Autogenerated by ../../build_app.js import value_set_concept_set_component from 'ember-fhir-adapter/models/value-set-concept-set-component'; export default value_set_concept_set_component;
/*! Sauron - v1.1.0 - 2013-01-07 * https://github.com/Ensighten/Sauron * Copyright (c) 2013 Ensighten; Licensed MIT */ define(function () { return (function () { var MiddleEarth = {}, Sauron = {}, console = window.console || {'log': function () {}}; /** * Found this goodie on wiki: (Palantir == Seeing Stone) * http://en.wikipedia.org/wiki/Palant%C3%ADr */ function Palantir() { this.stack = []; } function popStack() { return this.stack.pop(); } var PalantirProto = Palantir.prototype = { /** * Retrieval function for the current channel * @param {Boolean} raw If true, prefixing will be skipped * @returns {String} */ 'channel': function (raw) { var stack = this.stack, prefix = this._prefix, controller = this._controller, model = this._model, channel = stack[stack.length - 1] || ''; // If we don't want a raw channel if (!raw) { // If there is a prefix, use it if (prefix !== undefined) { channel = prefix + '/' + channel; } // If there is a controller, prefix the channel if (controller !== undefined) { channel = 'controller/' + controller + '/' + channel; } else if (model !== undefined) { // Otherwise, if there is a model, prefix the channel channel = 'model/' + model + '/' + channel; } } return channel; }, /** * Maintenance functions for the stack of channels * @returns {String} */ 'pushStack': function (channel) { this.stack.push(channel); return this; }, 'popStack': popStack, 'end': function () { var that = this.clone(); popStack.call(that); return that; }, 'of': function (subchannel) { var that = this.clone(), lastChannel = that.channel(true), channel = lastChannel + '/' + subchannel; that.pushStack(channel); that.log('CHANNEL EDITED: ', that.channel()); return that; }, /** * Subscribing function for event listeners * @param {String} [subchannel] Subchannel to listen to * @param {Function} [fn] Function to subscribe with * @returns {this.clone} */ 'on': function (subchannel, fn) { var that = this.clone(); // Move the track to do an 'on' action if (that.method !== 'on') { that.method = 'on'; that.log('METHOD CHANGED TO: on'); } // If there are are arguments if (arguments.length > 0) { // If there is only one argument and subchannel is a function, promote the subchannel to fn if (arguments.length === 1 && typeof subchannel === 'function') { fn = subchannel; subchannel = null; } // If there is a subchannel, add it to the current channel if (subchannel || subchannel === 0) { that = that.of(subchannel); } // If there is a function if (fn) { // Get the proper channel var channelName = that.channel(), channel = MiddleEarth[channelName]; that.log('FUNCTION ADDED TO: ', channelName); // If the channel does not exist, create it if (channel === undefined) { channel = []; MiddleEarth[channelName] = channel; } // Save the function to this and context to the function that.fn = fn; fn.SAURON_CONTEXT = that; // Add the function to the channel channel.push(fn); /* let the clone be returned so callers can easily unsubscribe their events // This is a terminal event so return Sauron return Sauron; */ } } // Return a clone return that; }, /** * Unsubscribing function for event listeners * @param {String} [subchannel] Subchannel to unsubscribe from to * @param {Function} [fn] Function to remove subscription on * @returns {this.clone} */ 'off': function (subchannel, fn) { var that = this.clone(); // Move the track to do an 'off' action if (that.method !== 'off') { that.method = 'off'; that.log('METHOD CHANGED TO: off'); } // If there are are arguments or there is a function fn = fn || that.fn; if (arguments.length > 0 || fn) { // If there is only one argument and subchannel is a function, promote the subchannel to fn if (arguments.length === 1 && typeof subchannel === 'function') { fn = subchannel; subchannel = null; } // If there is a subchannel, add it to the current channel if (subchannel || subchannel === 0) { that = that.of(subchannel); } // If there is a function var channelName = that.channel(); if (fn) { // Get the proper channel var channel = MiddleEarth[channelName] || [], i = channel.length; that.log('REMOVING FUNCTION FROM: ', channelName); // Loop through the subscribers while (i--) { // If an functions match, remove them if (channel[i] === fn) { channel.splice(i, 1); } } // This is a terminal event so return Sauron return Sauron; } else { // Otherwise, unbind all items from the channel MiddleEarth[channelName] = []; } } // Return a clone return that; }, /** * Voice/emit command for Sauron * @param {String|null} subchannel Subchannel to call on. If it is falsy, it will be skipped * @param {Mixed} [param] Parameter to voice to the channel. There can be infinite of these * @returns {Sauron} */ 'voice': function (subchannel/*, param, ... */) { var that = this.clone(); // If there is a subchannel, use it if (subchannel || subchannel === 0) { that = that.of(subchannel); } // Collect the data and channel var args = [].slice.call(arguments, 1), channelName = that.channel(), // Capture the subscribers in case of self-removal (e.g. once) channel = (MiddleEarth[channelName] || []).slice(), subscriber, i = 0, len = channel.length; that.log('EXECUTING FUNCTIONS IN: ', channelName); // Loop through the subscribers for (; i < len; i++) { subscriber = channel[i]; // Call the function within its original context subscriber.apply(subscriber.SAURON_CONTEXT, args); } // This is a terminal event so return Sauron return Sauron; }, /** * Returns a cloned copy of this * @returns {this.clone} */ 'clone': function () { var that = this, retObj = new Palantir(), key; for (key in that) { if (that.hasOwnProperty(key)) { retObj[key] = that[key]; } } // Special treatment for the stack retObj.stack = [].slice.call(that.stack); // Return the modified item return retObj; }, /** * Sugar subscribe function that listens to an event exactly once * @param {String} [subchannel] Subchannel to listen to * @param {Function} [fn] Function to subscribe with * @returns {this.clone} */ 'once': function (subchannel, fn) { var that = this.clone(); // Move the track to do an 'on' action that.method = 'once'; // If there are arguments if (arguments.length > 0) { // If there is only one argument and subchannel is a function, promote the subchannel to fn if (arguments.length === 1 && typeof subchannel === 'function') { fn = subchannel; subchannel = null; } // If there is no function, throw an error if (typeof fn !== 'function') { throw new Error('Sauron.once expected a function, received: ' + fn.toString); } // Upcast the function for subscription var subFn = function () { // Unsubcribe from this this.off(); // Call the function in this context var args = [].slice.call(arguments); return fn.apply(this, args); }; // Call .on and return return that.on(subchannel, subFn); } // Return a clone return that; }, // New hotness for creation/deletion 'make': function () { var that = this.clone(); that.log('PREFIX UPDATED TO: make'); that._prefix = 'make'; // If there are arguments, perform the normal action if (arguments.length > 0) { var args = [].slice.call(arguments), method = that.method || 'voice'; return that[method].apply(that, args); } else { // Otherwise, return that return that; } }, 'destroy': function () { var that = this.clone(); that.log('PREFIX UPDATED TO: destroy'); that._prefix = 'destroy'; // If there are arguments, perform the normal action if (arguments.length > 0) { var args = [].slice.call(arguments), method = that.method || 'voice'; return that[method].apply(that, args); } else { // Otherwise, return that return that; } }, // Controller methods /** * Fluent method for calling out a controller * @param {String} controller Name of the controller to invoke * @param {Mixed} * If there are any arguments, they will be passed to (on, off, once, voice) for invocation * @returns {Mixed} If there are more arguments than controller, the (on, off, once, voice) response will be returned. Otherwise, this.clone */ 'controller': function (controller) { var that = this.clone(); that._controller = controller; // this.log('CONTROLLER UPDATED TO:', controller); that.log('CHANNEL UPDATED TO:', that.channel()); // If require is present if (require) { var controllerUrl = require.getContext().config.paths._controllerDir || '', url = controllerUrl + controller; // If the controller has not yet been loaded by requirejs, notify if (!require.has(url)) { console.log(controller + ' has not been loaded by requirejs'); } } if (arguments.length > 1) { var args = [].slice.call(arguments, 1), method = that.method || 'voice'; args.unshift(null); return that[method].apply(that, args); } else { // Otherwise, return a clone return that; } }, 'createController': function (controller) { var that = this.clone(); that = that.make(); that = that.controller(controller); var args = [].slice.call(arguments, 1), method = that.method || 'voice'; args.unshift(null); return that[method].apply(that, args); }, 'start': execFn('start'), 'stop': execFn('stop'), // Model methods 'model': function (model) { var that = this.clone(); that._model = model; // this.log('MODEL UPDATED TO:', model); that.log('CHANNEL UPDATED TO:', that.channel()); // If require is present if (require) { var modelUrl = require.getContext().config.paths._modelDir || '', url = modelUrl + model; // If the controller has not yet been loaded by requirejs, notify if (!require.has(url)) { console.log(model + ' has not been loaded by requirejs'); } } if (arguments.length > 1) { var args = [].slice.call(arguments, 1), method = that.method || 'voice'; args.unshift(null); return that[method].apply(that, args); } else { // Otherwise, return a clone return that; } }, 'createModel': function (model) { var that = this.clone(); that = that.make(); that = that.model(model); var args = [].slice.call(arguments, 1), method = that.method || 'voice'; args.unshift(null); return that[method].apply(that, args); }, 'create': execFn('create'), 'retrieve': execFn('retrieve'), 'update': execFn('update'), 'delete': execFn('delete'), 'createEvent': execFn('createEvent'), 'retrieveEvent': execFn('retrieveEvent'), 'updateEvent': execFn('updateEvent'), 'deleteEvent': execFn('deleteEvent'), /** * Helper function for error first callbacks. If an error occurs, we will log it and not call the function. * @param {Function} fn Function to remove error for * @returns {Function} */ 'noError': function (fn) { return function (err) { // If an error occurred, log it and don't do anything else if (err) { return console.error(err); } // Otherwise, callback with the remaining arguments var args = [].slice.call(arguments, 1); fn.apply(this, args); }; }, // Debug functions /** * Setter function for debugging * @param {Boolean} debug If true, turn debugger on. Otherwise, leave it off * @returns {this} */ 'debug': function (debug) { var that = this.clone(); that._debug = debug; return that; }, /** * Debug logger for this object * @returns {this} */ 'log': function () { if (this._debug === true || Sauron._debug === true) { console.log.apply(console, arguments); } return this; } }; function execFn(subchannel) { return function () { var that = this.clone(); // Add subchannel to the channel that = that.of(subchannel); // If there are arguments, perform the normal action if (arguments.length > 0) { var args = [].slice.call(arguments), method = that.method || 'voice'; // If the method is voice, unshift an empty subchannel args.unshift(null); return that[method].apply(that, args); } else { // Otherwise, return a clone return that; } }; } // Copy over all of the items in the Palantir prototype to Sauron such that each one is run on a fresh Palantir for (var key in PalantirProto) { if (PalantirProto.hasOwnProperty(key)) { (function (fn) { Sauron[key] = function () { var args = [].slice.call(arguments); return fn.apply(new Palantir(), args); }; }(PalantirProto[key])); } } return Sauron; }()); });
version https://git-lfs.github.com/spec/v1 oid sha256:7387533a0fd036c92189e1199d45ba486b5bfb5928f50caaaf24c0d6e1bb341f size 3290
/* The following is the data used by the application. Typically this data is loaded from a server or from a file. To make life easier to see how the app works the data is provided here instead of loading it from somewhere. */ var title = 'Animal Photographs'; var photos = [ { uri : '../images/birdnest.png', title : 'Bird Nest' }, { uri : '../images/birdrow.png', title : 'Row of Birds' }, { uri : '../images/bluefootedbird.png', title : 'Blue-footed Birds' }, { uri : '../images/deer.png', title : 'Running Deer' }, { uri : '../images/hounds.png', title : 'Hound Dogs' }, { uri : '../images/parrots.png', title : 'Colorful Parrots' }, { uri : '../images/penguins.png', title : 'Rockhopper Penguins' }, { uri : '../images/pheasants.png', title : 'Pheasants' }, { uri : '../images/polarbears.png', title : 'Polar Bears' }, { uri : '../images/sheep.png', title : 'Flock of Sheep' } ]; // The following 'controller' code utilizes the above data. // The code and the html in index.html do not contain any specifics // of the images that are displayed. The data 'drives' what the logic does. // The paradigm is Model-View-Controller (MVC) // Model = the data // View - interface elements and CSS // Controller - the code // http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller // Do the initial setup. // - set the title based on the 'title' variable // - if there are photos, display the first one function prepareDisplay(photos) { $('#title').html(title); if (photos.length < 1) return; var firstPhoto = photos[0]; $('#imageHolder').attr('src', firstPhoto.uri); $('#photoTitle').html(firstPhoto.title); } // This function will display an item that is clicked-on in the menu. // Which item to display is in the data that was provided when // .click was set (see populateMenu) and provided with event data. function displayItem(event) { var data = event.data; var item = data.item; $('#imageHolder').attr('src', item.uri); $('#photoTitle').html(item.title); } // This function takes the data and creates menu items. // Each menu item is an <li> in a <ul>. // The .click() on each menu item is set to call displayItem // and provided the data contained in eventData. function populateMenu(items) { for (var i=0; i < items.length; i++) { var item = items[i]; // The following creates a new <li>. // When jquery ($) receives html it creates the element // rather than finding it. //var menuItem = $( '<li>' + item.title + '</li>' ); // version without thumbnail var menuItem = $( '<li><img class="thumbnail" src="' + item.uri + '" /> ' + item.title + '</li>' ); // version with thumbnail // Add the new <li> to the <ul> with an id of menuItems $('#menuItems').append(menuItem); // Create a data object to send as data to the click handler. var eventData = { 'num' : i, 'item' : item } // Add a click handler with event data to the <li> that was appended above. // eventData is the data received in the event received by displayItem // when a menu item is clicked menuItem.click(eventData, displayItem); } } // When the DOM is ready, the initial display is prepared and the // menu is populated. $(document).ready( function() { prepareDisplay(photos); populateMenu(photos); $('#photoMenu').draggable(); // make the menu draggable $('#photoDisplay').draggable(); // make the photo display draggable } );
import $ from 'jquery'; import interact from 'interact.js'; export default function() { console.log('dragAndHover'); // target elements with the "draggable" class interact('.grate-it').draggable({ // enable inertial throwing // inertia: true, // keep the element within the area of it's parent restrict: { restriction: '.quiz__dnh', endOnly: true, elementRect: { top: 0, left: 0, bottom: 1, right: 1 } }, // enable autoScroll autoScroll: true, // call this function on every dragmove event onmove: dragMoveListener, // call this function on every dragend event onend: function (event) { var textEl = event.target.querySelector('p'); textEl && (textEl.textContent = 'moved a distance of ' + (Math.sqrt(event.dx * event.dx + event.dy * event.dy)|0) + 'px'); } }); // enable draggables to be dropped into this interact('.hoverzone').dropzone({ // only accept elements matching this CSS selector accept: '.grate-it', // Require a 75% element overlap for a drop to be possible overlap: 0.75, // listen for drop related events: ondropactivate: function (event) { // add active dropzone feedback event.target.classList.add('drop-active'); }, ondragenter: function (event) { var draggableElement = event.relatedTarget, dropzoneElement = event.target; // feedback the possibility of a drop dropzoneElement.classList.add('drop-target'); console.log(globalVars.count = globalVars.count + 1); draggableElement.classList.add('can-drop'); // draggableElement.textContent = 'Dragged in'; }, ondragleave: function (event) { // remove the drop feedback style event.target.classList.remove('drop-target'); event.relatedTarget.classList.remove('can-drop'); // event.relatedTarget.textContent = 'Dragged out'; }, ondrop: function (event) { // event.relatedTarget.textContent = 'Dropped'; }, ondropdeactivate: function (event) { // remove active dropzone feedback event.target.classList.remove('drop-active'); event.target.classList.remove('drop-target'); } }); } let dragMoveListener = function(event) { var target = event.target, // keep the dragged position in the data-x/data-y attributes x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx, y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; // translate the element target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'; // update the posiion attributes target.setAttribute('data-x', x); target.setAttribute('data-y', y); }
/** * Date: 2013.04.15 * requestHandles dispatch. */ var requestHandlers = {}; var globaldata = root.globaldata; var verification = require('./handlers/verification'); requestHandlers.verification = function (request, response, pathObject, data) { var operation = pathObject["operation"]; if (operation == "get") { verification.get(data, response); }else if (operation == "auth") { verification.auth(data, response); } }; var orderManage = require('./handlers/orderManage'); requestHandlers.orderManage = function (request, response, pathObject, data) { var operation = pathObject["operation"]; if (operation == "create") { orderManage.create(data, response); } }; module.exports = requestHandlers;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import Chip from 'material-ui/Chip'; import Avatar from 'material-ui/Avatar'; import Paper from 'material-ui/Paper'; import EmailIcon from 'material-ui/svg-icons/communication/mail-outline'; import MessageIcon from 'material-ui/svg-icons/communication/message'; import CommunicationForm from 'components/CommunicationForm'; import { sendCommunication, removeDestinataire, setMessage, } from 'containers/AdminCommunication/actions'; import { makeSelectCommunicationDomain } from 'containers/AdminCommunication/selectors'; import { makeSelectAuthApiKey } from 'containers/CompteUtilisateur/selectors'; import { get } from 'utils/apiClient'; import styles from './styles.css'; class CommunicationFormContainer extends Component { // eslint-disable-line static propTypes = { communication: PropTypes.object.isRequired, apiKey: PropTypes.string.isRequired, sendMessage: PropTypes.func.isRequired, setMessage: PropTypes.func.isRequired, removeDest: PropTypes.func.isRequired, }; state = { smsOk: null, }; componentDidMount = () => { get('https://communication.proxiweb.fr/api/status', { headers: { 'Content-Type': 'application/json' }, }) .then(res => { const { Send } = res.datas; this.setState({ smsOk: Send }); }) .catch(() => this.setState({ smsOk: false })); }; handleSubmit = ({ message, objet, sms }) => { const communication = { siteExpediteur: 'proxiweb', messageCourt: sms, messageLong: message, objet, envoye: true, destinataires: this.props.communication.destinataires.map(d => ({ email: d.email, telPortable: d.telPortable, etat: 'attente', identite: d.identite, })), }; this.props.sendMessage(this.props.apiKey, communication); }; render() { if (!this.props.communication) return null; const { sms, objet, html } = this.props.communication.message; const destinataires = this.props.communication.destinataires; return ( <Paper> <div className="row"> <div className={`col-md-6 ${styles.panel} ${styles.dest}`}> {destinataires .slice() .sort((a, b) => a.identite > b.identite) .map((dest, idx) => (<div key={idx} className="row end-md"> <div className="col-md-4"> {dest.email && <Chip style={{ margin: 4 }} onRequestDelete={() => this.props.removeDest(dest.id, 'email')} > <Avatar color="#444" icon={<EmailIcon />} /> {dest.identite} </Chip>} </div> <div className="col-md-4"> {dest.telPortable && <Chip style={{ margin: 4 }} onRequestDelete={() => this.props.removeDest(dest.id, 'telPortable')} > <Avatar color="#444" icon={<MessageIcon />} /> {dest.identite} </Chip>} </div> </div>) )} </div> <div className={`col-md-6 ${styles.panel}`}> <CommunicationForm onSubmit={this.handleSubmit} message={{ sms, objet, html }} nbreDest={destinataires.length} setMessage={this.props.setMessage} smsOk={this.state.smsOk} /> </div> </div> </Paper> ); } } const mapStateToProps = createStructuredSelector({ communication: makeSelectCommunicationDomain(), apiKey: makeSelectAuthApiKey(), }); const mapDispatchToProps = dispatch => bindActionCreators( { sendMessage: sendCommunication, setMessage, removeDest: removeDestinataire, }, dispatch ); export default connect(mapStateToProps, mapDispatchToProps)( CommunicationFormContainer );
'use strict'; const TEMPLATES_PATH = `${__dirname}/../../web`; var uuid = require('node-uuid'), restify = require('restify'), fs = require('fs'), logger = require('winston'), Handlebars = require('handlebars'), Router = require('./abstract.router'); class StaticRouter extends Router { configure () { this.compileIndexTemplate(); this.server.get(/.*\.(gif|png|css|js|jpg|eot|woff|ttf|woff2|svg)/, restify.serveStatic({ directory: __dirname + '/../../web', maxAge: this.config.server.staticMaxAge })); this.bindGET(/^(?!\/api).*/, this.indexRender); } compileIndexTemplate () { this.template = Handlebars.compile(fs.readFileSync(`${TEMPLATES_PATH}/index.html`).toString(), {noEscape: true}); logger.debug('index.html template compiled'); } indexRender (req, res) { var data = {configurationString: ''}, cookies = req.cookies; if (cookies.token && cookies.username && cookies.role) { data.configurationString = `window.Auth = { username: '${cookies.username}', token: '${cookies.token}', role: '${cookies.role}' };`; } data.configurationString += `window.UUID = '${cookies.uuid ? cookies.uuid : uuid.v4()}';`; if (this.config.debug.disableTemplateCaching) this.compileIndexTemplate(); var body = this.template(data); res.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/html' }); res.write(body); res.end(); } } module.exports = StaticRouter;
'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var $ = require('gulp-load-plugins')({ pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del'] }); gulp.task('partials', function() { return gulp.src([ path.join(conf.paths.src, '/app/**/*.html'), path.join(conf.paths.tmp, '/serve/app/**/*.html') ]) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true })) .pipe($.angularTemplatecache('templateCacheHtml.js', { module: 'vmsFrontend', root: 'app' })) .pipe(gulp.dest(conf.paths.tmp + '/partials/')); }); gulp.task('html', ['inject', 'partials'], function() { var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false }); var partialsInjectOptions = { starttag: '<!-- inject:partials -->', ignorePath: path.join(conf.paths.tmp, '/partials'), addRootSlash: false }; var htmlFilter = $.filter('*.html', { restore: true }); var jsFilter = $.filter('**/*.js', { restore: true }); var cssFilter = $.filter('**/*.css', { restore: true }); var assets; return gulp.src(path.join(conf.paths.tmp, '/serve/*.html')) .pipe($.inject(partialsInjectFile, partialsInjectOptions)) .pipe(assets = $.useref.assets()) .pipe($.rev()) .pipe(jsFilter) .pipe($.sourcemaps.init()) .pipe($.ngAnnotate()) .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify')) .pipe($.sourcemaps.write('maps')) .pipe(jsFilter.restore) .pipe(cssFilter) .pipe($.sourcemaps.init()) .pipe($.replace('../../bower_components/bootstrap-sass/assets/fonts/bootstrap/', '../fonts/')) .pipe($.replace('../../bower_components/font-awesome/fonts', '../fonts')) .pipe($.minifyCss({ processImport: false })) .pipe($.sourcemaps.write('maps')) .pipe(cssFilter.restore) .pipe(assets.restore()) .pipe($.useref()) .pipe($.revReplace()) .pipe(htmlFilter) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true, conditionals: true })) .pipe(htmlFilter.restore) .pipe(gulp.dest(path.join(conf.paths.dist, '/'))) .pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true })); }); // Only applies for fonts from bower dependencies // Custom fonts are handled by the "other" task gulp.task('fonts', function() { return gulp.src($.mainBowerFiles()) .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}')) .pipe($.flatten()) .pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/'))); }); gulp.task('other', function() { var fileFilter = $.filter(function(file) { return file.stat.isFile(); }); return gulp.src([ path.join(conf.paths.src, '/**/*'), path.join('!' + conf.paths.src, '/**/*.{html,css,js,scss}') ]) .pipe(fileFilter) .pipe(gulp.dest(path.join(conf.paths.dist, '/'))); }); gulp.task('clean', function() { return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]); }); gulp.task('build', ['html', 'fonts', 'other']);
'use strict'; // This file is auto-generated using scripts/doc-sync.js /** * The security level of a page or resource. */ exports.SecurityState = String; /** * An explanation of an factor contributing to the security state. * * @param {SecurityState} securityState Security state representing the severity of the factor being explained. * @param {string} summary Short phrase describing the type of factor. * @param {string} description Full text explanation of the factor. */ exports.SecurityStateExplanation = function SecurityStateExplanation(props) { this.securityState = props.securityState; this.summary = props.summary; this.description = props.description; }; /** * Information about mixed content on the page. * * @param {boolean} ranInsecureContent True if the page ran insecure content such as scripts. * @param {boolean} displayedInsecureContent True if the page displayed insecure content such as images. * @param {SecurityState} ranInsecureContentStyle Security state representing a page that ran insecure content. * @param {SecurityState} displayedInsecureContentStyle Security state representing a page that displayed insecure content. */ exports.MixedContentStatus = function MixedContentStatus(props) { this.ranInsecureContent = props.ranInsecureContent; this.displayedInsecureContent = props.displayedInsecureContent; this.ranInsecureContentStyle = props.ranInsecureContentStyle; this.displayedInsecureContentStyle = props.displayedInsecureContentStyle; };
(function (win, doc, exports, undefined) { 'use strict'; var fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; function Class() { /* noop. */ } Class.extend = function (props) { var SuperClass = this; function Class() { if (typeof this.init === 'function') { this.init.apply(this, arguments); } } Class.prototype = Object.create(SuperClass.prototype, { constructor: { value: Class, writable: true, configurable: true } }); Object.keys(props).forEach(function (key) { var prop = props[key], _super = SuperClass.prototype[key], isMethodOverride = (typeof prop === 'function' && typeof _super === 'function' && fnTest.test(prop)); if (isMethodOverride) { Class.prototype[key] = function () { var ret, tmp = this._super; Object.defineProperty(this, '_super', { value: _super, configurable: true }); ret = prop.apply(this, arguments); Object.defineProperty(this, '_super', { value: tmp, configurable: true }); return ret; }; } else { Class.prototype[key] = prop; } }); Class.extend = SuperClass.extend; return Class; }; exports.Class = Class; }(window, window.document, window));
angular.module('demoApp').component('people', { bindings: { people: '<' }, templateUrl: 'partials/people.html' });
import { Store, createStore } from './store' import { storeKey, useStore } from './injectKey' import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from './helpers' import { createLogger } from './plugins/logger' export default { version: '__VERSION__', Store, storeKey, createStore, useStore, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers, createLogger }
/* * MIT License * * Copyright (c) 2016 yanbo * * 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'; import React, { Component } from 'react'; import { View, Text, Image, StyleSheet, } from 'react-native'; import NetUtils from './../utils/NetUtils'; import ActionBar from './../components/ActionBar'; import { connect } from 'react-redux'; import NavigatorRoute from './../common/NavigatorRoute'; import TabNavigator from 'react-native-tab-navigator' import HomePage from './HomePage'; import MinePage from './MinePage'; import WeiXinNewsPage from './WeiXinNewsPage'; /** * 主容器界面 * 核心知识点:使用React Native Redux框架管理 * react-native-tab-navigator第三方底部导航栏的使用及封装学习 */ class MainScene extends Component { static propTypes = { navigator: React.PropTypes.object.isRequired, route: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { selectedTab: 'home', }; } componentDidMount() { const {dispatch} = this.props; } render() { const {mainPage} = this.props; return ( <View style={styles.container}> <TabNavigator tabBarStyle={{ backgroundColor:'white' }} style={{backgroundColor: 'white'}}> <TabNavigator.Item title="潮流生活" selectedTitleStyle={{color: '#03a9f4'}} selected={this.state.selectedTab === 'home'} renderIcon={() => <Image source={require('./../res/ic_btm_home.png')} />} renderSelectedIcon={() => <Image source={require('./../res/ic_btm_home.png')} />} onPress={() => this.setState({ selectedTab: 'home' })}> <HomePage navigator={this.props.navigator} route={this.props.route}/> </TabNavigator.Item> <TabNavigator.Item title="微信精选" selectedTitleStyle={{color: '#03a9f4'}} selected={this.state.selectedTab === 'weixin'} renderIcon={() => <Image source={require('./../res/ic_btm_weixin.png')} />} renderSelectedIcon={() => <Image source={require('./../res/ic_btm_weixin.png')} />} onPress={() => this.setState({ selectedTab: 'weixin' })}> <WeiXinNewsPage navigator={this.props.navigator} route={this.props.route}/> </TabNavigator.Item> <TabNavigator.Item title="个人中心" selectedTitleStyle={{color: '#03a9f4'}} selected={this.state.selectedTab === 'person'} renderIcon={() => <Image source={require('./../res/ic_btm_persion.png')} />} renderSelectedIcon={() => <Image source={require('./../res/ic_btm_persion.png')} />} onPress={() => this.setState({ selectedTab: 'person' })}> <MinePage navigator={this.props.navigator} route={this.props.route}/> </TabNavigator.Item> </TabNavigator> </View> ); } } function mapStateToProps(state) { const { mainPage } = state; return { mainPage, } } export default connect(mapStateToProps)(MainScene); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f7f7f7', }, });
import {combineReducers} from "redux"; import {LOAD_ACCOUNT, LOAD_STATE, NEW_ACCOUNT} from "b:actions/index"; import {addSpecs} from "b:spec"; const noAccount = ""; const accounts = combineReducers({ byAddress, current, loaded, }); export default accounts; function byAddress(state = {}, action) { switch(action.type) { case LOAD_STATE: return action.wallet.byAddress || state; case NEW_ACCOUNT: let address = action.keypair.address(); let seed = action.keypair.seed(); return Object.assign({}, state, { [address]: { address, seed } }) default: return state; } } function current(state = noAccount, action) { switch(action.type) { case LOAD_STATE: if (state) return state; let fromWallet = action.wallet.current; if (fromWallet in action.wallet.byAddress) { return fromWallet; } return Object.keys(action.wallet.byAddress)[0] || noAccount; case LOAD_ACCOUNT: return action.address default: return state; } } function loaded(state = false, action) { switch(action.type) { case LOAD_STATE: return true default: return state; } } export function specs(s) { let {expect, contracts, describe} = s; describe.reducer(byAddress, context => { context({ state: {}, action: { type: LOAD_STATE, wallet: { byAddress: {"123": 3} } } }, it => { it("replaces the state", (state, action) => { expect(state).to.equal(action.wallet.byAddress); }); }); }); describe.reducer(current, context => { context({ state: noAccount, action: { type: LOAD_ACCOUNT, address: "123", } }, it => { it("replaces the state", (state, action) => { expect(state).to.equal(action.address); }) }) }) describe.reducer(loaded, context => { // for reducer tests, context takes both a // state matcher spec and an action matcher spec. context({ state: false, action: {type:LOAD_STATE}, }, it => { // it specifiers in reducer tests are provided with the // state, the action, and the previous state, which can // each be easily expected upon. it("moves state to true", (state, action, prev) => { expect(state).to.be.true; }); }); }); } addSpecs(specs);
import MainView from './MainView' export var buckConverterCalculator = { displayName: 'Buck Converter (SMPS)', description: 'This calculator can be used to calculate the values of the critical component values for a buck converter.', imagePath: require('./grid-icon.png'), category: [ 'Electronics', 'SMPS' ], tags: [ 'buck, converter, smps, psu, power, voltage, current, inductor, conversion' ], mainView: MainView }
import { combineReducers } from 'redux'; import searchReducer from './searchReducer'; import dialogReducer from './dialogReducer'; import legendReducer from './legendReducer'; import headerReducer from './headerReducer'; import mapReducer from './mapReducer'; // Bundled reducers used by store/store.js. export default combineReducers({ search: searchReducer, dialog: dialogReducer, legend: legendReducer, header: headerReducer, map: mapReducer, });
const bannedList = { version: '12', cards: [ 'guest-of-honor', 'charge', 'isawa-tadaka', 'karada-district', 'master-of-gisei-toshi', 'kanjo-district', 'jurojin-s-curse', 'hidden-moon-dojo', 'mirumoto-daisho' ] }; class BannedList { validate(cards) { let cardsOnBannedList = cards.filter(card => bannedList.cards.includes(card.id)); let errors = []; if(cardsOnBannedList.length > 1) { errors.push(`Contains a card on the FAQ v${bannedList.version} banned list: ${cardsOnBannedList.map(card => card.name).join(', ')}`); } return { version: bannedList.version, valid: errors.length === 0, errors: errors, restrictedCards: cardsOnBannedList }; } } module.exports = BannedList;
var assert = require('assert'); var sinon = require('sinon'); var director = require('../src/director.js'); var builder = require('../src/builder.js'); var converter = require('../src/converter.js'); describe("Projection converter\n", function() { before(function() { decoder = new director.Decoder(); }); it(" should convert coordinates for z=0, x=0, y=0, extent=4096 to a Leaflet geometry", function() { var z = 0, x = 0, y = 0; var geometry = ([9, 0, 8192]); //point at the SW corner of the tile var extent = 4096; var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tolatlon(z, x, y, tileGeometry, extent); result[0] = Math.round(result[0]*100)/100; assert.deepEqual(result, [-85.05, -180]); //verify the y value }) it(" should convert coordinates for z=1, x=0, y=1, extent=4096 to a Leaflet geometry", function() { var z = 1, x = 0, y = 1; var geometry = [9, 0, 8192]; var extent = 4096; var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tolatlon(z, x, y, tileGeometry, extent); result[0] = Math.round(result[0]*100)/100; assert.deepEqual(result, [-85.05, -180]); }) it(" should convert coordinates for z=2, x=0, y=3, extent=4096 to a Leaflet geometry", function() { var z = 2, x = 0, y = 3; var geometry = [9, 0, 8192]; var extent = 4096; var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tolatlon(z, x, y, tileGeometry, extent); result[0] = Math.round(result[0]*100)/100; assert.deepEqual(result, [-85.05, -180]); }) it(" should convert coordinates for z=2, x=3, y=3, extent=4096 to a Leaflet geometry", function() { var z = 2, x = 3, y = 3; var geometry = [9, 8192, 8192]; var extent = 4096; var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tolatlon(z, x, y, tileGeometry, extent); result[0] = Math.round(result[0]*100)/100; assert.deepEqual(result, [-85.05, 180]); }) it(" should return spherical Mercator coordinates for z=0, x=0, y=0, extent=4096", function() { var z = 0, x = 0, y = 0, extent = 4096; var geometry = ([9, 0, 8192]); var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tomercator(z, x, y, tileGeometry, extent); result = [Math.round(result[0]*100)/100, Math.round(result[1]*100)/100]; assert.deepEqual(result, [-20037508.34, -20037508.34]); }) it(" should return spherical Mercator coordinates for z=2, x=1, y=1, extent=4096", function() { var z = 2, x = 1, y = 1, extent = 4096; var geometry = ([9, 8192, 8192]); var tileGeometry = decoder.decode(geometry); var result = converter.Converter.tomercator(z, x, y, tileGeometry, extent); result = [Math.round(result[0]*100)/100, Math.round(result[1]*100)/100]; assert.deepEqual(result, [0, 0]); }) });
var set = Ember.set, get = Ember.get; // ....................................................... // render() // module("Ember.RenderBuffer"); test("RenderBuffers combine strings", function() { var buffer = new Ember.RenderBuffer('div'); buffer.pushOpeningTag(); buffer.push('a'); buffer.push('b'); equal("<div>ab</div>", buffer.string(), "Multiple pushes should concatenate"); }); test("value of 0 is included in output", function() { var buffer, $el; buffer = new Ember.RenderBuffer('input'); buffer.prop('value', 0); buffer.pushOpeningTag(); $el = buffer.element(); strictEqual($el.value, '0', "generated element has value of '0'"); buffer = new Ember.RenderBuffer('input'); buffer.prop('value', 0); buffer.push('<div>'); buffer.pushOpeningTag(); buffer.push('</div>'); $el = Ember.$(buffer.innerString()); strictEqual($el.find('input').val(), '0', "raw tag has value of '0'"); }); test("prevents XSS injection via `id`", function() { var buffer = new Ember.RenderBuffer('div'); buffer.push('<span></span>'); // We need the buffer to not be empty so we use the string path buffer.id('hacked" megahax="yes'); buffer.pushOpeningTag(); equal('<span></span><div id="hacked&quot; megahax=&quot;yes">', buffer.string()); }); test("prevents XSS injection via `attr`", function() { var buffer = new Ember.RenderBuffer('div'); buffer.push('<span></span>'); // We need the buffer to not be empty so we use the string path buffer.attr('id', 'trololol" onmouseover="pwn()'); buffer.attr('class', "hax><img src=\"trollface.png\""); buffer.pushOpeningTag(); equal('<span></span><div id="trololol&quot; onmouseover=&quot;pwn()" class="hax&gt;&lt;img src=&quot;trollface.png&quot;">', buffer.string()); }); test("prevents XSS injection via `addClass`", function() { var buffer = new Ember.RenderBuffer('div'); buffer.push('<span></span>'); // We need the buffer to not be empty so we use the string path buffer.addClass('megahax" xss="true'); buffer.pushOpeningTag(); // Regular check then check for IE equal('<span></span><div class="megahax&quot; xss=&quot;true">', buffer.string()); }); test("prevents XSS injection via `style`", function() { var buffer = new Ember.RenderBuffer('div'); buffer.push('<span></span>'); // We need the buffer to not be empty so we use the string path buffer.style('color', 'blue;" xss="true" style="color:red'); buffer.pushOpeningTag(); equal('<span></span><div style="color:blue;&quot; xss=&quot;true&quot; style=&quot;color:red;">', buffer.string()); }); test("handles null props - Issue #2019", function() { var buffer = new Ember.RenderBuffer('div'); buffer.push('<span></span>'); // We need the buffer to not be empty so we use the string path buffer.prop('value', null); buffer.pushOpeningTag(); equal('<span></span><div>', buffer.string()); }); test("handles browsers like Firefox < 11 that don't support outerHTML Issue #1952", function(){ var buffer = new Ember.RenderBuffer('div'); buffer.pushOpeningTag(); // Make sure element.outerHTML is falsy to trigger the fallback. var elementStub = '<div></div>'; buffer.element = function(){ return elementStub; }; equal(new XMLSerializer().serializeToString(elementStub), buffer.string()); }); module("Ember.RenderBuffer - without tagName"); test("It is possible to create a RenderBuffer without a tagName", function() { var buffer = new Ember.RenderBuffer(); buffer.push('a'); buffer.push('b'); buffer.push('c'); equal(buffer.string(), "abc", "Buffers without tagNames do not wrap the content in a tag"); }); module("Ember.RenderBuffer#element"); test("properly handles old IE's zero-scope bug", function() { var buffer = new Ember.RenderBuffer('div'); buffer.pushOpeningTag(); buffer.push('<script></script>foo'); var element = buffer.element(); ok(Ember.$(element).html().match(/script/i), "should have script tag"); ok(!Ember.$(element).html().match(/&shy;/), "should not have &shy;"); });
import React from 'react'; import PropTypes from 'prop-types'; class Knob extends React.Component { static propTypes = { value: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, onChangeEnd: PropTypes.func, min: PropTypes.number, max: PropTypes.number, step: PropTypes.number, log: PropTypes.bool, width: PropTypes.number, height: PropTypes.number, thickness: PropTypes.number, lineCap: PropTypes.oneOf(['butt', 'round']), bgColor: PropTypes.string, fgColor: PropTypes.string, inputColor: PropTypes.string, font: PropTypes.string, fontWeight: PropTypes.string, clockwise: PropTypes.bool, cursor: PropTypes.oneOfType([ PropTypes.number, PropTypes.bool, ]), stopper: PropTypes.bool, readOnly: PropTypes.bool, disableTextInput: PropTypes.bool, displayInput: PropTypes.bool, displayCustom: PropTypes.func, angleArc: PropTypes.number, angleOffset: PropTypes.number, disableMouseWheel: PropTypes.bool, title: PropTypes.string, className: PropTypes.string, canvasClassName: PropTypes.string, }; static defaultProps = { onChangeEnd: () => {}, min: 0, max: 100, step: 1, log: false, width: 200, height: 200, thickness: 0.35, lineCap: 'butt', bgColor: '#EEE', fgColor: '#EA2', inputColor: '', font: 'Arial', fontWeight: 'bold', clockwise: true, cursor: false, stopper: true, readOnly: false, disableTextInput: false, displayInput: true, angleArc: 360, angleOffset: 0, disableMouseWheel: false, className: null, canvasClassName: null, }; constructor(props) { super(props); this.w = this.props.width || 200; this.h = this.props.height || this.w; this.cursorExt = this.props.cursor === true ? 0.3 : this.props.cursor / 100; this.angleArc = this.props.angleArc * Math.PI / 180; this.angleOffset = this.props.angleOffset * Math.PI / 180; this.startAngle = (1.5 * Math.PI) + this.angleOffset; this.endAngle = (1.5 * Math.PI) + this.angleOffset + this.angleArc; this.digits = Math.max( String(Math.abs(this.props.min)).length, String(Math.abs(this.props.max)).length, 2 ) + 2; } componentDidMount() { this.drawCanvas(); if (!this.props.readOnly) { this.canvasRef.addEventListener('touchstart', this.handleTouchStart, { passive: false }); } } componentWillReceiveProps(nextProps) { if (nextProps.width && this.w !== nextProps.width) { this.w = nextProps.width; } if (nextProps.height && this.h !== nextProps.height) { this.h = nextProps.height; } } componentDidUpdate() { this.drawCanvas(); } componentWillUnmount() { this.canvasRef.removeEventListener('touchstart', this.handleTouchStart); } getArcToValue = (v) => { let startAngle; let endAngle; const angle = !this.props.log ? ((v - this.props.min) * this.angleArc) / (this.props.max - this.props.min) : Math.log(Math.pow((v / this.props.min), this.angleArc)) / Math.log(this.props.max / this.props.min); if (!this.props.clockwise) { startAngle = this.endAngle + 0.00001; endAngle = startAngle - angle - 0.00001; } else { startAngle = this.startAngle - 0.00001; endAngle = startAngle + angle + 0.00001; } if (this.props.cursor) { startAngle = endAngle - this.cursorExt; endAngle += this.cursorExt; } return { startAngle, endAngle, acw: !this.props.clockwise && !this.props.cursor, }; }; // Calculate ratio to scale canvas to avoid blurriness on HiDPI devices getCanvasScale = (ctx) => { const devicePixelRatio = window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI || // IE10 1; const backingStoreRatio = ctx.webkitBackingStorePixelRatio || 1; return devicePixelRatio / backingStoreRatio; }; coerceToStep = (v) => { let val = !this.props.log ? (~~(((v < 0) ? -0.5 : 0.5) + (v / this.props.step))) * this.props.step : Math.pow(this.props.step, ~~(((Math.abs(v) < 1) ? -0.5 : 0.5) + (Math.log(v) / Math.log(this.props.step)))); val = Math.max(Math.min(val, this.props.max), this.props.min); if (isNaN(val)) { val = 0; } return Math.round(val * 1000) / 1000; }; eventToValue = (e) => { const bounds = this.canvasRef.getBoundingClientRect(); const x = e.clientX - bounds.left; const y = e.clientY - bounds.top; let a = Math.atan2(x - (this.w / 2), (this.w / 2) - y) - this.angleOffset; if (!this.props.clockwise) { a = this.angleArc - a - (2 * Math.PI); } if (this.angleArc !== Math.PI * 2 && (a < 0) && (a > -0.5)) { a = 0; } else if (a < 0) { a += Math.PI * 2; } const val = !this.props.log ? (a * (this.props.max - this.props.min) / this.angleArc) + this.props.min : Math.pow(this.props.max / this.props.min, a / this.angleArc) * this.props.min; return this.coerceToStep(val); }; handleMouseDown = (e) => { this.props.onChange(this.eventToValue(e)); document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); document.addEventListener('keyup', this.handleEsc); }; handleMouseMove = (e) => { e.preventDefault(); this.props.onChange(this.eventToValue(e)); }; handleMouseUp = (e) => { this.props.onChangeEnd(this.eventToValue(e)); document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); document.removeEventListener('keyup', this.handleEsc); }; handleTouchStart = (e) => { e.preventDefault(); this.touchIndex = e.targetTouches.length - 1; this.props.onChange(this.eventToValue(e.targetTouches[this.touchIndex])); document.addEventListener('touchmove', this.handleTouchMove, { passive: false }); document.addEventListener('touchend', this.handleTouchEnd); document.addEventListener('touchcancel', this.handleTouchEnd); }; handleTouchMove = (e) => { e.preventDefault(); this.props.onChange(this.eventToValue(e.targetTouches[this.touchIndex])); }; handleTouchEnd = (e) => { this.props.onChangeEnd(this.eventToValue(e)); document.removeEventListener('touchmove', this.handleTouchMove); document.removeEventListener('touchend', this.handleTouchEnd); document.removeEventListener('touchcancel', this.handleTouchEnd); }; handleEsc = (e) => { if (e.keyCode === 27) { e.preventDefault(); this.handleMouseUp(); } }; handleTextInput = (e) => { const val = Math.max(Math.min(+e.target.value, this.props.max), this.props.min) || this.props.min; this.props.onChange(val); }; handleWheel = (e) => { e.preventDefault(); if (e.deltaX > 0 || e.deltaY > 0) { this.props.onChange(this.coerceToStep( !this.props.log ? this.props.value + this.props.step : this.props.value * this.props.step )); } else if (e.deltaX < 0 || e.deltaY < 0) { this.props.onChange(this.coerceToStep( !this.props.log ? this.props.value - this.props.step : this.props.value / this.props.step )); } }; handleArrowKey = (e) => { if (e.keyCode === 37 || e.keyCode === 40) { e.preventDefault(); this.props.onChange(this.coerceToStep( !this.props.log ? this.props.value - this.props.step : this.props.value / this.props.step )); } else if (e.keyCode === 38 || e.keyCode === 39) { e.preventDefault(); this.props.onChange(this.coerceToStep( !this.props.log ? this.props.value + this.props.step : this.props.value * this.props.step )); } }; inputStyle = () => ({ width: `${((this.w / 2) + 4) >> 0}px`, height: `${(this.w / 3) >> 0}px`, position: 'absolute', verticalAlign: 'middle', marginTop: `${(this.w / 3) >> 0}px`, marginLeft: `-${((this.w * 3 / 4) + 2) >> 0}px`, border: 0, background: 'none', font: `${this.props.fontWeight} ${(this.w / this.digits) >> 0}px ${this.props.font}`, textAlign: 'center', color: this.props.inputColor || this.props.fgColor, padding: '0px', WebkitAppearance: 'none', }); drawCanvas() { const ctx = this.canvasRef.getContext('2d'); const scale = this.getCanvasScale(ctx); this.canvasRef.width = this.w * scale; // clears the canvas this.canvasRef.height = this.h * scale; ctx.scale(scale, scale); this.xy = this.w / 2; // coordinates of canvas center this.lineWidth = this.xy * this.props.thickness; this.radius = this.xy - (this.lineWidth / 2); ctx.lineWidth = this.lineWidth; ctx.lineCap = this.props.lineCap; // background arc ctx.beginPath(); ctx.strokeStyle = this.props.bgColor; ctx.arc( this.xy, this.xy, this.radius, this.endAngle - 0.00001, this.startAngle + 0.00001, true ); ctx.stroke(); // foreground arc const a = this.getArcToValue(this.props.value); ctx.beginPath(); ctx.strokeStyle = this.props.fgColor; ctx.arc( this.xy, this.xy, this.radius, a.startAngle, a.endAngle, a.acw ); ctx.stroke(); } renderCenter = () => { const { displayCustom, displayInput, disableTextInput, readOnly, value, } = this.props; if (displayInput) { return ( <input style={this.inputStyle()} type="text" value={value} onChange={this.handleTextInput} onKeyDown={this.handleArrowKey} readOnly={readOnly || disableTextInput} /> ); } else if (displayCustom && typeof displayCustom === 'function') { return displayCustom(); } return null; }; render() { const { canvasClassName, className, disableMouseWheel, readOnly, title, value, } = this.props; return ( <div className={className} style={{ width: this.w, height: this.h, display: 'inline-block' }} onWheel={readOnly || disableMouseWheel ? null : this.handleWheel} > <canvas ref={(ref) => { this.canvasRef = ref; }} className={canvasClassName} style={{ width: '100%', height: '100%' }} onMouseDown={readOnly ? null : this.handleMouseDown} title={title ? `${title}: ${value}` : value} /> {this.renderCenter()} </div> ); } } export default Knob;
module.exports = function(RED) { function constantNode(config) { RED.nodes.createNode(this,config); this.name = config.name; this.value = config.value; this.repeat = config.repeat; var node = this; var output = 0; function setOutput() { output = node.value; node.status({fill:"green",shape:"dot",text: output.toString()}); var msg = {topic:node.name, payload:Number(output)}; node.send(msg); } // Set interval this.interval_id = setInterval(setOutput,this.repeat*1000); //start function once on start setTimeout( setOutput,100); } RED.nodes.registerType("constant",constantNode); constantNode.prototype.close = function(){ if (this.interval_id != null) { clearInterval(this.interval_id); } } }
// Workers can share any TCP connection var config = require(process.env.CONFIGFILE || './config'); var webConfig = config.web; var path = require('path'); var fs = require('fs'); var assert = require('assert'); var node_modules = config.node_modules; if(node_modules) { node_modules = [].concat(node_modules).map(function(p){ return path.resolve(p) }); module.paths = module.paths.concat(node_modules); } var app_modules = webConfig.app_modules; if(app_modules) { app_modules = [].concat(app_modules).map(function(p){ return path.resolve(p) }); module.paths = module.paths.concat(app_modules); } var express = require('express'); var app = express(); var logger = require('logger'); var info = logger.info; var pid = process.pid; var production = 'production' == app.settings.env; // general config app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); // disable them in production // use $ NODE_ENV=production node examples/error-pages if (production) { app.disable('verbose errors'); app.use(express.logger({stream: logger.stream})); }else{ // our custom "verbose errors" setting // which we can use in the templates // via settings['verbose errors'] app.enable('verbose errors'); app.use(express.logger('dev')); } app.use(express.favicon()); function scanRoutes(file, routes) { routes = routes || []; file = path.resolve(file); assert.ok(fs.existsSync(file), 'Route directory not found. (\'' + file + '\')'); var stats = fs.statSync(file); if (stats.isDirectory()) { fs.readdirSync(file).forEach(function (child) { scanRoutes(path.join(file, child), routes); }); } else if (stats.isFile()) { routes.push(file); } return routes; } var routes = scanRoutes(webConfig.routes.path); if (webConfig.routes.filter) { var filter = webConfig.routes.filter; routes = routes.filter(function(file){ try { if (typeof filter === 'function') { return filter(file); } else if (typeof filter.test === 'function'){ return filter.test(file); }else { assert.ok(false, 'Route filter type should be Function or Regexp.'); } } catch(e) { // Otherwise, it's probably not the right type. return false; } }); } routes.forEach(function (file) { var controller = require(file); if (typeof controller === 'function' && controller.length === 1) { controller(app); } }); // "app.router" positions our routes // above the middleware defined below, // this means that Express will attempt // to match & call routes _before_ continuing // on, at which point we assume it's a 404 because // no route has handled the request. app.use(app.router); // Since this is the last non-error-handling // middleware use()d, we assume 404, as nothing else // responded. // $ curl http://localhost:3000/notfound // $ curl http://localhost:3000/notfound -H "Accept: application/json" // $ curl http://localhost:3000/notfound -H "Accept: text/plain" app.use(function(req, res, next){ res.status(404); res.send('Not found'); }); // error-handling middleware, take the same form // as regular middleware, however they require an // arity of 4, aka the signature (err, req, res, next). // when connect has an error, it will invoke ONLY error-handling // middleware. // If we were to next() here any remaining non-error-handling // middleware would then be executed, or if we next(err) to // continue passing the error, only error-handling middleware // would remain being executed, however here // we simply respond with an error page. app.use(function(err, req, res, next){ // we may use properties of the error object // here and next(err) appropriately, or if // we possibly recovered from the error, simply next(). res.status(err.status || 500); res.send('Error'); }); app.get('/404', function(req, res, next){ // trigger a 404 since no other middleware // will match /404 after this one, and we're not // responding here next(); }); process.on('message', function(msg) { if(msg === 'shutdown') { info("Received kill signal, shutting down gracefully"); server.close(function() { info("Closed out remaining connections"); process.exit(0) }); // Normally below code should no opportunity to execution setTimeout(function() { info("Could not close connections in time, forcefully shutting down"); process.exit() }, 2000); } }) var server = app.listen(webConfig.http.port, webConfig.http.hostname, webConfig.http.backlog)
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides data persistence using IE userData mechanism. * UserData uses proprietary Element.addBehavior(), Element.load(), * Element.save(), and Element.XMLDocument() methods, see: * http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx. * */ goog.provide('goog.storage.mechanism.IEUserData'); goog.require('goog.asserts'); goog.require('goog.iter.Iterator'); goog.require('goog.iter.StopIteration'); goog.require('goog.storage.mechanism.ErrorCode'); goog.require('goog.storage.mechanism.IterableMechanism'); goog.require('goog.structs.Map'); goog.require('goog.userAgent'); /** * Provides a storage mechanism using IE userData. * * @param {string} storageKey The key (store name) to store the data under. * @param {string=} opt_storageNodeId The ID of the associated HTML element, * one will be created if not provided. * @constructor * @extends {goog.storage.mechanism.IterableMechanism} * @final */ goog.storage.mechanism.IEUserData = function(storageKey, opt_storageNodeId) { goog.base(this); // Tested on IE6, IE7 and IE8. It seems that IE9 introduces some security // features which make persistent (loaded) node attributes invisible from // JavaScript. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) { if (!goog.storage.mechanism.IEUserData.storageMap_) { goog.storage.mechanism.IEUserData.storageMap_ = new goog.structs.Map(); } this.storageNode_ = /** @type {Element} */ ( goog.storage.mechanism.IEUserData.storageMap_.get(storageKey)); if (!this.storageNode_) { if (opt_storageNodeId) { this.storageNode_ = document.getElementById(opt_storageNodeId); } else { this.storageNode_ = document.createElement('userdata'); // This is a special IE-only method letting us persist data. this.storageNode_['addBehavior']('#default#userData'); document.body.appendChild(this.storageNode_); } goog.storage.mechanism.IEUserData.storageMap_.set( storageKey, this.storageNode_); } this.storageKey_ = storageKey; /** @preserveTry */ try { // Availability check. this.loadNode_(); } catch (e) { this.storageNode_ = null; } } }; goog.inherits(goog.storage.mechanism.IEUserData, goog.storage.mechanism.IterableMechanism); /** * Encoding map for characters which are not encoded by encodeURIComponent(). * See encodeKey_ documentation for encoding details. * * @type {!Object} * @const */ goog.storage.mechanism.IEUserData.ENCODE_MAP = { '.': '.2E', '!': '.21', '~': '.7E', '*': '.2A', '\'': '.27', '(': '.28', ')': '.29', '%': '.' }; /** * Global storageKey to storageNode map, so we save on reloading the storage. * * @type {goog.structs.Map} * @private */ goog.storage.mechanism.IEUserData.storageMap_ = null; /** * The document element used for storing data. * * @type {Element} * @private */ goog.storage.mechanism.IEUserData.prototype.storageNode_ = null; /** * The key to store the data under. * * @type {?string} * @private */ goog.storage.mechanism.IEUserData.prototype.storageKey_ = null; /** * Encodes anything other than [-a-zA-Z0-9_] using a dot followed by hex, * and prefixes with underscore to form a valid and safe HTML attribute name. * * We use URI encoding to do the initial heavy lifting, then escape the * remaining characters that we can't use. Since a valid attribute name can't * contain the percent sign (%), we use a dot (.) as an escape character. * * @param {string} key The key to be encoded. * @return {string} The encoded key. * @private */ goog.storage.mechanism.IEUserData.encodeKey_ = function(key) { // encodeURIComponent leaves - _ . ! ~ * ' ( ) unencoded. return '_' + encodeURIComponent(key).replace(/[.!~*'()%]/g, function(c) { return goog.storage.mechanism.IEUserData.ENCODE_MAP[c]; }); }; /** * Decodes a dot-encoded and character-prefixed key. * See encodeKey_ documentation for encoding details. * * @param {string} key The key to be decoded. * @return {string} The decoded key. * @private */ goog.storage.mechanism.IEUserData.decodeKey_ = function(key) { return decodeURIComponent(key.replace(/\./g, '%')).substr(1); }; /** * Determines whether or not the mechanism is available. * * @return {boolean} True if the mechanism is available. */ goog.storage.mechanism.IEUserData.prototype.isAvailable = function() { return !!this.storageNode_; }; /** @override */ goog.storage.mechanism.IEUserData.prototype.set = function(key, value) { this.storageNode_.setAttribute( goog.storage.mechanism.IEUserData.encodeKey_(key), value); this.saveNode_(); }; /** @override */ goog.storage.mechanism.IEUserData.prototype.get = function(key) { // According to Microsoft, values can be strings, numbers or booleans. Since // we only save strings, any other type is a storage error. If we returned // nulls for such keys, i.e., treated them as non-existent, this would lead // to a paradox where a key exists, but it does not when it is retrieved. // http://msdn.microsoft.com/en-us/library/ms531348(v=vs.85).aspx var value = this.storageNode_.getAttribute( goog.storage.mechanism.IEUserData.encodeKey_(key)); if (!goog.isString(value) && !goog.isNull(value)) { throw goog.storage.mechanism.ErrorCode.INVALID_VALUE; } return value; }; /** @override */ goog.storage.mechanism.IEUserData.prototype.remove = function(key) { this.storageNode_.removeAttribute( goog.storage.mechanism.IEUserData.encodeKey_(key)); this.saveNode_(); }; /** @override */ goog.storage.mechanism.IEUserData.prototype.getCount = function() { return this.getNode_().attributes.length; }; /** @override */ goog.storage.mechanism.IEUserData.prototype.__iterator__ = function(opt_keys) { var i = 0; var attributes = this.getNode_().attributes; var newIter = new goog.iter.Iterator(); newIter.next = function() { if (i >= attributes.length) { throw goog.iter.StopIteration; } var item = goog.asserts.assert(attributes[i++]); if (opt_keys) { return goog.storage.mechanism.IEUserData.decodeKey_(item.nodeName); } var value = item.nodeValue; // The value must exist and be a string, otherwise it is a storage error. if (!goog.isString(value)) { throw goog.storage.mechanism.ErrorCode.INVALID_VALUE; } return value; }; return newIter; }; /** @override */ goog.storage.mechanism.IEUserData.prototype.clear = function() { var node = this.getNode_(); for (var left = node.attributes.length; left > 0; left--) { node.removeAttribute(node.attributes[left - 1].nodeName); } this.saveNode_(); }; /** * Loads the underlying storage node to the state we saved it to before. * * @private */ goog.storage.mechanism.IEUserData.prototype.loadNode_ = function() { // This is a special IE-only method on Elements letting us persist data. this.storageNode_['load'](this.storageKey_); }; /** * Saves the underlying storage node. * * @private */ goog.storage.mechanism.IEUserData.prototype.saveNode_ = function() { /** @preserveTry */ try { // This is a special IE-only method on Elements letting us persist data. // Do not try to assign this.storageNode_['save'] to a variable, it does // not work. May throw an exception when the quota is exceeded. this.storageNode_['save'](this.storageKey_); } catch (e) { throw goog.storage.mechanism.ErrorCode.QUOTA_EXCEEDED; } }; /** * Returns the storage node. * * @return {Element} Storage DOM Element. * @private */ goog.storage.mechanism.IEUserData.prototype.getNode_ = function() { // This is a special IE-only property letting us browse persistent data. var doc = /** @type {Document} */ (this.storageNode_['XMLDocument']); return doc.documentElement; };
'use strict'; angular.module('mean.system') .directive('scrollBottom', function () { return { scope: { scrollBottom: "=" }, link: function (scope, element) { scope.$watchCollection('scrollBottom', function (newValue) { if (newValue) { $(element).scrollTop($(element)[0].scrollHeight); } }); } } });
var arduino = require("arduino"); var spi = require("arduino-spi"); function setup() { spi.beginTransaction(14000, MSBFIRST, SPI_MODE0); } function loop() { }
var models = require( 'models' ); var User = models.User; var passport = require('passport'); var LocalStrategy = require('passport-local'); var FacebookStrategy = require('passport-facebook').Strategy; var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var config = require('config'); var Promise = require('bluebird'); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser( function(id, done){ User.findById(id).asCallback( done ); }); passport.use('local', new LocalStrategy({ usernameField : 'email', passwordField : 'password', passReqToCallback : true }, function(req, email, password,done ) { models.User.findOne({where:{email:email , password:password}}). then(function(user){ if(!user) return done(null, false); return done(null, user); }) })); passport.use(new FacebookStrategy({ clientID: config.fbLogin.appId, clientSecret: config.fbLogin.appSecret, callbackURL: '/auth/facebook/callback', profileFields: ['name', 'email', 'link', 'locale', 'timezone'], passReqToCallback: true }, (req, accessToken, refreshToken, profile, done) => { return User.findOne({where: { facebook: profile.id } } ) .then( function( existingUser ){ if (existingUser) { return existingUser; } var user = User.build({ name: profile.displayName || ( profile.name.givenName + ' ' + profile.name.familyName ), facebook: profile.id, facebookToken: accessToken, password: Math.random(10), email: profile.emails[0].value, username: profile.emails[0].value, profilePic: profile.picture || 'https://graph.facebook.com/'+profile.id+'/picture?type=large' }); return user.save(); }) .asCallback( done ); } ));
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error perferendis nam illum necessitatibus animi consequuntur maxime quod ducimus, voluptatem ipsa.
var net = require('net'); var clients = {}; var server = net.createServer(function (socket) { socket.name = socket.remoteAddress +':'+ socket.remotePort; if (typeof clients[socket.name] == 'undefined') { clients[socket.name] = {socket: socket, buffer: ''}; } socket.on('data', function(data) { console.log(socket.name +' > '+ data); var client = clients[socket.name]; client.buffer += data.toString('utf8'); var index = client.buffer.length - 2; if (index >= 0) { // chat commands end with \r\n, ladder seach ends with \n\n if (client.buffer.lastIndexOf('\n\n') === index) { core(client, client.buffer); client.buffer = ''; } } }); }); server.listen(4007); function core(user, data) { var data = data.split('\r\n'); if (data.length > 0) { for(var i = 0; i <= data.length - 1; i++) { var cmd = data[i].split(' '); if (cmd.length > 0 && cmd[0].length > 0) { switch(cmd[0].toUpperCase()) { case 'LISTSEARCH': listsearch(user, cmd); break; case 'HIGHSCORE': highscore(user, cmd); break; case 'RUNGSEARCH': rungsearch(user, cmd); break; } } } } }; function listsearch(user, cmd) { if (cmd.length > 5) { var r = ['', ''], cvers = cmd[1]; if (typeof cmd[6] != 'undefined') { var nicks = cmd[6].split(':'); for(var i = 0; i <= nicks.length - 1; i++) { var nick = nicks[i].toLowerCase(); if (nick.length < 3) continue; r.push('NOTFOUND'); } // ##end nicks for loop } console.log(user.socket.name +' < '+ r.join('\r\n')); user.socket.write(r.join('\r\n')); user.socket.destroy(); delete clients[user.socket.name]; } }; function highscore(user, cmd) { } function rungsearch(user, cmd) { }
var html = require('fs').readFileSync(__dirname+'/test5.html'); var app = require('http').createServer(function(req, res){ res.end(html); }); app.listen(8091); var io = require("socket.io"); var io = io.listen(app); io.sockets.on('connection', function (socket) { socket.emit('faitUneAlerte'); });
const PORT = 8022; export { PORT, };
'use strict' const tap = require('tap') const isTbr = require('../index') var options = { skoleid: 3840, postnummer: '', gatenavn: 'Djevelgaten', husnummer: '666' } options.postnummer = 3960 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3960 Stathelle') options.postnummer = 3800 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3800 Bø i Telemark') options.postnummer = 3801 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3801 Bø i Telemark') options.postnummer = 3802 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3802 Bø i Telemark') options.postnummer = 3803 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3803 Bø i Telemark') options.postnummer = 3804 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3804 Bø i Telemark') options.postnummer = 3750 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3750 Drangedal') options.postnummer = 3848 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3848 Morgedal') options.postnummer = 3854 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3854 Nissedal') options.postnummer = 3825 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3825 Lunde') options.postnummer = 3830 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3830 Ulefoss') options.postnummer = 3831 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3831 Ulefoss') options.postnummer = 3672 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns true from 3825 Notodden') options.postnummer = 3810 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3810 Gvarv') options.postnummer = 3811 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3811 Hørte') options.postnummer = 3812 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3812 Akkerhaugen') options.postnummer = 3820 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3820 Nordagutu') options.postnummer = 3834 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3834 Gvarv') options.postnummer = 3805 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3805 Bø i Telemark') options.postnummer = 3748 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3748 Siljan') options.postnummer = 3729 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3729 Skien') options.postnummer = 3650 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3650 Tinn i Austbygd') options.postnummer = 3891 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3891 Høydalsmo') options.postnummer = 3884 tap.equal(isTbr(options), false, 'Vest Telemark vgs, avdeling Seljord returns false from 3884 Rauland') options.postnummer = 3890 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3890 Vinje') options.postnummer = 3893 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3893 Vinjesvingen') options.postnummer = 3895 tap.equal(isTbr(options), true, 'Vest Telemark vgs, avdeling Seljord returns true from 3895 Edland')
module.exports = { "extends": "standard", "plugins": [ "standard", "promise" ], rules: { 'semi': 0, 'space-before-function-paren': 0, 'no-multiple-empty-lines': 0, "comma-dangle": 0 } };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './Header.css'; class Header extends Component { static propTypes = { title: PropTypes.string.isRequired, children: PropTypes.node, } render() { const { title, children } = this.props; return ( <header className="jumbotron"> <div className="container"> <h1>{title}</h1> {children} </div> </header> ); } } export default Header;
/* * Tests EasyAutocomplete - response json * * @author Łukasz Pawełczak */ QUnit.test('JSON - Simple list response', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(3, elements.length, 'Response size'); assert.equal('red', elements.eq(0).find('div').text(), 'First element value'); assert.equal('yellow', elements.eq(1).find('div').text(), 'Second element value'); assert.equal('brown', elements.eq(2).find('div').text(), 'Third element value'); done(); } }); QUnit.test('JSON - Simple object', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { getValue: function (element) { return element.name; }, url: 'resources/colors_object.json', ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(3, elements.length, 'Response size'); assert.equal('red', elements.eq(0).find('div').text(), 'First element value'); assert.equal('yellow', elements.eq(1).find('div').text(), 'Second element value'); assert.equal('brown', elements.eq(2).find('div').text(), 'Third element value'); done(); } }); QUnit.test('JSON - Simple object - getValue equals string', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { getValue: 'name', url: 'resources/colors_object.json', ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(3, elements.length, 'Response size'); assert.equal('red', elements.eq(0).find('div').text(), 'First element value'); assert.equal('yellow', elements.eq(1).find('div').text(), 'Second element value'); assert.equal('brown', elements.eq(2).find('div').text(), 'Third element value'); done(); } }); QUnit.test('JSON - Sorted list', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', list: {sort: {enabled: true}}, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(3, elements.length, 'Response size'); assert.equal('brown', elements.eq(0).find('div').text(), 'First element value'); assert.equal('red', elements.eq(1).find('div').text(), 'Second element value'); assert.equal('yellow', elements.eq(2).find('div').text(), 'Third element value'); done(); } }); QUnit.test('JSON - Reverse sorted list', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', list: { sort: { enabled: true, method: function (a, b) { //Reverse alphabeticall sort if (a < b) { return 1; } if (a > b) { return -1; } return 0; } } }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(3, elements.length, 'Response size'); assert.equal('yellow', elements.eq(0).find('div').text(), 'First element value'); assert.equal('red', elements.eq(1).find('div').text(), 'Second element value'); assert.equal('brown', elements.eq(2).find('div').text(), 'Third element value'); done(); } }); QUnit.test('JSON - Max elements number list', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', list: { maxNumberOfElements: 1 }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(1, elements.length, 'Response size'); assert.equal('red', elements.eq(0).find('div').text(), 'First element value'); done(); } }); QUnit.test('JSON - match - string list phrase \'re\'', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', list: { match: { enabled: true } }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('r').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(2, elements.length, 'Response size'); assert.equal('red', elements.eq(0).find('div').text(), 'Red element value'); assert.equal('brown', elements.eq(1).find('div').text(), 'Brown element value'); done(); } }); QUnit.test('JSON - Match all elements from list', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/countries.json', getValue: function (element) { return element.name; }, list: { maxNumberOfElements: 999, match: { enabled: true } }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('a').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(206, elements.length, 'Response size'); assert.equal('Cocos (Keeling) Islands', elements.eq(41).find('div').text(), 'Cocos (Keeling) Islands element value'); assert.equal('Malaysia', elements.eq(111).find('div').text(), 'Malaysia element value'); done(); } }); QUnit.test('JSON - Simple match list phrase \'ok\'', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/countries.json', getValue: function (element) { return element.name; }, list: { match: { enabled: true } }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('ok').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(2, elements.length, 'Response size'); assert.equal('Cook Islands', elements.eq(0).find('div').text(), 'Cook island element value'); assert.equal('Tokelau', elements.eq(1).find('div').text(), 'Tokelau element value'); done(); } }); QUnit.test('JSON - Dont highlight phrase', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', highlightPhrase: false, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('r').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal('red', elements.eq(0).find('div').html(), 'red element value'); assert.equal('brown', elements.eq(2).find('div').html(), 'brown element value'); done(); } }); QUnit.test('JSON - Highlight - string list ', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_string.json', highlightPhrase: true, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('r').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal('<b>r</b>ed', elements.eq(0).find('div').html(), 'red element value'); assert.equal('b<b>r</b>own', elements.eq(2).find('div').html(), 'brown element value'); done(); } }); QUnit.test('JSON - Highlight - object list', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { url: 'resources/colors_object.json', getValue: function (element) { return element.name; }, highlightPhrase: true, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('r').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal('<b>r</b>ed', elements.eq(0).find('div').html(), 'red element value'); assert.equal('b<b>r</b>own', elements.eq(2).find('div').html(), 'brown element value'); done(); } }); QUnit.test('JSON - duckduckgo response', function (assert) { // given var completerOne = new EasyAutocomplete.main($('#inputOne'), { listLocation: 'RelatedTopics', getValue: function (element) { return element.Text; }, url: 'resources/duckduckgo.json', list: { maxNumberOfElements: 10 }, ajaxCallback: function () { // then assertList(); } }); // when completerOne.init(); var e = $.Event('keyup'); e.keyCode = 50; $('#inputOne').val('c').trigger(e); var done = assert.async(); // then function assertList() { var elements = $('#inputOne').next().find('ul li'); assert.equal(10, elements.length, 'Response size'); assert.equal('Autocorrect, automatic correction of misspelled words.', elements.eq(0).find('div').text(), 'First element value'); assert.equal('Text editor features', elements.eq(6).find('div').text(), 'Second element value'); assert.equal('Disability software', elements.eq(7).find('div').text(), 'Third element value'); assert.equal('Free software', elements.eq(9).find('div').text(), 'Fourth element value'); done(); } });
'use strict'; const pathFn = require('path'); const fs = require('hexo-fs'); const Promise = require('bluebird'); const moment = require('moment'); const sinon = require('sinon'); describe('View', () => { const Hexo = require('../../../lib/hexo'); const hexo = new Hexo(pathFn.join(__dirname, 'theme_test')); const themeDir = pathFn.join(hexo.base_dir, 'themes', 'test'); hexo.env.init = true; function newView(path, data) { return new hexo.theme.View(path, data); } before(() => Promise.all([ fs.mkdirs(themeDir), fs.writeFile(hexo.config_path, 'theme: test') ]).then(() => hexo.init()).then(() => { // Setup layout hexo.theme.setView('layout.swig', [ 'pre', '{{ body }}', 'post' ].join('\n')); })); after(() => fs.rmdir(hexo.base_dir)); it('constructor', () => { const data = { _content: '' }; const view = newView('index.swig', data); view.path.should.eql('index.swig'); view.source.should.eql(pathFn.join(themeDir, 'layout', 'index.swig')); view.data.should.eql(data); }); it('parse front-matter', () => { const body = [ 'layout: false', '---', 'content' ].join('\n'); const view = newView('index.swig', body); view.data.should.eql({ layout: false, _content: 'content' }); }); it('precompile view if possible', () => { const body = 'Hello {{ name }}'; const view = newView('index.swig', body); view._compiledSync({ name: 'Hexo' }).should.eql('Hello Hexo'); return view._compiled({ name: 'Hexo' }).then(result => { result.should.eql('Hello Hexo'); }); }); it('generate precompiled function even if renderer does not provide compile function', () => { // Remove compile function const compile = hexo.extend.renderer.store.swig.compile; delete hexo.extend.renderer.store.swig.compile; const body = 'Hello {{ name }}'; const view = newView('index.swig', body); view._compiledSync({ name: 'Hexo' }).should.eql('Hello Hexo'); return view._compiled({ name: 'Hexo' }).then(result => { result.should.eql('Hello Hexo'); }).finally(() => { hexo.extend.renderer.store.swig.compile = compile; }); }); it('render()', () => { const body = [ '{{ test }}' ].join('\n'); const view = newView('index.swig', body); return view.render({ test: 'foo' }).then(content => { content.should.eql('foo'); }); }); it('render() - front-matter', () => { // The priority of front-matter is higher const body = [ 'foo: bar', '---', '{{ foo }}', '{{ test }}' ].join('\n'); const view = newView('index.swig', body); return view.render({ foo: 'foo', test: 'test' }).then(content => { content.should.eql('bar\ntest'); }); }); it('render() - helper', () => { const body = [ '{{ date() }}' ].join('\n'); const view = newView('index.swig', body); return view.render({ config: hexo.config, page: {} }).then(content => { content.should.eql(moment().format(hexo.config.date_format)); }); }); it('render() - layout', () => { const body = 'content'; const view = newView('index.swig', body); return view.render({ layout: 'layout' }).then(content => { content.should.eql('pre\n' + body + '\npost'); }); }); it('render() - layout not found', () => { const body = 'content'; const view = newView('index.swig', body); return view.render({ layout: 'wtf' }).then(content => { content.should.eql(body); }); }); it('render() - callback', callback => { const body = [ '{{ test }}' ].join('\n'); const view = newView('index.swig', body); view.render({ test: 'foo' }, (err, content) => { should.not.exist(err); content.should.eql('foo'); callback(); }); }); it('render() - callback (without options)', callback => { const body = [ 'test: foo', '---', '{{ test }}' ].join('\n'); const view = newView('index.swig', body); view.render((err, content) => { should.not.exist(err); content.should.eql('foo'); callback(); }); }); it('render() - execute after_render:html', () => { const body = [ '{{ test }}' ].join('\n'); const view = newView('index.swig', body); const filter = sinon.spy(result => { result.should.eql('foo'); return 'bar'; }); hexo.extend.filter.register('after_render:html', filter); return view.render({ test: 'foo' }).then(content => { content.should.eql('bar'); }).finally(() => { hexo.extend.filter.unregister('after_render:html', filter); }); }); it('renderSync()', () => { const body = [ '{{ test }}' ].join('\n'); const view = newView('index.swig', body); view.renderSync({test: 'foo'}).should.eql('foo'); }); it('renderSync() - front-matter', () => { // The priority of front-matter is higher const body = [ 'foo: bar', '---', '{{ foo }}', '{{ test }}' ].join('\n'); const view = newView('index.swig', body); view.renderSync({ foo: 'foo', test: 'test' }).should.eql('bar\ntest'); }); it('renderSync() - helper', () => { const body = [ '{{ date() }}' ].join('\n'); const view = newView('index.swig', body); view.renderSync({ config: hexo.config, page: {} }).should.eql(moment().format(hexo.config.date_format)); }); it('renderSync() - layout', () => { const body = 'content'; const view = newView('index.swig', body); view.renderSync({ layout: 'layout' }).should.eql('pre\n' + body + '\npost'); }); it('renderSync() - layout not found', () => { const body = 'content'; const view = newView('index.swig', body); view.renderSync({ layout: 'wtf' }).should.eql(body); }); it('renderSync() - execute after_render:html', () => { const body = [ '{{ test }}' ].join('\n'); const view = newView('index.swig', body); const filter = sinon.spy(result => { result.should.eql('foo'); return 'bar'; }); hexo.extend.filter.register('after_render:html', filter); view.renderSync({test: 'foo'}).should.eql('bar'); hexo.extend.filter.unregister('after_render:html', filter); }); it('_resolveLayout()', () => { const view = newView('partials/header.swig', 'header'); // Relative path view._resolveLayout('../layout').should.have.property('path', 'layout.swig'); // Absolute path view._resolveLayout('layout').should.have.property('path', 'layout.swig'); // Can't be itself should.not.exist(view._resolveLayout('header')); }); });
{ assert.equal(1, a); assert.isUndefined(b); assert.isUndefined(c); a = b = c = undefined; }
app.post('/login', function(req, res) { var query = base.extend({}, req.body, req.query); // TODO DB request sholud be here if (config.auth.hasOwnProperty(query.login) && query.password === config.auth[query.login]){ req.session.admin = true; res.send({access: 'granted'}); log.info('AUTH', 'User have just been logged-in >', query.login, '< Whoohaa! '); } else { res.send({error: 'auth pair does not exists'}); log.warning('AUTH', 'Fail login attempt', query.login); } }); app.auth = { adminOnly: function(req, res, next){ if (req.session.admin) { next(); } else { log.warning('AUTH', 'Attempt unauthorised access', req.ip); res.send({error: 'access denied'}); } } };
/** * @file This prototype contains all important environment data of a stage. * * @author Human Interactive */ "use strict"; var THREE = require( "three" ); var scene = require( "./Scene" ); var actionManager = require( "../action/ActionManager" ); var entityManager = require( "../game/entity/EntityManager" ); var GameEntity = require( "../game/entity/GameEntity" ); /** * Creates a world object. * * @constructor */ function World() { Object.defineProperties( this, { player : { value : null, configurable : false, enumerable : true, writable : true, }, scene : { value : scene, configurable : false, enumerable : true, writable : false }, grounds : { value : [], configurable : false, enumerable : true, writable : false }, walls : { value : [], configurable : false, enumerable : true, writable : false }, // this is just a reference to the action objects of the action manager actionObjects : { value : actionManager._actionObjects, configurable : false, enumerable : true, writable : false } } ); } /** * Initializes the world. */ World.prototype.init = function() { // create player instance this.player = entityManager.createPlayer( this ); // set the scope of this entity to WORLD. it won't get deleted within a // stage change this.player.scope = GameEntity.SCOPE.WORLD; // add player to world this.addObject3D( this.player.object3D ); }; /** * Adds a 3D object to the internal scene. * * @param {THREE.Mesh} ground - The ground to add. */ World.prototype.addObject3D = function( object ) { this.scene.add( object ); }; /** * Removes a 3D object from the internal scene. * * @param {THREE.Mesh} ground - The ground to add. */ World.prototype.removeObject3D = function( object ) { this.scene.remove( object ); }; /** * Removes all 3D object from the internal scene. */ World.prototype.removeObjects3D = function( object ) { this.scene.clear(); }; /** * Adds a ground to the internal array. * * @param {THREE.Mesh} ground - The ground to add. */ World.prototype.addGround = function( ground ) { this.grounds.push( ground ); // ground objects always needs to be added to the scene this.addObject3D( ground ); }; /** * Removes a ground from the internal array. * * @param {THREE.Mesh} ground - The ground to remove. */ World.prototype.removeGround = function( ground ) { var index = this.grounds.indexOf( ground ); this.grounds.splice( index, 1 ); // ground objects always needs to be removed from the scene this.removeObject3D( ground ); }; /** * Removes all grounds from the internal array. */ World.prototype.removeGrounds = function() { for ( var index = this.grounds.length - 1; index >= 0; index-- ) { this.removeGround( this.grounds[ index ] ); } }; /** * Adds a wall to the internal array. * * @param {THREE.Mesh} wall - The wall to add. */ World.prototype.addWall = function( wall ) { this.walls.push( wall ); // wall objects always needs to be added to the scene this.addObject3D( wall ); }; /** * Removes a wall from the internal array. * * @param {THREE.Mesh} wall - The wall to remove. */ World.prototype.removeWall = function( wall ) { var index = this.walls.indexOf( wall ); this.walls.splice( index, 1 ); // wall objects always needs to be removed from the scene this.removeObject3D( wall ); }; /** * Removes all walls from the internal array. */ World.prototype.removeWalls = function() { for ( var index = this.walls.length - 1; index >= 0; index-- ) { this.removeWall( this.walls[ index ] ); } }; /** * Calculates neighbors for a given vehicle. * * @param {Vehicle} vehicle - The given vehicle. * @param {number} viewDistance - The view distance of the vehicle. * @param {object} neighbors - The calculated neighbors. */ World.prototype.calculateNeighbors = ( function() { var toEntity = new THREE.Vector3(); return function( vehicle, viewDistance, neighbors ) { var index, entity; // reset array neighbors.length = 0; // iterate over all entities for ( index = 0; index < entityManager.entities.length; index++ ) { entity = entityManager.entities[ index ]; // in this case, the own vehicle AND the player will be ignored if ( entity !== vehicle && entity !== this.player ) { // calculate displacement vector toEntity.subVectors( entity.position, vehicle.object3D.position ); // if entity within range, push into neighbors array for further // consideration. if ( toEntity.lengthSq() < ( viewDistance * viewDistance ) ) { neighbors.push( entity ); } } } }; }() ); /** * Clears the world object. */ World.prototype.clear = function() { this.removeWalls(); this.removeGrounds(); this.removeObjects3D(); }; module.exports = new World();
'use strict'; var request = require('request'); var through = require('through2'); var DEFAULTS = { objectMode: false, request: request, retries: 2, noResponseRetries: 2, currentRetryAttempt: 0, shouldRetryFn: function (response) { var retryRanges = [ // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes // 1xx - Retry (Informational, request still processing) // 2xx - Do not retry (Success) // 3xx - Do not retry (Redirect) // 4xx - Do not retry (Client errors) // 429 - Retry ("Too Many Requests") // 5xx - Retry (Server errors) [100, 199], [429, 429], [500, 599] ]; var statusCode = response.statusCode; var range; while ((range = retryRanges.shift())) { if (statusCode >= range[0] && statusCode <= range[1]) { // Not a successful status or redirect. return true; } } } }; function retryRequest(requestOpts, opts, callback) { var streamMode = typeof arguments[arguments.length - 1] !== 'function'; if (typeof opts === 'function') { callback = opts; } opts = opts || DEFAULTS; if (typeof opts.objectMode === 'undefined') { opts.objectMode = DEFAULTS.objectMode; } if (typeof opts.request === 'undefined') { opts.request = DEFAULTS.request; } if (typeof opts.retries !== 'number') { opts.retries = DEFAULTS.retries; } if (typeof opts.currentRetryAttempt !== 'number') { opts.currentRetryAttempt = DEFAULTS.currentRetryAttempt; } if (typeof opts.shouldRetryFn !== 'function') { opts.shouldRetryFn = DEFAULTS.shouldRetryFn; } var currentRetryAttempt = opts.currentRetryAttempt; var numNoResponseAttempts = 0; var streamResponseHandled = false; var retryStream; var requestStream; var delayStream; var activeRequest; var retryRequest = { abort: function () { if (activeRequest && activeRequest.abort) { activeRequest.abort(); } } }; if (streamMode) { retryStream = through({ objectMode: opts.objectMode }); retryStream.abort = resetStreams; } makeRequest(); if (streamMode) { return retryStream; } else { return retryRequest; } function resetStreams() { delayStream = null; if (requestStream) { requestStream.abort && requestStream.abort(); requestStream.cancel && requestStream.cancel(); if (requestStream.destroy) { requestStream.destroy(); } else if (requestStream.end) { requestStream.end(); } } } function makeRequest() { currentRetryAttempt++; if (streamMode) { streamResponseHandled = false; delayStream = through({ objectMode: opts.objectMode }); requestStream = opts.request(requestOpts); setImmediate(function () { retryStream.emit('request'); }); requestStream // gRPC via google-cloud-node can emit an `error` as well as a `response` // Whichever it emits, we run with-- we can't run with both. That's what // is up with the `streamResponseHandled` tracking. .on('error', function (err) { if (streamResponseHandled) { return; } streamResponseHandled = true; onResponse(err); }) .on('response', function (resp, body) { if (streamResponseHandled) { return; } streamResponseHandled = true; onResponse(null, resp, body); }) .on('complete', retryStream.emit.bind(retryStream, 'complete')); requestStream.pipe(delayStream); } else { activeRequest = opts.request(requestOpts, onResponse); } } function retryAfterDelay(currentRetryAttempt) { if (streamMode) { resetStreams(); } setTimeout(makeRequest, getNextRetryDelay(currentRetryAttempt)); } function onResponse(err, response, body) { // An error such as DNS resolution. if (err) { numNoResponseAttempts++; if (numNoResponseAttempts <= opts.noResponseRetries) { retryAfterDelay(numNoResponseAttempts); } else { if (streamMode) { retryStream.emit('error', err); retryStream.end(); } else { callback(err, response, body); } } return; } // Send the response to see if we should try again. if (currentRetryAttempt <= opts.retries && opts.shouldRetryFn(response)) { retryAfterDelay(currentRetryAttempt); return; } // No more attempts need to be made, just continue on. if (streamMode) { retryStream.emit('response', response); delayStream.pipe(retryStream); requestStream.on('error', function (err) { retryStream.destroy(err); }); } else { callback(err, response, body); } } } module.exports = retryRequest; function getNextRetryDelay(retryNumber) { return (Math.pow(2, retryNumber) * 1000) + Math.floor(Math.random() * 1000); } module.exports.getNextRetryDelay = getNextRetryDelay;
import bound from './bound' const setX = x => () => ({x}) export const boundSetX = (x) => (state, props) => bound({ result: setX(x)(), ...state, ...props }) export default setX
var count = 0; function setup() { var can = createCanvas(windowWidth, 650); can.parent('p5-sketch'); } function draw() { var r = 255; var g = 255; var b = 255; var a = Math.floor(Math.random() * 82); background(0); drawCircle(width / 2, height / 2, count); count += 1; if (count === 2000) count = 1999; } function windowResized() { resizeCanvas(windowWidth, 650); } function drawCircle(x, y, radius) { noFill(); var r = 255; var g = 255; var b = 255; var a = Math.floor(Math.random() * 82); stroke(color(r, g, b, a)); ellipse(x, y, radius, radius); if (radius > 200) { drawCircle(x + radius, y, radius / 1.5); drawCircle(x - radius, y, radius / 1.5); } }
/* ************************************************************************ * * qooxdoo-compiler - node.js based replacement for the Qooxdoo python * toolchain * * https://github.com/qooxdoo/qooxdoo-compiler * * Copyright: * 2011-2017 Zenesis Limited, http://www.zenesis.com * * License: * MIT: https://opensource.org/licenses/MIT * * This software is provided under the same licensing terms as Qooxdoo, * please see the LICENSE file in the Qooxdoo project's top-level directory * for details. * * Authors: * * John Spackman ([email protected], @johnspackman) * * *********************************************************************** */ /* eslint no-inner-declarations: 0 */ var fs = require("fs"); var path = require("path"); var xml2js = require("xml2js"); const CLDR = require("cldr"); const {promisify} = require("util"); const readFile = promisify(fs.readFile); var log = qx.tool.utils.LogManager.createLog("cldr"); qx.Class.define("qx.tool.compiler.app.Cldr", { extend: qx.core.Object, statics: { /** * Returns the parent locale for a given locale */ getParentLocale: function(locale) { return CLDR.resolveParentLocaleId(locale.toLowerCase()); }, /** * Loads CLDR data from the Qx framework * * @param locale * @async */ loadCLDR: function(locale) { var parser = new xml2js.Parser(); let cldrPath = path.dirname(require.resolve("cldr")); const data_path = "../3rdparty/cldr/common/main"; if (!cldrPath) { throw new Error("Cannot find cldr path"); } log.debug("Loading CLDR " + cldrPath); return readFile(path.join(cldrPath, data_path, locale + ".xml"), {encoding: "utf-8"}) .then(data => qx.tool.utils.Utils.promisifyThis(parser.parseString, parser, data)) .then(src => { function find(arr, name, value, cb) { if (!arr) { return null; } for (var i = 0; i < arr.length; i++) { var row = arr[i]; if (row["$"] && row["$"][name] == value) { if (typeof cb == "function") { return cb(row); } return row; } } return null; } function get(path, node) { if (node === undefined) { node = src; } var segs = path.split("."); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; var pos = seg.indexOf("["); var index = null; if (pos > -1) { index = seg.substring(pos + 1, seg.length - 1); seg = seg.substring(0, pos); } var next = node[seg]; if (!next) { return null; } if (index !== null) { if (!qx.lang.Type.isArray(next)) { return null; } next = next[index]; if (next === undefined) { return null; } } node = next; } return node; } function getValue(path, node) { let result = get(path, node); if (result && typeof result != "string" && result["_"] !== undefined) { return result["_"]; } return result; } var cal = find(get("ldml.dates[0].calendars[0].calendar"), "type", "gregorian"); var cldr = {}; cldr.alternateQuotationEnd = get("ldml.delimiters[0].alternateQuotationEnd[0]"); cldr.alternateQuotationStart = get("ldml.delimiters[0].alternateQuotationStart[0]"); cldr.quotationEnd = get("ldml.delimiters[0].quotationEnd[0]"); cldr.quotationStart = get("ldml.delimiters[0].quotationStart[0]"); function getText(row) { if (typeof row == "string") { return row; } if (row && row["_"] !== undefined) { return row["_"]; } return ""; } function getDateFormatPattern(row) { return row.dateFormat[0].pattern[0]; } if (cal !== null) { find(get("dayPeriods[0].dayPeriodContext[0].dayPeriodWidth", cal), "type", "wide", function(row) { cldr.cldr_am = find(row.dayPeriod, "type", "am", getText); cldr.cldr_pm = find(row.dayPeriod, "type", "pm", getText);// "PM"; }); var dateFormatLength = get("dateFormats[0].dateFormatLength", cal); var dateFormatItem = get("dateTimeFormats[0].availableFormats[0].dateFormatItem", cal); cldr.cldr_date_format_full = find(dateFormatLength, "type", "full", getDateFormatPattern);// "EEEE, MMMM d, y"; cldr.cldr_date_format_long = find(dateFormatLength, "type", "long", getDateFormatPattern);// "MMMM d, y"; cldr.cldr_date_format_medium = find(dateFormatLength, "type", "medium", getDateFormatPattern);// "MMM d, y"; cldr.cldr_date_format_short = find(dateFormatLength, "type", "short", getDateFormatPattern);// "M/d/yy"; cldr.cldr_date_time_format_Ed = find(dateFormatItem, "id", "Ed", getText);// "d E"; cldr.cldr_date_time_format_Hm = find(dateFormatItem, "id", "Hm", getText);// "HH:mm"; cldr.cldr_date_time_format_Hms = find(dateFormatItem, "id", "Hms", getText);// "HH:mm:ss"; cldr.cldr_date_time_format_M = find(dateFormatItem, "id", "M", getText);// "L"; cldr.cldr_date_time_format_MEd = find(dateFormatItem, "id", "MEd", getText);// "E, M/d"; cldr.cldr_date_time_format_MMM = find(dateFormatItem, "id", "MMM", getText);// "LLL"; cldr.cldr_date_time_format_MMMEd = find(dateFormatItem, "id", "MMMEd", getText);// "E, MMM d"; cldr.cldr_date_time_format_MMMd = find(dateFormatItem, "id", "MMMd", getText);// "MMM d"; cldr.cldr_date_time_format_Md = find(dateFormatItem, "id", "Md", getText);// "M/d"; cldr.cldr_date_time_format_d = find(dateFormatItem, "id", "d", getText);// "d"; cldr.cldr_date_time_format_hm = find(dateFormatItem, "id", "hm", getText);// "h:mm a"; cldr.cldr_date_time_format_hms = find(dateFormatItem, "id", "hms", getText);// "h:mm:ss a"; cldr.cldr_date_time_format_ms = find(dateFormatItem, "id", "ms", getText);// "mm:ss"; cldr.cldr_date_time_format_y = find(dateFormatItem, "id", "y", getText);// "y"; cldr.cldr_date_time_format_yM = find(dateFormatItem, "id", "yM", getText);// "M/y"; cldr.cldr_date_time_format_yMEd = find(dateFormatItem, "id", "yMEd", getText);// "E, M/d/y"; cldr.cldr_date_time_format_yMMM = find(dateFormatItem, "id", "yMMM", getText);// "MMM y"; cldr.cldr_date_time_format_yMMMEd = find(dateFormatItem, "id", "yMMMEd", getText);// "E, MMM d, y"; cldr.cldr_date_time_format_yMMMd = find(dateFormatItem, "id", "yMMMd", getText);// "MMM d, y"; cldr.cldr_date_time_format_yMd = find(dateFormatItem, "id", "yMd", getText);// "M/d/y"; cldr.cldr_date_time_format_yQ = find(dateFormatItem, "id", "yQ", getText);// "Q y"; cldr.cldr_date_time_format_yQQQ = find(dateFormatItem, "id", "yQQQ", getText);// "QQQ y"; var dayContext = get("days[0].dayContext", cal); find(dayContext, "type", "format", function(row) { find(row.dayWidth, "type", "abbreviated", function(row) { cldr.cldr_day_format_abbreviated_fri = find(row.day, "type", "fri", getText);// "Fri"; cldr.cldr_day_format_abbreviated_mon = find(row.day, "type", "mon", getText);// "Mon"; cldr.cldr_day_format_abbreviated_sat = find(row.day, "type", "sat", getText);// "Sat"; cldr.cldr_day_format_abbreviated_sun = find(row.day, "type", "sun", getText);// "Sun"; cldr.cldr_day_format_abbreviated_thu = find(row.day, "type", "thu", getText);// "Thu"; cldr.cldr_day_format_abbreviated_tue = find(row.day, "type", "tue", getText);// "Tue"; cldr.cldr_day_format_abbreviated_wed = find(row.day, "type", "wed", getText);// "Wed"; }); }); find(dayContext, "type", "format", function(row) { find(row.dayWidth, "type", "wide", function(row) { cldr.cldr_day_format_wide_fri = find(row.day, "type", "fri", getText);// "Friday"; cldr.cldr_day_format_wide_mon = find(row.day, "type", "mon", getText);// "Monday"; cldr.cldr_day_format_wide_sat = find(row.day, "type", "sat", getText);// "Saturday"; cldr.cldr_day_format_wide_sun = find(row.day, "type", "sun", getText);// "Sunday"; cldr.cldr_day_format_wide_thu = find(row.day, "type", "thu", getText);// "Thursday"; cldr.cldr_day_format_wide_tue = find(row.day, "type", "tue", getText);// "Tuesday"; cldr.cldr_day_format_wide_wed = find(row.day, "type", "wed", getText);// "Wednesday"; }); }); find(dayContext, "type", "stand-alone", function(row) { cldr["cldr_day_stand-alone_narrow_fri"] = find(row.dayWidth[0].day, "type", "fri", getText);// "F"; cldr["cldr_day_stand-alone_narrow_mon"] = find(row.dayWidth[0].day, "type", "mon", getText);// "M"; cldr["cldr_day_stand-alone_narrow_sat"] = find(row.dayWidth[0].day, "type", "sat", getText);// "S"; cldr["cldr_day_stand-alone_narrow_sun"] = find(row.dayWidth[0].day, "type", "sun", getText);// "S"; cldr["cldr_day_stand-alone_narrow_thu"] = find(row.dayWidth[0].day, "type", "thu", getText);// "T"; cldr["cldr_day_stand-alone_narrow_tue"] = find(row.dayWidth[0].day, "type", "tue", getText);// "T"; cldr["cldr_day_stand-alone_narrow_wed"] = find(row.dayWidth[0].day, "type", "wed", getText);// "W"; }); var monthContext = get("months[0].monthContext", cal); find(monthContext, "type", "format", function(row) { find(row.monthWidth, "type", "abbreviated", function(row) { for (var i = 0; i < row.month.length; i++) { var m = row.month[i]; cldr["cldr_month_format_abbreviated_" + m["$"].type] = getText(m); } }); }); find(monthContext, "type", "format", function(row) { find(row.monthWidth, "type", "wide", function(row) { for (var i = 0; i < row.month.length; i++) { var m = row.month[i]; cldr["cldr_month_format_wide_" + m["$"].type] = getText(m); } }); }); find(monthContext, "type", "stand-alone", function(row) { for (var i = 0; i < row.monthWidth[0].month.length; i++) { var m = row.monthWidth[0].month[i]; cldr["cldr_month_stand-alone_narrow_" + m["$"].type] = getText(m); } }); function getTimeFormatPattern(row) { return row.timeFormat.pattern; } var timeFormatLength = get("timeFormats[0].timeFormatLength", cal); cldr.cldr_time_format_full = find(timeFormatLength, "type", "full", getTimeFormatPattern);// "h:mm:ss a zzzz"; cldr.cldr_time_format_long = find(timeFormatLength, "type", "long", getTimeFormatPattern);// "h:mm:ss a z"; cldr.cldr_time_format_medium = find(timeFormatLength, "type", "medium", getTimeFormatPattern);// "h:mm:ss a"; cldr.cldr_time_format_short = find(timeFormatLength, "type", "short", getTimeFormatPattern);// "h:mm a"; } var numberingSystem = getText(get("ldml.numbers[0].defaultNumberingSystem[0]")); if (numberingSystem) { find(get("ldml.numbers[0].symbols"), "numberSystem", numberingSystem, function(row) { cldr.cldr_number_decimal_separator = row.decimal[0]; cldr.cldr_number_group_separator = row.group[0]; }); } else { cldr.cldr_number_decimal_separator = getValue("ldml.numbers[0].symbols[0].decimal[0]");// "."; cldr.cldr_number_group_separator = getValue("ldml.numbers[0].symbols[0].group[0]");// ","; } cldr.cldr_number_percent_format = getValue("ldml.numbers[0].percentFormats[0].percentFormatLength[0].percentFormat[0].pattern[0]");// "#,##0%"; function getDisplayName(row) { if (qx.lang.Type.isArray(row.displayName)) { return row.displayName.map(elem => getText(elem)); } return getText(row.displayName); } var field = get("ldml.dates[0].fields[0].field"); cldr.day = find(field, "type", "day", getDisplayName);// "Day" cldr.dayperiod = find(field, "type", "dayperiod", getDisplayName);// "AM/PM"; cldr.era = find(field, "type", "era", getDisplayName);// "Era"; cldr.hour = find(field, "type", "hour", getDisplayName);// "Hour"; cldr.minute = find(field, "type", "minute", getDisplayName);// "Minute"; cldr.month = find(field, "type", "month", getDisplayName);// "Month"; cldr.second = find(field, "type", "second", getDisplayName);// "Second"; cldr.week = find(field, "type", "week", getDisplayName);// "Week"; cldr.weekday = find(field, "type", "weekday", getDisplayName);// "Day of the Week"; cldr.year = find(field, "type", "year", getDisplayName);// "Year"; cldr.zone = find(field, "type", "zone", getDisplayName);// "Time Zone"; return cldr; }); } } });