text
stringlengths
2
6.14k
var timeCheck = require('../checks/time.js'); var expect = require('chai').expect; var cases = require('cases'); describe('check response time', function() { it('returns true for responses faster than or equal to the limit', cases([[0], [1], [2340], [5000]], function(time) { var checker = timeCheck.create(5000); var result = checker.check('http://test.example.com/', { status: 200 }, time); expect(result).to.be.true(); }) ); it('returns false for responses slower than the limit', cases([[5001], [10000]], function(time) { var checker = timeCheck.create(5000); var result = checker.check('http://test.example.com/', { status: 200 }, time); expect(result).to.be.false(); }) ); })
/* --- script: Fx.SmoothScroll.js name: Fx.SmoothScroll description: Class for creating a smooth scrolling effect to all internal links on the page. license: MIT-style license authors: - Valerio Proietti requires: - Core/Selectors - /Fx.Scroll provides: [Fx.SmoothScroll] ... */ var SmoothScroll = Fx.SmoothScroll = new Class({ Extends: Fx.Scroll, initialize: function(options, context){ context = context || document; this.doc = context.getDocument(); var win = context.getWindow(); this.parent(this.doc, options); this.links = $$(this.options.links || this.doc.links); var location = win.location.href.match(/^[^#]*/)[0] + '#'; this.links.each(function(link){ if (link.href.indexOf(location) != 0) {return;} var anchor = link.href.substr(location.length); if (anchor) this.useLink(link, anchor); }, this); if (!Browser.Engine.webkit419) { this.addEvent('complete', function(){ win.location.hash = this.anchor; }, true); } }, useLink: function(link, anchor){ var el; link.addEvent('click', function(event){ if (el !== false && !el) el = document.id(anchor) || this.doc.getElement('a[name=' + anchor + ']'); if (el) { event.preventDefault(); this.anchor = anchor; this.toElement(el).chain(function(){ this.fireEvent('scrolledTo', [link, el]); }.bind(this)); link.blur(); } }.bind(this)); } });
; (function (w, d) { var conf = require('../../config.json').app, iframe = d.createElement('iframe'), settings = 0, btn = d.createElement('button'); //frame configuraction iframe.id = 'blob-frame'; iframe.name = 'helper'; iframe.frameBorder = 0; iframe.setAttribute('allowtransparency', true); iframe.src = conf.host+conf.path; iframe.setAttribute('style', 'background:transparent;width:100%!important;height:100%!important;overflow:hidden!important;position:fixed;top:0;left:0;z-index:2147483647;'); iframe.style.display = 'none'; btn.id = 'blob-btn'; //handler for communication between page and iframe addEvent('message',window,messanger); // ajax for get setting widget getWidgetSettings(function (data) { settings = data; btn.setAttribute('style', settings.btn.style || 'position:fixed;margin:0;padding:0;border:0;bottom:20px;right:20px;width: 50px;height: 50px;border-radius: 50%;background: #4194f1;text-align: center;line-height: 50px;color: #fff;font-size: 23px;cursor:pointer;font-weight:600;z-index:9999'); btn.innerHTML = settings.btn.text || '?'; settings.colorTheme = settings.colorTheme || 'theme-peter-river'; settings.functions = settings.functions || { doc: true, faq: true, video: true, recall: true, lk: true }; d.body.appendChild(iframe); addEvent('load', iframe, installWidget); }, function (err) { console.error(err); }, _BlobIS.id); // handler for communication with iframe function messanger() { if (event.data === 'close') { hideWidget(); } return; } // function initialization function installWidget() { var win = window.frames.helper; win.postMessage(JSON.stringify(settings), '*'); d.body.appendChild(btn); addEvent('click', btn, showWidet); try { _BlobIS_.remove = removeWidget } catch (err) { }; //function for admin panel, refresh preview function removeWidget() { removeEvent('load', iframe, installWidget); removeEvent('click', btn, showWidet); removeDomElement(iframe); removeDomElement(btn); } } function showWidet() { iframe.style.display = 'block'; } function hideWidget() { iframe.style.display = 'none'; } function addEvent(e, el, fn) { var ie; if (el.addEventListener) { el.addEventListener(e, fn, false); } else if (el.attachEvent) { ie = 'on' + e; el.attachEvent(ie, fn) } else { el[ie] = fn; } } function addClass(o, c) { var re = new RegExp("(^|\\s)" + c + "(\\s|$)", "g"); if (!o) { console.error('ошибка добавления класса') }; if (re.test(o.className)) return o.className = (o.className + " " + c).replace(/\s+/g, " ").replace(/(^ | $)/g, "") } // function removeClass(o, c){ // var re = new RegExp("(^|\\s)" + c + "(\\s|$)", "g") // o.className = o.className.replace(re, "$1").replace(/\s+/g, " ").replace(/(^ | $)/g, "") // } function removeEvent(e, el, fn) { if (el.addEventListener) { el.removeEventListener(e, fn, false); } else if (el.detachEvent) { el.detachEvent('on' + e, fn); } } function removeDomElement(el) { try { el.outerHTML = ""; } catch (err) { delete el; } } function getWidgetSettings(done, fail, id) { var url = conf.host+'/Services/GetSettings/', scr = d.createElement('script'); window.__asdf89gdjl43789fdsajlk43879 = function (data) { if (data.err) { fail(data.err, err.errmes); } else { done(JSON.parse(data.data)); } } scr.setAttribute('src', url + '?callback=__asdf89gdjl43789fdsajlk43879&service=' + id); d.body.appendChild(scr); } })(window, document);
/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. */ import ChromeDropdown from 'components/ChromeDropdown/ChromeDropdown.react'; import { Constraints } from 'lib/Filters'; import DateTimeEntry from 'components/DateTimeEntry/DateTimeEntry.react'; import Icon from 'components/Icon/Icon.react'; import Parse from 'parse'; import PropTypes from 'lib/PropTypes'; import React from 'react'; import ReactDOM from 'react-dom'; import styles from 'components/BrowserFilter/BrowserFilter.scss'; import validateNumeric from 'lib/validateNumeric'; let constraintLookup = {}; for (let c in Constraints) { constraintLookup[Constraints[c].name] = c; } let setFocus = (input) => { if (input !== null) { ReactDOM.findDOMNode(input).focus(); } } function compareValue(info, value, onChangeCompareTo, active) { switch (info.type) { case null: return null; case 'String': return <input type='text' value={value} onChange={(e) => onChangeCompareTo(e.target.value)} ref={setFocus}/>; case 'Pointer': return ( <input type='text' value={value.objectId || ''} onChange={(e) => { let obj = new Parse.Object(info.targetClass); obj.id = e.target.value; onChangeCompareTo(obj.toPointer()); }} ref={setFocus} /> ); case 'Boolean': return <ChromeDropdown color={active ? 'blue' : 'purple'} value={value ? 'True' : 'False'} options={['True', 'False']} onChange={(val) => onChangeCompareTo(val === 'True')} />; case 'Number': return <input type='text' value={value} onChange={(e) => onChangeCompareTo(validateNumeric(e.target.value) ? parseFloat(e.target.value) : (parseFloat(value) || ''))} />; case 'Date': return ( <DateTimeEntry fixed={true} className={styles.date} value={Parse._decode('date', value)} onChange={(value) => onChangeCompareTo(Parse._encode(value))} ref={setFocus} /> ); } } let FilterRow = ({ fields, constraints, compareInfo, currentField, currentConstraint, compareTo, onChangeField, onChangeConstraint, onChangeCompareTo, onDeleteRow, active, }) => ( <div className={styles.row}> <ChromeDropdown color={active ? 'blue' : 'purple'} value={currentField} options={fields} onChange={onChangeField} /> <ChromeDropdown width={compareInfo.type ? 175 : 325} color={active ? 'blue' : 'purple'} value={Constraints[currentConstraint].name} options={constraints.map((c) => Constraints[c].name)} onChange={(c) => onChangeConstraint(constraintLookup[c])} /> {compareValue(compareInfo, compareTo, onChangeCompareTo, active)} <a role='button' href='javascript:;' className={styles.remove} onClick={onDeleteRow}><Icon name='minus-solid' width={14} height={14} fill='rgba(0,0,0,0.4)' /></a> </div> ); export default FilterRow; FilterRow.propTypes = { fields: PropTypes.arrayOf(PropTypes.string).isRequired, currentField: PropTypes.string.isRequired, constraints: PropTypes.arrayOf(PropTypes.string).isRequired, currentConstraint: PropTypes.string.isRequired, compareTo: PropTypes.any, compareInfo: PropTypes.object };
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var lineuptypes = require('../../app/controllers/lineuptypes'); // Lineuptypes Routes app.route('/lineuptypes') .get(lineuptypes.list) .post(users.requiresLogin, lineuptypes.create); app.route('/lineuptypes/:lineuptypeId') .get(lineuptypes.read) .put(users.requiresLogin, lineuptypes.hasAuthorization, lineuptypes.update) .delete(users.requiresLogin, lineuptypes.hasAuthorization, lineuptypes.delete); // Finish by binding the Lineuptype middleware app.param('lineuptypeId', lineuptypes.lineuptypeByID); };
"use strict"; var assert = require("assert"), thicket = require("../../../../../lib-node/thicket"), Logger = thicket.c("logger"), ConsoleLogAppender = thicket.c("appenders/console-log"); describe("ConsoleLogAppender", function() { it("should log to the provided console", function() { Logger.resetRootLogger(); var log = Logger.create("Test"), callCount = 0; var c = { log: function(meta, arg1, arg2){ callCount++; assert.equal(meta, "[Debug][NOW][Test]"); assert.equal(arg1, "one"); assert.equal(arg2, "two"); } }; log.addAppender(new ConsoleLogAppender({console: c, timeDelegate: function() { return "NOW"; }})); log.setLogLevel(Logger.Level.Debug); log.debug("one", "two"); assert.equal(callCount, 1); }); });
module.exports = { current: "1.17.15154.0" };
version https://git-lfs.github.com/spec/v1 oid sha256:5fb0426b83eec81e9bc351a6b3d46b0fec8cc86b32ab8f45ce970f1542cbed86 size 268
var fs = require('fs'); var src = fs.readFileSync('/usr/local/Cellar/nvm/0.26.0/v0.10.28/lib/node_modules/browserify-adventure/problems/using_transforms/wake.txt', 'utf8'); var sprintf = require('sprintf-js').sprintf; src.split('\n').forEach(printLine); function printLine(line, index) { if (index % 5 === 0) { console.log(sprintf('%3d %s', index, line)); } else { console.log(' ' + line); } }
/* eslint-disable no-var */ var rimraf = require('rimraf') var chalk = require('chalk') var replace = require("replace") var prompt = require("prompt") var prompts = require('./setupPrompts') var chalkSuccess = chalk.green var chalkProcessing = chalk.blue /* eslint-disable no-console */ console.log(chalkSuccess('Dependencies installed.')) // remove the original git repository rimraf('.git', error => { if (error) throw new Error(error) }) console.log(chalkSuccess('Original Git repository removed.\n')) // prompt the user for updates to package.json console.log(chalkProcessing('Updating package.json settings:')) prompt.start() prompt.get(prompts, function(err, result) { // parse user responses // default values provided for fields that will cause npm to complain if left empty const responses = [ { key: 'name', value: result.projectName || 'new-project' }, { key: 'version', value: result.version || '0.1.0' }, { key: 'author', value: result.author }, { key: 'license', value: result.license || 'MIT' }, { key: 'description', value: result.description }, // simply use an empty URL here to clear the existing repo URL { key: 'url', value: '' } ] // update package.json with the user's values responses.forEach(res => { replace({ regex: `("${res.key}"): "(.*?)"`, replacement: `$1: "${res.value}"`, paths: ['package.json'], recursive: false, silent: true }) }) // reset package.json 'keywords' field to empty state replace({ regex: /"keywords": \[[\s\S]+\]/, replacement: `"keywords": []`, paths: ['package.json'], recursive: false, silent: true }) // remove all setup scripts from the 'tools' folder console.log(chalkSuccess('\nSetup complete! Cleaning up...\n')) rimraf('./tools/setup', error => { if (error) throw new Error(error) }) })
'use strict'; const { TimedDiscovery, BasicDiscovery, search, addService, removeService } = require('tinkerhub-discovery'); const { Children } = require('abstract-things'); const util = require('util'); const dns = require('dns'); const network = require('./network'); const infoFromHostname = require('./infoFromHostname'); const connectToDevice = require('./connectToDevice'); const tryAdd = Symbol('tryAdd'); const Browser = module.exports.Browser = class Browser extends TimedDiscovery { static get type() { return 'miio'; } constructor(options) { super({ maxStaleTime: (options.cacheTime || 1800) * 1000 }); if(typeof options.useTokenStorage !== 'undefined' ? options.useTokenStorage : true) { this.tokens = require('./tokens'); } this.manualTokens = options.tokens || {}; this[tryAdd] = this[tryAdd].bind(this); this.start(); } _manualToken(id) { return this.manualTokens[id] || null; } start() { this.handle = network.ref(); network.on('device', this[tryAdd]); super.start(); } stop() { super.stop(); network.removeListener('device', this[tryAdd]); this.handle.release(); } [search]() { network.search(); } [tryAdd](device) { const service = { id: device.id, address: device.address, port: device.port, token: device.token || this._manualToken(device.id), autoToken: device.autoToken, connect: function(options={}) { return connectToDevice(Object.assign({ address: this.address, port: this.port, model: this.model }, options)); } }; const add = () => this[addService](service); // Give us five seconds to try resolve some extras for new devices setTimeout(add, 5000); dns.lookupService(service.address, service.port, (err, hostname) => { if(err || ! hostname) { add(); return; } service.hostname = hostname; const info = infoFromHostname(hostname); if(info) { service.model = info.model; } add(); }); } [util.inspect.custom]() { return 'MiioBrowser{}'; } }; class Devices extends BasicDiscovery { static get type() { return 'miio:devices'; } constructor(options) { super(); this._filter = options && options.filter; this._skipSubDevices = options && options.skipSubDevices; this._browser = new Browser(options) .map(reg => { return connectToDevice({ address: reg.address, port: reg.port, model: reg.model, withPlaceholder: true }); }); this._browser.on('available', s => { this[addService](s); if(s instanceof Children) { this._bindSubDevices(s); } }); this._browser.on('unavailable', s => { this[removeService](s); }); } start() { super.start(); this._browser.start(); } stop() { super.stop(); this._browser.stop(); } [util.inspect.custom]() { return 'MiioDevices{}'; } _bindSubDevices(device) { if(this._skipSubDevices) return; const handleAvailable = sub => { if(! sub.miioModel) return; const reg = { id: sub.internalId, model: sub.model, type: sub.type, parent: device, device: sub }; if(this._filter && ! this._filter(reg)) { // Filter does not match sub device return; } // Register and emit event this[addService](sub); }; device.on('thing:available', handleAvailable); device.on('thing:unavailable', sub => this[removeService](sub.id)); // Register initial devices for(const child of device.children()) { handleAvailable(child); } } } module.exports.Devices = Devices;
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import { connect } from 'react-redux'; import { defer } from 'lodash'; import key from 'keymaster'; import walletOneApp from './reducers/index'; import {loadState} from './actions/index'; import wallet from "./middleware/wallet"; import logger from "./middleware/logger"; import UI from './ui.js'; import DevTools from './dev-tools.js'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); let createStoreWithMiddleware = applyMiddleware(thunk, wallet, logger)(createStore) var store = createStoreWithMiddleware(walletOneApp); const style = { display: 'flex', flexDirection: 'row-reverse', height: "100%", position: "relative", }; let devToolsVisible = false; let toggleDevTools = () => { devToolsVisible = !devToolsVisible; render(); } key('`', toggleDevTools); function render() { ReactDOM.render( <Provider store={store}> <div style={style}> <DevTools isVisible={devToolsVisible} /> <UI /> </div> </Provider>, document.getElementById('app') ); } defer(() => { store.dispatch(loadState()); render(); });
'use strict'; angular.module('NTDomo.i2cRequest.service', ['ngResource', 'NTDomo.config']) .factory('I2CRequestService', I2CRequestService); I2CRequestService.$inject = ['$resource', 'devices', 'ENV']; function I2CRequestService($resource, devices, ENV) { console.log('i2cRequest Query'); return $resource(ENV.server + devices.i2cRequest, '@data', { query: { method: 'GET', isArray: false }, get: { method: 'GET', isArray: false } }); }
#!/usr/bin/env node var PerfTest = require('../perf/perftest'); var DeLorean = require('../perf/lib/delorean.min'); var store = DeLorean.Flux.createStore({ data : {}, actions : { action1 : 'onAction1', action2 : 'onAction2' }, onAction1: function (data) { this.data = data; this.emit('change'); }, onAction2: function (data) { this.data = data; this.emit('change'); } }); var dispatcher = DeLorean.Flux.createDispatcher({ action1: function (data) { this.dispatch('action1', data); }, action2: function (data) { this.dispatch('action2', data); }, getStores : function(){ return { store : store } } }); var actions = { action1: function (test) { dispatcher.action1(test); }, action2: function (test) { dispatcher.action2(test); } }; module.exports = PerfTest.createPerfTest('delorean-perf', { before: function () { store.onChange(function () { var localData = store.data; // copy operation }.bind(this)); }, exec: function (i) { actions.action1("test 1." + i); actions.action2("test 2." + i); }, after: function () { } });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var platform_browser_1 = require('@angular/platform-browser'); var forms_1 = require('@angular/forms'); var http_1 = require('@angular/http'); var app_routing_module_1 = require("./app-routing.module"); var angular_in_memory_web_api_1 = require('angular-in-memory-web-api'); var in_memory_data_service_1 = require('./in-memory-data.service'); var app_component_1 = require('./app.component'); var dashboard_component_1 = require("./dashboard.component"); var heroes_component_1 = require("./heroes.component"); var hero_detail_component_1 = require('./hero-detail.component'); var hero_service_1 = require("./hero.service"); var hero_search_component_1 = require("./hero-search.component"); var AppModule = (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [ platform_browser_1.BrowserModule, forms_1.FormsModule, app_routing_module_1.AppRoutingModule, http_1.HttpModule, angular_in_memory_web_api_1.InMemoryWebApiModule.forRoot(in_memory_data_service_1.InMemoryDataService) ], declarations: [ app_component_1.AppComponent, hero_detail_component_1.HeroDetailComponent, heroes_component_1.HeroesComponent, dashboard_component_1.DashboardComponent, hero_search_component_1.HeroSearchComponent ], providers: [ hero_service_1.HeroService ], bootstrap: [app_component_1.AppComponent] }), __metadata('design:paramtypes', []) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
export { default } from 'em-tgraph/utils/fullscreen';
let id = 0 export default function uid(prefix = '') { return String(prefix + id++) }
import React from 'react'; const sectionStyle = { flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }; export default () => ({children, style}) => <section style={{...sectionStyle, ...style}}>{children}</section>;
exports.modulariseTemplate = function(template) { var jade = require('jade') var test = jade.compile(template,{client:true,compileDebug:false,filename:template}); return "var jade = require('lib/jade_runtime'); module.exports=" + test; } exports.modulariseTemplateFile = function(filename) { var fs = require('fs') var template = fs.readFileSync(template,"UTF8"); return exports.modulariseTemplate(template); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnouncementStatusV1 = exports.AnnouncementV1Schema = exports.AnnouncementV1 = exports.PartyReferenceV1Schema = exports.PartyReferenceV1 = exports.AttachmentV1Schema = exports.AttachmentV1 = exports.LocationV1Schema = exports.LocationV1 = void 0; var LocationV1_1 = require("./LocationV1"); Object.defineProperty(exports, "LocationV1", { enumerable: true, get: function () { return LocationV1_1.LocationV1; } }); var LocationV1Schema_1 = require("./LocationV1Schema"); Object.defineProperty(exports, "LocationV1Schema", { enumerable: true, get: function () { return LocationV1Schema_1.LocationV1Schema; } }); var AttachmentV1_1 = require("./AttachmentV1"); Object.defineProperty(exports, "AttachmentV1", { enumerable: true, get: function () { return AttachmentV1_1.AttachmentV1; } }); var AttachmentV1Schema_1 = require("./AttachmentV1Schema"); Object.defineProperty(exports, "AttachmentV1Schema", { enumerable: true, get: function () { return AttachmentV1Schema_1.AttachmentV1Schema; } }); var PartyReferenceV1_1 = require("./PartyReferenceV1"); Object.defineProperty(exports, "PartyReferenceV1", { enumerable: true, get: function () { return PartyReferenceV1_1.PartyReferenceV1; } }); var PartyReferenceV1Schema_1 = require("./PartyReferenceV1Schema"); Object.defineProperty(exports, "PartyReferenceV1Schema", { enumerable: true, get: function () { return PartyReferenceV1Schema_1.PartyReferenceV1Schema; } }); var AnnouncementV1_1 = require("./AnnouncementV1"); Object.defineProperty(exports, "AnnouncementV1", { enumerable: true, get: function () { return AnnouncementV1_1.AnnouncementV1; } }); var AnnouncementV1Schema_1 = require("./AnnouncementV1Schema"); Object.defineProperty(exports, "AnnouncementV1Schema", { enumerable: true, get: function () { return AnnouncementV1Schema_1.AnnouncementV1Schema; } }); var AnnouncementStatusV1_1 = require("./AnnouncementStatusV1"); Object.defineProperty(exports, "AnnouncementStatusV1", { enumerable: true, get: function () { return AnnouncementStatusV1_1.AnnouncementStatusV1; } }); //# sourceMappingURL=index.js.map
const always = require('./always') module.exports = always(false)
import PowerSelect from './PowerSelect'; import TypeAhead from './TypeAhead'; import TypeAheadSelectTrigger from './TypeAhead/SelectTrigger'; import PowerSelectMultiple from './PowerSelectMultiple'; TypeAhead.Trigger = TypeAheadSelectTrigger; export { PowerSelect, TypeAhead, PowerSelectMultiple };
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { connect } from "react-redux"; var FontAwesome = require('font-awesome/css/font-awesome.css'); import './forms.css'; import { getFormData } from "../../actions/actions" @connect((store) => { return { formData: store.forms.data } }) class Forms extends Component { constructor(props) { super(props); } componentWillMount() { this.props.dispatch(getFormData()); } componentWillUnmount() { }; render() { console.log(this.props); let Content = null; if (this.props.type === "enrollment") { Content = <EnrollmentForm state={this.props.formData.enrollment} /> } else if (this.props.type === "contact") { Content = <ContactUsForm state={this.props.formData.contact} /> } else { Content = <fourOhFour /> } return ( <div className="container formContent"> {Content} </div> ); } }; function renderFieldsets(fieldsets) { if (fieldsets.length > 0) { return fieldsets.map((fieldset, index) => ( <Fieldset key={index} set={fieldset} /> )); } else return []; } function renderFormElements(formElements) { if (formElements.length > 0) { return formElements.map((formElement, i) => ( <FormElement key={i} set={formElement} /> )); } else return []; } const FormElement = (props, index) => { if (props.set.tag === "input") { return ( <div key={index} className={props.set.class}> <label>{props.set.label}</label> <input type={props.set.type} name={props.set.name} placeholder={props.set.placeholder} required={props.set.required} disabled={props.set.disabled} /> </div> ); } else if (props.set.tag === "select") { return ( <div key={index} className={props.set.class}> <label>{props.set.label}</label> <select key={index} name={props.set.name} required={props.set.required} disabled={props.set.disabled} /> </div> ); }else if (props.set.tag === "textarea") { return ( <div key={index} className={props.set.class}> <label>{props.set.label}</label> <textarea key={index} name={props.set.name} required={props.set.required} disabled={props.set.disabled} /> </div> ); } return <div>Something which is not a form element</div>; }; const Fieldset = (props, index) => { const elements = renderFormElements(props.set.formElements); return ( <fieldset key={index}> <legend> <span className="number fa fa-address-card"></span> {props.set.title} </legend> <div className="formElementsContainer">{elements}</div> </fieldset> ); }; function EnrollmentForm(form) { const fieldsets = renderFieldsets(form.state.fieldsets); return ( <form className={form.state.class}> <div> {fieldsets} </div> <input type="submit" /> </form> ); } function ContactUsForm(form) { const fieldsets = renderFieldsets(form.state.fieldsets); return ( <form className={form.state.class}> <div> {fieldsets} </div> <input type="submit" /> </form> ); } export default Forms;
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]); //bla //vl
var Q = require('q'); var fs = require('fs'); module.exports.write = function (data, fileName) { data = data.reduce(function (result, dataLine) { return result += ('\n' + dataLine); }, ''); return Q.nfcall(fs.writeFile, fileName, data); };
require("kaoscript/register"); module.exports = function() { var {CarFactory, Car: OldCar} = require("./type.scope.source.ks")(); const factory = new CarFactory(); console.log(factory.makeCar().getType()); console.log((new OldCar()).getType()); };
import {colours} from '../../../App/constants' export const style = { backgroundColor: colours.blue.dark.base.toString(), borderTopWidth: 0.5, borderTopColor: colours.blue.dark.baboon.toString() }
require("should"); const isInfinite = require("../../lib/object/isInfinite.js"); describe("isInfinite", function() { it("Should be able to say Infinity is infinite.", function() { let result = isInfinite(Infinity); result.should.be.exactly(true); }); it("Should be able to say -Infinity is infinite.", function() { let result = isInfinite(-Infinity); result.should.be.exactly(true); }); it("Should be able to say a date object is not infinite.", function() { let result = isInfinite(new Date()); result.should.be.exactly(false); }); it("Should be able to say false is not infinite.", function() { let result = isInfinite(false); result.should.be.exactly(false); }); it("Should be able to say true is not infinite.", function() { let result = isInfinite(true); result.should.be.exactly(false); }); it("Should be able to say an array is not infinite.", function() { let result = isInfinite([]); result.should.be.exactly(false); }); it("Should be able to say empty string is not infinite.", function() { let result = isInfinite(""); result.should.be.exactly(false); }); it("Should be able to say null is not infinite.", function() { let result = isInfinite(null); result.should.be.exactly(false); }); it("Should be able to say undefined is not infinite.", function() { let result = isInfinite(undefined); result.should.be.exactly(false); }); it("Should be able to say NaN is not infinite.", function() { let result = isInfinite(NaN); result.should.be.exactly(false); }); it("Should be able to say 110 is not infinite.", function() { let result = isInfinite(110); result.should.be.exactly(false); }); it("Should be able to say -13 is not infinite.", function() { let result = isInfinite(-13); result.should.be.exactly(false); }); it("Should be able to say tata is not infinite.", function() { let result = isInfinite("tata"); result.should.be.exactly(false); }); it("Should be able to say object is not infinite.", function() { let result = isInfinite({}); result.should.be.exactly(false); }); });
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './app' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new ExtractTextPlugin('style.css', { allChunks: true }), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('development') } }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass') } ] } }; // When inside Chat repo, prefer src to compiled version. // You can safely delete these lines in your project. var chatSrc = path.join(__dirname, '..', '..', 'src'); var chatNodeModules = path.join(__dirname, '..', '..', 'node_modules'); var fs = require('fs'); if (fs.existsSync(chatSrc) && fs.existsSync(chatNodeModules)) { // Resolve to source module.exports.resolve = { alias: { 'react-chat': chatSrc } }; // Compile from source module.exports.module.loaders.push({ test: /\.js$/, loaders: ['babel'], include: chatSrc }); }
var spawn = require('child_process').spawn; var options = { env: {user:'brad'}, detached:false, stdio: ['pipe','pipe','pipe'] }; var child = spawn('netstat', ['-A']); child.stdout.on('data', function(data) { console.log(data.toString()); }); child.stderr.on('data', function(data) { console.log(data.toString()); }); child.on('exit', function(code) { console.log('Child exited with code', code); });
(function() { var container = document.getElementById('container'), filter = document.getElementById('filter-input'), closedTabs; function getList(tabs) { return tabs.map(function (session) { var faviconUrl = session.tab.favIconUrl, matches; if (!faviconUrl) { matches = /^http(?:s)?:\/\/[^\/]+/.exec(session.tab.url); faviconUrl = matches && matches.length ? matches[0] + '/favicon.ico' : 'media/icon_16.png'; } return '<a class="li" data-id="' + session.tab.sessionId + '" title="' + session.tab.url + '"><div class="item"><img src="' + faviconUrl + '"/><span>' + session.tab.title + '</span></div></a>'; }).join(''); } function render(tabs) { if (tabs.length) { container.innerHTML = getList(tabs); bindClicks(); } else { container.innerHTML = '<div class="li"><span>Nothing found</span></div>' } } chrome.runtime.getBackgroundPage(function(bg) { bg.getClosedTabs(function (tabs) { closedTabs = tabs; render(tabs); }); }); function restoreTab(id) { chrome.runtime.getBackgroundPage(function(bg) { bg.restoreTab(id); }); } function bindClicks() { Array.prototype.forEach.call(document.querySelectorAll('.li'), function (el) { el.addEventListener('click', function (e) { e.preventDefault(); restoreTab(this.getAttribute('data-id')); }, false); }); } function filterTabs(term) { if (term.length === 0) { render(closedTabs); return; } term = term.toLowerCase(); var filtered = closedTabs.filter(function (session) { return session.tab.title.toLowerCase().indexOf(term) !== -1 || session.tab.url.toLowerCase().indexOf(term) !== -1; }); render(filtered); } function moveSelection(delta) { var tab = document.querySelector('.highlighted'), index, newIndex, len = container.childNodes.length; if (tab) { tab.classList.remove('highlighted'); index = Array.prototype.indexOf.call(container.childNodes, tab); } else { index = -1; } newIndex = index + delta; if (newIndex < 0 && delta < 0) { newIndex = len + delta - index; } else if (newIndex >= len) { newIndex = index - len + delta; } container.childNodes[newIndex].classList.add('highlighted'); if (newIndex === 0) { window.scrollTo(0, 0); } else if (newIndex === len - 1) { window.scrollTo(0, document.body.scrollHeight); } } filter.addEventListener('keydown', function (event) { var tab; switch (event.keyCode) { //up case 38: moveSelection(-1); break; //down case 40: moveSelection(1); break; case 13: tab = document.querySelector('.highlighted'); if (tab) { restoreTab(tab.getAttribute('data-id')); } break; default: filterTabs(this.value.trim()); break; } }) })();
define([ "core/scope/NlsScope", "../scope/LayoutScope", "i18n!nls/menu" ], function (NlsScope, LayoutScope, menu) { return ['$scope', "$routeSegment", function ($scope, $routeSegment) { NlsScope($scope, "view.LayoutController"); LayoutScope($scope, $routeSegment, menu); document.title = $scope.msgNS("title"); }]; });
'use strict'; var fs = require('fs'); var path = require('path'); var directory = process.argv[2]; var extension = process.argv[3]; fs.readdir(directory, function (err, files) { var match = files.filter(function (file) { return (path.extname(file) === '.' + extension); }); match.forEach(function (file) { console.log(file); }); });
const debug = require('@tryghost/debug')('web:api:canary:content:app'); const boolParser = require('express-query-boolean'); const bodyParser = require('body-parser'); const express = require('../../../../../shared/express'); const shared = require('../../../shared'); const routes = require('./routes'); module.exports = function setupApiApp() { debug('Content API canary setup start'); const apiApp = express('canary content'); // API middleware // @NOTE: req.body is undefined if we don't use this parser, this can trouble if components rely on req.body being present apiApp.use(bodyParser.json({limit: '1mb'})); // Query parsing apiApp.use(boolParser()); // send 503 json response in case of maintenance apiApp.use(shared.middlewares.maintenance); // API shouldn't be cached apiApp.use(shared.middlewares.cacheControl('private')); // Routing apiApp.use(routes()); // API error handling apiApp.use(shared.middlewares.errorHandler.resourceNotFound); apiApp.use(shared.middlewares.errorHandler.handleJSONResponse); debug('Content API canary setup end'); return apiApp; };
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var GitHubApi = require('github'); var template_setting = require('./template_setting'); var github = new GitHubApi({ version: '3.0.0' }); var githubUserInfo = function (name, cb) { github.user.getFrom({ user: name }, function (err, res) { if (err) { throw err; } cb(JSON.parse(JSON.stringify(res))); }); }; var TmlibGenerator = module.exports = function TmlibGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.spawnCommand('bower', ['cache-clean']) .on('exit', function(err) { if (err) console.log(err); var skip_install = options['skip-install']; var grunt_bower_task = function() { if (!skip_install) { this.spawnCommand('grunt', ['bower:install']) .on('exit', function (err) { if (err) console.log(err); }); } }.bind(this); this.installDependencies({ skipInstall: skip_install, callback: grunt_bower_task}); }.bind(this)); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(TmlibGenerator, yeoman.generators.Base); TmlibGenerator.prototype.askFor = function askFor() { var cb = this.async(); // welcome message var welcome = "This is a generator for tmlib. tmlib can make javascript easy!"; console.log(welcome); var prompts = [ { name: 'yourname', message: 'What is your github name?', default: 'someuser', warning: '' }, { name: 'appname', message: 'What is your applicaiton name?', default: 'My Apps', warning: '' }, { name: 'version', message: 'What version?', default: '0.0.0', warning: '' }, { name: 'description', message: 'Description about your app', default: '', warning: '' }, { name: 'template_engine', message: 'What is your favorite template engine? [jade, ejs, swig, hogan]', default: 'jade', warning: '' }, { name: 'use_heroku', message: 'Use Heroku? [Y/n]', default: 'n', warning: '' }, ]; this.prompt(prompts, function (props) { this.appname = props.appname; this.version = props.version; this.description = props.description; this.yourname = props.yourname; this.template_engine = template_setting(props.template_engine); this.use_heroku = props.use_heroku == "Y" ? true : false; cb(); }.bind(this)); }; TmlibGenerator.prototype.userInfo = function userInfo() { var done = this.async(); githubUserInfo(this.yourname, function (res) { this.yourname = res.name; this.email = res.email; this.githubUrl = res.html_url; done(); }.bind(this)); }; TmlibGenerator.prototype.app = function app() { this.template('_package.json', 'package.json'); this.template('_bower.json', 'bower.json'); this.copy('_bowerrc', '.bowerrc'); this.directory('public', 'public'); this.mkdir('public/vendor'); this.mkdir('views'); var viewPath = 'views/*.'+this.template_engine.extension; var viewFiles = this.expandFiles(viewPath, {dot: true, cwd: this.sourceRoot()}); viewFiles.forEach(function(viewFile) { this.copy(viewFile, viewFile); }.bind(this)); this.mkdir('lib'); this.template('lib/socket.io-server.js', 'lib/socket.io-server.js'); this.directory('routes', 'routes'); this.template('app.js', 'app.js'); this.copy('Gruntfile.js', 'Gruntfile.js'); if (this.use_heroku) this.copy('Procfile', 'Procfile'); }; TmlibGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); this.copy('gitignore', '.gitignore'); };
var test = require('tape') var budo = require('../') var spawn = require('win-spawn') var fs = require('fs') var path = require('path') var cleanup = require('./cleanup') var ndjson = require('ndjson') var kill = require('tree-kill') var cliPath = path.resolve(__dirname, '..', 'bin', 'cmd.js') test('should close budo API and delete tmp dirs', function(t) { t.plan(3) t.timeoutAfter(5000) var tmpFile var app = budo('test/app.js', { dir: __dirname, port: 8000, }) .on('connect', function(ev) { tmpFile = ev.from t.ok(true, 'connected') setTimeout(function() { app.close() }, 1000) }) .on('exit', function() { t.ok(true, 'exiting') doesNotExist(t, tmpFile) }) .on('error', function(err) { t.fail(err) }) }) test('should close budo CLI and delete tmp dirs', function(t) { t.plan(2) var timeout = 2000 t.timeoutAfter(timeout) var tmpDir var proc = spawn(cliPath, ['app.js'], { cwd: __dirname, env: process.env }) proc.stdout.pipe(ndjson.parse()) .on('data', function(data) { if (!data || !data.message) return var msg = 'temp directory created at' var idx = data.message.indexOf(msg) if (idx === -1) return tmpDir = data.message.substring(idx).trim() proc.on('exit', function() { t.ok(true, 'got exit event') doesNotExist(t, tmpDir) }) kill(proc.pid) }) proc.stderr.pipe(process.stderr) }) function doesNotExist(t, file) { setTimeout(function() { fs.stat(file, function(err) { if (err) t.ok(true, 'tmpfile removed') else t.fail('tmpfile was not destroyed') }) }, 500) }
var middleware = function (req, res, next) { res.locals.props.blog = { cover: '/static_assets/cover.jpg', name: 'Bunkuro Zingdema', tagline: 'Hello' }; res.locals.props.user = {alias: 'lihengl', id: 0}; next(); }; module.exports = middleware;
module.exports = { sendTweet: function(text, cb) { var oauth = { "consumer_key": process.env.TWITTER_API_KEY, "consumer_secret": process.env.TWITTER_API_SECRET, "token": process.env.TWITTER_TOKEN, "token_secret": process.env.TWITTER_TOKEN_SECRET }; var form, r; r = request.post("https://api.twitter.com/1.1/statuses/update.json", {oauth: oauth}, cb); form = r.form(); form.append('status', text); r.on('error', function(e) { console.error("Error while sending the tweet: ", e); }); } }
//Propagate engine events onto targets var event = (function () { var propagateEvents = function() { ['collisionStart', 'collisionEnd', 'collisionActive'].forEach(function (collisionEvent) { Events.on(engine, collisionEvent, function (e) { var pairs = e.pairs; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; var craftyEvent = collisionEvent.charAt(0).toUpperCase() + collisionEvent.slice(1); pair.bodyA.entity.trigger(craftyEvent, { target: pair.bodyB.entity, event: e }); pair.bodyB.entity.trigger(craftyEvent, { target: pair.bodyA.entity, event: e }); } }); }); }; return { propagateEvents: propagateEvents }; })();
/** * Connections * (sails.config.connections) * * `Connections` are like "saved settings" for your adapters. What's the difference between * a connection and an adapter, you might ask? An adapter (e.g. `sails-mysql`) is generic-- * it needs some additional information to work (e.g. your database host, password, user, etc.) * A `connection` is that additional information. * * Each model must have a `connection` property (a string) which is references the name of one * of these connections. If it doesn't, the default `connection` configured in `config/models.js` * will be applied. Of course, a connection can (and usually is) shared by multiple models. * . * Note: If you're using version control, you should put your passwords/api keys * in `config/local.js`, environment variables, or use another strategy. * (this is to prevent you inadvertently sensitive credentials up to your repository.) * * For more information on configuration, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.connections.html */ module.exports.connections = { /*************************************************************************** * * * Local disk storage for DEVELOPMENT ONLY * * * * Installed by default. * * * ***************************************************************************/ localDiskDb: { adapter: 'sails-disk' }, /*************************************************************************** * * * MySQL is the world's most popular relational database. * * http://en.wikipedia.org/wiki/MySQL * * * * Run: npm install sails-mysql * * * ***************************************************************************/ // someMysqlServer: { // adapter: 'sails-mysql', // host: 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS', // user: 'YOUR_MYSQL_USER', //optional // password: 'YOUR_MYSQL_PASSWORD', //optional // database: 'YOUR_MYSQL_DB' //optional // }, /*************************************************************************** * * * MongoDB is the leading NoSQL database. * * http://en.wikipedia.org/wiki/MongoDB * * * * Run: npm install sails-mongo * * * ***************************************************************************/ mLabMongodbServer: { adapter: 'sails-mongo', url: process.env.MLAB_URI, }, // someMongodbServer: { // adapter: 'sails-mongo', // host: 'localhost', // port: 27017, // user: 'username', //optional // password: 'password', //optional // database: 'your_mongo_db_name_here' //optional // }, /*************************************************************************** * * * PostgreSQL is another officially supported relational database. * * http://en.wikipedia.org/wiki/PostgreSQL * * * * Run: npm install sails-postgresql * * * * * ***************************************************************************/ // somePostgresqlServer: { // adapter: 'sails-postgresql', // host: 'YOUR_POSTGRES_SERVER_HOSTNAME_OR_IP_ADDRESS', // user: 'YOUR_POSTGRES_USER', // optional // password: 'YOUR_POSTGRES_PASSWORD', // optional // database: 'YOUR_POSTGRES_DB' //optional // } /*************************************************************************** * * * More adapters: https://github.com/balderdashy/sails * * * ***************************************************************************/ };
/** * @ngdoc overview * @name mainMenu * @requires ftiApp.lodash * @description * The `ftiApp.mainMenu` module which provides: * * - {@link mainMenu.controller:MainMenuController MainMenuController} * - {@link mainMenu.service:mainMenu mainMenu-service} */ (function () { 'use strict'; angular.module('ftiApp.mainMenu', [ 'ftiApp.lodash' ]) })();
import { validator } from "../common/validator.js"; export class Vehicle { constructor(make, model, firstRegistration, fuelType, hp, price, info) { this.make = make; this.model = model; this.firstRegistration = firstRegistration; this.fuelType = fuelType; this.hp = hp; this.price = price; this.info = info; } get make() { return this._make; } set make(value) { validator.validateStringLength(value, 2, 12); this._make = value.trim(); } get model() { return this._model; } set model(value) { validator.validateStringLength(value, 2, 12); this._model = value.trim(); } get firstRegistration() { return this._firstRegistration; } set firstRegistration(value) { const now = new Date().getFullYear(); validator.validateInteger(+value); validator.validateNumberInRange(+value, 1900, +now); this._firstRegistration = +value; } get fuelType() { return this._fuelType; } set fuelType(value) { this._fuelType = value; } get hp() { return this._hp; } set hp(value) { validator.validateInteger(+value); validator.validateNumberInRange(+value, 0, 1000); this._hp = +value; } get price() { return this._price; } set price(value) { validator.validateNumberInRange(+value, 0, Number.MAX_VALUE); this._price = +value; } get info() { return this._info; } set info(value) { this._info = value.trim(); } }
import connectComponent from './connectComponent'; import AsyncUpdater from './AsyncUpdater'; const defaultPropsMapper = store => props => ({ store, ...props, }); export default function createConnector(watcher) { return function connect(Component, { propsMapper = defaultPropsMapper, compareProps, }) { return connectComponent(Component, { watcher, propsMapper, compareProps, makeUpdater: update => new AsyncUpdater(update), }); }; }
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'gringo', environment: environment, contentSecurityPolicy: { 'connect-src': "'self' wss://*.firebaseio.com wss://*.firebase.com https://auth.firebase.com", 'font-src': "'self' data: use.typekit.net http://fonts.gstatic.com https://auth.firebase.com", 'img-src': "'self' www.google-analytics.com stats.g.doubleclick.net p.typekit.net data:", 'style-src': "'self' 'unsafe-inline' use.typekit.net http://fonts.googleapis.com", 'script-src': "'self' https://*.firebaseio.com", 'frame-src': "'self' https://*.firebaseio.com" }, firebase: 'https://radiant-fire-7768.firebaseio.com/', baseURL: '/', defaultLocationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, cordova: { rebuildOnChange: false, emulate: false } }; // ENV.contentSecurityPolicy = { // 'default-src': "'none'", // 'script-src': "'self' 'unsafe-inline' 'unsafe-eval' use.typekit.net", // 'font-src': "'self' data: use.typekit.net", // 'connect-src': "'self' wss://*.firebaseio.com", // 'img-src': "'self' p.typekit.net data:", // 'style-src': "'self' 'unsafe-inline' use.typekit.net", // 'frame-src': "" // } if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
import { compare } from '@ember/utils'; import { get } from '@ember/object'; import { normalizeArray } from './-utils'; export default function(array, sortDefinition) { let computedCallback; if (sortDefinition === undefined) { computedCallback = array => array.slice().sort(); } else { computedCallback = function(array, sortDefinition) { let sortCallback; if (typeof sortDefinition === 'function') { sortCallback = sortDefinition.bind(this); } else { sortCallback = (a, b) => { let result = 0; // https://kangax.github.io/compat-table/es6/#test-generators // for (let key of sortDefinition) { for (let i = 0; i < sortDefinition.length; i++) { let key = sortDefinition[i]; let [prop, direction] = key.split(':'); result = compare(get(a, prop), get(b, prop)); if (result !== 0) { if (direction === 'desc') { result *= -1; } break; } } return result; }; } return array.slice().sort(sortCallback); }; } return normalizeArray({}, computedCallback)(array, sortDefinition); }
'use strict'; //Setting up route angular.module('lookbook').config(['$stateProvider', function($stateProvider) { // Lookbook state routing $stateProvider. state('lookbook', { url: '/lookbook/:type', templateUrl: 'modules/lookbook/views/lookbook.client.view.html', controller: 'LookbookController', resolve: { theLooks: ['looks', 'lookConfig', '$stateParams', function(looks, lookConfig, $stateParams) { return looks.getRandomLooks(1, lookConfig.limit, $stateParams.type); }] } }); } ]);
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ENV = require('./env'); const PATHS = require('./paths'); const DEFAULT_DEV_SERVER_HOST = '0.0.0.0'; const DEFAULT_DEV_SERVER_PORT = 3000; const DEV_SERVER_HOST = process.env.HOST || DEFAULT_DEV_SERVER_HOST; const DEV_SERVER_PORT = process.env.PORT || DEFAULT_DEV_SERVER_PORT; const webpackConfig = { devtool: 'cheap-module-source-map', entry: { app: [ `${PATHS.SRC}/index.jsx` ], plugins: [ 'replugger', 'replugger-demo-plugin-foo', 'replugger-demo-plugin-bar' ], vendor: [ 'react', 'react-dom', 'react-router-dom', 'react-router-config', 'classnames' ] }, output: { filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].js', path: PATHS.DIST }, resolve: { extensions: ['.js', '.json', '.jsx'], modules: [ PATHS.SRC, PATHS.MODULES ], alias: { components: path.resolve(PATHS.SRC, 'components'), constants: path.resolve(PATHS.SRC, 'constants'), containers: path.resolve(PATHS.SRC, 'containers'), decorators: path.resolve(PATHS.SRC, 'decorators'), helpers: path.resolve(PATHS.SRC, 'helpers'), pages: path.resolve(PATHS.SRC, 'pages'), services: path.resolve(PATHS.SRC, 'services') } }, module: { rules: [ { test: /\.jsx?$/, enforce: 'pre', use: 'eslint-loader', include: PATHS.SRC }, { test: /\.(jsx|less)?$/, loader: 'source-map-loader', enforce: 'pre', include: PATHS.SRC }, { exclude: [ /\.(html|ejs)$/, /\.(js|jsx)$/, /\.(css|less)$/, /\.json$/, /\.svg$/, /\.(ttf|eot|woff2?)$/, /\.(png|jpe?g|gif)$/ ], use: [{ loader: 'url-loader', options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }] }, { test: /\.jsx?$/, exclude: [...PATHS.EXCLUDED_MODULES], include: [ PATHS.SRC, ...PATHS.LINKED_MODULES ], use: [ { loader: 'react-hot-loader/webpack' }, { loader: 'babel-loader', options: { cacheDirectory: true } } ] }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: true, camelCase: true } } ] }) }, { test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: true, camelCase: true, modules: true } }, { loader: 'less-loader', options: { strictMath: true, sourceMap: true, modules: true } } ] }) }, { test: /\.(png|jpe?g|gif)$/, use: [{ loader: 'url-loader', options: { limit: 1000, name: '[hash:8].[ext]' } }] }, { test: /\.(ttf|eot|woff2?)$/, use: 'file-loader' }, { test: /atlassian-icons\.svg$/, use: 'file-loader' }, { test: /\.svg$/, use: [{ loader: 'url-loader', options: { limit: 1000, name: '[hash:8].[ext]' } }] } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(ENV) }, 'process.versions': { node: JSON.stringify(process.versions.node) } }), new ExtractTextPlugin({ filename: '[name].[contenthash].css', disable: ENV === 'development' }), new webpack.NamedModulesPlugin(), new webpack.NamedChunksPlugin((chunk) => { if (chunk.name) { return chunk.name; } return chunk.mapModules(m => path.relative(m.context, m.request)).join('_'); }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }), new webpack.optimize.CommonsChunkPlugin({ name: 'runtime' }), new HtmlWebpackPlugin({ filename: 'index.html', template: `${PATHS.SRC}/index.ejs`, title: 'Replugger App', appMountId: 'root', xhtml: true, mobile: true, inject: false, chunks: ['runtime', 'vendor', 'app'], minify: { useShortDoctype: true, keepClosingSlash: true, collapseWhitespace: true, preserveLineBreaks: true } }) ] }; module.exports = webpackConfig; if (ENV === 'development') { webpackConfig.entry.app.unshift( 'react-hot-loader/patch', require.resolve('react-dev-utils/webpackHotDevClient') ); webpackConfig.devServer = { contentBase: PATHS.DIST, compress: true, host: DEV_SERVER_HOST, port: DEV_SERVER_PORT, historyApiFallback: true, inline: true, hot: true }; webpackConfig.plugins.push( new webpack.HotModuleReplacementPlugin() ); Object.assign(webpackConfig.output, { filename: '[name].[hash].js' }); webpackConfig.devtool = 'cheap-module-source-map'; } else { webpackConfig.devtool = 'source-map'; webpackConfig.plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, drop_console: true }, comments: false, mangle: false, beautify: false, sourceMap: true }) ); } module.exports = webpackConfig;
import backgroundImage from 'resize-image?sizes[]=360w&placeholder=100!./Cape_York_2015-50.jpg'; export default { title: 'Rainbow Beach\'s hidden gem: Carlo Point', description: 'Tucked in the bay a few minutes out from Rainbow Beach is a great family destination.', image: backgroundImage, date: '14 January 2016' };
'use strict'; module.exports = (function () { return { db: process.env.TEAM_MONGOLAB_URI_TEST, port: 5555 }; })();
/* Constructs a an OpenStack Swift temporary URL param method: GET or PUT, other methods may or may not be supported/tested param expires: A UNIX timestamp of when the URL should expire param path: The path to use param key: The key that is set for this account Note: requires crypto-js */ function constructTempUrl(method, expires, path, key) { hmacmsg = 'method'+'\n'+expires+'\n'+path; sig = Crypto.HMAC(Crypto.SHA1, hmacmsg, key); return path+"?temp_url_sig="+sig+"&temp_url_expires="+expires; }
'use strict'; var _ = require('lodash'); // default config var default_config = { server: { port: 40000 }, proxy: {} }; function config (user_options) { if (typeof user_options !== 'object') user_options = {}; return _.assign({}, default_config, user_options); } module.exports = config;
module.exports = (function (collection) { return collection.getFilteredByGlob([ "src/articles/*.md", "src/notes/*.md", "src/photos/*.md" ]); });
i18n({ "people.title": "People" });
var test = require('tessed').namespace('app') var app = require('.') test('returns tree', function (t) { var tree = {key: 'value'} t.deepEqual(app(tree)(), [tree], 'tree as array') t.deepEqual(app([tree])(), [tree], 'flattened tree') })
// Imports import angular from 'angular'; import routes from './workshop.routes'; import WorkshopSharedDataService from './workshop-shared-data.service'; // SCSS styles import './workshop.scss'; /** * @desc Module initialize. * * @ngInject */ export default angular .module('app.modules.workshop', []) .service('WorkshopSharedDataService', WorkshopSharedDataService) .run(routes) .name;
// Copyright 2013-2020, University of Colorado Boulder /** * Atoms look like shaded spheres. * Origin is at geometric center of bounding rectangle. * * @author Chris Malley (PixelZoom, Inc.) */ import merge from '../../../phet-core/js/merge.js'; import ShadedSphereNode from '../../../scenery-phet/js/ShadedSphereNode.js'; import Element from '../Element.js'; import nitroglycerin from '../nitroglycerin.js'; // constants const RATE_OF_CHANGE = 0.75; // >0 and <1, increase this to make small atoms appear smaller const MAX_RADIUS = Element.P.covalentRadius; // not actually the maximum, but this is a constant from the previous version const MODEL_TO_VIEW_SCALE = 0.11; class AtomNode extends ShadedSphereNode { /** * @param {Element} element * @param {Object} [options] */ constructor( element, options ) { options = merge( { mainColor: element.color }, options ); super( 2 * radiusScalingFunction( element.covalentRadius ), options ); } } /* * There is a large difference between the radii of the smallest and largest atoms. * This function adjusts scaling so that the difference is still noticeable, but not as large. */ function radiusScalingFunction( radius ) { const adjustedRadius = ( MAX_RADIUS - RATE_OF_CHANGE * ( MAX_RADIUS - radius ) ); return MODEL_TO_VIEW_SCALE * adjustedRadius; } nitroglycerin.register( 'AtomNode', AtomNode ); export default AtomNode;
import MarkdownContainer from './MarkdownContainer'; export default MarkdownContainer;
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "selectpdf");
import React from 'react-native' import { N_5, COLOR_RED_L, } from '../../theme/ume-theme/variable.js' const { StyleSheet, Dimensions } = React const deviceHeight = Dimensions.get('window').height const deviceWidth = Dimensions.get('window').width export default { content: { flex: 1, paddingLeft: 30, paddingRight: 30, paddingTop: deviceHeight / 5.8, }, text: { marginTop: 15, marginBottom: 20, color: COLOR_RED_L, }, title: { alignSelf: 'center', color: '#383838', fontSize: 32, marginBottom: 20, fontWeight: 'bold', }, listItem: { borderBottomWidth: 0, padding: 0, margin: 0, }, listItem_left_text: { position: 'absolute', marginTop: N_5, color: '#3DA8F5', }, }
"use strict"; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } let Base = function Base() { _classCallCheck(this, Base); }; let value = 2; let Obj = /*#__PURE__*/ function (_Base) { function Obj() { _classCallCheck(this, Obj); return _possibleConstructorReturn(this, _getPrototypeOf(Obj).apply(this, arguments)); } _createClass(Obj, [{ key: "set", value: function set() { return _set(_getPrototypeOf(Obj.prototype), "test", 3, this, true); } }, { key: "test", set: function (v) { expect(this).toBe(obj); value = v; } }]); _inherits(Obj, _Base); return Obj; }(Base); const obj = new Obj(); expect(obj.set()).toBe(3); expect(Base.prototype.test).toBeUndefined(); expect(Obj.prototype.test).toBeUndefined(); expect(value).toBe(2); expect(obj.test).toBe(3);
/* global ChapterSelector, $new, $ez, $state */ var _style = { img: { width: "20rem", height: "30rem", margin: "0 auto", backgroundColor: "grey" }, info: { }, title: { overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", fontSize: "3.5rem", textAlign: "center", color: "#BCBCBC", fontVariant: "small-caps", position: "absolute", width: "100%", bottom: "-3.4rem", right: 0, textShadow: "-0.3rem -0.3rem #464646" }, description: { }, content: { backgroundColor: "#464646", padding: "1rem", outline: "none", opacity: 1, maxHeight: "100%", borderBottom: "0.8rem solid #BCBCBC", color: "white", boxShadow: "0 0 0 0.1rem #A8A8A8", height: "33rem", position: "relative" }, chapterContainer: { maxHeight: "35rem", overflow: "auto" }, chapter: { }, }; function StoryDetails() { this.selector = new ChapterSelector(); this.img = $new.div({ style: _style.img, onclick: function () { $state.View.fullscreen(); $state.View.load("Story", function (Story) { Story.load(this.data).loadChapter(this.selector.index, 0); }.bind(this)); }.bind(this) }); this.title = $new.h1({ style: _style.title }); this.description = { content: $new.p({ style: _style.description }), placeholder: $new.p("NO_DESCRIPTION") }; this.chapters = $new.div({ style: _style.chapterContainer }); this.HTMLElement = $new.div({ id: "story-details", tabIndex: 0, style: _style.content, }, this.img, $new.div({ style: _style.info }/*, this.description.placeholder, this.description.content*/), this.title, this.chapters); } StoryDetails.prototype.load = function (data) { this.data = data; if (data.description) { this.description.content.textContent = data.description; this.description.placeholder.style.display = 'none'; this.description.content.style.display = ''; } else { this.description.placeholder.style.display = ''; this.description.content.style.display = 'none'; } this.title.textContent = data.title || data.path; this.selector.load(data.chapters); return this; }; StoryDetails.prototype.update = function () { return this; };
var config = require('../config.js'); describe("'sort by length' button", function () { var btnSelector = 'button=sort by length (reverse)'; var inputText; var expectedText; var actualText; before(function () { browser.url(config.baseUrl); }); afterEach(function () { browser.setValue('textarea', ''); }); it('should sort words by length (reverse)', function () { inputText = 'The lurking imbalance poles the debt.'; expectedText = [ 'imbalance', 'lurking', 'poles', 'debt.', 'The', 'the' ].join('\n'); browser.setValue('textarea', inputText); browser.click(btnSelector); actualText = browser.getValue('textarea'); expect(actualText).to.equal(expectedText); }); });
/* globals DatabaseTable:false */ var futureLinksTable = new DatabaseTable('future_links'); var future_links = []; var save_btn = document.getElementById('a_save'); var database_btn = document.getElementById('a_database'); var current_url = null; var current_title = null; chrome.tabs.query({'active': true}, function(tabs){ current_url = tabs[0].url; current_title = tabs[0].title; document.getElementById('current_title').innerHTML = current_title; document.getElementById('current_link').innerHTML = current_url; }); /** * OnClick method for the SAve Button. * It will generate an Object for the current tab page * and then save it to the localStorage database */ save_btn.onclick = function(){ var description = document.getElementById('i_description').value; var data = new Date(); var future_link = { "url": current_url, "data": data, "title": current_title, "description": description, "item_id": data.getTime() }; futureLinksTable.putObject(future_link); this.innerHTML = "Saved!"; this.setAttribute("style","opacity:0.4"); }; /** * Opens a new tab for the DAtabase section */ database_btn.onclick = function(){ chrome.tabs.create( {"url": "database.html"}, function(tab){ }); };
define( { status: "${start} - ${end} av ${total} resultater", gotoFirst: "Gå til første side", gotoNext: "Gå til neste side", gotoPrev: "Gå til forrige side", gotoLast: "Gå til siste side", gotoPage: "Gå til side", jumpPage: "Hopp til side" } );
module.exports = { IndexError: function(index) { return index + " is not an integer between 0 and the length of the tuple, inclusive"; }, ElementError: function(element) { return element + " is not a valid element, make sure the element is a string, boolean, number, or an object which contains a one key-value pair"; }, InputError: function(input) { return input + " is not a valid tuple function whose state can be modified"; }, KeyOrIndexError: function(keyOrIndex) { return keyOrIndex + " is invalid"; }, KeyError: function() { var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { if (!isNaN(args[i])) { return args[i] + " is a number and not a valid key"; } } }, ArrayError: function(array) { return array + " is not a valid array"; }, StateError: function(functionName) { return functionName + "'s state is off, please turn on if want to use with the following method applied to your tuple instance: \n modifyState(\"" + functionName + "\")"; }, ConstructorInputError: function(input) { return "the inputted element:\"" + input + "\" in your tuple is invalid"; }, TupleInputError: function(tuple) { return "the tuple inputted is invalid"; }, ModifyStateError: function() { return "the syntax used to modify which functions can be used and which one's cannot is not correct, please review the documentation"; }, };
var path = require('path'); var fs = require('fs-extra'); var Promise = require('promise'); var arrDiff = require('array-differ'); var utils = require('./utils'); var cwd = process.cwd(); var _copyPromise = Promise.denodeify(fs.copy); var _symlinkPromise = Promise.denodeify(fs.ensureSymlink); var _removePromise = Promise.denodeify(fs.remove); module.exports.copyDeps = function(src, target, deps, opts) { return new Promise(function(resolve) { if (deps.length === 0) { resolve(); } deps = deps.map(function(depName) { var srcDir = path.join(cwd, src, depName); var targetDir = path.join(cwd, target, depName); if (opts.symlink) { return _symlinkPromise(srcDir, targetDir); } return _copyPromise(srcDir, targetDir, { clobber: true }); }); resolve(Promise.all(deps)); }); }; module.exports.removeDeps = function(target, deps, opts) { return new Promise(function(resolve) { var rmDeps = []; if (opts.updateAndDelete && utils.existsSync(target)) { // Get a list of directories that can remove // difference bower.json dependencies and dependencies in the destination directory rmDeps = arrDiff(fs.readdirSync(target), deps); } else { resolve(); } // If list empty if (rmDeps.length === 0) { resolve(); } rmDeps = rmDeps.map(function(depName) { return _removePromise(path.join(cwd, target, depName)); }); resolve(Promise.all(rmDeps)); }); };
// @flow import { h } from '@cycle/dom'; import xs from 'xstream'; import { nth, pick, prop, clamp } from 'ramda'; import { aEntity } from './utils/AframeHyperscript'; function renderCam(newAttr) { const defaultAttr = { camera: true, 'mouse-events': true }; return h('a-entity', { attrs: { ...defaultAttr, ...newAttr } }); } function calcRotation(oldRot, deltaRot) { const newRot = { xdeg: oldRot.xdeg - (deltaRot.dx / 10), ydeg: oldRot.ydeg - (deltaRot.dy / 10), }; return newRot; } function intent(sources) { const mouseFalse$ = xs.merge( sources.mouseUp$.mapTo(false), sources.mouseLeave$.mapTo(false) ); const isMouseDown$ = xs.merge( sources.mouseDown$.mapTo(true), mouseFalse$ ); const mouseDrag$ = xs.combine(isMouseDown$, sources.mouseMove$) .filter(([isDown]) => isDown) .map(nth(1)); const mouseWheel$ = sources .mouseWheel$ .map(pick(['deltaX', 'deltaY'])); const intents = { mouseDrag$, mouseWheel$, }; return intents; } function model(actions) { const rotation$ = actions .mouseDrag$ .fold(calcRotation, { xdeg: 0, ydeg: 0 }); const zoom$ = actions .mouseWheel$ .map(prop('deltaY')) .fold((zoom, dZoom) => clamp(2, Infinity)(zoom - (dZoom / 50)), 5); const state = { rotation$, zoom$, }; return state; } function view(state) { const state$ = xs.combine(state.rotation$, state.zoom$); return state$.map(([rot, zoom]) => aEntity( '#camera-x-container', { attrs: { rotation: `0 ${rot.xdeg} 0` } }, [ aEntity( '#camera-y-container', { attrs: { rotation: `${rot.ydeg} 0 0` } }, [renderCam({ position: `0 0 ${zoom}` })] ), ] ) ); } type CameraSources = { mouseDown$: any; mouseUp$: any; mouseLeave$: any; mouseUp$: any; mouseWheel$: any; mouseMove$: any; DOM: any; }; type CameraSinks = { DOM: any; }; function Camera(sources: CameraSources): CameraSinks { const actions = intent(sources); const state = model(actions); const vdom$ = view(state); const sinks = { DOM: vdom$, }; return sinks; } export default Camera;
// const { mix } = require('laravel-mix'); // // /* // |-------------------------------------------------------------------------- // | Mix Asset Management // |-------------------------------------------------------------------------- // | // | Mix provides a clean, fluent API for defining some Webpack build steps // | for your Laravel application. By default, we are compiling the Sass // | file for the application as well as bundling up all the JS files. // | // */ // // mix.js('resources/assets/js/app.js', 'public/js') // .sass('resources/assets/sass/app.scss', 'public/css');
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _message = require('../message'); var _message2 = _interopRequireDefault(_message); var _item = require('./item'); var _item2 = _interopRequireDefault(_item); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Section = function (_React$Component) { _inherits(Section, _React$Component); function Section() { _classCallCheck(this, Section); return _possibleConstructorReturn(this, (Section.__proto__ || Object.getPrototypeOf(Section)).apply(this, arguments)); } _createClass(Section, [{ key: 'render', value: function render() { var _props = this.props, component = _props.component, content = _props.content, empty = _props.empty, items = _props.items, title = _props.title; return _react2.default.createElement( 'div', { className: 'reframe-list-section' }, title && _react2.default.createElement( 'div', { className: 'reframe-list-title' }, title ), component && _lodash2.default.isFunction(component) ? _react2.default.createElement(component, content) : component, content && _react2.default.createElement( 'div', { className: 'reframe-list-item' }, _react2.default.createElement( 'div', { className: 'reframe-list-item-content' }, _react2.default.createElement( 'div', { className: 'reframe-list-item-content-value' }, content ) ) ), items && items.length > 0 && items.map(function (item, itemIndex) { return _react2.default.createElement(_item2.default, _extends({ key: 'list_item_' + itemIndex }, item)); }), empty && items && items.length === 0 && _react2.default.createElement( 'div', { className: 'reframe-list-item' }, _lodash2.default.isPlainObject(empty) ? _react2.default.createElement(_message2.default, empty) : _react2.default.createElement( 'div', { className: 'reframe-list-item-content' }, _react2.default.createElement( 'div', { className: 'reframe-list-item-content-value' }, _lodash2.default.isFunction(empty) ? _react2.default.createElement(empty, this.props) : empty ) ) ) ); } }]); return Section; }(_react2.default.Component); exports.default = Section;
StageAssistant = Class.create({ setup: function() { SpareTime.Metrix.postDeviceData() DataStore.initialize( function() { this.controller.pushScene("login") }.bind(this), function() { this.controller.pushScene("bail", "error initializing datastore") }.bind(this) ) } })
$(document).ready(function () { console.log("ready"); var overlay = { newDiv : $('<div>', {class: 'overlay'}) } var overlay_gallery ={ newDiv : $('<div>', {class: 'overlay-gallery'}) } $(".item-c-1").on ('mouseenter', function () { $(this).children('h4').addClass('blue'); $(this).addClass('gray-bg'); overlay.newDiv.prependTo('figure.img-c-1'); }); $(".item-c-1").on( 'mouseleave', function () { $(this).children('h4').removeClass('blue'); $(this).removeClass('gray-bg'); overlay.newDiv.remove(); }); $(".item-c-2").on ('mouseenter', function () { $(this).children('h4').addClass('blue'); $(this).addClass('gray-bg'); overlay.newDiv.prependTo('figure.img-c-2'); }); $(".item-c-2").on( 'mouseleave', function () { $(this).children('h4').removeClass('blue'); $(this).removeClass('gray-bg'); overlay.newDiv.remove(); }); $(".item-c-3").on ('mouseenter', function () { $(this).children('h4').addClass('blue'); $(this).addClass('gray-bg'); overlay.newDiv.prependTo('figure.img-c-3'); }); $(".item-c-3").on( 'mouseleave', function () { $(this).children('h4').removeClass('blue'); $(this).removeClass('gray-bg'); overlay.newDiv.remove(); }); $(".item-c-4").on ('mouseenter', function () { $(this).children('h4').addClass('blue'); $(this).addClass('gray-bg'); overlay.newDiv.prependTo('figure.img-c-4'); }); $(".item-c-4").on( 'mouseleave', function () { $(this).children('h4').removeClass('blue'); $(this).removeClass('gray-bg'); overlay.newDiv.remove(); }); $("li.item-gallery" ) .on( "mouseenter", function() { overlay_gallery.newDiv.prependTo(this); }) .on( "mouseleave", function() { overlay_gallery.newDiv.remove(); }); });
define('v3grid/SortDataProvider', ['v3grid/Adapter', 'v3grid/SortDataProviderBase'], function (Adapter, SortDataProviderBase) { var SortDataProvider = function (config) { SortDataProviderBase.call(this, config); this.index = []; this.invIndex = []; this.unSort(true); }; SortDataProvider.prototype = new SortDataProviderBase({ /* DataProvider API - start */ getRowCount: function () { return this.index.length; }, getRowId: function (row) { return this.dataProvider.getRowId(this.index[row]); }, getCellData: function (row, col) { return this.dataProvider.getCellData(this.index[row], col); }, refresh: function () { var oldFields = this.sortedBy; this.unSort(true); this.sort(oldFields); }, invalidateCell: function (row, column) { var sortedColIdx = Adapter.indexOf(this.sortedBy, column); // if index is even (0, 2, ... and not -1) // we found 'column' in 'sortedBy', so we need to re-sort. if ((sortedColIdx & 1) == 0) { this.refresh(); return; } this.fireEvent('cellChanged', this.invIndex[row], column); }, /* DataProvider API - end */ sort: function (fields, noUpdate) { this.setFields(fields, noUpdate); var index = this.index, invIdx = this.invIndex; index.sort(this.getCompareFunction()); for (var rowCount = index.length, i = 0; i < rowCount; ++i) invIdx[index[i]] = i; if (!noUpdate) this.fireEvent('dataChanged'); }, unSort: function (noUpdate) { this.setFields([], noUpdate); var rowCount = this.dataProvider.getRowCount(); var index = this.index, invIdx = this.invIndex; index.length = invIdx.length = rowCount; for (var i = 0; i < rowCount; ++i) invIdx[i] = index[i] = i; if (!noUpdate) this.fireEvent('dataChanged'); } }); return SortDataProvider; } );
/** * Created by singgum3b on 1/1/14. */ //Modified from MDN example https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas function htmlCapture(domobj) { var canvas = document.createElement("canvas"), documentBody = document.querySelector('body'); canvas.width = documentBody.offsetWidth; canvas.height = documentBody.offsetHeight; documentBody.insertBefore(canvas, documentBody.firstChild); //---------------Building html ------------------------------// var html = document.createElement('html'); var body = document.createElement('body'); var header = document.createElement('head'); header.innerHTML = '<link type="text/css" rel="stylesheet" href="css/style.css" />'; body.innerHTML = domobj.outerHTML; html.appendChild(header); html.appendChild(body); html.setAttribute('xmlns', document.documentElement.namespaceURI); console.log(html.innerHTML); // Get well-formed markup // Webkit families generate false xml format output (eg. self-contained tag get stripped : <br/> -> <br>) html = (new XMLSerializer()).serializeToString(html); var ctx = canvas.getContext("2d"); var data = "<svg xmlns='http://www.w3.org/2000/svg' width='" + documentBody.offsetWidth + "' height='" + documentBody.offsetHeight + "'>" + "<foreignObject width='100%' height='100%'>" + html + "</foreignObject>" + "</svg>"; var DOMURL = self.URL || self.webkitURL || self; var img = new Image(); var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"}); var url = DOMURL.createObjectURL(svg); img.onload = function () { ctx.drawImage(img, 0, 0); DOMURL.revokeObjectURL(url); }; img.src = url; }
module.exports = { "inputs": { "offset": { "friendlyName": "offset", "description": "Offset number", "example": 123, "addedManually": true, "requiredManually": true, "required": true }, "type": { "id": "77643aa2-b722-41d7-a4b9-876b9333add3", "friendlyName": "type", "description": "Offset time type:\nyears\ty\nquarters\tQ\nmonths\tM\nweeks\tw\ndays\t d\nhours\th\nminutes\tm\nseconds\ts\nmilliseconds\tms", "example": "months", "requiredManually": true, "addedManually": true, "required": true } }, "exits": { "error": { "example": undefined }, "success": { "id": "success", "friendlyName": "then", "description": "Return Unix time offset", "example": 12345 } }, "sync": false, "cacheable": false, "defaultExit": "success", "fn": function(inputs, exits, env) { var moment = require('moment'), offset = inputs.offset, type = inputs.type, types = [ "years", "y", "quarters", "Q", "months", "M", "weeks", "w", "days", "d", "hours", "h", "minutes", "m", "seconds", "s", "milliseconds", "ms" ]; if (offset !== 0 && types.indexOf(type) !== -1) { return exits.success(moment.utc().add(offset, type).unix()); } else { return exits.error("Wrong input format"); } }, "identity": "date-string" };
import React from 'react'; import GameModePlayer from './GameModePlayer'; export default class GameMode extends React.Component { render() { const disableSumbit = (!this.state.playerOne || !this.state.playerTwo) || (this.state.playerOne === this.state.playerTwo); return ( <div> <GameModePlayer players={this.props.players} onSelect={this.getPlayerOneDetails} /> vs <GameModePlayer players={this.props.players} onSelect={this.getPlayerTwoDetails} /> <button onClick={this.submit} disabled={disableSumbit}> Submit </button> </div> ); } constructor(props) { super(props); this.state = { playerOne: undefined, playerTwo: undefined, }; } componentWillUnmount() { this.props.database.ref(`players`).off(`child_added`); this.props.database.ref(`players`).off(`child_changed`); } getPlayerOneDetails = playerOne => { this.setState({ playerOne }, () => { this.recalculate(); }); } getPlayerTwoDetails = playerTwo => { this.setState({ playerTwo }, () => { this.recalculate(); }); } recalculate = () => { if (this.state.playerOne && this.state.playerTwo) { console.log(this.state.playerOne); // eslint-disable-line console.log(this.state.playerTwo); // eslint-disable-line } } submit = () => { console.log(this.state.playerOne); // eslint-disable-line console.log(this.state.playerTwo); // eslint-disable-line } } GameMode.propTypes = { database: React.PropTypes.object.isRequired, players: React.PropTypes.arrayOf(React.PropTypes.shape({ name: React.PropTypes.string.isRequired, rank: React.PropTypes.string.isRequired, id: React.PropTypes.string.isRequired, })).isRequired, };
'use strict'; app.directive('siafileRow', function() { return { templateUrl: 'views/siafilerow.html', controller: 'siafileRowCtrl' } });
import { queryAll } from '../utils'; const markSwupElements = (element, containers) => { let blocks = 0; for (let i = 0; i < containers.length; i++) { if (element.querySelector(containers[i]) == null) { console.warn(`Element ${containers[i]} is not in current page.`); } else { queryAll(containers[i]).forEach((item, index) => { queryAll(containers[i], element)[index].setAttribute('data-swup', blocks); blocks++; }); } } }; export default markSwupElements;
(function() { "use strict"; var PIXI = require('pixi.js'); var asset_loader = require('./asset_loader'); var StartGameScene = require('./game_start_scene/main'); var GameOverScene = require('./game_over_scene/main'); var Clouds = require('./background/clouds'); var Ground = require('./background/ground'); var Rocks = require('./rocks/rocks_manager'); var Plane = require('./planes/main'); var Score = require('./game_score/main'); var Puffs = require('./puffs/puffs_manager'); var ads = require('../banner_adds/ads_m'); var renderer; var canvas; var game_stage; function Main() { PIXI.Stage.call(this, 0x000000, true); this.mousedown = this.touchstart = this.onScreenTouch; this.mouseup = this.touchend = this.onScreenTouchEnd; this.setupCanvas(); this.loadAssets(); this.initGameLoop(); } Main.prototype = Object.create(PIXI.Stage.prototype); Main.prototype.constructor = Main; Main.prototype.onScreenTouch = function() { FP.PLANE_FALLING = false; }; Main.prototype.onScreenTouchEnd = function() { FP.PLANE_FALLING = true; }; Main.prototype.setupCanvas = function() { if(FP.IS_NATIVE) { canvas = document.createElement('screencanvas'); canvas.style.cssText="idtkscale:ScaleAspectFill;"; canvas.width = FP.WW; canvas.height = FP.WH; document.body.appendChild(canvas); renderer = new PIXI.CanvasRenderer(FP.WW, FP.WH, canvas); game_stage = new PIXI.DisplayObjectContainer(); ads.init(canvas.getContext("2d")); } else { renderer = PIXI.autoDetectRenderer(FP.getWidth(), FP.getHeight()); game_stage = new PIXI.DisplayObjectContainer(); //game_stage.scale.x = FP.WW / FP.getWidth(); //game_stage.scale.y = FP.WH / FP.getHeight(); document.body.appendChild(renderer.view); } this.addChild(game_stage); }; Main.prototype.loadAssets = function() { asset_loader.onComplete = this.onDoneLoadingAssets.bind(this); asset_loader.load(); }; Main.prototype.onDoneLoadingAssets = function() { game_stage.addChild(new Clouds()); var plane = new Plane(); game_stage.addChild(plane); if(FP.IS_NATIVE) game_stage.addChild(new Puffs(plane)); game_stage.addChild(new Rocks()); game_stage.addChild(new Ground()); var score = new Score(); score.position.x = FP.getWidth() / 2 - score.width / 2; game_stage.addChild(score); game_stage.addChild(new StartGameScene()); }; Main.prototype.showGameOver = function() { game_stage.addChild(new GameOverScene()); }; Main.prototype.restartGame = function() { FP.PLANE_OBSTICLES = []; game_stage.children = []; this.onDoneLoadingAssets(); }; Main.prototype.initGameLoop = function() { requestAnimFrame(this.initGameLoop.bind(this)); game_stage.children.forEach(function(child) { child.update(); }); renderer.render(this); }; module.exports = Main; })();
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars'); var mongoose = require('mongoose'); var index = require('./routes/index'); var myMinor = require('./routes/myMinor'); var allClasses = require('./routes/allClasses'); var course = require('./routes/course'); var about = require('./routes/about'); var rate = require('./routes/rate'); var indexB = require('./routes/indexB'); // Example route // var user = require('./routes/user'); // Connect to the Mongo database, whether locally or on Heroku // MAKE SURE TO CHANGE THE NAME FROM 'lab7' TO ... IN OTHER PROJECTS var local_database_name = 'classapped'; var local_database_uri = 'mongodb://localhost/' + local_database_name var database_uri = process.env.MONGOLAB_URI || local_database_uri mongoose.connect(database_uri); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('Intro HCI secret key')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } // Add routes here app.get('/', index.view); app.get('/indexB', indexB.view); app.get('/minor', myMinor.view); app.get('/courses', allClasses.view); app.get('/courses/:name', course.viewCourse); app.get('/about', about.view); app.get('/courses/:name/rate', rate.view); app.post('/rating/new', rate.addRating); // Example route // app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var ALIGN_CONST = require('../const'); var AlignInMap = []; AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = require('./BottomCenter'); AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = require('./BottomLeft'); AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = require('./BottomRight'); AlignInMap[ALIGN_CONST.CENTER] = require('./Center'); AlignInMap[ALIGN_CONST.LEFT_CENTER] = require('./LeftCenter'); AlignInMap[ALIGN_CONST.RIGHT_CENTER] = require('./RightCenter'); AlignInMap[ALIGN_CONST.TOP_CENTER] = require('./TopCenter'); AlignInMap[ALIGN_CONST.TOP_LEFT] = require('./TopLeft'); AlignInMap[ALIGN_CONST.TOP_RIGHT] = require('./TopRight'); /** * Takes given Game Object and aligns it so that it is positioned relative to the other. * The alignment used is based on the `position` argument, which is an `ALIGN_CONST` value, such as `LEFT_CENTER` or `TOP_RIGHT`. * * @function Phaser.Display.Align.In.QuickSet * @since 3.0.0 * * @generic {Phaser.GameObjects.GameObject} G - [child,$return] * * @param {Phaser.GameObjects.GameObject} child - The Game Object that will be positioned. * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. * @param {integer} position - The position to align the Game Object with. This is an align constant, such as `ALIGN_CONST.LEFT_CENTER`. * @param {number} [offsetX=0] - Optional horizontal offset from the position. * @param {number} [offsetY=0] - Optional vertical offset from the position. * * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. */ var QuickSet = function (child, alignIn, position, offsetX, offsetY) { return AlignInMap[position](child, alignIn, offsetX, offsetY); }; module.exports = QuickSet;
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zm5.66 3H6.43c.61-.52 2.06-1 5.57-1 3.71 0 5.12.46 5.66 1zM11 7v3H6V7h5zm2 0h5v3h-5V7zm3.5 10h-9c-.83 0-1.5-.67-1.5-1.5V12h12v3.5c0 .83-.67 1.5-1.5 1.5z" }), h("circle", { cx: "8.5", cy: "14.5", r: "1.5" }), h("circle", { cx: "15.5", cy: "14.5", r: "1.5" })), 'DirectionsTransitOutlined');
/* Top toolbar area with buttons and title ----------------------------------------------------------------------------------------------------------------------*/ // TODO: rename all header-related things to "toolbar" function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; t.getViewsWithButtons = getViewsWithButtons; // locals var el = $(); var viewsWithButtons = []; var tm; function render() { var sections = options.header; tm = options.theme ? 'ui' : 'fc'; if (sections) { el = $("<div class='fc-toolbar'/>") .append(renderSection('left')) .append(renderSection('right')) .append(renderSection('center')) .append('<div class="fc-clear"/>'); return el; } } function destroy() { el.remove(); } function renderSection(position) { var sectionEl = $('<div class="fc-' + position + '"/>'); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { var groupChildren = $(); var isOnlyButtons = true; var groupEl; $.each(this.split(','), function(j, buttonName) { var buttonClick; var themeIcon; var normalIcon; var defaultText; var viewText; // highest priority var customText; var innerHtml; var classes; var button; if (buttonName == 'title') { groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height isOnlyButtons = false; } else { if (calendar[buttonName]) { // a calendar method buttonClick = function() { calendar[buttonName](); }; } else if (calendar.isValidViewType(buttonName)) { // a view type buttonClick = function() { calendar.changeView(buttonName); }; viewsWithButtons.push(buttonName); viewText = calendar.getViewButtonText(buttonName); } if (buttonClick) { // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week") themeIcon = smartProperty(options.themeButtonIcons, buttonName); normalIcon = smartProperty(options.buttonIcons, buttonName); defaultText = smartProperty(options.defaultButtonText, buttonName); // from languages customText = smartProperty(options.buttonText, buttonName); if (viewText || customText) { innerHtml = htmlEscape(viewText || customText); } else if (themeIcon && options.theme) { innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>"; } else if (normalIcon && !options.theme) { innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>"; } else { innerHtml = htmlEscape(defaultText || buttonName); } classes = [ 'fc-' + buttonName + '-button', tm + '-button', tm + '-state-default' ]; button = $( // type="button" so that it doesn't submit a form '<button type="button" class="' + classes.join(' ') + '">' + innerHtml + '</button>' ) .click(function() { // don't process clicks for disabled buttons if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); // after the click action, if the button becomes the "active" tab, or disabled, // it should never have a hover class, so remove it now. if ( button.hasClass(tm + '-state-active') || button.hasClass(tm + '-state-disabled') ) { button.removeClass(tm + '-state-hover'); } } }) .mousedown(function() { // the *down* effect (mouse pressed in). // only on buttons that are not the "active" tab, or disabled button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { // undo the *down* effect button.removeClass(tm + '-state-down'); }) .hover( function() { // the *hover* effect. // only on buttons that are not the "active" tab, or disabled button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { // undo the *hover* effect button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup } ); groupChildren = groupChildren.add(button); } } }); if (isOnlyButtons) { groupChildren .first().addClass(tm + '-corner-left').end() .last().addClass(tm + '-corner-right').end(); } if (groupChildren.length > 1 || isOnlyButtons) { groupEl = $('<div/>'); if (isOnlyButtons) { groupEl.addClass('fc-button-group'); } groupEl.append(groupChildren); sectionEl.append(groupEl); } else { sectionEl.append(groupChildren); // 1 or 0 children } }); } return sectionEl; } function updateTitle(text) { el.find('h2').text(text); } function activateButton(buttonName) { el.find('.fc-' + buttonName + '-button') .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { el.find('.fc-' + buttonName + '-button') .removeClass(tm + '-state-active'); } function disableButton(buttonName) { el.find('.fc-' + buttonName + '-button') .attr('disabled', 'disabled') .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { el.find('.fc-' + buttonName + '-button') .removeAttr('disabled') .removeClass(tm + '-state-disabled'); } function getViewsWithButtons() { return viewsWithButtons; } }
export const setUser = user => ({ type: 'SET_USER', user, });
var zmq = require('zmq'); var Readable = require('readable-stream').Readable; var debug = require('debug')('pigato:Client'); var uuid = require('node-uuid'); var util = require('util'); var events = require('events'); var _ = require('lodash'); var MDP = require('./mdp'); var putils = require('./utils'); var HEARTBEAT_LIVENESS = 3; function Client(brokers, conf) { if (_.isString(brokers)) { brokers = [brokers]; } this.brokers = brokers; this.conf = { heartbeat: 2500, timeout: 60000, retry: 0, name: 'C' + uuid.v4() }; this.reqs = {}; _.extend(this.conf, conf); events.EventEmitter.call(this); }; util.inherits(Client, events.EventEmitter); Client.prototype.start = function() { var self = this; this.socket = zmq.socket('dealer'); this.socket.identity = new Buffer(this.conf.name); this.socket.on('message', function() { self.onMsg.call(self, putils.args(arguments)); }); this.socket.on('error', function(err) { self.emitErr(err); }); _.each(this.brokers, function(b) { self.socket.connect(b); }); debug('Client connected to %s', this.broker); this.hbTimer = setInterval(function() { self.heartbeat(); _.each(self.reqs, function(req, rid) { if (req.timeout > -1 && ((new Date()).getTime() > req.lts + req.timeout)) { self.onMsg([MDP.CLIENT, MDP.W_REPLY, '', new Buffer(rid), new Buffer(JSON.stringify('C_TIMEOUT'))]); } return true; }); }, this.conf.heartbeat); }; Client.prototype.stop = function() { clearInterval(this.hbTimer); if (this.socket) { if(this.socket._zmq.state != zmq.STATE_CLOSED) { this.socket.close(); } delete this.socket; } }; Client.prototype.send = function(msg) { if (!this.socket) { return; } this.socket.send(msg); }; Client.prototype.onMsg = function(msg) { msg = putils.mparse(msg); var header = msg[0]; var type = msg[1]; if (header != MDP.CLIENT) { this.emitErr('ERR_MSG_HEADER'); return; } if (msg.length < 3) { return; } var rid = msg[3]; var req = this.reqs[rid]; if (!req) { return; } var err = msg[4] || null; var data = msg[5] || null; if (err) { err = err; if (err == 0) { err = null; } else { err = JSON.parse(err); } } if (data) { data = JSON.parse(data); } if (type == MDP.W_REPLY || type == MDP.W_REPLY_PARTIAL) { req.lts = new Date().getTime(); if (type == MDP.W_REPLY) { req._finalMsg = [err, data]; req.ended = true; delete this.reqs[rid]; } if (err) { req.stream.emit('error', err); } req.stream.push(data); if (type == MDP.W_REPLY) { req.stream.push(null); } } else { this.emitErr('ERR_MSG_TYPE'); } }; Client.prototype.emitErr = function(msg) { this.emit.apply(this, ['error', msg]); }; function noop() {} function _request(serviceName, data, opts) { var self = this; var rid = uuid.v4(); if (typeof opts !== 'object') { opts = {}; } opts.timeout = opts.timeout || this.conf.timeout; opts.retry = opts.retry || this.conf.retry; var req = this.reqs[rid] = { rid: rid, timeout: opts.timeout, ts: new Date().getTime(), opts: opts, heartbeat: function() { self.heartbeat(rid); }, _finalMsg: null, ended: false }; req.lts = req.ts; var stream = new Readable({ objectMode: true }); stream._read = noop; stream.heartbeat = req.heartbeat; req.stream = stream; debug('C: send request', serviceName, rid); this.send([ MDP.CLIENT, MDP.W_REQUEST, serviceName, rid, JSON.stringify(data), JSON.stringify(opts) ]); return req; }; Client.prototype.requestStream = function(serviceName, data, opts) { return this.request(serviceName, data, undefined, undefined, opts); }; Client.prototype.request = function(serviceName, data, partialCb, finalCb, opts) { var mode = 'stream'; var serviceName = arguments[0]; var data = arguments[1]; var opts, partialCb, finalCb; if (arguments.length >= 4) { mode = 'callback'; partialCb = arguments[2]; finalCb = arguments[3]; opts = arguments[4]; } else { opts = arguments[2]; } var req = _request.call(this, serviceName, data, opts); if (mode === 'callback') { req.stream.on('data', function(data) { if (req.ended) { return; } if (partialCb) { partialCb(null, data); } }); req.stream.on('end', function() { var msg = req._finalMsg; if (finalCb) { finalCb(msg[0], msg[1]); } }); req.stream.on('error', noop); } else { return req.stream; } }; Client.prototype.heartbeat = function(rid) { var msg = [MDP.CLIENT, MDP.W_HEARTBEAT]; if (rid) { msg.push(rid); } this.send(msg); }; module.exports = Client;
/** Checks if one of the usernames is part of the rights list A right may be a regular expression. */ module.exports = function checkRights( usernames, rights = '', defaultValue = false ) { if (!rights) return defaultValue; if (!usernames) return false; if (!Array.isArray(usernames)) usernames = [usernames]; var alloweds = rights.split(/[ ,;\r\n]+/).filter((a) => a); for (let allowed of alloweds) { let isRegExp = false; if (allowed.startsWith('/') && allowed.endsWith('/')) { isRegExp = true; var regexp = new RegExp(allowed.substring(1, allowed.length - 1)); } for (let username of usernames) { if (!username) continue; if (isRegExp) { if (username.match(regexp)) return true; } else { if (username.toLowerCase() === allowed.toLowerCase()) return true; } } } return false; };
import path from 'path'; import fs from 'fs'; const cwd = process.cwd(); const pkgPath = path.resolve('package.json'); const pkg = JSON.parse(fs.readFileSync(pkgPath)); // Base config const config = { name: pkg.name, version: pkg.version, moduleName: 'InputRange', src: 'src', scss: 'scss', build: 'build', dist: 'dist', lib: 'lib', test: 'test', tasks: 'tasks', example: { js: 'example/js', scss: 'example/scss', build: 'example/build', }, }; // Script config config.script = { build: { paths: [ config.src, ], entries: [ config.src + '/' + config.moduleName, ], external: 'react', output: pkg.name + '.js', standalone: config.moduleName, dest: config.build, }, lib: { src: config.src + '/**/*.js', dest: config.lib, }, example: { paths: [ config.build, config.src, config.example.js, ], entries: [ config.example.js + '/example.js', ], noParse: [ path.join(cwd, config.build, config.name + '.js'), ], output: 'example.js', dest: config.example.build, debug: true, }, dist: { src: config.build + '/**/*.js', dest: config.dist, rename: { suffix: '.min', }, }, }; // Style config config.style = { build: { src: config.scss + '/**/*.scss', output: pkg.name + '.css', dest: config.build, sass: { includePaths: [ config.scss, ], }, }, dist: { src: config.build + '/**/*.css', dest: config.dist, rename: { suffix: '.min', }, }, example: { src: config.example.scss + '/**/*.scss', output: 'example.css', dest: config.example.build, sass: { includePaths: [ config.build, config.scss, config.example.scss, ], }, }, }; // Clean config config.clean = { script: { src: [ config.build + '/**/*.js*', ], }, lib: { src: [ config.lib + '/**/*', ], }, style: { src: [ config.build + '/**/*.css*', ], }, example: { style: { src: [ config.example.build + '/**/*.css*', ], }, script: { src: [ config.example.build + '/**/*.js*', ], }, }, dist: { style: { src: [ config.dist + '/**/*.css*', ], }, script: { src: [ config.dist + '/**/*.js*', ], }, }, }; // Connect config config.connect = { server: { root: 'example', livereload: true, port: 8080, }, }; // Watch config config.watch = { style: { src: [ config.style.build.src, config.style.example.src, ], }, script: { src: [ config.src + '/**/*.js', config.example.js + '/**/*.js', config.test + '/**/*.js', ], build: config.script.build, example: config.script.example, }, task: { src: [ config.tasks + '/**/*.js', ], }, }; // Lint config config.lint = { script: { src: [ config.src + '/**/*.js', config.test + '/**/*.js', ], }, task: { src: config.tasks + '/**/*.js', }, style: { src: config.scss + '/**/*.scss', bundleExec: true, }, }; // Test config config.test = { unit: { configFile: cwd + '/karma.conf.js', autoWatch: false, singleRun: true, }, watch: { configFile: cwd + '/karma.conf.js', }, }; // Release config config.release = { src: [ pkgPath, 'bower.json', ], }; export default config;
// Sanitizing const normalise = function(s) { if (s && s.replace) { return s.replace(/\s+/g, " "); } return ""; }; const clean = function(s) { if (s && s.trim) { return normalise(s).trim(); } return ""; }; const oneWord = function(s) { const cleanedString = clean(s); // Only return the first word in the string, for strings where space is not allowed if (cleanedString) { return cleanedString.replace(/\s.*$/, ""); } return ""; }; const formatUriName = function(s) { const oneWordString = oneWord(s); // No slashes allowed, and all lowercase if (oneWordString) { return oneWordString.replace(/\//g, "").toLowerCase(); } return ""; }; const lowerClean = function(s) { const cleanedString = clean(s); // All lowercase if (cleanedString) { return cleanedString.toLowerCase(); } return ""; }; // Misc const pluralize = function(value, base, addition) { // Example: 8, "banana", "s", returns either "banana" or "bananas" value = parseInt(value, 10); if (value === 1) { return base; } return base + addition; }; module.exports = { clean, formatUriName, lowerClean, normalise, oneWord, pluralize };
/*jshint browserify: true */ 'use strict'; module.exports = listenToProp; function listenToProp(prop, fn) { return { componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var func = typeof fn === 'function' ? fn : this[fn]; if (nextProps[prop]) { if (nextProps[prop] === this.props[prop]) return; nextProps[prop].listen(func, this); if (this.props[prop]) { this.props[prop].unlisten(func, this); } } else { if (!this.props[prop]) return; this.props[prop].unlisten(func, this); } }, componentDidMount: function componentDidMount() { if (!this.props[prop]) return; var func = typeof fn === 'function' ? fn : this[fn]; this.props[prop].listen(func, this); }, componentWillUnmount: function componentWillUnmount() { if (!this.props[prop]) return; var func = typeof fn === 'function' ? fn : this[fn]; this.props[prop].unlisten(func, this); } }; }
module.exports = require('./lib/downloads');
var utils = require('../utils.js'); module.exports = function(config, data){ var url = 'https://www.openarch.nl/search.php?lang=en&name='; // defaults to English version of website var query = ''; if(data.givenName) { query += data.givenName; } if(data.familyName) { if(query) { query += ' '; } query += data.familyName; } // Replace spaces with + query = query.replace(/ /g, '+'); return url + query; };
import each from "lodash/collection/each"; import * as t from "../../types"; export function JSXAttribute(node, print) { print(node.name); if (node.value) { this.push("="); print(node.value); } } export function JSXIdentifier(node) { this.push(node.name); } export function JSXNamespacedName(node, print) { print(node.namespace); this.push(":"); print(node.name); } export function JSXMemberExpression(node, print) { print(node.object); this.push("."); print(node.property); } export function JSXSpreadAttribute(node, print) { this.push("{..."); print(node.argument); this.push("}"); } export function JSXExpressionContainer(node, print) { this.push("{"); print(node.expression); this.push("}"); } export function JSXElement(node, print) { var open = node.openingElement; print(open); if (open.selfClosing) return; this.indent(); for (var child of (node.children: Array)) { if (t.isLiteral(child)) { this.push(child.value, true); } else { print(child); } } this.dedent(); print(node.closingElement); } export function JSXOpeningElement(node, print) { this.push("<"); print(node.name); if (node.attributes.length > 0) { this.push(" "); print.join(node.attributes, { separator: " " }); } this.push(node.selfClosing ? " />" : ">"); } export function JSXClosingElement(node, print) { this.push("</"); print(node.name); this.push(">"); } export function JSXEmptyExpression() {}
//canopies number of leaf sections, height of tree, materials var simplePineGenerator = function(canopies, height, trunkMaterial, leafMaterial, scene) { var curvePoints = function(l, t) { var path = []; var step = l / t; for (var i = 0; i < l; i += step ) { path.push(new BABYLON.Vector3(0, i, 0)); path.push(new BABYLON.Vector3(0, i, 0 )); } return path; }; var nbL = canopies + 1; var nbS = height; var curve = curvePoints(nbS, nbL); var radiusFunction = function (i, distance) { var fact = 1; if (i % 2 == 0) { fact = .5; } var radius = (nbL * 2 - i - 1) * fact; return radius; }; var leaves = BABYLON.Mesh.CreateTube("tube", curve, 0, 10, radiusFunction, 1, scene); var trunk = BABYLON.Mesh.CreateCylinder("trunk", nbS/nbL, nbL*1.5 - nbL/2 - 1, nbL*1.5 - nbL/2 - 1, 12, 1, scene); leaves.material = leafMaterial; trunk.material = trunkMaterial; var tree = new BABYLON.Mesh.CreateBox('',1,scene); tree.isVisible = false; leaves.parent = tree; trunk.parent = tree; return tree; }
define("ace/snippets/mushcode", ["require", "exports", "module"], function (e, t, n) { "use strict"; t.snippetText = undefined, t.scope = "mushcode" })
define([ 'jquery', 'underscore', 'backbone', ], function( $, _, Backbone ) { var AppView = Backbone.View.extend({ el: 'body', // The DOM events specific to an item. events: { }, // The AppView listens for changes to its model, re-rendering. Since there's // a one-to-one correspondence between a **Todo** and a **AppView** in this // app, we set a direct reference on the model for convenience. initialize: function() { }, // Re-render the titles of the todo item. render: function() { return this; }, }); return AppView; });
function leadingZeros(z, n) { return ("0".repeat(z) + n.toString()).slice(-z); } function parseData(csv) { const rows = csv.trim().split(/\n+/).slice(1).map(line => { const tokens = line.split(","); const ymd = tokens[0].split("-").map(t => parseInt(t)); const date = new Date(); date.setFullYear(ymd[0], ymd[1]-1, ymd[2]); return { date: date, value: parseFloat(tokens[1].trim()) }; }); let minValue = 1e9; let maxValue = -1e9; let sum = 0; for (let i = 0; i < rows.length; i++) { minValue = Math.min(minValue, rows[i].value); maxValue = Math.max(maxValue, rows[i].value); sum += rows[i].value; } const average = sum / rows.length; return { rows: rows, min: minValue, max: maxValue, average: average }; } function loadData(url, callback) { fetch(url) .then( resp => { if (resp.ok) { return resp.text(); } else { return Promise.reject(`${resp.status} ${resp.statusText}`); } }) .then( csv => { const data = parseData(csv); callback({ ok: true, data: data, msg: "", }); }) .catch( err => { callback({ ok: false, data: null, msg: `${err}`, }); }); } function iterateDays(sy, sm, ey, em, omit, callback) { let year = sy; let month = sm; while (year < ey || (year === ey && month <= em)) { let ok = true; if (Array.isArray(omit)) { for (let i = 0; i < omit.length; i++) { if (omit[i][0] === year && omit[i][1] === month) { ok = false; break; } } } else if (typeof omit === "function") { if (omit(year, month)) { ok = false; } } if (ok) { callback(year, month); } month++; if (month > 12) { month = 1; year++; } } }
import createTest from '@r/platform/createTest'; import messages from './messages'; import * as loginActions from 'app/actions/login'; import * as mailActions from 'app/actions/mail'; createTest({ reducers: { messages } }, ({ getStore, expect }) => { describe('messages', () => { describe('LOGGED_IN and LOGGED_OUT', () => { it('should return default on log out', () => { const { store } = getStore({ messages: { t4_1: {} }, }); store.dispatch(loginActions.loggedOut()); const { messages } = store.getState(); expect(messages).to.eql({}); }); it('should return the default on log in', () => { const { store } = getStore({ messages: { t4_1: {} }, }); store.dispatch(loginActions.loggedIn()); const { messages } = store.getState(); expect(messages).to.eql({}); }); }); describe('RECEIVING MESSAGES', () => { it('should pull messages from all expected sources', () => { const { store } = getStore(); const message = { uuid: 't4_1', subreddit: 'mwebisboss', }; store.dispatch(mailActions.setInboxSuccess('', { messages: { [message.uuid]: message, }, })); expect(store.getState().messages).to.eql({ [message.uuid]: message, }); }); }); describe('ADDING REPLY', () => { it('should add a message', () => { const { store } = getStore(); const message = { uuid: 't4_1', subreddit: 'mwebisboss', }; store.dispatch(mailActions.addReply({ messages: { [message.uuid]: message, }, })); expect(store.getState().messages).to.eql({ [message.uuid]: message, }); }); }); }); });
import React, { Component, PropTypes } from 'react' class Counter extends Component { render() { //从组件的props属性中导入四个方法和一个变量 const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props; //渲染组件,包括一个数字,四个按钮 return ( <p> Clicked: {counter} times {' '} <button onClick={increment}>+</button> {' '} <button onClick={decrement}>-</button> {' '} <button onClick={incrementIfOdd}>Increment if odd</button> {' '} <button onClick={() => incrementAsync()}>Increment async</button> </p> ) } } //限制组件的props安全 Counter.propTypes = { //increment必须为fucntion,且必须存在 increment: PropTypes.func.isRequired, incrementIfOdd: PropTypes.func.isRequired, incrementAsync: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired, //counter必须为数字,且必须存在 counter: PropTypes.number.isRequired }; export default Counter /** 上述代码,我们干了几件事: 1. 从props中导入变量和方法 2. 渲染组件 */
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var workingWithNestedObject_1 = require("../../src/object/workingWithNestedObject"); var workingWithNestedObjectExample = new workingWithNestedObject_1.WorkingWithNestedObjectExample(); var complexObject = { firstName: 'Bob', lastName: 'Smith', addresses: [ { address1: '123 Main St', city: 'Chicago', state: 'IL', zip: '60614' }, { address1: '123 Elm St', city: 'Melbourn', state: 'IL', zip: '60614' } ], }; test('get nested property', function () { var firstAdressCity = workingWithNestedObjectExample.get(complexObject, 'addresses[0].city'); var notExistingProp = workingWithNestedObjectExample.get(complexObject, 'addresses[28].city', 'default'); expect(firstAdressCity).toEqual('Chicago'); expect(notExistingProp).toEqual('default'); }); test('pick multiple nested properies - preserving object structure', function () { var adresses = workingWithNestedObjectExample.pick(complexObject, ['addresses[0].city', 'addresses[1].city']); expect(adresses).toEqual({ "addresses": [{ "city": "Chicago" }, { "city": "Melbourn" }] }); }); test('omit properties', function () { var adresses = workingWithNestedObjectExample.omit(complexObject, ['addresses[0].city', 'addresses[1].city']); var withoutCityAdress = { firstName: 'Bob', lastName: 'Smith', addresses: [ { address1: '123 Main St', state: 'IL', zip: '60614' }, { address1: '123 Elm St', state: 'IL', zip: '60614' } ], }; expect(adresses).toEqual(withoutCityAdress); });
'use strict'; const createError = require('create-error'); module.exports = createError('AuthorizationError');
import alt from './../alt.js'; import _ from 'lodash'; class UsersActions { add({groupId, userId}) { this.dispatch({groupId, userId}); } remove({groupId, userId}) { this.dispatch({groupId, userId}); } } export default alt.createActions(UsersActions);